libvnode_xen.pm 60.4 KB
Newer Older
Jon Rafkind's avatar
Jon Rafkind committed
1
#!/usr/bin/perl -wT
2
#
Leigh B Stoller's avatar
Leigh B Stoller committed
3
# Copyright (c) 2008-2012 University of Utah and the Flux Group.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#
# Implements the libvnode API for Xen support in Emulab.
#
# Note that there is no distinguished first or last call of this library
# in the current implementation.  Every vnode creation (through mkvnode.pl)
# will invoke all the root* and vnode* functions.  It is up to us to make
# sure that "one time" operations really are executed only once.
#
# TODO:
# + Clear out old, incorrect state in /var/lib/xend.
#   Maybe have to do this when tearing down (killing) vnodes.
#
# + Make more robust, little turds of state still get left around
#   that wreak havoc on reboot.
#
# + Support image loading.
#
Jon Rafkind's avatar
Jon Rafkind committed
40
41
42
43
44
45
package libvnode_xen;
use Exporter;
@ISA    = "Exporter";
@EXPORT = qw( init setDebug rootPreConfig
              rootPreConfigNetwork rootPostConfig
	      vnodeCreate vnodeDestroy vnodeState
46
	      vnodeBoot vnodePreBoot vnodeHalt vnodeReboot
47
	      vnodeUnmount
Jon Rafkind's avatar
Jon Rafkind committed
48
49
	      vnodePreConfig vnodePreConfigControlNetwork
              vnodePreConfigExpNetwork vnodeConfigResources
50
              vnodeConfigDevices vnodePostConfig vnodeExec vnodeTearDown
Jon Rafkind's avatar
Jon Rafkind committed
51
	    );
52
use vars qw($VGNAME);
Jon Rafkind's avatar
Jon Rafkind committed
53
54
55
56
57
58
59
60

%ops = ( 'init' => \&init,
         'setDebug' => \&setDebug,
         'rootPreConfig' => \&rootPreConfig,
         'rootPreConfigNetwork' => \&rootPreConfigNetwork,
         'rootPostConfig' => \&rootPostConfig,
         'vnodeCreate' => \&vnodeCreate,
         'vnodeDestroy' => \&vnodeDestroy,
61
	 'vnodeTearDown' => \&vnodeTearDown,
Jon Rafkind's avatar
Jon Rafkind committed
62
63
64
         'vnodeState' => \&vnodeState,
         'vnodeBoot' => \&vnodeBoot,
         'vnodeHalt' => \&vnodeHalt,
65
# XXX needs to be implemented
66
         'vnodeUnmount' => \&vnodeUnmount,
Jon Rafkind's avatar
Jon Rafkind committed
67
         'vnodeReboot' => \&vnodeReboot,
68
# XXX needs to be implemented
69
         'vnodeExec' => \&vnodeExec,
Jon Rafkind's avatar
Jon Rafkind committed
70
71
72
73
74
75
76
77
         'vnodePreConfig' => \&vnodePreConfig,
         'vnodePreConfigControlNetwork' => \&vnodePreConfigControlNetwork,
         'vnodePreConfigExpNetwork' => \&vnodePreConfigExpNetwork,
         'vnodeConfigResources' => \&vnodeConfigResources,
         'vnodeConfigDevices' => \&vnodeConfigDevices,
         'vnodePostConfig' => \&vnodePostConfig,
       );

Jon Rafkind's avatar
Jon Rafkind committed
78

79
80
81
82
83
84
85
86
87
use strict;
use English;
use Data::Dumper;
use Socket;
use File::Basename;
use File::Path;
use File::Copy;

# Pull in libvnode
88
BEGIN { require "/etc/emulab/paths.pm"; import emulabpaths; }
89
90
use libvnode;
use libtestbed;
91
use libsetup;
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the OS independent support library. It will load the OS dependent
# library and initialize itself. 
# 

##
## Standard utilities and files section
##

107
my $BRCTL = "brctl";
108
109
110
111
112
113
my $IFCONFIG = "/sbin/ifconfig";
my $ROUTE = "/sbin/route";
my $SYSCTL = "/sbin/sysctl";
my $VLANCONFIG = "/sbin/vconfig";
my $MODPROBE = "/sbin/modprobe";
my $DHCPCONF_FILE = "/etc/dhcpd.conf";
114
my $NEW_DHCPCONF_FILE = "/etc/dhcp/dhcpd.conf";
115
my $RESTOREVM	= "$BINDIR/restorevm.pl";
116
my $IPTABLES	= "/sbin/iptables";
117

118
my $debug  = 0;
119
120
121
122
123
124
125
126
127

##
## Randomly chosen convention section
##

# global lock
my $GLOBAL_CONF_LOCK = "xenconf";

# default image to load on logical disks
128
129
# Just symlink /boot/vmlinuz-xenU and /boot/initrd-xenU
# to the kernel and ramdisk you want to use by default.
130
my %defaultImage = (
131
 'name'    => "emulab-ops-emulab-ops-XEN-GUEST-F8-XXX",
132
133
134
135
# 'kernel'  => "/boot/vmlinuz-2.6.18.8-xenU",
# 'ramdisk' => "/boot/initrd-2.6.18.8-xenU.img"
 'kernel'  => "/boot/vmlinuz-xenU",
 'ramdisk' => "/boot/initrd-xenU"
136
137
138
);

# where all our config files go
139
my $VMDIR = "/var/emulab/vms/vminfo";
140
141
my $XENDIR = "/var/xen";

142
# Extra space for restore.
143
my $EXTRAFS = "/capture";
144
145
146

# Xen LVM volume group name. Accessible outside this file.
$VGNAME = "xen-vg";
147
148
149
150
151
152

##
## Indefensible, arbitrary constant section
##

# Maximum vnodes per physical host, used to size memory and disks
153
my $MAX_VNODES = 32;
154
155

# Minimum GB of disk per vnode
156
my $MIN_GB_DISK = 6;
157
158
159
160
161
162
163
164
165
166
167
168
169

# Minimum MB of memory per vnode
my $MIN_MB_VNMEM = 64;

# Minimum memory for dom0
my $MIN_MB_DOM0MEM = 256;

# Minimum acceptible size (in GB) of LVM VG for domUs.
my $XEN_MIN_VGSIZE = ($MAX_VNODES * $MIN_GB_DISK);

# XXX fixed-for-now LV size for all logical disks
my $XEN_LDSIZE = $MIN_GB_DISK;

170
171
172
173
174
#
# Information about the running Xen hypervisor
#
my %xeninfo = ();

175
176
177
178
# Local functions
sub findRoot();
sub copyRoot($$);
sub createRootDisk($);
179
sub createAuxDisk($$);
180
181
182
183
184
185
186
sub replace_hacks($);
sub disk_hacks($);
sub configFile($);
sub domain0Memory();
sub totalMemory();
sub memoryPerVnode();
sub hostIP($);
187
sub createDHCP();
188
189
sub addDHCP($$$$);
sub subDHCP($$);
190
sub restartDHCP();
191
192
193
sub formatDHCP($$$);
sub fixupMac($);
sub createControlNetworkScript($$$);
194
sub createExpNetworkScript($$$$$);
195
196
197
198
199
200
201
sub createExpBridges($$);
sub destroyExpBridges($$);
sub domainStatus($);
sub domainExists($);
sub addConfig($$$);
sub createXenConfig($$);
sub readXenConfig($);
202
sub lookupXenConfig($$);
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
sub getXenInfo();

sub getXenInfo()
{
    open(XM,"xm info|") 
        or die "getXenInfo: could not run 'xm info': $!";

    while (<XM>) {
	    chomp;
	    /^(\S+)\s*:\s+(.*)$/;
	    $xeninfo{$1} = $2;
    }
    
    close XM;
}
218
219
220
221
222
223
224

sub init($)
{
    my ($pnode_id,) = @_;

    makeIfaceMaps();
    makeBridgeMaps();
225
    getXenInfo();
226

Jon Rafkind's avatar
Jon Rafkind committed
227
228
229
    return 0;
}

230
231
232
233
234
235
236
237
238
239
240
241
sub setDebug($)
{
    $debug = shift;
    libvnode::setDebug($debug);
    print "libvnode_xen: debug=$debug\n"
	if ($debug);
}

#
# Called on each vnode, but should only be executed once per boot.
# We use a file in /var/run (cleared on reboots) to ensure this.
#
242
sub rootPreConfig()
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
{
    #
    # Haven't been called yet, grab the lock and double check that someone
    # didn't do it while we were waiting.
    #
    if (! -e "/var/run/xen.ready") {
	my $locked = TBScriptLock($GLOBAL_CONF_LOCK,
				  TBSCRIPTLOCK_GLOBALWAIT(), 900);
	if ($locked != TBSCRIPTLOCK_OKAY()) {
	    return 0
		if ($locked == TBSCRIPTLOCK_IGNORE());
	    print STDERR "Could not get the xeninit lock after a long time!\n";
	    return -1;
	}
    }
    if (-e "/var/run/xen.ready") {
        TBScriptUnlock();
        return 0;
    }
    
    print "Configuring root vnode context\n";

    #
    # Start the Xen daemon if not running.
    # There doesn't seem to be a sure fire way to tell this.
    # However, one of the important things xend should do for us is
    # set up a bridge device for the control network, so we look for this.
    # The bridge should have the same name as the control network interface.
    #
    my ($cnet_iface,undef,undef,undef,undef,undef,$cnet_gw) = findControlNet();
    if (!existsBridge($cnet_iface)) {
	print "Starting xend and configuring cnet bridge...\n"
	    if ($debug);
	mysystem("/usr/sbin/xend start");

	#
	# xend tends to lose the default route, so make sure it exists.
	#
	system("route del default >/dev/null 2>&1");
	mysystem("route add default gw $cnet_gw");
    }

285
286
287
288
289
290
291
292
293
294
    #
    # We use xen's antispoofing when constructing the guest control net
    # interfaces. This is most useful on a shared host, but no harm
    # in doing it all the time. 
    #
    mysystem("$IPTABLES -P FORWARD DROP");
    mysystem("$IPTABLES -F FORWARD");
    mysystem("$IPTABLES -A FORWARD ".
	     "-m physdev --physdev-in $cnet_iface -j ACCEPT");

295
296
297
298
299
300
301
302
303
304
305
306
307
308
    #
    # Ensure that LVM is loaded in the kernel and ready.
    #
    print "Enabling LVM...\n"
	if ($debug);

    # We assume our kernels support this.
    mysystem2("$MODPROBE dm-snapshot");
    if ($?) {
	print STDERR "ERROR: could not load snaphot module!\n";
	TBScriptUnlock();
	return -1;
    }

309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    #
    # See if our LVM volume group for VMs exists and create it if not.
    #
    my $vg = `vgs | grep $VGNAME`;
    if ($vg !~ /^\s+${VGNAME}\s/) {
	print "Creating volume group...\n"
	    if ($debug);

	#
	# Find available devices of sufficient size, prepare them,
	# and incorporate them into a volume group.
	#
	my $blockdevs = "";
	my %devs = libvnode::findSpareDisks();
	my $totalSize = 0;
	foreach my $dev (keys(%devs)) {
	    if (defined($devs{$dev}{"size"})) {
		$blockdevs .= " /dev/$dev";
		$totalSize += $devs{$dev}{"size"};
	    }
	    else {
		foreach my $part (keys(%{$devs{$dev}})) {
		    $blockdevs .= " /dev/${dev}${part}";
		    $totalSize += $devs{$dev}{$part}{"size"};
		}
	    }
	}
	if ($blockdevs eq '') {
	    print STDERR "ERROR: findSpareDisks found no disks for LVM!\n";
	    TBScriptUnlock();
	    return -1;
	}
		    
	mysystem("pvcreate $blockdevs");
	mysystem("vgcreate $VGNAME $blockdevs");

	my $size = lvmVGSize($VGNAME);
	if ($size < $XEN_MIN_VGSIZE) {
	    print STDERR "ERROR: physical disks not big enough to support".
		" VMs ($size < $XEN_MIN_VGSIZE)\n";
	    TBScriptUnlock();
	    return -1;
	}
    }

    #
    # Make sure our volumes are active -- they seem to become inactive
    # across reboots
    #
    mysystem("vgchange -a y $VGNAME");

    #
    # For compatibility with existing (physical host) Emulab images,
    # the physical host provides DHCP info for the vnodes.  So we create
    # a skeleton dhcpd.conf file here.
    #
    # Note that we must first add an alias to the control net bridge so
    # that we (the physical host) are in the same subnet as the vnodes,
    # otherwise dhcpd will fail.
    #
    if (system("ifconfig $cnet_iface:1 | grep -q 'inet addr'")) {
	print "Creating $cnet_iface:1 alias...\n"
	    if ($debug);
	my ($vip,$vmask) = domain0ControlNet();
	mysystem("ifconfig $cnet_iface:1 $vip netmask $vmask");
    }

    print "Creating dhcp.conf skeleton...\n"
        if ($debug);
378
    createDHCP();
379

380
381
382
383
384
    print "Creating scratch FS ...\n";
    if (createExtraFS($EXTRAFS, $VGNAME, "50G")) {
	TBScriptUnlock();
	return -1;
    }
385
386
    mysystem("touch /var/run/xen.ready");
    TBScriptUnlock();
Jon Rafkind's avatar
Jon Rafkind committed
387
388
389
    return 0;
}

390
sub rootPreConfigNetwork($$$$)
391
{
392
393
394
    my ($vnode_id, undef, $vnconfig, $private) = @_;
    my @node_ifs = @{ $vnconfig->{'ifconfig'} };
    my @node_lds = @{ $vnconfig->{'ldconfig'} };
Jon Rafkind's avatar
Jon Rafkind committed
395

396
397
398
399
400
    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
	print STDERR "Could not get the xennetwork lock after a long time!\n";
	return -1;
    }

401
    createDHCP()
402
	if (! -e $DHCPCONF_FILE && ! -e $NEW_DHCPCONF_FILE);
403

404
405
406
407
408
409
    #
    # If we blocked, it would be because vnodes have come or gone,
    # so we need to rebuild the maps.
    #
    makeIfaceMaps();
    makeBridgeMaps();
Jon Rafkind's avatar
Jon Rafkind committed
410

411
    TBScriptUnlock();
Jon Rafkind's avatar
Jon Rafkind committed
412
413
414
    return 0;
}

415
416
sub rootPostConfig($)
{
Jon Rafkind's avatar
Jon Rafkind committed
417
418
419
    return 0;
}

420
421
#
# Create the basic context for the VM and give it a unique ID for identifying
422
423
# "internal" state.  If $raref is set, then we are in a RELOAD state machine
# and need to walk the appropriate states.
424
#
425
sub vnodeCreate($$$$)
426
{
427
    my ($vnode_id, undef, $vnconfig, $private) = @_;
428
    my $attributes = $vnconfig->{'attributes'};
429
    my $imagename = $vnconfig->{'image'};
Leigh B Stoller's avatar
Leigh B Stoller committed
430
    my $raref = $vnconfig->{'reloadinfo'};
431
    my $vninfo = $private;
432
    my %image = %defaultImage;
433
    my $lvname;
434
    my $inreload = 0;
435
436
437
438
439
440
441
442

    my $vmid;
    if ($vnode_id =~ /^\w+\d+\-(\d+)$/) {
	$vmid = $1;
    }
    else {
	fatal("xen_vnodeCreate: bad vnode_id $vnode_id!");
    }
443
444
445
446
447
448
449
450
451
452
453
    $vninfo->{'vmid'} = $vmid;

    #
    # We need to lock while messing with the image.
    #
    my $imagelockname = "xenimage." .
	(defined($imagename) ? $imagename : $defaultImage{'name'});
    if (TBScriptLock($imagelockname, TBSCRIPTLOCK_GLOBALWAIT(), 1800)
	!= TBSCRIPTLOCK_OKAY()) {
	fatal("Could not get $imagelockname lock after a long time!");
    }
454

455
456
457
458
    #
    # No image specified, use a default based on the dom0 OS.
    #
    if (!defined($imagename)) {
459
460
	$lvname = $image{'name'};
	
461
462
463
464
465
466
	#
	# Setup the default image now.
	# XXX right now this is a hack where we just copy the dom0
	# filesystem and clone (snapshot) that.
	#
	$imagename = $defaultImage{'name'};
467
468
	print STDERR "xen_vnodeCreate: ".
	    "no image specified, using default ('$imagename')\n";
469
470

	my $vname = $imagename . ".0";
471
	$lvname = $vname;
472
473
474
	if (!findLVMLogicalVolume($vname)) {
	    createRootDisk($vname);
	}
475
    }
476
477
478
479
480
481
482
    elsif (!defined($raref)) {
	#
	# Boot existing image. The base volume has to exist, since we do
	# not have any reload info to get it.
	#
	$lvname = $imagename;
	if (!findLVMLogicalVolume($lvname)) {
483
	    TBScriptUnlock();
484
485
486
	    fatal("xen_vnodeCreate: ".
		  "cannot find logical volume for $lvname, and no reload info");
	}
487
    }
488
489
490
491
492
    else {
	$lvname = $imagename;
	$inreload = 1;

	print STDERR "xen_vnodeCreate: loading image '$imagename'\n";
493

494
495
496
497
498
499
500
501
502
503
	# Tell stated we are getting ready for a reload
	libvnode::setState("RELOADSETUP");

	#
	# Immediately drop into RELOADING before calling createImageDisk as
	# that is the place where any image will be downloaded from the image
	# server and we want that download to take place in the longer timeout
	# period afforded by the RELOADING state.
	#
	libvnode::setState("RELOADING");
504

505
	if (createImageDisk($imagename, $vnode_id, $raref)) {
506
	    TBScriptUnlock();
507
508
509
	    fatal("xen_vnodeCreate: ".
		  "cannot create logical volume for $imagename");
	}
510
511
    }

512
    #
513
    # See if the image is really a package.
514
    #
515
516
517
518
    if (-e "$DBDIR/${imagename}.package") {
	my $imagepath = lvmVolumePath($imagename);
	mysystem("mount $imagepath /mnt/$imagename")
	    if (! -e "/mnt/$imagename/.mounted");
519

520
521
522
523
524
525
	mysystem2("$RESTOREVM -t $VMDIR/$vnode_id $vnode_id /mnt/$imagename");
	if ($?) {
	    mysystem2("umount /mnt/$imagename");
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: ".
		  "cannot restore logical volumes from $imagename");
526
	}
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
	mysystem2("umount /mnt/$imagename");
	
	#
	# All of the lvms are created and a new xm.conf created.
	# Read that xm.conf in so we can figure out what lvms we
	# need to delete later (recreate the disks array). 
	#
	my $conf = configFile($vnode_id);
	my $aref = readXenConfig($conf);
	if (!$aref) {
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: ".
		  "Cannot read restored config file from $conf");
	}
	$vninfo->{'cffile'} = $aref;
	
	my $disks = parseXenDiskInfo($vnode_id, $aref);
	if (!defined($disks)) {
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: Could not restore disk info from $conf");
	}
	$private->{'disks'} = $disks;
549
	TBScriptUnlock();
550
	goto done;
551
552
    }

553
    #
554
    # XXX need a better way to determine this stuff.
555
    #
556
    my $vdiskprefix = "sd";	# yes, this is right for FBSD too
557
    my $os;
558
    if ($imagename =~ /FBSD/) {
559
	$os = "FreeBSD";
560
	if ($imagename =~ /FBSD9/) {
561
	    $image{'kernel'} = "/boot/freebsd9/kernel";
562
563
564
	    if (exists($attributes->{'XEN_IPFWKERNEL'})) {
		$image{'kernel'} = $image{'kernel'} . ".ipfw";
	    }
565
	} elsif ($imagename =~ /FBSD8/) {
566
	    $image{'kernel'} = "/boot/freebsd8/kernel";
567
568
569
570
	} else {
	    $image{'kernel'} = "/boot/freebsd/kernel";
	}
	if (! -e "$image{'kernel'}") {
571
572
	    fatal("libvnode_xen: ".
		  "no FreeBSD kernel for '$imagename' on $vnode_id");
573
	}
574
	undef $image{'ramdisk'};
575
576
    }
    else {
577
	$os = "Linux";
578
579
580
581
582
583
584
585

	if ($imagename =~ /F8-STD/) {
	    $image{'kernel'}  = "/boot/fedora8/vmlinuz-xenU";
	    $image{'ramdisk'} = "/boot/fedora8/initrd-xenU";
	}
	elsif ($xeninfo{xen_major} >= 4) {
	    $vdiskprefix = 'xvd';
	}
586
    }
587
588
589
590
591
592
593
594
595
596
    $private->{'os'} = $os;

    # All of the disk stanzas for the config file.
    my @alldisks = ();
    # Cache the config file, but will read it later.
    $private->{'disks'} = {};

    #
    # The root disk.
    #
597
    my $rootvdisk  = $vdiskprefix . "a";
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
    my $rootvndisk = lvmVolumePath($vnode_id);
    my $rootstanza = "phy:$rootvndisk,$rootvdisk,w";
    push(@alldisks, "'$rootstanza'");

    #
    # Since we may have (re)loaded a new image for this vnode, check
    # and make sure the vnode snapshot disk is associated with the
    # correct image.  Otherwise destroy the current vnode LVM so it
    # will get correctly associated below.
    #
    if (findLVMLogicalVolume($vnode_id)) {
	my $olvname = findLVMOrigin($vnode_id);
	if ($olvname ne $lvname) {
	    if (system("lvremove -f $VGNAME/$vnode_id")) {
		TBScriptUnlock();
		fatal("xen_vnodeCreate: ".
		      "could not destroy old disk for $vnode_id");
	    }
	}
    }

    #
    # Create the snapshot LVM.
    #
    if (!findLVMLogicalVolume($vnode_id)) {
	my $basedisk = lvmVolumePath($lvname);
	if (system("lvcreate -s -L ${XEN_LDSIZE}G -n $vnode_id $basedisk")) {
	    TBScriptUnlock();
	    fatal("libvnode_xen: could not create disk for $vnode_id");
	}
    }
    # Mark the lvm as created, for cleanup on error.
    $private->{'disks'}->{$vnode_id} = $vnode_id;

    #
    # The rest of this can proceed in parallel with other VMs.
    #
    TBScriptUnlock();
636

637
638
639
640
641
642
643
    my $auxchar  = ord('b');
    #
    # Create a swap disk.
    #
    if ($os eq "FreeBSD") {
	my $auxlvname = "${vnode_id}.swap";
	if (createAuxDisk($auxlvname, "2G")) {
644
	    fatal("libvnode_xen: could not create swap disk");
645
646
	}
	my $vndisk = lvmVolumePath($auxlvname);
647
	my $vdisk  = $vdiskprefix . chr($auxchar++);
648
649
	my $stanza = "phy:$vndisk,$vdisk,w";

650
651
	$private->{'disks'}->{$auxlvname} = $auxlvname;
	push(@alldisks, "'$stanza'");
652
653
654
655
656

	#
	# Mark it as a linux swap partition. 
	#
	if (system("echo ',,S' | sfdisk $vndisk -N0")) {
657
	    fatal("libvnode_xen: could not partition swap disk");
658
659
660
661
662
663
664
665
666
667
668
669
670
	}
    }

    #
    # Create aux disks.
    #
    if (exists($attributes->{'XEN_EXTRADISKS'})) {
	my @list = split(",", $attributes->{'XEN_EXTRADISKS'});
	foreach my $disk (@list) {
	    my ($name,$size) = split(":", $disk);

	    my $auxlvname = "${vnode_id}.${name}";
	    if (createAuxDisk($auxlvname, $size)) {
671
		fatal("libvnode_xen: could not create aux disk: $name");
672
673
	    }
	    my $vndisk = lvmVolumePath($auxlvname);
674
675
	    
	    my $vdisk  = $vdiskprefix . chr($auxchar++);
676
677
	    my $stanza = "phy:$vndisk,$vdisk,w";

678
679
	    $private->{'disks'}->{$auxlvname} = $auxlvname;
	    push(@alldisks, "'$stanza'");
680
681
	}
    }
682
    print "All disks: @alldisks\n" if ($debug);
683

684
685
686
687
688
689
    #
    # Create the config file and fill in the disk/filesystem related info.
    # Since we don't want to leave a partial config file in the event of
    # a failure down the road, we just accumulate the config info in a string
    # and write it out right before we boot.
    #
690
691
692
    # BSD stuff inspired by:
    # http://wiki.freebsd.org/AdrianChadd/XenHackery
    #
693
    $vninfo->{'cffile'} = [];
694

695
696
    my $kernel = $image{'kernel'};
    my $ramdisk = $image{'ramdisk'};
697

698
699
700
701
    addConfig($vninfo, "# Xen configuration script for $os vnode $vnode_id", 2);
    addConfig($vninfo, "name = '$vnode_id'", 2);
    addConfig($vninfo, "kernel = '$kernel'", 2);
    addConfig($vninfo, "ramdisk = '$ramdisk'", 2)
702
	if (defined($ramdisk));
703
    addConfig($vninfo, "disk = [" . join(",", @alldisks) . "]", 2);
Mike Hibler's avatar
Mike Hibler committed
704

705
    if ($os eq "FreeBSD") {
706
707
708
	addConfig($vninfo, "extra = 'boot_verbose=1" .
		  ",vfs.root.mountfrom=ufs:/dev/da0a".
		  ",kern.bootfile=/boot/kernel/kernel'", 2);
709
    } else {
710
711
	addConfig($vninfo, "root = '/dev/$rootvdisk ro'", 2);
	addConfig($vninfo, "extra = 'console=hvc0 xencons=tty'", 2);
712
    }
713
  done:
714
    #
715
    # Finish off the state transitions as necessary.
716
    #
717
    if ($inreload) {
718
719
720
721
722
	libvnode::setState("RELOADDONE");
	sleep(4);
	libvnode::setState("SHUTDOWN");
    }

723
724
725
726
727
728
729
    return $vmid;
}

#
# The logical disk has been created.
# Here we just mount it and invoke the callback.
#
730
# XXX note that the callback only works when we can mount the VM OS's
731
732
# filesystems!  Since all we do right now is Linux, this is easy.
#
733
734
sub vnodePreConfig($$$$$){
    my ($vnode_id, $vmid, $vnconfig, $private, $callback) = @_;
735
    my $vninfo = $private;
736
737
738

    #
    # XXX vnodeCreate is not called when a vnode was halted or is rebooting.
739
740
    # In that case, we read in any existing config file and restore the
    # disk info. 
741
    #
742
    if (!exists($vninfo->{'cffile'})) {
743
744
	my $aref = readXenConfig(configFile($vnode_id));
	if (!$aref) {
745
746
747
748
749
750
751
752
753
754
	    fatal("vnodePreConfig: no Xen config for $vnode_id!");
	}
	$vninfo->{'cffile'} = $aref;

	#
	# And, we need to recover the disk info from the config file.
	#
	my $disks = parseXenDiskInfo($vnode_id, $aref);
	if (!defined($disks)) {
	    fatal("vnodePreConfig: Could not restore disk info from config");
755
	}
756
	$private->{'disks'} = $disks;
757
    }
758
759
    return 0
	if (!exists($vninfo->{'os'}));
760

761
762
763
    #
    # XXX can only do the rest for Linux vnodes
    #
764
    if ($vninfo->{'os'} !~ /Linux/) {
765
766
767
768
	print "libvnode_xen: vnodePreConfig: short-circuit non-Linux vnode\n";
	return 0;
    }

769
770
771
772
773
    mkpath(["/mnt/xen/$vnode_id"]);
    my $dev = lvmVolumePath($vnode_id);
    my $vnoderoot = "/mnt/xen/$vnode_id";
    mysystem("mount $dev $vnoderoot");

774
775
776
777
778
779
780
781
782
    # XXX this should no longer be needed, but just in case
    if (! -e "$vnoderoot/var/emulab/boot/vmname" ) {
	print STDERR
	    "libvnode_xen: WARNING: vmname not set by dhclient-exit-hook\n";
	open(FD,">$vnoderoot/var/emulab/boot/vmname") 
	    or die "vnodePreConfig: could not open vmname for $vnode_id: $!";
	print FD "$vnode_id\n";
	close(FD);
    }
783
784
785
786
787
788

    # Use the physical host pubsub daemon
    my (undef, $ctrlip) = findControlNet();
    if (!$ctrlip || $ctrlip !~ /^(\d+\.\d+\.\d+\.\d+)$/) {
	die "vnodePreConfig: could not get control net IP for $vnode_id";
    }
789
790
791
792
793
794
795
796

    # Should be handled in libsetup.pm, but just in case
    if (! -e "$vnoderoot/var/emulab/boot/localevserver" ) {
	open(FD,">$vnoderoot/var/emulab/boot/localevserver") 
	    or die "vnodePreConfig: could not open localevserver for $vnode_id: $!";
	print FD "$ctrlip\n";
	close(FD);
    }
797
798
799
800
801
802
803
804
805
806
807
808
809

    my $ret = &$callback($vnoderoot);

    mysystem("umount $dev");
    return $ret;
}

#
# Configure the control network for a vnode.
#
# XXX for now, I just perform all the actions here til everything is working.
# This means they cannot easily be undone if something fails later on.
#
810
sub vnodePreConfigControlNetwork($$$$$$$$$$$$)
811
{
812
813
    my ($vnode_id, $vmid, $vnconfig, $private,
	$ip,$mask,$mac,$gw, $vname,$longdomain,$shortdomain,$bossip) = @_;
814
    my $vninfo = $private;
815

816
    if (!exists($vninfo->{'cffile'})) {
817
818
819
820
821
822
823
824
825
	die("libvnode_xen: vnodePreConfig: no state for $vnode_id!?");
    }

    my $fmac = fixupMac($mac);
    # Note physical host control net IF is really a bridge
    my ($cbridge) = findControlNet();
    my $cscript = "$VMDIR/$vnode_id/cnet-$mac";

    # Save info for the control net interface for config file.
826
827
828
829
    $vninfo->{'cnet'} = {};
    $vninfo->{'cnet'}->{'mac'} = $fmac;
    $vninfo->{'cnet'}->{'bridge'} = $cbridge;
    $vninfo->{'cnet'}->{'script'} = $cscript;
830
    $vninfo->{'cnet'}->{'ip'} = $ip;
831
832
833
834
835
836
837
838
839
840

    # Create a network config script for the interface
    my $stuff = {'name' => $vnode_id,
		 'ip' => $ip,
		 'hip' => $gw,
		 'fqdn', => $longdomain,
		 'mac' => $fmac};
    createControlNetworkScript($vmid, $stuff, $cscript);

    # Create a DHCP entry
841
842
843
844
    $vninfo->{'dhcp'} = {};
    $vninfo->{'dhcp'}->{'name'} = $vnode_id;
    $vninfo->{'dhcp'}->{'ip'} = $ip;
    $vninfo->{'dhcp'}->{'mac'} = $fmac;
845
846
847
848

    # a route to reach the vnode
    system("$ROUTE add $ip dev $cbridge");

Jon Rafkind's avatar
Jon Rafkind committed
849
850
851
    return 0;
}

852
853
854
855
856
857
858
#
# This is where new interfaces get added to the experimental network.
# For each vnode we need to:
#  - possibly create (or arrange to have created) a bridge device
#  - create config file lines for each interface
#  - arrange for the correct routing
#
859
sub vnodePreConfigExpNetwork($$$$)
860
{
861
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
862
    my $vninfo = $private;
863
864
865
    my $ifconfigs  = $vnconfig->{'ifconfig'};
    my $ldconfigs  = $vnconfig->{'ldconfig'};
    my $tunconfigs = $vnconfig->{'tunconfig'};
866
867
868
869
870
871

    # Keep track of links (and implicitly, bridges) that need to be created
    my @links = ();

    # Build up a config file line for all interfaces, starting with cnet
    my $vifstr = "vif = ['" .
872
	"mac=" . $vninfo->{'cnet'}->{'mac'} . ", " .
873
874
	# This tells vif-bridge to use antispoofing iptable rules.
	"ip=" . $vninfo->{'cnet'}->{'ip'} . ", " .
875
876
        "bridge=" . $vninfo->{'cnet'}->{'bridge'} . ", " .
        "script=" . $vninfo->{'cnet'}->{'script'} . "'";
877
878
879
880
881
882

    foreach my $interface (@$ifconfigs){
        print "interface " . Dumper($interface) . "\n"
	    if ($debug > 1);
        my $mac = "";
        my $physical_mac = "";
883
	my $physical_dev;
884
        my $tag = 0;
885
886
	my $ifname = "veth.${vmid}." . $interface->{'ID'};
	
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
	#
	# In the era of shared nodes, we cannot name the bridges
	# using experiment local names (e.g., the link name).
	# Bridges are now named after either the physical interface
	# they are associated with or the "tag" if there is no physical
	# interface.
	#
        my $brname;

	if ($interface->{'ITYPE'} eq "loop") {
	    #
	    # No physical device. Its a loopback (trivial) link/lan
	    # All we need is a common bridge to put the veth ifaces into.
	    #
	    $brname = "br" . $interface->{'VTAG'};
            $mac = $interface->{'MAC'};
	}
	elsif ($interface->{'ITYPE'} eq "veth"){
	    #
	    # We will never see a veth on a shared node, thus they
	    # have already been created during the physnode config.
	    #
909
910
911
            $mac = $interface->{'MAC'};
            if ($interface->{'PMAC'} ne "none"){
                $physical_mac = $interface->{'PMAC'};
912
		$brname = "br" . findIface($interface->{'PMAC'});
913
            }
914
915
916
917
918
919
920
921
922
923
924
925
	    else {
		$brname = "br" . $interface->{'VTAG'};
	    }
        }
	elsif ($interface->{'ITYPE'} eq "vlan"){
	    my $iface = $interface->{'IFACE'};
	    my $vtag  = $interface->{'VTAG'};
	    #
	    # On a shared node, these interfaces might not exist. This will
	    # happen when the bridges are created, for lack of a better
	    # place. 
	    #
926
927
928
            $mac = $interface->{'MAC'};
            $tag = $interface->{'VTAG'};
            $physical_mac = $interface->{'PMAC'};
929
930
931
932
	    $physical_dev = "${iface}.${vtag}";
	    $brname = "br" . $physical_dev;
	}
	else {
933
            $mac = $interface->{'MAC'};
934
	    $brname = "pbr" . findIface($interface->{'MAC'});
935
936
937
938
939
940
941
942
943
944
        }

	#
	# If there is shaping info associated with the interface
	# then we need a custom script.
	#
	my $script = "";
	foreach my $ldinfo (@$ldconfigs) {
	    if ($ldinfo->{'IFACE'} eq $mac) {
		$script = "$VMDIR/$vnode_id/enet-$mac";
945
946
947
		my $sh  = "${script}.sh";
		my $log = "${script}.log";
		createExpNetworkScript($vmid, $ldinfo, $script, $sh, $log);
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
	    }
	}

	# add interface to config file line
	$vifstr .= ", 'vifname=$ifname, mac=" .
	    fixupMac($mac) . ", bridge=$brname";
	if ($script ne "") {
	    $vifstr .= ", script=$script";
	}
	$vifstr .= "'";

	# Push vif info
        my $link = {'mac' => fixupMac($mac),
		    'ifname' => $ifname,
                    'brname' => $brname,
		    'script' => $script,
                    'physical_mac' => $physical_mac,
965
966
967
                    'physical_dev' => $physical_dev,
                    'tag' => $tag,
		    'itype' => $interface->{'ITYPE'},
968
969
970
971
972
973
974
                    };
        push @links, $link;
    }

    # push out config file line for all interfaces
    # XXX note that we overwrite since a modify might add/sub IFs
    $vifstr .= "]";
975
    addConfig($vninfo, $vifstr, 1);
976

977
    $vninfo->{'links'} = \@links;
978
    return 0;
Jon Rafkind's avatar
Jon Rafkind committed
979
980
}

981
982
sub vnodeConfigResources($$$$){
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
983
984
    my $attributes = $vnconfig->{'attributes'};
    my $memory;
985
986

    #
987
988
    # Give the vnode some memory. We allow the user to specify this
    # when not a shared host. 
989
    #
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
    if (!SHAREDHOST() && exists($attributes->{'XEN_MEMSIZE'})) {
	# Better be MB.
	$memory = $attributes->{'XEN_MEMSIZE'};
    }
    else  {
	#
	# XXX no way to specify this right now, so we give each vnode
	# the same amount based on an arbitrary maximum vnode limit.
	#
	$memory = memoryPerVnode();
	if ($memory < 48){
	    die("48MB is the minimum amount of memory for a Xen VM; ".
		"could only get {$memory}MB.".
		"Adjust libvnode_xen::MAX_VNODES");
	}
Jon Rafkind's avatar
Jon Rafkind committed
1005
    }
1006
    addConfig($private, "memory = $memory", 1);
1007
    return 0;
Jon Rafkind's avatar
Jon Rafkind committed
1008
1009
}

1010
sub vnodeConfigDevices($$$$)
1011
{
1012
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
1013
1014
1015
    return 0;
}

1016
sub vnodeState($$$$)
1017
{
1018
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
1019
1020
1021
1022
1023
1024
1025
1026

    my $err = 0;
    my $out = VNODE_STATUS_UNKNOWN();

    # right now, if it shows up in the list, consider it running
    if (domainExists($vnode_id)) {
	$out = VNODE_STATUS_RUNNING();
    }
1027
1028
1029
    # otherwise, if the logical (root) disk exists, consider it stopped
    elsif (exists($private->{'disks'}->{$vnode_id}) &&
	   findLVMLogicalVolume($private->{'disks'}->{$vnode_id})) {
1030
1031
1032
1033
1034
	$out = VNODE_STATUS_STOPPED();
    }
    return ($err, $out);
}

1035
sub vnodeBoot($$$$)
1036
{
1037
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
1038
    my $vninfo = $private;
1039

1040
    if (!exists($vninfo->{'cffile'})) {
1041
1042
1043
1044
1045
1046
1047
1048
	die("libvnode_xen: vnodeBoot $vnode_id: no essential state!?");
    }

    #
    # We made it here without error, so create persistent state.
    # Xen config file...
    #
    my $config = configFile($vnode_id);
1049
1050
    if ($vninfo->{'cfchanged'}) {
	if (createXenConfig($config, $vninfo->{'cffile'})) {
1051
1052
1053
1054
1055
1056
1057
	    die("libvnode_xen: vnodeBoot $vnode_id: could not create $config");
	}
    } elsif (! -e $config) {
	die("libvnode_xen: vnodeBoot $vnode_id: $config file does not exist!");
    }

    # DHCP entry...
1058
1059
1060
1061
    if (exists($vninfo->{'dhcp'})) {
	my $name = $vninfo->{'dhcp'}->{'name'};
	my $ip = $vninfo->{'dhcp'}->{'ip'};
	my $mac = $vninfo->{'dhcp'}->{'mac'};
1062
1063
1064
1065
	addDHCP($name, $ip, $mac, 1);
    }

    # physical bridge devices...
1066
    if (createExpBridges($vnode_id, $vninfo->{'links'})) {
1067
1068
1069
	die("libvnode_xen: vnodeBoot $vnode_id: could not create bridges");
    }

1070
    # notify stated that we are about to boot
1071
    libvnode::setState("BOOTING");
1072

1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
    # and finally, create the VM
    mysystem("xm create $config");
    print "Created virtual machine $vnode_id\n";
    return 0;
}

sub vnodePostConfig($)
{
    return 0;
}

1084
sub vnodeReboot($$$$)
1085
{
1086
1087
1088
1089
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    if ($vmid =~ m/(.*)/){
        $vmid = $1;
1090
    }
1091
1092
1093
    mysystem("/usr/sbin/xm reboot $vmid");
}

1094
sub vnodeTearDown($$$$)
1095
1096
1097
1098
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    return 0;
1099
}
Jon Rafkind's avatar
Jon Rafkind committed
1100

1101
sub vnodeDestroy($$$$)
1102
{
1103
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
1104
1105
    my $vninfo = $private;
    
1106
1107
1108
1109
1110
1111
    if ($vnode_id =~ m/(.*)/){
        $vnode_id = $1;
    }
    if (domainExists($vnode_id)) {
	mysystem("/usr/sbin/xm destroy $vnode_id");
	# XXX hang out awhile waiting for domain to disappear
1112
	domainGone($vnode_id, 15);
1113
1114
    }

1115
1116
    # Always do this.
    return -1
1117
	if (vnodeTearDown($vnode_id, $vmid, $vnconfig, $private));
1118

1119
1120
1121
1122
1123
1124
    # DHCP entry...
    if (exists($vninfo->{'dhcp'})) {
	my $mac = $vninfo->{'dhcp'}->{'mac'};
	subDHCP($mac, 1);
    }

1125
1126
1127
    #
    # We do these whether or not the domain existed
    #
1128
1129
    # Note to Mike from Leigh; this should maybe move to TearDown above?
    #
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
    destroyExpBridges($vnode_id, $vninfo->{'links'});

    # Destroy the all the disks.
    foreach my $key (keys(%{ $private->{'disks'} })) {
	my $lvname = $private->{'disks'}->{$key};
	
	if (findLVMLogicalVolume($lvname)) {
	    if (system("lvremove -f $VGNAME/$lvname")) {
		print STDERR "libvnode_xen: could not destroy disk $lvname!\n";
	    }
	    else {
		delete($private->{'disks'}->{$key});
1142
1143
1144
	    }
	}
    }
1145
    return 0;
Jon Rafkind's avatar
Jon Rafkind committed
1146
1147
}

1148
sub vnodeHalt($$$$)
1149
{
1150
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
1151
1152
1153
1154

    if ($vnode_id =~ m/(.*)/) {
        $vnode_id = $1;
    }
1155
1156
1157
    # This runs async so use -w. And actually destroys the container!
    # Just wait, cause otherwise we get into an obvious race. 
    mysystem("/usr/sbin/xm shutdown -w $vnode_id");
1158
1159
1160
1161
1162

    return 0;
}

# XXX implement these!
1163
sub vnodeExec($$$$$)
1164
{
1165
    my ($vnode_id, $vmid, $vnconfig, $private, $command) = @_;
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183

    if ($command eq "sleep 100000000") {
	while (1) {
	    my $stat = domainStatus($vnode_id);
	    # shutdown/destroyed
	    if (!$stat) {
		return 0;
	    }
	    # crashed
	    if ($stat =~ /c/) {
		return -1;
	    }
	    sleep(5);
	}
    }
    return -1;
}

1184
sub vnodeUnmount($$$$)
1185
{
1186
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207

    return 0;
}

#
# Local functions
#

sub findRoot()
{
    my $rootfs = `df / | grep /dev/`;
    if ($rootfs =~ /^(\/dev\/\S+)/) {
	my $dev = $1;
	return $dev;
    }
    die "libvnode_xen: cannot determine root filesystem";
}

sub copyRoot($$)
{
    my ($from, $to) = @_;
Jon Rafkind's avatar
Jon Rafkind committed
1208
1209
1210
    my $disk_path = "/mnt/xen/disk";
    my $root_path = "/mnt/xen/root";
    print "Mount root\n";
1211
1212
    mkpath(['/mnt/xen/root']);
    mkpath(['/mnt/xen/disk']);
1213
1214
    mysystem("mount $from $root_path");
    mysystem("mount -o loop $to $disk_path");
Jon Rafkind's avatar
Jon Rafkind committed
1215
    mkpath([map{"$disk_path/$_"} qw(proc sys home tmp)]);
1216
    print "Copying files\n";
1217
    system("cp -a $root_path/* $disk_path");
Jon Rafkind's avatar
Jon Rafkind committed
1218
1219
1220
1221
1222
1223

    # hacks to make things work!
    disk_hacks($disk_path);

    mysystem("umount $root_path");
    mysystem("umount $disk_path");
Jon Rafkind's avatar
Jon Rafkind committed
1224
1225
}

1226
1227
#
# Create the root "disk" (logical volume)
1228
# XXX this is a temp hack til all vnode creations have an explicit image.
1229
1230
1231
1232
1233
1234
#
sub createRootDisk($)
{
    my ($lv) = @_;
    my $full_path = lvmVolumePath($lv);
    my $size = $XEN_LDSIZE;
1235
1236

    #
1237
    # We only want to do this once.
1238
    #
1239
    system("lvcreate -n $lv -L ${size}G $VGNAME");
1240
1241
1242
    system("echo y | mkfs -t ext3 $full_path");
    mysystem("e2label $full_path /");
    copyRoot(findRoot(), $full_path);
1243
1244
}

1245
#
1246
# Create an extra, empty disk volume. 
1247
1248
1249
1250
1251
1252
#
sub createAuxDisk($$)
{
    my ($lv,$size) = @_;
    my $full_path = lvmVolumePath($lv);

1253
    system("lvcreate -n $lv -L ${size} $VGNAME");
1254
1255
1256
1257
1258
1259
    if ($?) {
	return -1;
    }
    return 0;
}

1260
1261
1262
#
# Create a logical volume for the image if it doesn't already exist.
#
1263
sub createImageDisk($$$)
1264
{
1265
    my ($image,$vnode_id,$raref) = @_;
1266
    my $tstamp = $raref->{'IMAGEMTIME'};
1267
    my $lvname = $image;
1268
    my $unpack = 0;
1269

1270
    # We are locked by the caller.
1271

1272
1273
1274
1275
1276
1277
    #
    # Do we have the right image file already? No need to download it
    # again if the timestamp matches. Note that we are using the mod
    # time on the lvm volume path for this, which we set below when
    # the image is downloaded.
    #
Mike Hibler's avatar