TCK.pm 35.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
#
# Copyright (C) 2009-2010 Red Hat, Inc.
# Copyright (C) 2009 Daniel P. Berrange
#
# This program is free software; You can redistribute it and/or modify
# it under the GNU General Public License as published by the Free
# Software Foundation; either version 2, or (at your option) any
# later version
#
# The file "LICENSE" distributed along with this file provides full
# details of the terms and conditions
#
13 14 15 16 17 18 19 20

package Sys::Virt::TCK;

use strict;
use warnings;

use Sys::Virt;
use Sys::Virt::TCK::DomainBuilder;
21 22 23
use Sys::Virt::TCK::NetworkBuilder;
use Sys::Virt::TCK::StoragePoolBuilder;
use Sys::Virt::TCK::StorageVolBuilder;
24 25
use Sys::Virt::TCK::Capabilities;

26
use Config::Record;
27 28 29 30 31
use File::Copy qw(copy);
use File::Path qw(mkpath);
use File::Spec::Functions qw(catfile catdir rootdir);
use Cwd qw(cwd);
use LWP::UserAgent;
32 33
use IO::Uncompress::Gunzip qw(gunzip);
use IO::Uncompress::Bunzip2 qw(bunzip2);
34
use XML::XPath;
35
use Carp qw(cluck carp);
36
use Fcntl qw(O_RDONLY SEEK_END);
37
use NetAddr::IP qw(:lower);
38

39
use Test::More;
40 41 42
use Sub::Uplevel qw(uplevel);
use base qw(Exporter);

43 44
our @EXPORT = qw(ok_error ok_domain ok_domain_snapshot ok_pool
                 ok_volume ok_network ok_interface ok_node_device
45 46 47
                 xpath err_not_implemented get_first_macaddress
                 get_first_interface_target_dev get_network_ip
                 get_ip_from_leases shutdown_vm_gracefully);
48

49
our $VERSION = 'v0.1.0';
50 51 52 53 54 55 56 57

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};
    my %params = @_;

    $self->{config} = $params{config} ? $params{config} :
58
        Config::Record->new(file => ($ENV{LIBVIRT_TCK_CONFIG} || "/etc/tck.conf"));
59

60
    $self->{autoclean} = $params{autoclean} ? $params{autoclean} :
61
        ($ENV{LIBVIRT_TCK_AUTOCLEAN} || 0);
62

63
    if ($ENV{LIBVIRT_TCK_DEBUG}) {
64 65
        $SIG{__WARN__} = sub { Carp::cluck $_[0]; };
        $SIG{__DIE__} = sub { Carp::confess $_[0]; };
66 67
    }

68 69 70 71 72
    bless $self, $class;

    return $self;
}

73 74 75 76 77 78
sub root_password {
    my $self = shift;

    return $self->{config}->get("rootpassword", "123456");
}

79 80 81 82 83 84 85 86 87 88 89 90 91
sub setup_conn {
    my $self = shift;
    my $uri = shift;

    my $conn = Sys::Virt->new(address => $uri);
    my $type = lc ($conn->get_type());

    $self->reset($conn) if $self->{autoclean};

    $self->sanity_check($conn);

    return $conn;
}
92 93 94

sub setup {
    my $self = shift;
95 96
    my %params = @_;
    my $dualhost = $params{dualhost} || 0;
97

98
    my $uri = $self->config("uri", undef);
99 100 101 102 103 104
    my $otheruri;
    $otheruri = $self->config("otheruri", undef) if $dualhost;

    my $conn = $self->setup_conn($uri);
    my $otherconn;
    $otherconn = $self->setup_conn($otheruri) if $otheruri;
105

106 107 108
    $self->{conns} = [ $conn, $otherconn ];

    return wantarray ? @{$self->{conns}} : $self->{conns}->[0];
109 110
}

111 112 113

sub sanity_check {
    my $self = shift;
114
    my $conn = shift;
115

116
    my @doms = grep { $_->get_name =~ /^tck/ } $conn->list_domains;
117
    if (@doms) {
118
        die "there is/are " . int(@doms) . " pre-existing active domain(s) in this driver";
119 120
    }

121
    @doms = grep { $_->get_name =~ /^tck/ } $conn->list_defined_domains;
122
    if (@doms) {
123
        die "there is/are " . int(@doms) . " pre-existing inactive domain(s) in this driver";
124
    }
125

126
    my @nets = grep { $_->get_name =~ /^tck/ } $conn->list_networks;
127
    if (@nets) {
128
        die "there is/are " . int(@nets) . " pre-existing active network(s) in this driver";
129 130
    }

131
    @nets = grep { $_->get_name =~ /^tck/ } $conn->list_defined_networks;
132
    if (@nets) {
133
        die "there is/are " . int(@nets) . " pre-existing inactive network(s) in this driver";
134 135
    }

136 137 138 139 140
    my @nwfilters = grep { $_->get_name =~ /^tck/ } $conn->list_nwfilters;
    if (@nwfilters) {
        die "there is/are " . int(@nwfilters) . " pre-existing nwfilter(s) in this driver";
    }

141
    my @pools = grep { $_->get_name =~ /^tck/ } $conn->list_storage_pools;
142
    if (@pools) {
143
        die "there is/are " . int(@pools) . " pre-existing active storage_pool(s) in this driver";
144 145
    }

146
    @pools = grep { $_->get_name =~ /^tck/ } $conn->list_defined_storage_pools;
147
    if (@pools) {
148
        die "there is/are " . int(@pools) . " pre-existing inactive storage_pool(s) in this driver";
149
    }
150 151
}

152 153 154 155
sub reset_snapshots {
    my $self = shift;
    my $dom = shift;

156 157
    # Use eval as not all drivers support snapshots
    my @domss = eval { $dom->list_snapshots };
158
    foreach my $domss (@domss) {
159
        $domss->delete;
160 161 162
    }
}

163
sub reset_domains {
164
    my $self = shift;
165
    my $conn = shift;
166

167
    my @doms = grep { $_->get_name =~ /^tck/ } $conn->list_domains;
168
    foreach my $dom (@doms) {
169 170 171 172
        $self->reset_snapshots($dom);
        if ($dom->get_id != 0) {
            $dom->destroy;
        }
173 174
    }

175
    @doms = grep { $_->get_name =~ /^tck/ } $conn->list_defined_domains();
176
    foreach my $dom (@doms) {
177 178
        $self->reset_snapshots($dom);
        $dom->undefine;
179
    }
180
}
181

182 183 184 185 186
sub reset_networks {
    my $self = shift;
    my $conn = shift;

    my @nets = grep { $_->get_name =~ /^tck/ } $conn->list_networks;
187
    foreach my $net (@nets) {
188 189 190
        if ($net->is_active()) {
            $net->destroy;
        }
191 192
    }

193
    @nets = grep { $_->get_name =~ /^tck/ } $conn->list_defined_networks();
194
    foreach my $net (@nets) {
195
        $net->undefine;
196
    }
197
}
198

199 200 201 202 203 204 205 206 207 208
sub reset_nwfilters {
    my $self = shift;
    my $conn = shift;

    my @nwfilters = grep { $_->get_name =~ /^tck/ } $conn->list_nwfilters;
    foreach my $nwfilter (@nwfilters) {
        $nwfilter->undefine;
    }
}

209 210 211 212 213
sub reset_storage_pools {
    my $self = shift;
    my $conn = shift;

    my @pools = grep { $_->get_name =~ /^tck/ } $conn->list_storage_pools;
214
    foreach my $pool (@pools) {
215 216 217 218 219
        my @vols = $pool->list_volumes;
        foreach my $vol (@vols) {
            eval { $vol->delete(0) };
        }
        $pool->destroy;
220 221
    }

222
    @pools = grep { $_->get_name =~ /^tck/ } $conn->list_defined_storage_pools();
223
    foreach my $pool (@pools) {
224 225 226 227
        eval {
            $pool->delete(0);
        };
        $pool->undefine;
228
    }
229 230
}

231 232 233 234 235 236 237

sub reset {
    my $self = shift;
    my $conn = shift || $self->conn;

    $self->reset_domains($conn);
    $self->reset_networks($conn);
238
    $self->reset_nwfilters($conn);
239 240 241
    $self->reset_storage_pools($conn);
}

242 243
sub cleanup {
    my $self = shift;
244

245
    foreach my $conn (@{$self->{conns}}) {
246
        $self->reset($conn);
247
    }
248

249
    delete $self->{conns};
250 251 252 253 254
}

sub config {
    my $self = shift;
    my $key = shift;
255
    if (@_) {
256 257
        my $default = shift;
        return $self->{config}->get($key, $default);
258
    } else {
259
        return $self->{config}->get($key);
260
    }
261 262 263 264 265
}


sub conn {
    my $self = shift;
266 267
    my $index = @_ ? shift : 0;
    return $self->{conns}->[$index];
268 269 270
}


271 272 273 274
sub scratch_dir {
    my $self = shift;

    my $scratch = $self->config("scratch_dir", $< > 0 ?
275 276
                                catdir(cwd(), "libvirt-tck") :
                                catdir(rootdir(), "var", "cache", "libvirt-tck"));
277 278 279 280 281 282

    mkpath($scratch) unless -e $scratch;

    return $scratch;
}

283
sub bucket_dir {
284 285 286 287 288
    my $self = shift;
    my $name = shift;

    my $scratch = $self->scratch_dir;

289 290 291 292 293
    my $bucket = catdir($scratch, $name);
    mkpath($bucket) unless -e $bucket;

    return $bucket;
}
294

295 296 297 298 299 300 301
sub get_scratch_resource {
    my $self = shift;
    my $source = shift;
    my $bucket = shift;
    my $name = shift;

    my $dir = $self->bucket_dir($bucket);
302 303 304 305
    my $target = catfile($dir, $name);

    return $target if -e $target;

306 307
    my $uncompress = undef;
    if (ref($source)) {
308 309
        $uncompress = $source->{uncompress};
        $source = $source->{source};
310 311
    }

312
    if ($source =~ m,^/,) {
313
        $self->copy_scratch($source, $target, $uncompress);
314
    } else {
315
        $self->download_scratch($source, $target, $uncompress);
316 317 318 319 320 321 322 323 324 325
    }

    return $target;
}


sub download_scratch {
    my $self = shift;
    my $source = shift;
    my $target = shift;
326
    my $uncompress = shift;
327

328
    print "# downloading $source\n";
329 330 331 332 333 334 335
    my $ua = LWP::UserAgent->new;
    $ua->timeout(10);
    $ua->env_proxy;

    my $response = $ua->get($source);

    if ($response->is_success) {
336 337 338 339 340 341 342 343 344 345 346 347 348 349
        open TGT, ">$target" or die "cannot create $target: $!";
        if (defined $uncompress) {
            my $data = $response->content;
            if ($uncompress eq "gzip") {
                gunzip \$data => \*TGT;
            } elsif ($uncompress eq "bzip2") {
                bunzip2 \$data => \*TGT;
            } else {
                die "unknown compression method '$uncompress'";
            }
        } else {
            print TGT $response->content or die "cannot write $target: $!";
        }
        close TGT or die "cannot save $target: $!";
350
    } else {
351
        die "cannot download $source: " . $response->status_line;
352 353 354 355 356 357 358 359
    }

}

sub copy_scratch {
    my $self = shift;
    my $source = shift;
    my $target = shift;
360 361
    my $uncompress = shift;

362
    print "# copying $source\n";
363
    if (defined $uncompress) {
364 365 366 367 368 369 370
        if ($uncompress eq "gzip") {
            gunzip $source => $target;
        } elsif ($uncompress eq "bzip2") {
            bunzip2 $source => $target;
        } else {
            die "unknown compression method '$uncompress'";
        }
371
    } else {
372
        copy ($source, $target) or die "cannot copy $source to $target: $!";
373 374
    }
}
375

376 377 378 379 380 381 382 383 384 385 386

sub create_sparse_disk {
    my $self = shift;
    my $bucket = shift;
    my $name = shift;
    my $size = shift;

    my $dir = $self->bucket_dir($bucket);

    my $target = catfile($dir, $name);

387
    open DISK, ">>$target" or die "cannot create $target: $!";
388 389 390 391 392 393

    truncate DISK, ($size * 1024 * 1024);

    close DISK or die "cannot save $target: $!";

    return $target;
394 395 396
}


397 398 399 400 401 402 403 404 405 406 407 408 409
sub has_disk_image {
    my $self = shift;
    my $bucket = shift;
    my $name = shift;
    my $osname = shift;

    my $dir = $self->bucket_dir($bucket);

    my $target = catfile($dir, $name);

    return -f $target
}

410 411 412 413 414 415 416 417 418 419 420 421
sub create_virt_builder_disk {
    my $self = shift;
    my $bucket = shift;
    my $name = shift;
    my $osname = shift;

    my $dir = $self->bucket_dir($bucket);

    my $target = catfile($dir, $name);

    my $password = $self->root_password;

422
    if ($self->has_disk_image($bucket, $name, $osname)) {
423
        return $target;
424 425 426
    }

    print "# running virt-builder $osname\n";
427
    system "virt-builder", "--install", "dsniff", "--selinux-relabel", "--root-password", "password:$password", "--output", $target, $osname;
428 429

    die "cannot run virt-builder: $?" if $? != 0;
430 431 432 433

    return $target;
}

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
sub create_empty_dir {
    my $self = shift;
    my $bucket = shift;
    my $name = shift;

    my $dir = $self->bucket_dir($bucket);

    my $target = catfile($dir, $name);

    mkpath($target) unless -e $target;

    return $target;
}


449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
sub create_minimal_vroot {
    my $self = shift;
    my $bucket = shift;
    my $name = shift;

    my $dir = $self->bucket_dir($bucket);
    my $target = catdir($dir, $name);

    mkpath($target) unless -e $target;

    my $busybox = $self->config("busybox", "/sbin/busybox");

    die "$busybox does not exist" unless $busybox;

    my $type = `file $busybox 2>&1`;

    die "$busybox is not statically linked" unless $type =~ /statically/;

    my @dirs = qw(sbin bin dev proc sys tmp);

    foreach my $dir (@dirs) {
470 471 472
        my $fulldir = catdir($target, $dir);
        next if -e $fulldir;
        mkpath($fulldir);
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    }

    my $dst = catfile($target, "sbin", "busybox");
    copy ($busybox, $dst) or die "cannot copy $busybox to $dst: $!";
    chmod 0755, $dst or die "cannot make $dst executable: $!";

    my @links = qw(
            ed           kill        ping6              svlogd
            egrep        killall     pipe_progress      swapoff
addgroup    eject        killall5    pivot_root         swapon
adduser     env          klogd       pkill              switch_root
adjtimex    envdir       last        poweroff           sync
ar          envuidgid    length      printenv           sysctl
arp         expand       less        printf             syslogd
arping      expr         linux32     ps                 tail
ash         fakeidentd   linux64     pscan              tar
awk         false        linuxrc     pwd                tcpsvd
basename    fbset        ln          raidautorun        tee
bunzip2     fdformat     loadfont    rdate              telnet
busybox     fdisk        loadkmap    readahead          telnetd
bzcat       fgrep        logger      readlink           test
bzip2       find         login       readprofile        tftp
cal         fold         logname     realpath           time
cat         free         logread     reboot             top
catv        freeramdisk  losetup     renice             touch
chattr      fsck         ls          reset              tr
chgrp       fsck.minix   lsattr      resize             traceroute
chmod       ftpget       lsmod       rm                 true
chown       ftpput       lzmacat     rmdir              tty
chpasswd    fuser        makedevs    rmmod              ttysize
chpst       getopt       md5sum      route              udhcpc
chroot      getty        mdev        rpm                udhcpd
chrt        grep         mesg        rpm2cpio           udpsvd
chvt        gunzip       microcom    runlevel           umount
cksum       gzip         mkdir       run-parts          uname
clear       halt         mkfifo      runsv              uncompress
cmp         hdparm       mkfs.minix  runsvdir           unexpand
comm        head         mknod       rx                 uniq
cp          hexdump      mkswap      sed                unix2dos
cpio        hostid       mktemp      seq                unlzma
crond       hostname     modprobe    setarch            unzip
crontab     httpd        more        setconsole         uptime
cryptpw     hwclock      mount       setkeycodes        usleep
cut         id           mountpoint  setlogcons         uudecode
date        ifconfig     msh         setsid             uuencode
dc          ifdown       mt          setuidgid          vconfig
dd          ifup         mv          sh                 vi
deallocvt   inetd        nameif      sha1sum            vlock
delgroup    init         nc          slattach           watch
deluser     insmod       netstat     sleep              watchdog
df          install      nice        softlimit          wc
dhcprelay   ip           nmeter      sort               wget
diff        ipaddr       nohup       split              which
dirname     ipcalc       nslookup    start-stop-daemon  who
dmesg       ipcrm        od          stat               whoami
dnsd        ipcs         openvt      strings            xargs
dos2unix    iplink       passwd      stty               yes
du          iproute      patch       su                 zcat
dumpkmap    iprule       pgrep       sulogin            zcip
dumpleases  iptunnel     pidof       sum
echo        kbd_mode     ping        sv);

    foreach my $file (@links) {
536 537 538 539
        my $fullfile = catfile($target, "bin", $file);
        next if -e $fullfile;
        symlink "../sbin/busybox", $fullfile
            or die "cannot symlink $fullfile to ../sbin/busybox: $!";
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    }

    my $init = catfile($target, "sbin", "init");
    open INIT, ">$init" or die "cannot create $init: $!";

    print INIT <<EOF;
#!/sbin/busybox

sh
EOF

    close INIT or die "cannot save $init: $!";
    chmod 0755, $init or die "cannot make $init executable: $!";

    return ($target, catfile(rootdir, "sbin", "init"));
}

557 558 559 560 561 562
sub best_domain {
    my $self = shift;
    my $caps = shift;
    my $ostype = shift;

    for (my $i = 0 ; $i < $caps->num_guests ; $i++) {
563 564
        if ($caps->guest_os_type($i) eq $ostype &&
            $caps->guest_arch_name($i) eq $caps->host_cpu_arch()) {
565

566 567
            my @domains = $caps->guest_domain_types($i);
            next unless int(@domains);
568

569 570
            # Prefer kvm if multiple domain types are returned
            my $domain = (grep /^kvm$/, @domains) ? "kvm" : $domains[0];
571

572 573 574
            return ($domain,
                    $caps->host_cpu_arch());
        }
575 576 577 578 579 580 581
    }

    return ();
}


sub match_guest_domain {
582
    my $self = shift;
583
    my $caps = shift;
584 585 586
    my $arch = shift;
    my $ostype = shift;

587
    for (my $i = 0 ; $i < $caps->num_guests ; $i++) {
588 589
        if ($caps->guest_os_type($i) eq $ostype &&
            $caps->guest_arch_name($i) eq $arch) {
590

591 592
            my @domains = $caps->guest_domain_types($i);
            next unless int(@domains);
593

594 595
            # Prefer kvm if multiple domain types are returned
            my $domain = (grep /^kvm$/, @domains) ? "kvm" : $domains[0];
596

597 598 599 600
            return ($domain,
                    $caps->guest_domain_emulator($i, $domain),
                    $caps->guest_domain_loader($i, $domain));
        }
601
    }
602

603 604 605 606 607 608
    return ();
}


sub best_kernel {
    my $self = shift;
609
    my $caps = shift;
610
    my $wantostype = shift;
611

612
    my $kernels = $self->config("kernels", []);
613
    my $hostarch = $caps->host_cpu_arch();
614 615

    for (my $i = 0 ; $i <= $#{$kernels} ; $i++) {
616 617 618
        my $arch = $kernels->[$i]->{arch};
        my $ostype = $kernels->[$i]->{ostype};
        my @ostype = ref($ostype) ? @{$ostype} : ($ostype);
619

620
        next unless $arch eq $hostarch;
621

622 623 624 625 626
        foreach $ostype (@ostype) {
            if ((defined $wantostype) &&
                ($wantostype ne $ostype)) {
                next;
            }
627

628 629
            my ($domain, $emulator, $loader) =
                $self->match_guest_domain($caps, $arch, $ostype);
630

631 632 633 634
            if (defined $domain) {
                return ($i, $domain, $arch, $ostype, $emulator, $loader)
            }
        }
635 636 637 638
    }

    return ();
}
639

640 641 642 643 644 645 646 647 648 649 650

# Find an image matching the host arch and requested ostype
sub best_image {
    my $self = shift;
    my $caps = shift;
    my $wantostype = shift;

    my $images = $self->config("images", []);
    my $hostarch = $caps->host_cpu_arch();

    for (my $i = 0 ; $i <= $#{$images} ; $i++) {
651 652 653
        my $arch = $images->[$i]->{arch};
        my $ostype = $images->[$i]->{ostype};
        my @ostype = ref($ostype) ? @{$ostype} : ($ostype);
654

655
        next unless $arch eq $hostarch;
656

657 658 659 660 661
        foreach $ostype (@ostype) {
            if ((defined $wantostype) &&
                ($wantostype ne $ostype)) {
                next;
            }
662

663 664
            my ($domain, $emulator, $loader) =
                $self->match_guest_domain($caps, $arch, $ostype);
665

666 667 668 669
            if (defined $domain) {
                return ($i, $domain, $arch, $ostype, $emulator, $loader)
            }
        }
670 671 672 673 674 675 676 677 678 679 680 681
    }

    return ();
}

sub get_disk_dev {
    my $self = shift;
    my $ostype = shift;
    my $domain = shift;

    my $dev;
    if ($ostype eq "xen") {
682
        $dev = "xvda";
683
    } elsif ($ostype eq "uml") {
684
        $dev = "ubda";
685
    } elsif ($ostype eq "hvm") {
686 687 688 689 690 691 692
        if ($domain eq "kvm" ||
            $domain eq "qemu" ||
            $domain eq "kqemu") {
            $dev = "vda";
        } else {
            $dev = "hda";
        }
693 694 695 696 697
    }
    return $dev;
}


698 699
sub get_kernel {
    my $self = shift;
700
    my $caps = shift;
701
    my $wantostype = shift;
702 703

    my ($cfgindex, $domain, $arch, $ostype, $emulator, $loader) =
704
        $self->best_kernel($caps, $wantostype);
705 706

    if (!defined $cfgindex) {
707
        die "cannot find any supported kernel configuration";
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    }

    my $kernels = $self->config("kernels", []);

    my $kernel = $kernels->[$cfgindex]->{kernel};
    my $initrd = $kernels->[$cfgindex]->{initrd};
    my $disk = $kernels->[$cfgindex]->{disk};

    my $bucket = "os-$arch-$ostype";

    my $kfile = $self->get_scratch_resource($kernel, $bucket, "vmlinuz");
    my $ifile = $initrd ? $self->get_scratch_resource($initrd, $bucket, "initrd") : undef;
    my $dfile = $disk ? $self->get_scratch_resource($disk, $bucket, "disk.img") : undef;

    unless (defined $dfile) {
723
        $dfile = $self->create_sparse_disk($bucket, "disk.img", 100);
724 725 726 727
    }

    chmod 0755, $kfile;

728
    my $dev = $self->get_disk_dev($ostype, $domain);
729

730
    return (
731 732 733 734 735 736 737 738 739
        domain => $domain,
        arch => $arch,
        ostype => $ostype,
        emulator => $emulator,
        loader => $loader,
        kernel => $kfile,
        initrd => $ifile,
        root => $dfile,
        dev => $dev,
740
    );
741 742 743
}


744
sub get_image {
745
    my $self = shift;
746 747
    my $caps = shift;
    my $wantostype = shift;
748

749
    my ($cfgindex, $domain, $arch, $ostype, $emulator, $loader) =
750
        $self->best_image($caps, $wantostype);
751

752
    if (!defined $cfgindex) {
753
        die "cannot find any supported image configuration";
754
    }
755

756
    my $kernels = $self->config("images", []);
757

758
    my $osname = $kernels->[$cfgindex]->{osname};
759

760 761
    my $bucket = "os-$arch-$ostype";

762
    my $needs_firstboot = ! $self->has_disk_image($bucket, "disk-$osname.img", $osname);
763 764 765 766 767
    my $dfile = $self->create_virt_builder_disk($bucket, "disk-$osname.img", $osname);

    my $dev = $self->get_disk_dev($ostype, $domain);

    return (
768 769 770 771 772 773 774
        domain => $domain,
        arch => $arch,
        ostype => $ostype,
        emulator => $emulator,
        loader => $loader,
        root => $dfile,
        dev => $dev,
775
    firstboot => $needs_firstboot,
776 777 778 779 780 781 782 783 784 785 786 787
    );
}



sub generic_machine_domain {
    my $self = shift;
    my %params = @_;
    my $name = exists $params{name} ? $params{name} : "tck";
    my $caps = exists $params{caps} ? $params{caps} : die "caps parameter is required";
    my $ostype = exists $params{ostype} ? $params{ostype} : "hvm";
    my $fullos = exists $params{fullos} ? $params{fullos} : 0;
788
    my $shareddisk = exists $params{shareddisk} ? $params{shareddisk} : 0;
789
    my $filterref = exists $params{filterref} ? $params{filterref} : undef;
790
    my %filterparams = exists $params{filterparams} ? %{$params{filterparams}} : ();
791 792

    if ($fullos) {
793
        my %config = $self->get_image($caps, $ostype);
794 795

        my $b = Sys::Virt::TCK::DomainBuilder->new(conn => $self->conn,
796 797 798 799 800 801 802
                                                   name => $name,
                                                   arch => $config{arch},
                                                   domain => $config{domain},
                                                   ostype => $config{ostype});
        $b->memory(1024 * 1024);
        $b->with_acpi();
        $b->with_apic();
803

804
        $b->boot_disk();
805

806 807 808
        $b->disk(src => $config{root},
                 dst => $config{dev},
                 type => "file");
809

810 811
        if ($config{firstboot}) {
            print "# Running the first boot\n";
812

813 814
            $b->interface(type => "network",
                          source => "default",
815
                          model => "virtio",
816
                          mac => "52:54:00:11:11:11",
817 818
                          filterref => $filterref,
                          filterparams => \%filterparams);
819 820 821 822 823 824 825 826
            my $xml = $b->as_xml();
            # Cleanup the temporary interface
            $b->rminterface();

            my $dom = $self->conn->define_domain($xml);
            $dom->create();

            # Wait for the first boot to reach network setting
827
            my $iface = get_first_interface_target_dev($dom);
828 829 830 831
            my $stats;
            my $tries = 0;
            do {
                sleep(10);
832
                $stats  = $dom->interface_stats($iface);
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
                $tries++;
            } while ($stats->{"tx_packets"} < 10 && $tries < 10);

            # Safe to shutdown domain now
            my $target = time() + 30;
            $dom->shutdown;
            while ($dom->is_active()) {
                sleep(1);
                $dom->destroy() if time() > $target;
            }
            sleep(1);
            $dom->undefine();
        }

        return $b;
848
    } else {
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
        my %config = $self->get_kernel($caps, $ostype);

        my $b = Sys::Virt::TCK::DomainBuilder->new(conn => $self->conn,
                                                   name => $name,
                                                   arch => $config{arch},
                                                   domain => $config{domain},
                                                   ostype => $config{ostype});
        $b->memory(1024 * 1024);
        $b->with_acpi();
        $b->with_apic();

        # XXX boot CDROM or vroot for other HVs
        $b->boot_kernel($config{kernel}, $config{initrd});

        $b->disk(src => $config{root},
                 dst => $config{dev},
865 866
                 type => "file",
                 shareable => $shareddisk);
867
        return $b;
868
    }
869 870
}

871

872 873 874 875 876
sub best_container_domain {
    my $self = shift;
    my $caps = shift;

    for (my $i = 0 ; $i < $caps->num_guests ; $i++) {
877 878 879
        if ($caps->guest_os_type($i) eq "exe") {
            my @domains = $caps->guest_domain_types($i);
            next unless int(@domains);
880

881 882
            return $domains[0];
        }
883 884 885 886 887 888 889 890
    }

    return undef;

}

sub generic_container_domain {
    my $self = shift;
891 892 893 894
    my %params = @_;
    my $name = exists $params{name} ? $params{name} : "tck";
    my $caps = exists $params{caps} ? $params{caps} : die "caps parameter is required";
    my $domain = exists $params{domain} ? $params{domain} : die "domain parameter is required";
895 896 897

    my $bucket = "os-exe";

898
    my $b = Sys::Virt::TCK::DomainBuilder->new(conn => $self->conn,
899 900 901
                                               name => $name,
                                               domain => $domain,
                                               ostype => "exe");
902 903 904 905 906 907 908
    $b->memory(64 * 1024);

    my ($root, $init) = $self->create_minimal_vroot($bucket, $name);

    $b->boot_init($init);

    $b->filesystem(src => $root,
909 910
                   dst => "/",
                   type => "mount");
911 912 913 914 915 916 917

    return $b;
}


sub generic_domain {
    my $self = shift;
918 919 920 921
    my %params = @_;

    my $name = exists $params{name} ? $params{name} : "tck";
    my $ostype = exists $params{ostype} ? $params{ostype} : "hvm";
922
    my $fullos = exists $params{fullos} ? $params{fullos} : 0;
923
    my $netmode = exists $params{netmode} ? $params{netmode} : undef;
924
    my $shareddisk = exists $params{shareddisk} ? $params{shareddisk} : 0;
925
    my $filterref = exists $params{filterref} ? $params{filterref} : undef;
926
    my %filterparams = exists $params{filterparams} ? %{$params{filterparams}} : ();
927

928
    my $caps = Sys::Virt::TCK::Capabilities->new(xml => $self->conn->get_capabilities);
929

930 931 932
    my $container;

    $container = $self->best_container_domain($caps)
933
        unless $ostype && $ostype ne "exe";
934

935
    my $b;
936
    if ($container) {
937
        die "Full provisioned OS not supported with containers yet" if $fullos;
938

939 940 941
        $b = $self->generic_container_domain(name => $name,
                                             caps => $caps,
                                             domain => $container);
942
    } else {
943 944 945
        $b = $self->generic_machine_domain(name => $name,
                                           caps => $caps,
                                           ostype => $ostype,
946
					   shareddisk => $shareddisk,
947
                                           fullos => $fullos,
948 949
                                           filterref => $filterref,
                                           filterparams => \%filterparams);
950 951
    }
    if ($netmode) {
952 953 954
        if ($netmode eq "vepa") {
            $b->interface(type => "direct",
                          source => "default",
955
                          model => "virtio",
956 957 958 959 960 961 962
                          mac => "52:54:00:11:11:11",
                          dev => $self->get_host_network_device(),
                          mode => "vepa",
                          virtualport => "802.1Qbg");
        } else {
            $b->interface(type => "network",
                          source => "default",
963
                          model => "virtio",
964
                          mac => "52:54:00:11:11:11",
965 966
                          filterref => $filterref,
                          filterparams => \%filterparams);
967
        }
968
    }
969
    return $b;
970 971
}

972 973 974
sub generic_pool {
    my $self = shift;
    my $type = shift;
975
    my $name = @_ ? shift : "tck";
976 977 978 979

    my $bucket = $self->bucket_dir("storage-fs");

    my $b = Sys::Virt::TCK::StoragePoolBuilder->new(name => $name,
980
                                                    type => $type);
981 982 983 984 985 986 987

    $b->target(catdir($bucket, $name));

    return $b;
}


988 989 990 991 992 993
sub generic_network {
    my $self = shift;
    my $name = @_ ? shift : "tck";

    my $b = Sys::Virt::TCK::NetworkBuilder->new(name => $name);

994
    $b->bridge($name);
995 996 997 998 999 1000 1001
    # XXX check for host clash
    #$b->ipaddr("10.250.250.250", "255.255.255.0");

    return $b;
}


1002 1003
sub generic_volume {
    my $self = shift;
1004
    my $name = @_ ? shift : "tck";
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    my $format = @_ ? shift :undef;
    my $capacity = @_ ? shift : 1024*1024*50;

    my $b = Sys::Virt::TCK::StorageVolBuilder->new(name => $name);
    $b->format($format) if $format;
    $b->capacity($capacity);

    return $b;
}

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
# Borrowed from Test::Exception

sub _quiet_caller (;$) { ## no critic Prototypes
    my $height = $_[0];
    $height++;
    if( wantarray and !@_ ) {
        return (CORE::caller($height))[0..2];
    }
    else {
        return CORE::caller($height);
    }
1026
                   }
1027 1028 1029

sub _try_as_caller {
    my $coderef = shift;
1030
    my $depth = shift;
1031 1032 1033 1034 1035

    # local works here because Sub::Uplevel has already overridden caller
    local *CORE::GLOBAL::caller;
    { no warnings 'redefine'; *CORE::GLOBAL::caller = \&_quiet_caller; }

1036
    my $ret = eval { uplevel $depth, $coderef };
1037 1038 1039 1040
    return ($ret, $@);
};


1041
sub ok_object($$$;$) {
1042
    my $coderef = shift;
1043
    my $class = shift;
1044 1045 1046
    my $description = shift;
    my $name = shift;

1047
    die "must pass coderef, class, description and (optional) expected name"
1048
        unless defined $description;
1049

1050
    my ($ret, $exception) = _try_as_caller($coderef, 4);
1051 1052

    my $ok = "$exception" eq "" &&
1053 1054
        $ret && ref($ret) && $ret->isa($class) &&
        (!defined $name || ($ret->get_name() eq $name));
1055

1056
    ok($ok, $description);
1057
    unless ($ok) {
1058
        diag("expected $class object" . ($name ? " with name $name" : ""));
1059
        if ($exception) {
1060
            diag("found '$exception'");
1061 1062
        } else {
            if ($ret && ref($ret) && $ret->isa($class)) {
1063
                diag("found $class object with name " . $ret->get_name);
1064
            } else {
1065
                diag("found '$ret'");
1066 1067
            }
        }
1068 1069 1070
    }
}

1071
sub ok_domain(&$;$) {
1072 1073 1074 1075
    my $coderef = shift;
    my $description = shift;
    my $name = shift;

1076 1077
    ok_object($coderef, "Sys::Virt::Domain", $description, $name);
}
1078

1079 1080 1081 1082
sub ok_domain_snapshot(&$;$) {
    my $coderef = shift;
    my $description = shift;
    my $name = shift;
1083

1084
    ok_object($coderef, "Sys::Virt::DomainSnapshot", $description, $name);
1085 1086
}

1087
sub ok_pool(&$;$) {
1088 1089 1090 1091
    my $coderef = shift;
    my $description = shift;
    my $name = shift;

1092 1093
    ok_object($coderef, "Sys::Virt::StoragePool", $description, $name);
}
1094

1095 1096 1097 1098
sub ok_network(&$;$) {
    my $coderef = shift;
    my $description = shift;
    my $name = shift;
1099

1100
    ok_object($coderef, "Sys::Virt::Network", $description, $name);
1101 1102
}

1103
sub ok_volume(&$;$) {
1104 1105 1106 1107
    my $coderef = shift;
    my $description = shift;
    my $name = shift;

1108 1109
    ok_object($coderef, "Sys::Virt::StorageVol", $description, $name);
}
1110

1111 1112 1113 1114
sub ok_interface(&$;$) {
    my $coderef = shift;
    my $description = shift;
    my $name = shift;
1115

1116 1117
    ok_object($coderef, "Sys::Virt::Interface", $description, $name);
}
1118

1119 1120 1121 1122 1123 1124
sub ok_node_device(&$;$) {
    my $coderef = shift;
    my $description = shift;
    my $name = shift;

    ok_object($coderef, "Sys::Virt::NodeDevice", $description, $name);
1125 1126
}

1127

1128 1129 1130 1131 1132 1133
sub ok_error(&$;$) {
    my $coderef = shift;
    my $description = shift;
    my $code = shift;

    die "must pass coderef, description and (optional) expected error code"
1134
        unless defined $description;
1135

1136
    my ($ret, $exception) = _try_as_caller($coderef, 3);
1137 1138

    my $ok = ref($exception) && $exception->isa("Sys::Virt::Error") &&
1139
        (!defined $code || ($exception->code() == $code));
1140

1141
    ok($ok, $description);
1142
    unless ($ok) {
1143 1144
        diag("expecting Sys::Virt::Error object" . ($code ?  " with code $code" : ""));
        diag("found '$exception'");
1145 1146 1147 1148 1149
    }
    $@ = $exception;
    return $ok;
}

1150

1151 1152 1153 1154
sub err_not_implemented {
    my $exception = shift;

    if ($exception &&
1155 1156 1157 1158
        ref($exception) &&
        $exception->isa("Sys::Virt::Error") &&
        $exception->code() == 3) {
        return 1;
1159 1160 1161 1162
    }
    return 0;
}

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
sub xpath {
    my $object = shift;
    my $path = shift;

    my $xml = $object->get_xml_description;

    my $xp = XML::XPath->new(xml => $xml);

    return $xp->find($path);
}

1174 1175 1176 1177 1178 1179 1180
sub get_host_usb_device {
    my $self = shift;
    my $devindex = @_ ? shift : 0;

    my $devs = $self->config("host_usb_devices", []);

    if ($devindex > $#{$devs}) {
1181
        return ();
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    }

    my $bus = $self->config("host_usb_devices/[$devindex]/bus", undef);
    my $device = $self->config("host_usb_devices/[$devindex]/device", undef);
    my $vendor = $self->config("host_usb_devices/[$devindex]/vendor", undef);
    my $product = $self->config("host_usb_devices/[$devindex]/product", undef);

    return ($bus, $device, $vendor, $product);
}

1192 1193 1194 1195 1196 1197 1198
sub get_host_pci_device {
    my $self = shift;
    my $devindex = @_ ? shift : 0;

    my $devs = $self->config("host_pci_devices", []);

    if ($devindex > $#{$devs}) {
1199
        return ();
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    }

    my $domain = $self->config("host_pci_devices/[$devindex]/domain", 0);
    my $bus = $self->config("host_pci_devices/[$devindex]/bus", 0);
    my $slot = $self->config("host_pci_devices/[$devindex]/slot");
    my $function = $self->config("host_pci_devices/[$devindex]/function", 0);

    return ($domain, $bus, $slot, $function);
}

1210 1211 1212 1213
sub get_host_block_device {
    my $self = shift;
    my $devindex = @_ ? shift : 0;

1214
    my $device = ($self->config("host_block_devices/[$devindex]/path", undef)
1215
                  || $self->config("host_block_devices/[$devindex]", undef));
1216 1217 1218 1219 1220 1221 1222
    return undef unless $device;

    my $kb_blocks = $self->config("host_block_devices/[$devindex]/size", 0);

    # Filter out devices that the current user can't open.
    sysopen(BLK, $device, O_RDONLY) or return undef;
    my $match = ($kb_blocks ? sysseek(BLK, 0, SEEK_END) == $kb_blocks * 1024
1223
                 : 1);
1224 1225 1226
    close BLK;

    return $match ? $device : undef;
1227 1228
}

1229 1230 1231 1232 1233 1234 1235
sub get_host_network_device {
    my $self = shift;
    my $devindex = @_ ? shift : 0;

    return $self->config("host_network_devices/[$devindex]", undef);
}

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
sub get_first_macaddress {
    my $dom = shift;
    my $mac = xpath($dom, "string(/domain/devices/interface[1]/mac/\@address)");
    utf8::encode($mac);
    return $mac;
}

sub get_first_interface_target_dev {
    my $dom = shift;
    my $targetdev = xpath($dom, "string(/domain/devices/interface[1]/target/\@dev)");
    return $targetdev;
}

sub get_network_ip {
    my $conn = shift;
    my $netname = shift;
    diag "getting ip for network $netname";
    my $net = $conn->get_network_by_name($netname);
    my $net_ip = xpath($net, "string(/network/ip[1]/\@address");
    my $net_mask = xpath($net, "string(/network/ip[1]/\@netmask");
    my $net_prefix = xpath($net, "string(/network/ip[1]/\@prefix");
    my $ip;

    if ($net_mask) {
        $ip = NetAddr::IP->new($net_ip, $net_mask);
    } elsif ($net_prefix) {
1262
        $ip = NetAddr::IP->new("$net_ip/$net_prefix");
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    } else {
        $ip = NetAddr::IP->new("$net_ip");
    }
    return $ip;
}


sub get_ip_from_leases{
    my $conn = shift;
    my $netname = shift;
    my $mac = shift;

    my $net = $conn->get_network_by_name($netname);
    if ($net->can('get_dhcp_leases')) {
        my @leases = $net->get_dhcp_leases($mac);
1278
        return @leases ? $leases[0]->{'ipaddr'} : undef;
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    }

    my $tmp = `grep $mac /var/lib/libvirt/dnsmasq/default.leases`;
    my @fields = split(/ /, $tmp);
    my $ip = $fields[2];
    return $ip;
}


sub shutdown_vm_gracefully {
    my $dom = shift;

    my $target = time() + 30;
    $dom->shutdown;
    while ($dom->is_active()) {
        sleep(1);
        diag ".. waiting for virtual machine to shutdown.. ";
        $dom->destroy() if time() > $target;
    }
    sleep(1);
    diag ".. shutdown complete.. ";
}

1302
1;