4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

KVM Disk Images Backup Script with "ruby-libvirt"

Posted at

This is script which backup KVM disk image by using ruby-libvirt

Test Enviroment

  • KVM on CentOS release 6.3 (Final)
  • ruby 1.9.3p194 (2012-04-20) [x86_64-linux]
  • ruby-libvirt (0.4.0)

Script

#
# 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
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?