Test Enviroment
- CentOS release 6.3 (Final)
- ruby 1.9.3p194 (2012-04-20) [x86_64-linux]
- ruby-libvirt (0.4.0)
# # KVM Disk Image Backup Script # # fetaro@gmail.com # # usage : $ ruby kvmbackup.rb (domain-name) # # 1. Get Disk image paths from domain-xml # 2. Susupend domain if running # 3. Backup Disk image to BACKUP_DIR with BACKUP_CMD (cp or scp) # 4. Resume domain if suspended # require 'libvirt' BACKUP_CMD="scp" #BACKUP_CMD="cp" BACKUP_DIR="host:/path/to/backup/dir" #BACKUP_DIR="/path/to/backup/dir" if ARGV[0].nil? STDERR.puts "There is no argument" exit 1 end domain=ARGV[0] conn = Libvirt::open("qemu:///system") dom = conn.lookup_domain_by_name(domain) # get disk image path img_paths = [] require "rexml/document" xml = REXML::Document.new(dom.xml_desc) xml.elements.to_a("domain/devices/disk").each do |disk| if disk.attributes["device"] == "disk" img_paths << disk.elements["source"].attributes["file"] end end return_code = 0 begin if dom.state[0] == 1 # domain is running puts "suspend #{domain}" dom.suspend end img_paths.each do |img_path| cmd = "#{BACKUP_CMD} #{img_path} #{BACKUP_DIR}" puts cmd system cmd if($? != 0) then STDERR.puts "fail to #{cmd}" return_code=1 end end rescue => e p e return_code = 1 ensure if dom.state[0] == 3 # domain is paused puts "resume #{domain}" dom.resume end end exit return_code