libvnode_xen.pm 162 KB
Newer Older
Jon Rafkind's avatar
Jon Rafkind committed
1
#!/usr/bin/perl -wT
2
#
3
# Copyright (c) 2008-2017 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
use POSIX qw(:signal_h);
88
89

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

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

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

#
# Set to enable vnodesetup to exit before vnode is completely up
# (see vnodesetup::hackwaitandexit). Allows more parallelism during
# boot-time vnode setup. Note that concurrency may still be constrained
# by $MAXCONCURRENT (defined below) which limits how many new VMs can
# be created at once.
#
my $vsrelease = "immediate";	# or "early" or "none"
142

Mike Hibler's avatar
Mike Hibler committed
143
144
145
146
147
148
149
#
# Some commands/subsystems have evolved in incompatible ways over time,
# these vars keep track of such things.
#
my $newsfdisk = 0;
my $newlvm = 0;

150
151
152
153
154
155
156
157
158
159
160
161
#
# Image wait time.
#
# How long (seconds) we will wait to when trying to grab a lock on
# an image. Should be set to the max time you think it could take frisbee
# to download the largest (compressed) OS image you will support in a VM.
# Also consider that there could be multiple frisbees running at once for
# multiple images (currently limited by the vnode create lock concurrency
# ($MAXCONCURRENT) below.
#
my $MAXIMAGEWAIT = 1800;

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#
# Serial console handling. We fire up a capture per active vnode.
# We use a fine assortment of capture options:
#
#	-i: standalone mode, don't try to contact capserver directly
#	-l: (added later) set directory where log, ACL, and pid files are kept.
#	-C: use a circular buffer to capture activity while no user
#	    is connected. This gets dumped to the user when they connect.
#	-X: (added later) run in "Xen mode" on the given domain.
#	    Monitors the pty exported by xenconsoled. Note that the
#	    specific pty can change when a domain reboots; capture
#	    deals with this.
#	-R: Retry interval of 2 seconds. When capture is disconnected
#	    from the pty (due to domain reboot/shutdowns), this is how
#	    long we wait between attempts to reconnect.
#
my $CAPTURE     = "/usr/local/sbin/capture-nossl";
my $CAPTUREOPTS	= "-i -C -R 2000";

Mike Hibler's avatar
Mike Hibler committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#
# 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; }
203

204
205
206
207
208
209
210
211
##
## Randomly chosen convention section
##

# global lock
my $GLOBAL_CONF_LOCK = "xenconf";

# default image to load on logical disks
212
213
# Just symlink /boot/vmlinuz-xenU and /boot/initrd-xenU
# to the kernel and ramdisk you want to use by default.
214
my %defaultImage = (
215
216
217
218
219
220
    'name'      => "emulab-ops-emulab-ops-XEN-STD",
    'kernel'    => "/boot/vmlinuz-xenU",
    'ramdisk'   => "/boot/initrd-xenU",
    'OSVERSION' => "any",
    'PARTOS'    => "Linux",
    'ISPACKAGE' => 0,
221
222
    'PART'      => 2,
    'BOOTPART'  => 2,
223
224
225
);

# where all our config files go
226
227
my $VMS    = "/var/emulab/vms";
my $VMDIR  = "$VMS/vminfo";
228
229
my $XENDIR = "/var/xen";

230
# Extra space for capture/restore.
231
my $EXTRAFS = "/capture";
232

233
# Extra space for image metadata between reloads.
Leigh B Stoller's avatar
Leigh B Stoller committed
234
my $METAFS = "/metadata";
235
236
# So we can ask this from outside;
sub METAFS()  { return $METAFS; }
Leigh B Stoller's avatar
Leigh B Stoller committed
237

238
239
240
# Extra space for vminfo (/var/emulab/vms) between reloads.
my $INFOFS = "/vminfo";

241
242
# Xen LVM volume group name. Accessible outside this file.
$VGNAME = "xen-vg";
Leigh B Stoller's avatar
Leigh B Stoller committed
243
244
# So we can ask this from outside;
sub VGNAME()  { return $VGNAME; }
245
246
247
248
249
250
251
252

##
## Indefensible, arbitrary constant section
##

# Minimum memory for dom0
my $MIN_MB_DOM0MEM = 256;

Mike Hibler's avatar
Mike Hibler committed
253
#
254
# Minimum acceptible size (in GB) of LVM VG for domUs.
Mike Hibler's avatar
Mike Hibler committed
255
256
257
258
259
260
#
# 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;
261

262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#
# 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
#
279
280
281
282
283
# 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.
#
284
285
286
287
288
289
# Sizes below are in 1K blocks.
#
my $XEN_LDSIZE    =  6152895;
my $XEN_LDSIZE_3  = 16777216;
my $XEN_SWAPSIZE  =  1048576;
my $XEN_EMPTYSIZE =     1024;
290
my $XEN_EXTRASIZE =  1048576;
291

Leigh B Stoller's avatar
Leigh B Stoller committed
292
293
294
295
296
297
298
299
300
301
302
# 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;

303
304
305
# Striping
my $STRIPE_COUNT   = 1;

306
307
308
# Setup a RAID10 underneath the LVM
my $LVM_RAID = SHAREDHOST() ? 1 : 0;

309
310
311
# Avoid using SSDs unless there are only SSDs
my $LVM_AVOIDSSD = 1;

312
313
314
# Whether or not to use only unpartitioned (unused) disks to form the Xen VG.
my $LVM_FULLDISKONLY = 0;

315
316
# Whether or not to use partitions only when they are big.
my $LVM_ONLYLARGEPARTS = 1;
317
my $LVM_LARGEPARTPCT = 10;
318
319
320

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

322
# Use openvswitch for gre tunnels.
Mike Hibler's avatar
Mike Hibler committed
323
# Use a custom version if present, the standard version otherwise.
324
325
my $OVSCTL   = "/usr/local/bin/ovs-vsctl";
my $OVSSTART = "/usr/local/share/openvswitch/scripts/ovs-ctl";
Mike Hibler's avatar
Mike Hibler committed
326
327
328
329
if (! -x "$OVSCTL") {
    $OVSCTL   = "/usr/bin/ovs-vsctl";
    $OVSSTART = "/usr/share/openvswitch/scripts/ovs-ctl";
}
330

331
332
my $ISREMOTENODE = REMOTEDED();
my $BRIDGENAME   = "xenbr0";
333
my $VIFROUTING   = ((-e "$ETCDIR/xenvifrouting") ? 1 : 0);
334

335
336
my $TMCD_PORT	 = 7777;

337
338
339
340
341
#
# Information about the running Xen hypervisor
#
my %xeninfo = ();

342
343
344
345
# Local functions
sub findRoot();
sub copyRoot($$);
sub createRootDisk($);
346
sub createAuxDisk($$);
347
348
349
350
351
352
sub replace_hacks($);
sub disk_hacks($);
sub configFile($);
sub domain0Memory();
sub totalMemory();
sub hostIP($);
353
sub createDHCP();
354
355
sub addDHCP($$$$);
sub subDHCP($$);
356
sub restartDHCP();
357
358
sub formatDHCP($$$);
sub fixupMac($);
359
sub createControlNetworkScript($$$$);
360
sub createExpNetworkScript($$$$$$$$);
361
sub createTunnelScript($$$$$);
Leigh B Stoller's avatar
Leigh B Stoller committed
362
sub createExpBridges($$$);
363
364
365
366
367
368
sub destroyExpBridges($$);
sub domainStatus($);
sub domainExists($);
sub addConfig($$$);
sub createXenConfig($$);
sub readXenConfig($);
369
sub lookupXenConfig($$);
370
sub getXenInfo();
Leigh B Stoller's avatar
Leigh B Stoller committed
371
372
373
374
375
sub AllocateIFBs($$$);
sub InitializeRouteTable();
sub AllocateRouteTable($);
sub LookupRouteTable($);
sub FreeRouteTable($);
Mike Hibler's avatar
Mike Hibler committed
376
sub downloadOneImage($$$);
377
sub captureRunning($);
378
sub checkForInterrupt();
379
380
381

sub getXenInfo()
{
382
383
    open(XM,"$XM info|") 
        or die "getXenInfo: could not run '$XM info': $!";
384
385
386
387
388
389
390
391
392

    while (<XM>) {
	    chomp;
	    /^(\S+)\s*:\s+(.*)$/;
	    $xeninfo{$1} = $2;
    }
    
    close XM;
}
393

394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
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
#
# Things that matter:
#
# - RAM in dom0.
#   Swapping is deadly. Looks like 1024MB is NOT enough based on experience
#   noted below. 4096MB is plenty and seems to override most of the other
#   concerns.
#
# - Number of CPUs.
#   Have not seen any appreciable difference with 32 CPUs vs. 4. Other
#   things cause problems well before this.
#
# - The number of disks in the VG.
#   LVM performance is generally unpredicable. More than one disk is
#   good, but haven't seen much improvement with, e.g., 6 instead of 2.
#   The killer is concurrent frisbees (write to LVM) and even more so,
#   imageunzips (read from and write to LVM).
#
# - The BW from the frisbee server.
#   Possibly an issue if nothing else stands in the way, due to subboss
#   disk speed that tops out at about 150MB/sec. Given random I/O and
#   multiple images, probably going to get less than 50MB/sec.
#
# Random proposal based on tests run on Emulab d710/d820/d430 nodes and
# Apt c6220 nodes:
#
# * Change the arbitrary 164MB write buf memory to an equally arbitrary,
#   but more aestetically pleasing, 128MB (where the hell did 164 come from?)
#
# * Adjust concurrency based on:
#
# if (dom0 physical RAM < 1GB) MAX = 1;
# if (any swap activity) MAX = 1;
#
#    This captures pc3000s/other old machines and overloaded (RAM) machines.
#
# if (# physical CPUs <= 2) MAX = 3;
# if (# physical spindles == 1) MAX = 3;
# if (dom0 physical RAM <= 2GB) MAX = 3;
#
#    This captures d710s, Apt r320, and Cloudlab m510s. We may need to
#    reconsider the latter since its single drive is an NVMe device.
#    But first we have to get Xen working with them (UEFI issues)...
#
# MAX = 5;
#
#    This captures Emulab d430/d820s, Apt c6220s, and probably all
#    Clemson and Wisconsin Cloudlab nodes.
#
# Random observations based on waaay too much time spent on d710s:
#
# Observation: d710 with 5 vnodes and all different images does not
# boot first time with MAXCONCURRENT==5. 4 vnodes appear to be downloading
# their disk image when the BSD domU tries to boot--qemu times out.
# Restarting the vnode later works fine. The reason for this is that dom0
# starts swapping due to imageunzip processes running. 164MB of write
# buffering per imageunzip is too much for 3 imageunzips and 1GB of dom0 mem.
# Even dropping to 128MB of write buffering is not enough. Single-threading
# imageunzip (-n -W 1) works fine, but things go really slow. We need a
# buffering based on the available dom0 RAM and the max number of concurrent
# imageunzips (MAXCONCURRENT) independent of how the latter is calculated.
#
# Observation: qemu processes blow up huge when they first start (500MB) but
# don't require that much afterward (20MB). So most of our d710 problems
# stem from qemu blasting off while imageunzips are running. This happens
# because qemu is outside of the MAXCONCURRENT lock.
#
# Empirically, based on a d710 with 1GB of dom0 RAM, we can pull off 3
# imageunzips + 1 qemu with just a tad of swapping--not enough to cause
# the qemu to timeout. Full imageunzips seem to be about 32MB + writebuf
# memory. No swapping until the qemu starts. The number of qemus we launch
# will be implicitly constrained by this limit as qemu startups (vnodeBoot)
# take less time than vnodeCreate so we should not have more than MAXCONCURRENT
# vnodes in vnodeBoot at once.
#

#
# Historic concurrency value. Should get overwritten in setConcurrency.
#
my $MAXCONCURRENT = 3;

#
# Number of concurrent containers set up in parallel. See the big, long
# navel-gazing comment just above...
#
sub setConcurrency($)
{
    my ($maxval) = @_;
   
    if ($maxval) {
	$MAXCONCURRENT = 5;
    } else {
	my ($ram,$cpus) = domain0Resources();
	my $disks = $STRIPE_COUNT;
	my $hasswapped = domain0Swapping();

	print STDERR "setConcurrency: cpus=$cpus, ram=$ram, disks=$disks hasswapped=$hasswapped\n"
	    if ($debug);

	if ($cpus > 0 && $disks > 0 && $ram > 0) {
	    if ($ram < 1024 || (!SHAREDHOST() && $hasswapped)) {
		$MAXCONCURRENT = 1;
	    } elsif ($cpus <= 2 || $disks == 1 || $ram <= 2048) {
		$MAXCONCURRENT = 3;
	    } else {
		$MAXCONCURRENT = 5;
	    }
	}
    }
    print STDERR "Limiting to $MAXCONCURRENT concurrent vnode creations.\n";
}

506
507
508
509
510
511
sub init($)
{
    my ($pnode_id,) = @_;

    makeIfaceMaps();
    makeBridgeMaps();
512

Mike Hibler's avatar
Mike Hibler committed
513
514
515
516
517
518
    my $toolstack;
    if (-x "/usr/lib/xen-common/bin/xen-toolstack") {
	$toolstack = `/usr/lib/xen-common/bin/xen-toolstack`;
    } else {
	$toolstack = `grep TOOLSTACK /etc/default/xen`;
    }
519
520
521
    if ($toolstack =~ /xl$/) {
	$XM = "/usr/sbin/xl";
    }
522
    getXenInfo();
523

Mike Hibler's avatar
Mike Hibler committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
    # See which sfdisk we have. Version 2.26 removed some options we used.
    my $out = `sfdisk -v`;
    if (defined($out) && $out =~ /2\.(\d+)(\.\d+)$/) {
	if (int($1) >= 26) {
	    $newsfdisk = 1;
	}
    }

    # See what version of LVM we have. Again, some commands are different.
    $out = `lvm version | grep 'LVM version'`;
    if (defined($out) && $out =~ /LVM version:\s+(\d+)\.(\d+)\.(\d+)/) {
	if (int($1) > 2 ||
	    (int($1) == 2 && int($2) > 2) ||
	    (int($1) == 2 && int($2) == 2 && int($3) >= 99)) {
	    $newlvm = 1;
	}
    }

542
543
544
    # Compute the strip size for new lvms.
    if (-e "/var/run/xen.ready") {
	$STRIPE_COUNT = computeStripeSize($VGNAME);
545
    }
Jon Rafkind's avatar
Jon Rafkind committed
546
547
548
    return 0;
}

549
550
551
552
sub setDebug($)
{
    $debug = shift;
    libvnode::setDebug($debug);
553
554
555
556
    $lockdebug = 1;
    if ($debug > 1) {
	$sleepdebug = 1;
    }
557
558
559
560
    print "libvnode_xen: debug=$debug\n"
	if ($debug);
}

561
562
563
564
565
566
567
sub ImageLockName($)
{
    my ($imagename) = @_;

    return "xenimage." .
	(defined($imagename) ? $imagename : $defaultImage{'name'});
}
568
569
570
571
572
573
sub ImageLVName($)
{
    my ($imagename) = @_;

    return "image+" . $imagename;
}
574

575
576
577
578
#
# 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.
#
579
sub rootPreConfig($)
580
{
581
    my $bossip = shift;
582
583
584
585
586
    #
    # 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
587
588
	TBDebugTimeStamp("rootPreConfig: grabbing global lock $GLOBAL_CONF_LOCK")
	    if ($lockdebug);
589
590
591
592
593
594
595
596
597
	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
598
599
    TBDebugTimeStamp("  got global lock")
	if ($lockdebug);
600
    if (-e "/var/run/xen.ready") {
Mike Hibler's avatar
Mike Hibler committed
601
602
	TBDebugTimeStamp("  releasing global lock")
	    if ($lockdebug);
603
604
605
606
607
608
        TBScriptUnlock();
        return 0;
    }
    
    print "Configuring root vnode context\n";

609
610
611
612
613
614
615
616
617
618
619
    #
    # 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);

620
    #
621
622
623
    # Locally, we just need to add the alias to the control interface
    # (which might be a bridge).
    # 
624
    if (!$ISREMOTENODE) {
625
	my ($cnet_iface) = findControlNet();
626
627

	#
628
629
630
	# 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.
631
	#
632
633
634
635
636
	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");
637
638
639
640
641
642
643
	
	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");
	}
644
645
646
647
648
649
650
651

	# 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");
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
    }
    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;
670
671
672
673
674

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

677
678
679
680
    # For tunnels
    mysystem("$MODPROBE openvswitch");
    mysystem("$OVSSTART --delete-bridges start");

681
682
683
684
    # For gre tunnels to work with iptables
    mysystem("$MODPROBE nf_conntrack_proto_gre");
    mysystem("$MODPROBE nf_conntrack_pptp");

685
    # For bandwidth contraints.
Leigh B Stoller's avatar
Leigh B Stoller committed
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
    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);
    
701
702
703
704
705
706
707
708
709
710
711
712
713
714
    #
    # 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;
    }

715
    #
716
    # Make sure pieces are at least 5 GiB.
717
    #
718
    my $minpsize = 5 * 1024;
719
    my %devs = libvnode::findSpareDisks($minpsize, $LVM_AVOIDSSD);
720
721
722

    # if ignoring SSDs but came up with nothing, we have to use them!
    if ($LVM_AVOIDSSD && keys(%devs) == 0) {
723
	%devs = libvnode::findSpareDisks($minpsize, 0);
724
    }
725

Leigh B Stoller's avatar
Leigh B Stoller committed
726
727
    #
    # Turn on write caching. Hacky. 
728
729
    # 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
730
    #
731
    my %diddev = ();
Leigh B Stoller's avatar
Leigh B Stoller committed
732
    foreach my $dev (keys(%devs)) {
733
	# only mess with the disks we are going to use
734
735
	if (!exists($diddev{$dev}) &&
	    (exists($devs{$dev}{"size"}) || $LVM_FULLDISKONLY == 0)) {
736
	    mysystem2("hdparm -W1 /dev/$dev");
737
	    $diddev{$dev} = 1;
738
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
739
    }
740
    undef %diddev;
Leigh B Stoller's avatar
Leigh B Stoller committed
741

742
743
744
745
746
747
748
749
    #
    # 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);

750
	#
751
752
	# Total up potential maximum size.
	# Also determine mix of SSDs and non-SSDs if required.
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
	#
	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);
	}

769
770
771
772
	#
	# Find available devices of sufficient size, prepare them,
	# and incorporate them into a volume group.
	#
773
      again:
774
	my $totalSize = 0;
775
	my $minSize;
776
	my @blockdevs = ();
777
	foreach my $dev (sort keys(%devs)) {
778
	    #
779
	    # Whole disk is available, use it.
780
	    #
781
	    if (defined($devs{$dev}{"size"})) {
782
783
		my $psize = $devs{$dev}{"size"};

784
		push(@blockdevs, $devs{$dev}{"path"});
785
786
787
788
		$totalSize += $psize;
		if (!defined($minSize) || $psize < $minSize) {
		    $minSize = $psize;
		}
789
		next;
790
	    }
791

792
	    #
793
	    # Disk contains partitions that are available.
794
	    #
795
796
797
798
799
800
801
802
803
804
805
806
	    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.
		#
807
		if ($LVM_FULLDISKONLY || $LVM_RAID) {
808
809
810
811
		    print STDERR
			"WARNING: not using partition $ppath for LVM\n";
		    next;
		}
812

813
814
815
816
		#
		# 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,
817
		# avoid it. At Utah this one is tuned (10%) to avoid using
818
		# left over space on the system disk of d820s (which have
819
820
		# six other larger drives) or d430s (which have two large
		# disks) while using it on the pc3000s and d710s.
821
822
823
824
825
		#
		if ($LVM_ONLYLARGEPARTS && $psize < $sizeThreshold) {
		    print STDERR "WARNING: not using $ppath for LVM (too small)\n";
		    next;
		}
826

827
828
829
830
831
832
833
834
835
836
837
838
		#
		# 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;
839
		}
840
841
842
843
844
845

		#
		# It ran the gauntlet of feeble filters, use it!
		#
		push(@blockdevs, $ppath);
		$totalSize += $psize;
846
847
848
		if (!defined($minSize) || $psize < $minSize) {
		    $minSize = $psize;
		}
849
850
851
852
	    }
	    if ($LVM_ONEPARTPERDISK && defined($lppath)) {
		push(@blockdevs, $lppath);
		$totalSize += $lpsize;
853
854
855
		if (!defined($minSize) || $lpsize < $minSize) {
		    $minSize = $lpsize;
		}
856
857
	    }
	}
858
	if (@blockdevs == 0) {
859
860
861
862
863
	    print STDERR "ERROR: findSpareDisks found no disks for LVM!\n";
	    TBScriptUnlock();
	    return -1;
	}
		    
864
	my $blockdevstr = join(' ', sort @blockdevs);
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895

	#
	# If we are doing a reliable LVM setup, setup an mdadm RAID10
	# with two copies. This seems to be the least expensive form
	# of redundancy we can get (as opposed to using RAID5 when there
	# are three or more disks).
	#
	# Note that this setup is unique to mdadm and is equivalent to
	# RAID1 with two disks, and equivalent to RAID1+0 (i.e., what is
	# typically referred to as "RAID10") with four disks.
	#
	if ($LVM_RAID) {
	    my $rdev = "/dev/md/xen";
	    my $rargs;
	    my $ndevs = int(@blockdevs);

	    if ($ndevs == 1) {
		print STDERR "WARNING: only one disk/partition available, ".
		    "not configuring RAID.\n";
		$LVM_RAID = 0;
		goto again;
	    }
	    mysystem("mdadm --create --verbose $rdev ".
		     "--level=10 --raid-devices=$ndevs $blockdevstr");
	    sleep(1);
	    # XXX raid5 config lists parity drive as spare til initialized
	    mysystem("mdadm --detail --scan | sed -e 's/spares=1//' ".
		     ">>/etc/mdadm/mdadm.conf");
	    $blockdevstr = $rdev;
	}

896
897
	mysystem("pvcreate $blockdevstr");
	mysystem("vgcreate $VGNAME $blockdevstr");
898
899
900

	my $size = lvmVGSize($VGNAME);
	if ($size < $XEN_MIN_VGSIZE) {
Mike Hibler's avatar
Mike Hibler committed
901
902
903
904
905
906
907
908
	    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!
	#
909
	if ($usethin && createThinPool($blockdevstr)) {
Mike Hibler's avatar
Mike Hibler committed
910
911
912
	    print STDERR "WARNING: could not create a thin pool, ".
		"disabling golden image support\n";
	    $usethin = 0;
913
914
	}
    }
915
916
    $STRIPE_COUNT = computeStripeSize($VGNAME);
    
917
918
919
920
921
922
923
924
    #
    # 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);
925
    createDHCP();
926

927
    print "Creating scratch FS ...\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
928
    if (createExtraFS($EXTRAFS, $VGNAME, "25G")) {
929
930
931
	TBScriptUnlock();
	return -1;
    }
932
    print "Creating image metadata FS ...\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
933
    if (createExtraFS($METAFS, $VGNAME, "1G")) {
Leigh B Stoller's avatar
Leigh B Stoller committed
934
935
936
	TBScriptUnlock();
	return -1;
    }
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
    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
957
958
959
960
961
    if (InitializeRouteTables()) {
	print STDERR "*** Could not initialize routing table DB\n";
	TBScriptUnlock();
	return -1;
    }
962

963
964
965
966
967
    #
    # 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
968
969
970
971
972
973
    #
    # 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");

974
975
976
    #
    # Need these to avoid overflowing the NAT tables.
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
977
978
979
980
981
982
    mysystem2("$MODPROBE nf_conntrack");
    if ($?) {
	print STDERR "ERROR: could not load nf_conntrack module!\n";
	TBScriptUnlock();
	return -1;
    }
983
    mysystem2("$SYSCTL -w ".
984
	     "  net.netfilter.nf_conntrack_generic_timeout=120");
985
    mysystem2("$SYSCTL -w ".
986
	     "  net.netfilter.nf_conntrack_tcp_timeout_established=54000");
987
    mysystem2("$SYSCTL -w ".
988
	     "  net.netfilter.nf_conntrack_max=131071");
989
    mysystem2("echo 16384 > /sys/module/nf_conntrack/parameters/hashsize");
990
991
992
993
994
995
996
 
    # 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");

997
    mysystem("touch /var/run/xen.ready");
Mike Hibler's avatar
Mike Hibler committed
998
999
    TBDebugTimeStamp("  releasing global lock")
	if ($lockdebug);
1000
    TBScriptUnlock();
Jon Rafkind's avatar
Jon Rafkind committed
1001
1002
1003
    return 0;
}

1004
sub rootPreConfigNetwork($$$$)
1005
{
1006
1007
1008
    my ($vnode_id, undef, $vnconfig, $private) = @_;
    my @node_ifs = @{ $vnconfig->{'ifconfig'} };
    my @node_lds = @{ $vnconfig->{'ldconfig'} };
Jon Rafkind's avatar
Jon Rafkind committed
1009

Mike Hibler's avatar
Mike Hibler committed
1010
1011
    TBDebugTimeStamp("rootPreConfigNetwork: grabbing global lock $GLOBAL_CONF_LOCK")
	if ($lockdebug);
1012
1013
1014
    if (TBScriptLock($GLOBAL_CONF_LOCK,
		     TBSCRIPTLOCK_INTERRUPTIBLE(), 900) != TBSCRIPTLOCK_OKAY()){
	print STDERR "Could not get the global lock!\n";
1015
1016
	return -1;
    }
Mike Hibler's avatar
Mike Hibler committed
1017
1018
    TBDebugTimeStamp("  got global lock")
	if ($lockdebug);
1019

1020
    createDHCP()
1021
	if (! -e $DHCPCONF_FILE && ! -e $NEW_DHCPCONF_FILE);
1022

1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
    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");
	}
    }

1034
1035
1036
1037
1038
1039
    #
    # 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
1040

Mike Hibler's avatar
Mike Hibler committed
1041
1042
    TBDebugTimeStamp("  releasing global lock")
	if ($lockdebug);
1043
    TBScriptUnlock();
1044
1045
1046
1047
1048
    # XXX let vnodesetup exit early
    if ($vsrelease eq "immediate") {
	TBDebugTimeStamp("rootPreConfigNetwork: touching $VMS/$vnode_id/running");
	mysystem2("touch $VMS/$vnode_id/running");
    }
Jon Rafkind's avatar
Jon Rafkind committed
1049
    return 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
1050
1051
1052
bad:
    TBScriptUnlock();
    return -1;
Jon Rafkind's avatar
Jon Rafkind committed
1053
1054
}

1055
1056
sub rootPostConfig($)
{
Jon Rafkind's avatar
Jon Rafkind committed
1057
1058
1059
    return 0;
}

1060
1061
#
# Create the basic context for the VM and give it a unique ID for identifying
1062
1063
# "internal" state.  If $raref is set, then we are in a RELOAD state machine
# and need to walk the appropriate states.
1064
#
1065
sub vnodeCreate($$$$)
1066
{
1067
    my ($vnode_id, undef, $vnconfig, $private) = @_;
1068
    my $attributes = $vnconfig->{'attributes'};
1069
    my $imagename = $vnconfig->{'image'};
Leigh B Stoller's avatar
Leigh B Stoller committed
1070
    my $raref = $vnconfig->{'reloadinfo'};
1071
    my $vninfo = $private;
1072
    my %image = %defaultImage;
Leigh B Stoller's avatar
Leigh B Stoller committed
1073
    my $imagemetadata;
1074
    my $lvname;
1075
    my $inreload = 0;
Mike Hibler's avatar
Mike Hibler committed
1076
    my $dothinlv = doingThinLVM();
1077
1078

    my $vmid;
1079
    if ($vnode_id =~ /^[-\w]+\-(\d+)$/) {
1080
1081
1082
1083
1084
	$vmid = $1;
    }
    else {
	fatal("xen_vnodeCreate: bad vnode_id $vnode_id!");
    }
1085
1086
    $vninfo->{'vmid'} = $vmid;

1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
    #
    # XXX future optimization possibility.
    #
    # Try to be smart about holding the vnode creation lock which is not
    # a single lock, but rather a small set of locks intended to limit
    # concurrency in the vnode creation process. Specifically, if we grab
    # a create_vnode lock and then block waiting for our image lock, then
    # we might prevent someone else (using a different image) from making 
    # progress. So we could instead: grab a create_vnode lock, make a short
    # attempt (5-10 seconds) to grab the image lock and, failing that, back
    # off of the create_vnode lock, wait and then try the whole process again.
    #
    # The problem is that we may block again down in downloadOneImage when
    # we try to grab the image lock exclusively. Not sure we can back all
    # the way out easily in that case!
    #
    # This is also a bit of a de-optimization when we have a set of vnodes
    # all using the same image. We just cause a bit of excess context
    # switching in that (probably more common) case.
    #

Leigh B Stoller's avatar
Leigh B Stoller committed
1108
    if (CreateVnodeLock() != 0) {
1109
	fatal("CreateVnodeLock()");
Leigh B Stoller's avatar
Leigh B Stoller committed
1110
1111
1112
1113
1114
1115
    }

    #
    # 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.
1116
    #
1117
    my $imagelockname = ImageLockName($imagename);
Mike Hibler's avatar
Mike Hibler committed
1118
1119
    TBDebugTimeStamp("grabbing image lock $imagelockname shared")
	if ($lockdebug);
1120
1121
    if (TBScriptLock($imagelockname,
		     TBSCRIPTLOCK_INTERRUPTIBLE()|TBSCRIPTLOCK_SHAREDLOCK(),
1122
		     $MAXIMAGEWAIT) != TBSCRIPTLOCK_OKAY()) {
1123
	fatal("Could not get $imagelockname lock!");
1124
    }
Mike Hibler's avatar
Mike Hibler committed
1125
1126
    TBDebugTimeStamp("  got image lock")
	if ($lockdebug);
1127

1128
1129
1130
1131
    #
    # No image specified, use a default based on the dom0 OS.
    #
    if (!defined($imagename)) {
1132
1133
	$lvname = $image{'name'};
	
1134
1135
1136
1137
1138
1139
	#
	# 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'};
1140
1141
	print STDERR "xen_vnodeCreate: ".
	    "no image specified, using default ('$imagename')\n";
1142

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

1146
	$lvname = ImageLVName($imagename);
1147
	if (!lvmFindVolume($lvname) && !defined($imagemetadata)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1148
1149
1150
1151
	    
	    #
	    # Need an exclusive lock for this.
	    #
Mike Hibler's avatar
Mike Hibler committed
1152
1153
	    TBDebugTimeStamp("  releasing image lock")
		if ($lockdebug);
Leigh B Stoller's avatar
Leigh B Stoller committed
1154
	    TBScriptUnlock();	    
Mike Hibler's avatar
Mike Hibler committed
1155
1156
	    TBDebugTimeStamp("grabbing image lock $imagelockname exclusive")
		if ($lockdebug);
1157
1158
	    if (TBScriptLock($imagelockname, TBSCRIPTLOCK_INTERRUPTIBLE(),
			     $MAXIMAGEWAIT) != TBSCRIPTLOCK_OKAY()) {
1159
		fatal("Could not get $imagelockname write lock!");
Leigh B Stoller's avatar
Leigh B Stoller committed
1160
	    }
Mike Hibler's avatar
Mike Hibler committed
1161
1162
	    TBDebugTimeStamp("  got image lock")
		if ($lockdebug);
Leigh B Stoller's avatar
Leigh B Stoller committed
1163
	    # And now check again in case someone else snuck in.
1164
	    if (!lvmFindVolume($lvname) && createRootDisk($imagename)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1165
1166
1167
1168
1169
		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
1170
1171
	    TBDebugTimeStamp("  releasing image lock")
		if ($lockdebug);
1172
	    TBScriptUnlock();
Mike Hibler's avatar
Mike Hibler committed
1173
1174
	    TBDebugTimeStamp("grabbing image lock $imagelockname shared")
		if ($lockdebug);
1175
1176
	    if (TBScriptLock($imagelockname,
			     TBSCRIPTLOCK_INTERRUPTIBLE()|
1177
			     TBSCRIPTLOCK_SHAREDLOCK(), $MAXIMAGEWAIT)
Leigh B Stoller's avatar
Leigh B Stoller committed
1178
1179
1180
1181
1182
		!= TBSCRIPTLOCK_OKAY()) {
		fatal("Could not get $imagelockname lock back ".
		      "after a long time!");
	    }
	    $imagemetadata = undef;
1183
	}
1184
    }
1185
1186
1187
1188
1189
    elsif (!defined($raref)) {
	#
	# Boot existing image. The base volume has to exist, since we do
	# not have any reload info to get it.
	#
1190
	$lvname = ImageLVName($imagename);
1191
	if (!lvmFindVolume($lvname)) {
1192
	    TBScriptUnlock();
1193
1194
1195
	    fatal("xen_vnodeCreate: ".
		  "cannot find logical volume for $lvname, and no reload info");
	}
1196
    }
1197
    else {
1198
	$lvname = ImageLVName($imagename);
1199
1200
1201
	$inreload = 1;

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

1203
	# Tell stated we are getting ready for a reload
1204
	libutil::setState("RELOADSETUP");
1205
1206
1207
1208
1209
1210
1211

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

Mike Hibler's avatar
Mike Hibler committed
1214
	if (createImageDisk($imagename, $vnode_id, $raref, $dothinlv)) {
1215
1216
	    # XXX not strictly necessary since our caller will send TBFAILED
	    libutil::setState("RELOADFAILED");
1217
	    TBScriptUnlock();
1218
1219
1220
	    fatal("xen_vnodeCreate: ".
		  "cannot create logical volume for $imagename");
	}
1221
1222
    }

Leigh B Stoller's avatar
Leigh B Stoller committed
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
    #
    # Load this from disk.
    #
    if (!defined($imagemetadata)) {
	if (LoadImageMetadata($imagename, \$imagemetadata)) {
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: ".
		  "cannot load image metadata for $imagename");
	}
    }

1234
    #
1235
    # See if the image is really a package.
1236
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
1237
1238
1239
1240
1241
    if (exists($imagemetadata->{'ISPACKAGE'}) && $imagemetadata->{'ISPACKAGE'}){
	my $imagepath = lvmVolumePath($lvname);
	# In case of reboot.
	mysystem("mkdir -p /mnt/$imagename")
	    if (! -e "/mnt/$imagename");
1242
1243
	mysystem("mount $imagepath /mnt/$imagename")
	    if (! -e "/mnt/$imagename/.mounted");
1244

1245
1246
1247
1248
1249
	mysystem2("$RESTOREVM -t $VMDIR/$vnode_id $vnode_id /mnt/$imagename");
	if ($?) {
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: ".
		  "cannot restore logical volumes from $imagename");
1250
	}
1251
1252
	if ($inreload) {
	    libutil::setState("RELOADDONE");
1253
1254
1255
	    # XXX why do we need to wait for this to take effect?
	    print "waiting 4 sec after asserting RELOADDONE...\n"
		if ($sleepdebug);
1256
1257
	    sleep(4);
	}
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
	
	#
	# 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;
1279
1280
1281
1282
1283
1284
	#
	# 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.
	#
1285
1286
1287
1288