libvnode_xen.pm 137 KB
Newer Older
Jon Rafkind's avatar
Jon Rafkind committed
1
#!/usr/bin/perl -wT
2
#
3
# Copyright (c) 2008-2015 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
Leigh B Stoller's avatar
Leigh B Stoller committed
50
              vnodeConfigDevices vnodePostConfig vnodeExec vnodeTearDown VGNAME
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
use strict;
use English;
use Data::Dumper;
use Socket;
use File::Basename;
use File::Path;
use File::Copy;
86
use File::Temp;
87
88

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

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

110
my $BRCTL = "brctl";
111
my $IFCONFIG = "/sbin/ifconfig";
Leigh B Stoller's avatar
Leigh B Stoller committed
112
my $ETHTOOL = "/sbin/ethtool";
113
114
115
116
117
my $ROUTE = "/sbin/route";
my $SYSCTL = "/sbin/sysctl";
my $VLANCONFIG = "/sbin/vconfig";
my $MODPROBE = "/sbin/modprobe";
my $DHCPCONF_FILE = "/etc/dhcpd.conf";
118
my $NEW_DHCPCONF_FILE = "/etc/dhcp/dhcpd.conf";
119
my $RESTOREVM	= "$BINDIR/restorevm.pl";
Leigh B Stoller's avatar
Leigh B Stoller committed
120
my $LOCALIZEIMG	= "$BINDIR/localize_image";
121
my $IPTABLES	= "/sbin/iptables";
Leigh B Stoller's avatar
Leigh B Stoller committed
122
123
124
125
my $IPBIN	= "/sbin/ip";
my $NETSTAT     = "/bin/netstat";
my $IMAGEZIP    = "/usr/local/bin/imagezip";
my $IMAGEUNZIP  = "/usr/local/bin/imageunzip";
126
my $IMAGEDUMP   = "/usr/local/bin/imagedump";
127
my $XM          = "/usr/sbin/xm";
128
my $debug  = 0;
Mike Hibler's avatar
Mike Hibler committed
129
my $lockdebug = 0;
130

Mike Hibler's avatar
Mike Hibler committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#
# Create a thin pool with the name $POOL_NAME using not more
# than $POOL_FRAC of any disk.
# 
my $usethin = 1;
my $POOL_NAME = "disk-pool";
my $POOL_FRAC = 0.75;

#
# If set to one, we will destroy a golden disk when no vnode disks
# are derived from it. Otherwise, we leave it around and it must be
# explicitly GCed by some yet-to-be-written daemon. 
#
my $REAP_GDS = 0;

#
# Flags for allocating LVs
#
sub ALLOC_NOPOOL()	{ return 0; }
sub ALLOC_INPOOL()	{ return 1; }
sub ALLOC_PREFERNOPOOL	{ return 2; }
sub ALLOC_PREFERINPOOL	{ return 3; }
153

154
155
156
157
158
159
160
161
##
## Randomly chosen convention section
##

# global lock
my $GLOBAL_CONF_LOCK = "xenconf";

# default image to load on logical disks
162
163
# Just symlink /boot/vmlinuz-xenU and /boot/initrd-xenU
# to the kernel and ramdisk you want to use by default.
164
my %defaultImage = (
165
166
167
168
169
170
    'name'      => "emulab-ops-emulab-ops-XEN-STD",
    'kernel'    => "/boot/vmlinuz-xenU",
    'ramdisk'   => "/boot/initrd-xenU",
    'OSVERSION' => "any",
    'PARTOS'    => "Linux",
    'ISPACKAGE' => 0,
171
172
    'PART'      => 2,
    'BOOTPART'  => 2,
173
174
175
);

# where all our config files go
176
177
my $VMS    = "/var/emulab/vms";
my $VMDIR  = "$VMS/vminfo";
178
179
my $XENDIR = "/var/xen";

180
# Extra space for capture/restore.
181
my $EXTRAFS = "/capture";
182

183
# Extra space for image metadata between reloads.
Leigh B Stoller's avatar
Leigh B Stoller committed
184
185
my $METAFS = "/metadata";

186
187
188
# Extra space for vminfo (/var/emulab/vms) between reloads.
my $INFOFS = "/vminfo";

189
190
# Xen LVM volume group name. Accessible outside this file.
$VGNAME = "xen-vg";
Leigh B Stoller's avatar
Leigh B Stoller committed
191
192
# So we can ask this from outside;
sub VGNAME()  { return $VGNAME; }
193
194
195
196
197
198
199
200

##
## Indefensible, arbitrary constant section
##

# Minimum memory for dom0
my $MIN_MB_DOM0MEM = 256;

Mike Hibler's avatar
Mike Hibler committed
201
#
202
# Minimum acceptible size (in GB) of LVM VG for domUs.
Mike Hibler's avatar
Mike Hibler committed
203
204
205
206
207
208
#
# XXX we used to calculate this in terms of anticipated maximum number
# of vnodes and minimum vnode images size, blah, blah. Now we just pick
# a value that allows us to use a pc3000 node with a single 144GB disk!
#
my $XEN_MIN_VGSIZE = 120;
209

210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#
# When loading an Emulab partition image, we use a compressed version of our
# standard MBR layout:
#
# MBR 1 or 2 FreeBSD:
#    P1: 6GB (XEN_LDSIZE) offset at 63, OS goes here
#    P2: 1MB (XEN_EMPTYSIZE), as small as we can make it
#    P3: 1GB (XEN_SWAPSIZE), standard MBR2 swap size
# MBR 1 or 2 Linux:
#    P1: 1MB (XEN_EMPTYSIZE), as small as we can make it
#    P2: 6GB (XEN_LDSIZE) offset at 63, OS goes here
#    P3: 1GB (XEN_SWAPSIZE), standard MBR2 swap size
# MBR 3:
#    P1: 16GB (XEN_LDSIZE_3) offset at 2048, standard OS partition
#    P2: 1MB (XEN_EMPTYSIZE), as small as we can make it
#    P3: 1GB (XEN_SWAPSIZE), standard MBR2 swap size
#
227
228
229
230
231
# P4 is sized based on what the user told us. If they do not specify
# XEN_EXTRA, then we default to 1G (XEN_EXTRASIZE). We need enough
# space here to support uses of mkextrafs in the clientside (e.g., for
# "no nfs" experiments where local homedirs are created.
#
232
233
234
235
236
237
# Sizes below are in 1K blocks.
#
my $XEN_LDSIZE    =  6152895;
my $XEN_LDSIZE_3  = 16777216;
my $XEN_SWAPSIZE  =  1048576;
my $XEN_EMPTYSIZE =     1024;
238
my $XEN_EXTRASIZE =  1048576;
239

Leigh B Stoller's avatar
Leigh B Stoller committed
240
241
242
243
244
245
246
247
248
249
250
# IFBs
my $IFBDB      = "/var/emulab/db/ifbdb";
# Kernel auto-creates only two! Sheesh, why a fixed limit?
my $MAXIFB     = 1024;

# Route tables for tunnels
my $RTDB           = "/var/emulab/db/rtdb";
my $RTTABLES       = "/etc/iproute2/rt_tables";
# Temporary; later kernel version increases this.
my $MAXROUTETTABLE = 255;

251
252
253
# Striping
my $STRIPE_COUNT   = 1;

254
255
256
# Whether or not to use only unpartitioned (unused) disks to form the Xen VG.
my $LVM_FULLDISKONLY = 0;

257
258
# Whether or not to use partitions only when they are big.
my $LVM_ONLYLARGEPARTS = 1;
259
260
261
262
my $LVM_LARGEPARTPCT = 8;

# In general, you only want to use one partition per disk since we stripe.
my $LVM_ONEPARTPERDISK = 1;
263

264
265
266
267
# Use openvswitch for gre tunnels.
my $OVSCTL   = "/usr/local/bin/ovs-vsctl";
my $OVSSTART = "/usr/local/share/openvswitch/scripts/ovs-ctl";

268
269
my $ISREMOTENODE = REMOTEDED();
my $BRIDGENAME   = "xenbr0";
270
my $VIFROUTING   = ((-e "$ETCDIR/xenvifrouting") ? 1 : 0);
271

272
273
my $TMCD_PORT	 = 7777;

274
275
276
277
278
#
# Information about the running Xen hypervisor
#
my %xeninfo = ();

279
280
281
282
# Local functions
sub findRoot();
sub copyRoot($$);
sub createRootDisk($);
283
sub createAuxDisk($$);
284
285
286
287
288
289
sub replace_hacks($);
sub disk_hacks($);
sub configFile($);
sub domain0Memory();
sub totalMemory();
sub hostIP($);
290
sub createDHCP();
291
292
sub addDHCP($$$$);
sub subDHCP($$);
293
sub restartDHCP();
294
295
296
sub formatDHCP($$$);
sub fixupMac($);
sub createControlNetworkScript($$$);
297
sub createExpNetworkScript($$$$$$$$);
298
sub createTunnelScript($$$$$);
Leigh B Stoller's avatar
Leigh B Stoller committed
299
sub createExpBridges($$$);
300
301
302
303
304
305
sub destroyExpBridges($$);
sub domainStatus($);
sub domainExists($);
sub addConfig($$$);
sub createXenConfig($$);
sub readXenConfig($);
306
sub lookupXenConfig($$);
307
sub getXenInfo();
Leigh B Stoller's avatar
Leigh B Stoller committed
308
309
310
311
312
sub AllocateIFBs($$$);
sub InitializeRouteTable();
sub AllocateRouteTable($);
sub LookupRouteTable($);
sub FreeRouteTable($);
Mike Hibler's avatar
Mike Hibler committed
313
sub downloadOneImage($$$);
314
315
316

sub getXenInfo()
{
317
318
    open(XM,"$XM info|") 
        or die "getXenInfo: could not run '$XM info': $!";
319
320
321
322
323
324
325
326
327

    while (<XM>) {
	    chomp;
	    /^(\S+)\s*:\s+(.*)$/;
	    $xeninfo{$1} = $2;
    }
    
    close XM;
}
328
329
330
331
332
333
334

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

    makeIfaceMaps();
    makeBridgeMaps();
335
336
337
338
339

    my $toolstack = `grep TOOLSTACK /etc/default/xen`;
    if ($toolstack =~ /xl$/) {
	$XM = "/usr/sbin/xl";
    }
340
    getXenInfo();
341

342
343
344
    # Compute the strip size for new lvms.
    if (-e "/var/run/xen.ready") {
	$STRIPE_COUNT = computeStripeSize($VGNAME);
345
    }
Jon Rafkind's avatar
Jon Rafkind committed
346
347
348
    return 0;
}

349
350
351
352
353
354
355
356
sub setDebug($)
{
    $debug = shift;
    libvnode::setDebug($debug);
    print "libvnode_xen: debug=$debug\n"
	if ($debug);
}

357
358
359
360
361
362
363
364
sub ImageLockName($)
{
    my ($imagename) = @_;

    return "xenimage." .
	(defined($imagename) ? $imagename : $defaultImage{'name'});
}

365
366
367
368
#
# 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.
#
369
sub rootPreConfig($)
370
{
371
    my $bossip = shift;
372
373
374
375
376
    #
    # 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") {
Mike Hibler's avatar
Mike Hibler committed
377
378
	TBDebugTimeStamp("rootPreConfig: grabbing global lock $GLOBAL_CONF_LOCK")
	    if ($lockdebug);
379
380
381
382
383
384
385
386
387
	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;
	}
    }
Mike Hibler's avatar
Mike Hibler committed
388
389
    TBDebugTimeStamp("  got global lock")
	if ($lockdebug);
390
    if (-e "/var/run/xen.ready") {
Mike Hibler's avatar
Mike Hibler committed
391
392
	TBDebugTimeStamp("  releasing global lock")
	    if ($lockdebug);
393
394
395
396
397
398
        TBScriptUnlock();
        return 0;
    }
    
    print "Configuring root vnode context\n";

399
400
401
402
403
404
405
406
407
408
409
    #
    # For compatibility with existing (physical host) Emulab images,
    # the physical host provides DHCP info for the vnodes. We manage
    # the dhcpd.conf file here. See below. 
    #
    # 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.
    #
    my ($alias_iface, $alias_ip, $alias_mask);

410
    #
411
412
413
    # Locally, we just need to add the alias to the control interface
    # (which might be a bridge).
    # 
414
    if (!$ISREMOTENODE) {
415
	my ($cnet_iface) = findControlNet();
416
417

	#
418
419
420
	# 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.
421
	#
422
423
424
425
426
	mysystem("$IPTABLES -P FORWARD DROP");
	mysystem("$IPTABLES -F FORWARD");
	# This says to forward traffic across the bridge.
	mysystem("$IPTABLES -A FORWARD ".
		 "-m physdev --physdev-in $cnet_iface -j ACCEPT");
427
428
429
430
431
432
433
	
	if ($VIFROUTING) {
	    mysystem("echo 1 >/proc/sys/net/ipv4/conf/$cnet_iface/proxy_arp");
	    mysystem("echo 1 >/proc/sys/net/ipv4/ip_forward");
	    # This is for arping -A to work. See emulab-cnet.pl
	    mysystem("echo 1 >/proc/sys/net/ipv4/ip_nonlocal_bind");
	}
434
435
436
437
438
439
440
441

	# Set up for metadata server for ec2 support
	print "Setting up redirection for meta server...\n";
	mysystem("$IPBIN addr add 169.254.169.254/32 ".
		 "   scope global dev $cnet_iface");
	mysystem("$IPTABLES -t nat -A PREROUTING -d 169.254.169.254/32 " .
		 "   -p tcp -m tcp --dport 80 -j DNAT ".
		 "   --to-destination ${bossip}:8787");
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    }
    else {
	if (!existsBridge($BRIDGENAME)) {
	    if (mysystem2("$BRCTL addbr $BRIDGENAME")) {
		TBScriptUnlock();
		return -1;
	    }
	    #
	    # We do not set the mac address; we want it to take
	    # on the address of the attached vif interfaces so that
	    # arp works. This is quite kludgy of course, but otherwise
	    # the arp comes into the bridge interface and then kernel
	    # drops it. There is a brouter (ebtables) work around
	    # but not worth worrying about. 
	    #
	}
	(undef,$alias_mask,$alias_ip) = findVirtControlNet();
	$alias_iface = $BRIDGENAME;
460
461
462
463
464

	if (system("ifconfig $alias_iface | grep -q 'inet addr'")) {
	    print "Creating $alias_iface alias...\n";
	    mysystem("ifconfig $alias_iface $alias_ip netmask $alias_mask");
	}
465
466
    }

467
468
469
470
    # For tunnels
    mysystem("$MODPROBE openvswitch");
    mysystem("$OVSSTART --delete-bridges start");

471
    # For bandwidth contraints.
Leigh B Stoller's avatar
Leigh B Stoller committed
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
    mysystem("$MODPROBE ifb numifbs=$MAXIFB");

    # Create a DB to manage them. 
    my %MDB;
    if (!dbmopen(%MDB, $IFBDB, 0660)) {
	print STDERR "*** Could not create $IFBDB\n";
	TBScriptUnlock();
	return -1;
    }
    for (my $i = 0; $i < $MAXIFB; $i++) {
	$MDB{"$i"} = ""
	    if (!defined($MDB{"$i"}));
    }
    dbmclose(%MDB);
    
487
488
489
490
491
492
493
494
495
496
497
498
499
500
    #
    # 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;
    }

501
    #
502
    # Make sure pieces are at least a 5GiB.
503
    #
504
    my %devs = libvnode::findSpareDisks(5 * 1024);
505

Leigh B Stoller's avatar
Leigh B Stoller committed
506
507
    #
    # Turn on write caching. Hacky. 
508
509
    # XXX note we do not use the returned "path" here as we need to
    # change the setting on all devices, not just the whole disk devices.
Leigh B Stoller's avatar
Leigh B Stoller committed
510
511
    #
    foreach my $dev (keys(%devs)) {
512
513
514
515
	# only mess with the disks we are going to use
	if (exists($devs{$dev}{"size"}) || $LVM_FULLDISKONLY == 0) {
	    mysystem2("hdparm -W1 /dev/$dev");
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
516
517
    }

518
519
520
521
522
523
524
525
    #
    # 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);

526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
	#
	# Total up potential maximum size
	#
	my $maxtotalSize = 0;
	my $sizeThreshold = 0;
	foreach my $dev (keys(%devs)) {
	    if (defined($devs{$dev}{"size"})) {
		$maxtotalSize += $devs{$dev}{"size"};
	    } else {
		foreach my $part (keys(%{$devs{$dev}})) {
		    $maxtotalSize += $devs{$dev}{$part}{"size"};
		}
	    }
	}
	if ($maxtotalSize > 0) {
	    $sizeThreshold = int($maxtotalSize * $LVM_LARGEPARTPCT / 100.0);
	}

544
545
546
547
548
	#
	# Find available devices of sufficient size, prepare them,
	# and incorporate them into a volume group.
	#
	my $totalSize = 0;
549
	my @blockdevs = ();
550
	foreach my $dev (keys(%devs)) {
551
	    #
552
	    # Whole disk is available, use it.
553
	    #
554
	    if (defined($devs{$dev}{"size"})) {
555
		push(@blockdevs, $devs{$dev}{"path"});
556
		$totalSize += $devs{$dev}{"size"};
557
		next;
558
	    }
559

560
	    #
561
	    # Disk contains partitions that are available.
562
	    #
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
	    my ($lpsize,$lppath);
	    foreach my $part (keys(%{$devs{$dev}})) {
		my $psize = $devs{$dev}{$part}{"size"};
		my $ppath = $devs{$dev}{$part}{"path"};

		#
		# XXX one way to avoid using the system disk, just ignore
		# all partition devices. However, in cases where the
		# remainder of the system disk represents the majority of
		# the available space (e.g., Utah d710s), this is a bad
		# idea.
		#
		if ($LVM_FULLDISKONLY) {
		    print STDERR
			"WARNING: not using partition $ppath for LVM\n";
		    next;
		}
580

581
582
583
584
585
586
587
588
589
590
591
592
593
		#
		# XXX Another heurstic to try to weed out the system
		# disk whenever feasible: if a partition device represents
		# less than some percentage of the max possible space,
		# avoid it. At Utah this one is tuned (8%) to avoid using
		# left over space on the system disk of d820s (which have
		# six other larger drives) while using it on the pc3000s
		# and d710s.
		#
		if ($LVM_ONLYLARGEPARTS && $psize < $sizeThreshold) {
		    print STDERR "WARNING: not using $ppath for LVM (too small)\n";
		    next;
		}
594

595
596
597
598
599
600
601
602
603
604
605
606
		#
		# XXX If we are only going to use one partition per disk,
		# record the largest one we find here. This check will
		# filter out the small "other OS" partition (3-6GB) in
		# favor of the larger "rest of the disk" partition.
		#
		if ($LVM_ONEPARTPERDISK) {
		    if (!defined($lppath) || $psize > $lpsize) {
			$lppath = $ppath;
			$lpsize = $psize;
		    }
		    next;
607
		}
608
609
610
611
612
613
614
615
616
617

		#
		# It ran the gauntlet of feeble filters, use it!
		#
		push(@blockdevs, $ppath);
		$totalSize += $psize;
	    }
	    if ($LVM_ONEPARTPERDISK && defined($lppath)) {
		push(@blockdevs, $lppath);
		$totalSize += $lpsize;
618
619
	    }
	}
620
	if (@blockdevs == 0) {
621
622
623
624
625
	    print STDERR "ERROR: findSpareDisks found no disks for LVM!\n";
	    TBScriptUnlock();
	    return -1;
	}
		    
626
627
628
	my $blockdevstr = join(' ', sort @blockdevs);
	mysystem("pvcreate $blockdevstr");
	mysystem("vgcreate $VGNAME $blockdevstr");
629
630
631

	my $size = lvmVGSize($VGNAME);
	if ($size < $XEN_MIN_VGSIZE) {
Mike Hibler's avatar
Mike Hibler committed
632
633
634
635
636
637
638
639
	    print STDERR "WARNING: physical disk space below the desired ".
		" minimum value ($size < $XEN_MIN_VGSIZE), expect trouble.\n";
	}

	#
	# Create an image pool for golden images.
	# If this fails, we just don't use thin volumes!
	#
640
	if ($usethin && createThinPool($blockdevstr)) {
Mike Hibler's avatar
Mike Hibler committed
641
642
643
	    print STDERR "WARNING: could not create a thin pool, ".
		"disabling golden image support\n";
	    $usethin = 0;
644
645
	}
    }
646
647
    $STRIPE_COUNT = computeStripeSize($VGNAME);
    
648
649
650
651
652
653
654
655
    #
    # Make sure our volumes are active -- they seem to become inactive
    # across reboots
    #
    mysystem("vgchange -a y $VGNAME");

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

658
    print "Creating scratch FS ...\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
659
    if (createExtraFS($EXTRAFS, $VGNAME, "25G")) {
660
661
662
	TBScriptUnlock();
	return -1;
    }
663
    print "Creating image metadata FS ...\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
664
    if (createExtraFS($METAFS, $VGNAME, "1G")) {
Leigh B Stoller's avatar
Leigh B Stoller committed
665
666
667
	TBScriptUnlock();
	return -1;
    }
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
    print "Creating container info FS ...\n";
    if (createExtraFS($INFOFS, $VGNAME, "3G")) {
	TBScriptUnlock();
	return -1;
    }
    if (! -l $VMS) {
	#
	# We need this stuff to be sticky across reloads, so move it
	# into an lvm. If we lose the lvm, well then we are screwed.
	#
	my @files = glob("$VMS/*");
	foreach my $file (@files) {
	    my $base = basename($file);
	    mysystem("/bin/mv $file $INFOFS")
		if (! -e "$INFOFS/$base");
	}
	mysystem("/bin/rm -rf $VMS");
	mysystem("/bin/ln -s $INFOFS $VMS");
    }

Leigh B Stoller's avatar
Leigh B Stoller committed
688
689
690
691
692
    if (InitializeRouteTables()) {
	print STDERR "*** Could not initialize routing table DB\n";
	TBScriptUnlock();
	return -1;
    }
693

694
695
696
697
698
    #
    # Make sure IP forwarding is enabled on the host
    #
    mysystem2("$SYSCTL -w net.ipv4.conf.all.forwarding=1");

Mike Hibler's avatar
Mike Hibler committed
699
700
701
702
703
704
    #
    # Increase socket buffer size for frisbee download of images.
    #
    mysystem2("$SYSCTL -w net.core.rmem_max=1048576");
    mysystem2("$SYSCTL -w net.core.wmem_max=1048576");

705
706
707
    #
    # Need these to avoid overflowing the NAT tables.
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
708
709
710
711
712
713
    mysystem2("$MODPROBE nf_conntrack");
    if ($?) {
	print STDERR "ERROR: could not load nf_conntrack module!\n";
	TBScriptUnlock();
	return -1;
    }
714
    mysystem2("$SYSCTL -w ".
715
	     "  net.netfilter.nf_conntrack_generic_timeout=120");
716
    mysystem2("$SYSCTL -w ".
717
	     "  net.netfilter.nf_conntrack_tcp_timeout_established=54000");
718
    mysystem2("$SYSCTL -w ".
719
	     "  net.netfilter.nf_conntrack_max=131071");
720
    mysystem2("echo 16384 > /sys/module/nf_conntrack/parameters/hashsize");
721
722
723
724
725
726
727
 
    # These might fail on new kernels.  
    mysystem2("$SYSCTL -w ".
	      " net.ipv4.netfilter.ip_conntrack_generic_timeout=120");
    mysystem2("$SYSCTL -w ".
	      " net.ipv4.netfilter.ip_conntrack_tcp_timeout_established=54000");

728
    mysystem("touch /var/run/xen.ready");
Mike Hibler's avatar
Mike Hibler committed
729
730
    TBDebugTimeStamp("  releasing global lock")
	if ($lockdebug);
731
    TBScriptUnlock();
Jon Rafkind's avatar
Jon Rafkind committed
732
733
734
    return 0;
}

735
sub rootPreConfigNetwork($$$$)
736
{
737
738
739
    my ($vnode_id, undef, $vnconfig, $private) = @_;
    my @node_ifs = @{ $vnconfig->{'ifconfig'} };
    my @node_lds = @{ $vnconfig->{'ldconfig'} };
Jon Rafkind's avatar
Jon Rafkind committed
740

Mike Hibler's avatar
Mike Hibler committed
741
742
    TBDebugTimeStamp("rootPreConfigNetwork: grabbing global lock $GLOBAL_CONF_LOCK")
	if ($lockdebug);
743
    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
744
	print STDERR "Could not get the global lock after a long time!\n";
745
746
	return -1;
    }
Mike Hibler's avatar
Mike Hibler committed
747
748
    TBDebugTimeStamp("  got global lock")
	if ($lockdebug);
749

750
    createDHCP()
751
	if (! -e $DHCPCONF_FILE && ! -e $NEW_DHCPCONF_FILE);
752

753
754
755
756
757
758
759
760
761
762
763
    if (!$ISREMOTENODE) {
	my ($cnet_iface) = findControlNet();
	my ($alias_ip,$alias_mask) = domain0ControlNet();
	my $alias_iface = "$cnet_iface:1";

	if (system("ifconfig $alias_iface | grep -q 'inet addr'")) {
	    print "Creating $alias_iface alias...\n";
	    mysystem("ifconfig $alias_iface $alias_ip netmask $alias_mask");
	}
    }

764
765
766
767
768
769
    #
    # 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
770

Mike Hibler's avatar
Mike Hibler committed
771
772
    TBDebugTimeStamp("  releasing global lock")
	if ($lockdebug);
773
    TBScriptUnlock();
Jon Rafkind's avatar
Jon Rafkind committed
774
    return 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
775
776
777
bad:
    TBScriptUnlock();
    return -1;
Jon Rafkind's avatar
Jon Rafkind committed
778
779
}

780
781
sub rootPostConfig($)
{
Jon Rafkind's avatar
Jon Rafkind committed
782
783
784
    return 0;
}

785
786
#
# Create the basic context for the VM and give it a unique ID for identifying
787
788
# "internal" state.  If $raref is set, then we are in a RELOAD state machine
# and need to walk the appropriate states.
789
#
790
sub vnodeCreate($$$$)
791
{
792
    my ($vnode_id, undef, $vnconfig, $private) = @_;
793
    my $attributes = $vnconfig->{'attributes'};
794
    my $imagename = $vnconfig->{'image'};
Leigh B Stoller's avatar
Leigh B Stoller committed
795
    my $raref = $vnconfig->{'reloadinfo'};
796
    my $vninfo = $private;
797
    my %image = %defaultImage;
Leigh B Stoller's avatar
Leigh B Stoller committed
798
    my $imagemetadata;
799
    my $lvname;
800
    my $inreload = 0;
Mike Hibler's avatar
Mike Hibler committed
801
    my $dothinlv = doingThinLVM();
802
803

    my $vmid;
804
    if ($vnode_id =~ /^[-\w]+\-(\d+)$/) {
805
806
807
808
809
	$vmid = $1;
    }
    else {
	fatal("xen_vnodeCreate: bad vnode_id $vnode_id!");
    }
810
811
    $vninfo->{'vmid'} = $vmid;

Leigh B Stoller's avatar
Leigh B Stoller committed
812
    if (CreateVnodeLock() != 0) {
813
	fatal("CreateVnodeLock()");
Leigh B Stoller's avatar
Leigh B Stoller committed
814
815
816
817
818
819
    }

    #
    # We need to lock while messing with the image. But we can use
    # shared lock so that others can proceed in parallel. We will have
    # to promote to an exclusive lock if the image has to be changed.
820
    #
821
    my $imagelockname = ImageLockName($imagename);
Mike Hibler's avatar
Mike Hibler committed
822
823
    TBDebugTimeStamp("grabbing image lock $imagelockname shared")
	if ($lockdebug);
Leigh B Stoller's avatar
Leigh B Stoller committed
824
    if (TBScriptLock($imagelockname, TBSCRIPTLOCK_SHAREDLOCK(), 1800)
825
826
827
	!= TBSCRIPTLOCK_OKAY()) {
	fatal("Could not get $imagelockname lock after a long time!");
    }
Mike Hibler's avatar
Mike Hibler committed
828
829
    TBDebugTimeStamp("  got image lock")
	if ($lockdebug);
830

831
832
833
834
    #
    # No image specified, use a default based on the dom0 OS.
    #
    if (!defined($imagename)) {
835
836
	$lvname = $image{'name'};
	
837
838
839
840
841
842
	#
	# 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'};
843
844
	print STDERR "xen_vnodeCreate: ".
	    "no image specified, using default ('$imagename')\n";
845

Leigh B Stoller's avatar
Leigh B Stoller committed
846
847
848
	# Okay to fail if image does not exist yet.
	LoadImageMetadata($imagename, \$imagemetadata);

849
	$lvname = "image+" . $imagename;
850
	if (!lvmFindVolume($lvname) && !defined($imagemetadata)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
851
852
853
854
	    
	    #
	    # Need an exclusive lock for this.
	    #
Mike Hibler's avatar
Mike Hibler committed
855
856
	    TBDebugTimeStamp("  releasing image lock")
		if ($lockdebug);
Leigh B Stoller's avatar
Leigh B Stoller committed
857
	    TBScriptUnlock();	    
Mike Hibler's avatar
Mike Hibler committed
858
859
	    TBDebugTimeStamp("grabbing image lock $imagelockname exclusive")
		if ($lockdebug);
Leigh B Stoller's avatar
Leigh B Stoller committed
860
861
	    if (TBScriptLock($imagelockname, undef, 1800)
		!= TBSCRIPTLOCK_OKAY()) {
862
		fatal("Could not get $imagelockname write lock ".
Leigh B Stoller's avatar
Leigh B Stoller committed
863
864
		      "after a long time!");
	    }
Mike Hibler's avatar
Mike Hibler committed
865
866
	    TBDebugTimeStamp("  got image lock")
		if ($lockdebug);
Leigh B Stoller's avatar
Leigh B Stoller committed
867
	    # And now check again in case someone else snuck in.
868
	    if (!lvmFindVolume($lvname) && createRootDisk($imagename)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
869
870
871
872
873
		TBScriptUnlock();
		fatal("xen_vnodeCreate: ".
		      "cannot find create root disk for default image");
	    }
	    # And back to a shared lock.
Mike Hibler's avatar
Mike Hibler committed
874
875
	    TBDebugTimeStamp("  releasing image lock")
		if ($lockdebug);
876
	    TBScriptUnlock();
Mike Hibler's avatar
Mike Hibler committed
877
878
	    TBDebugTimeStamp("grabbing image lock $imagelockname shared")
		if ($lockdebug);
Leigh B Stoller's avatar
Leigh B Stoller committed
879
880
881
882
883
884
	    if (TBScriptLock($imagelockname, TBSCRIPTLOCK_SHAREDLOCK(), 1800)
		!= TBSCRIPTLOCK_OKAY()) {
		fatal("Could not get $imagelockname lock back ".
		      "after a long time!");
	    }
	    $imagemetadata = undef;
885
	}
886
    }
887
888
889
890
891
    elsif (!defined($raref)) {
	#
	# Boot existing image. The base volume has to exist, since we do
	# not have any reload info to get it.
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
892
	$lvname = "image+" . $imagename;
893
	if (!lvmFindVolume($lvname)) {
894
	    TBScriptUnlock();
895
896
897
	    fatal("xen_vnodeCreate: ".
		  "cannot find logical volume for $lvname, and no reload info");
	}
898
    }
899
    else {
Leigh B Stoller's avatar
Leigh B Stoller committed
900
	$lvname = "image+" . $imagename;
901
902
903
	$inreload = 1;

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

905
	# Tell stated we are getting ready for a reload
906
	libutil::setState("RELOADSETUP");
907
908
909
910
911
912
913

	#
	# 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.
	#
914
	libutil::setState("RELOADING");
915

Mike Hibler's avatar
Mike Hibler committed
916
	if (createImageDisk($imagename, $vnode_id, $raref, $dothinlv)) {
917
	    TBScriptUnlock();
918
919
920
	    fatal("xen_vnodeCreate: ".
		  "cannot create logical volume for $imagename");
	}
921
922
    }

Leigh B Stoller's avatar
Leigh B Stoller committed
923
924
925
926
927
928
929
930
931
932
933
    #
    # Load this from disk.
    #
    if (!defined($imagemetadata)) {
	if (LoadImageMetadata($imagename, \$imagemetadata)) {
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: ".
		  "cannot load image metadata for $imagename");
	}
    }

934
    #
935
    # See if the image is really a package.
936
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
937
938
939
940
941
    if (exists($imagemetadata->{'ISPACKAGE'}) && $imagemetadata->{'ISPACKAGE'}){
	my $imagepath = lvmVolumePath($lvname);
	# In case of reboot.
	mysystem("mkdir -p /mnt/$imagename")
	    if (! -e "/mnt/$imagename");
942
943
	mysystem("mount $imagepath /mnt/$imagename")
	    if (! -e "/mnt/$imagename/.mounted");
944

945
946
947
948
949
	mysystem2("$RESTOREVM -t $VMDIR/$vnode_id $vnode_id /mnt/$imagename");
	if ($?) {
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: ".
		  "cannot restore logical volumes from $imagename");
950
	}
951
952
953
954
	if ($inreload) {
	    libutil::setState("RELOADDONE");
	    sleep(4);
	}
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
	
	#
	# 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;
976
977
978
979
980
981
	#
	# We want to support extra disk space on this path, but we cannot
	# just stick into the 4th partition like we do below, but have to
	# add an extra disk instead. But to do that we have to look at the
	# disks we just parsed and see what the highest lettered drive is.
	#
982
983
984
985
986
	if (exists($attributes->{'XEN_EXTRAFS'})) {
	    my $dsize   = $attributes->{'XEN_EXTRAFS'};
	    my $auxchar = ord('c');
	    my @stanzas = ();
	    
987
	    my $dpre = "xvd";
988
989
	    foreach my $disk (keys(%{$private->{'disks'}})) {
		my ($lvname,$vndisk,$vdisk) = @{$private->{'disks'}->{$disk}};
990
991
992
993
994
		if ($vdisk =~ /^(sd)(\w)$/ || $vdisk =~ /^(xvd)(\w)$/ ||
		    $vdisk =~ /^(hd)(\w)$/) {
		    $dpre = $1;
		    $auxchar = ord($2)
			if (ord($2) > $auxchar);
995
996
997
998
		}
		# Generate a new set of stanzas. see below.
		push(@stanzas, "'phy:$vndisk,$vdisk,w'");
	    }
999
	    my $vdisk = $dpre .	chr($auxchar);
1000
1001
	    my $auxlvname = "${vnode_id}.${vdisk}";
	    
1002
	    if (!lvmFindVolume($auxlvname)) {
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
		if (createAuxDisk($auxlvname, $dsize . "G")) {
		    fatal("libvnode_xen: could not create aux disk: $vdisk");
		}
	    }
	    my $vndisk = lvmVolumePath($auxlvname);
	    my $stanza = "'phy:$vndisk,$vdisk,w'";
	    $private->{'disks'}->{$auxlvname} = [$auxlvname, $vndisk, $vdisk];
	    push(@stanzas, $stanza);

	    #
	    # Replace the existing line in the conf file. 
	    #
	    addConfig($vninfo, "disk = [" . join(",", @stanzas) . "]", 2);
1016
1017
1018

	    # Cause we have no idea.
	    $private->{'os'} = "other";
1019
	}
1020
	
Mike Hibler's avatar
Mike Hibler committed
1021
1022
	TBDebugTimeStamp("  releasing image lock")
	    if ($lockdebug);
1023
	TBScriptUnlock();
Leigh B Stoller's avatar
Leigh B Stoller committed
1024
	CreateVnodeUnlock();
1025
	goto done;
1026
1027
    }

1028
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
1029
    # We get the OS and version from loadinfo.
1030
    #
1031
    my $vdiskprefix = "sd";	# yes, this is right for FBSD too
1032
    my $ishvm = 0;
1033
    my $os;
Leigh B Stoller's avatar
Leigh B Stoller committed
1034
1035
    
    if ($imagemetadata->{'PARTOS'} =~ /freebsd/i) {
1036
	$os = "FreeBSD";
1037
1038
1039
1040
1041

	# XXX we assume that all 10.0 and above will be PVHVM
	if ($imagemetadata->{'OSVERSION'} >= 10) {
	    $ishvm = 1;
	}
1042
1043
    }
    else {
1044
	$os = "Linux";
1045

Leigh B Stoller's avatar
Leigh B Stoller committed
1046
	if ($xeninfo{xen_major} >= 4) {
1047
	    $vdiskprefix = "xvd";
1048
	}
1049
    }
1050
    $private->{'os'} = $os;
1051
    $private->{'ishvm'} = $ishvm;
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068

    # 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.
    #
    my $rootvndisk = lvmVolumePath($vnode_id);

    #
    # 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.
    #
1069
1070
    if (lvmFindVolume($vnode_id)) {
	my $golden = ($dothinlv ? lvmFindOrigin($vnode_id) : "");
Mike Hibler's avatar
Mike Hibler committed
1071
1072
1073
1074
1075
	my $ngolden = nameGoldenImage($imagename);

	if (defined($raref) || ($golden && $golden ne $ngolden)) {
	    print STDERR "$vnode_id: destroying old disk, ".
		"golden='$golden', ngolden='$ngolden'\n";
1076
	    if (lvmDestroyVolume($vnode_id, 1)) {
1077
1078
1079
1080
		TBScriptUnlock();
		fatal("xen_vnodeCreate: ".
		      "could not destroy old disk for $vnode_id");
	    }
Mike Hibler's avatar
Mike Hibler committed
1081
1082
1083
1084
1085
1086
1087
1088

	    #
	    # Attempt to GC the old golden image we were associated with,
	    # unless it is the same as what we are moving to.
	    #
	    if ($REAP_GDS && $golden && $golden ne $ngolden) {
		(my $oimage = $golden) =~ s/^_G_//;
		my $glock = grabGoldenLock($oimage);
1089
		if ($glock && lvmGC($golden, 0)) {
Mike Hibler's avatar
Mike Hibler committed
1090
1091
1092
1093
1094
1095
		    print STDERR "xen_vnodeCreate: could not GC ".
			"unreferenced golden image '$golden'\n";
		}
		releaeseGoldenLock($glock)
		    if ($glock);
	    }
1096
1097
1098
	}
    }

1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
    #
    # Figure out what slice the image is going in. It might be a whole
    # disk image though, so need to figure out what partition to boot.
    # Otherwise we force single slice images into its partition, and
    # put a swap partition after it. Lastly, if an extra disk partition
    # was requested, put that after the swap partition. This will allow
    # the user to take a whole disk image snapshot and load it on a physical
    # node later. 
    #
    print Dumper($imagemetadata);
    my $loadslice  = $imagemetadata->{'PART'};
    my $bootslice  = $loadslice;
    my $rootvdisk  = "${vdiskprefix}a";
    my $rootstanza = "phy:$rootvndisk,${vdiskprefix}a,w";
    push(@alldisks, "'$rootstanza'");

1115
1116
1117
    #
    # Create the snapshot LVM.
    #
1118
    if (!lvmFindVolume($vnode_id)) {
1119
1120
	#
	# Need to create a new disk for the container. But lets see
1121
1122
1123
1124
1125
1126
	# if we have a disk cached or a golden image. We still have
	# the imagelock at this point.
	#

	#
	# Cached image. Grab one to use.
1127
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
1128
1129
1130
1131
1132
1133
	# Ick, this has to be done under an exclusive lock, but we
	# are currently running under a shared lock. We cannot drop
	# the shared lock though (and flock does promotion by drop
	# and relock). So, need to take another lock if we find
	# cached files.
	#
Mike Hibler's avatar
Mike Hibler committed
1134
	if (my (@files) = glob("/dev/$VGNAME/_C_${imagename}_*")) {
1135
1136
1137
1138
1139
1140
	    #
	    # Grab the first file and rename it. It becomes ours.
	    # Then drop the lock.
	    #
	    my $file = $files[0];
	    if (mysystem2("lvrename $file $rootvndisk")) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1141
		TBScriptUnlock();
1142
		fatal("libvnode_xen: could not rename cache file");
Leigh B Stoller's avatar
Leigh B Stoller committed
1143
1144
	    }
	}
Mike Hibler's avatar
Mike Hibler committed
1145

1146
	#
Mike Hibler's avatar
Mike Hibler committed
1147
	# Clone or create one from scratch.
1148
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
1149
	else {
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
	    #
	    # Cannot use/create a golden image if there is a user-specified
	    # extra filesystem.
	    #
	    my $extrafs = 
		(exists($attributes->{'XEN_EXTRAFS'}) ?
		 $attributes->{'XEN_EXTRAFS'} : undef);
	    if ($extrafs) {
		$dothinlv = 0;
	    }

Mike Hibler's avatar
Mike Hibler committed
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
	    #
	    # Golden image. Create a clone of the golden image.
	    #
	    my $glock;
	    if ($dothinlv) {
		$glock = grabGoldenLock($imagename);
		if (!$glock) {
		    TBScriptUnlock();
		    fatal("libvnode_xen: could not lock golden image");
		}
		if (hasGoldenImage($imagename)) {
		    print "Cloning $imagename golden image for $vnode_id\n";
		    #
		    # XXX We probably don't have to hold the lock during
		    # the clone, but lets be conservative
		    #
		    if (cloneGoldenImage($imagename, $vnode_id)) {
			releaseGoldenLock($glock);
			TBScriptUnlock();
			fatal("libvnode_xen: could not clone golden image");
		    }
		    releaseGoldenLock($glock);
		    goto okay;
		}
	    }

	    #
	    # Not doing golden images or golden image does not exist yet.
	    # Either way, we need to unpack the images to create a disk.
	    #
1191
	    if (CreatePrimaryDisk($lvname, $imagemetadata,
Mike Hibler's avatar
Mike Hibler committed
1192
1193
1194
				  $vnode_id, $extrafs, $dothinlv)) {
		releaseGoldenLock($glock)
		    if ($glock);
1195
1196
		TBScriptUnlock();
		fatal("libvnode_xen: could not clone $lvname");
1197
	    }
Mike Hibler's avatar
Mike Hibler committed
1198
1199
1200
1201
	    releaseGoldenLock($glock)
		if ($glock);

okay:
1202
1203
1204
	    if ($inreload) {
		libutil::setState("RELOADDONE");
		
1205
		#
1206
1207
1208
		# We have to ask what partition to boot, since the
		# that info does not come across in the loadinfo, and
		# we cannot ask until RELOADDONE is sent. 
1209
		#
Leigh B Stoller's avatar
Leigh B Stoller committed
1210
		if ($loadslice == 0 && !exists($imagemetadata->{'BOOTPART'})) {
1211
1212
		    my @tmp;

1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
		    #
		    # XXX If may take a while for the state change above to
		    # take effect and set the bootwhat info. Sleep a short
		    # time and try. If that fails, sleep longer and try
		    # one more time.
		    #
		    sleep(1);
		    my $rv = getbootwhat(\@tmp);
		    if ($rv || !scalar(@tmp) || !exists($tmp[0]->{"WHAT"})) {
			sleep(4);
			$rv = getbootwhat(\@tmp);
		    }

		    if ($rv || !scalar(@tmp) || !exists($tmp[0]->{"WHAT"}) ||
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
			$tmp[0]->{"WHAT"} !~ /^\d*$/) {
			print STDERR Dumper(\@tmp);
			TBScriptUnlock();
			fatal("libvnode_xen: could not get bootwhat info");
		    }
		    $bootslice = $tmp[0]->{"WHAT"};
		    #
		    # Store it back into the metadata for next time.
		    #
		    $imagemetadata->{'BOOTPART'} = $bootslice;
		    StoreImageMetadata($imagename, $imagemetadata);
1238
		}
Leigh B Stoller's avatar
Leigh B Stoller committed
1239
	    }
1240
	}
1241
1242
1243
1244
1245
1246
1247
	if ($loadslice == 0) {
	    $bootslice = $imagemetadata->{'BOOTPART'};
	}
	#
	# Need to create mapper entries so we can mount the
	# boot filesystem later, for slicefix.
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
1248
	if (RunWithLock("kpartx", "kpartx -av $rootvndisk")) {
1249
1250
1251
1252
1253
	    TBScriptUnlock();
	    fatal("libvnode_xen: could not add /dev/mapper entries");
	}
	# Hmm, some kind of kpartx race ...
	sleep(2);
1254
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1255
1256
1257
1258
1259
1260
1261
1262
    # Need to tell slicefix where to find the root partition.
    # Naming convention is a pain.
    my $devname = "$VGNAME/${vnode_id}p$bootslice";
    $devname =~ s/\-/\-\-/g;
    $devname =~ s/\//\-/g;
    $private->{'rootpartition'} = "/dev/mapper/$devname";
    $rootvdisk .= "${bootslice}";