Perl: wrapper for virt-install to provide iSCSI storage pool creation

So I've been working on a setup for virtualization, where currently I'm using one large iSCSI target from an OpenSolaris machine. It occurred to me that there is a downside to this. I cannot use zfs snapshots for individual machines and backups/restores will be more difficult. I also did not want to be hassled with having to connect the iscsi targets using iscsiadm every time I spin up a new VM.

Luckily libvirt provides iSCSI storage pool methods which will connect the targets and manage them for you. This makes life much easier for me, however, virt-install does not have the functionality to install on these. Me being more proficient in Perl, I decided to take up the task of creating a simple wrapper. To use it, first you need this template XML file called "disk.xml."

      $NAME
        
          <host name="$PORTAL"/>
          <device path="$TARGET"/>
       
/dev/disk/by-path

Here's my script that I call virt-iscsi-install, and it's pretty easy to use. Not the greatest solution as it does not do much for error checking, but for now this is what I'll be using. I may consider venturing into some Python and patch virt-install to include similar functionality as the libvirt library is well documented and not hard to understand.

#!/usr/bin/perl
use Sys::Virt;
use Getopt::Long;

usage() if ( ! GetOptions(
        'name|n=s'      => \$name,
        'ram|r=s'       => \$ram,
        'target|t=s'    => \$target,
        'portal|p=s'    => \$portal,
        'mirror|m=s'    => \$mirror
)) ;

#print "name: $name\nram: $ram\ntarget: $target\nportal: $portal\n";

sub usage {
        print "usage: $0 --name  --ram  --target ".
                " --portal  --mirror \n";
        exit;
}

my $path = createPool($target,$portal,$name);
print "Volume: $path\n";
print "Launching virt-install..\n";
system ("virt-install -n $name -r $ram --location $mirror --file $path --vnc --bridge=br0");

sub createPool {
        my ($target, $portal, $name) = @_;
        my $vmm = Sys::Virt->new(address => 'qemu:///system');


        open my $fh, ') {
                s/\$NAME/$name/;
                s/\$TARGET/$target/;
                s/\$PORTAL/$portal/;
                $xml = "$xml $_";
        }
        close $fh;
        #print $xml;
        my $pool = $vmm->define_storage_pool($xml);
        $pool->create();

        if (!$pool->get_autostart) {
                print "setting pool to auto-start\n";
                $pool->set_autostart(1);
        }

        my @volNames = $pool->list_volumes;
        foreach my $vol (@volNames) {
                return $vol->get_path;
        }
}

Tags: