libvnode_xen.pm 160 KB
Newer Older
Jon Rafkind's avatar
Jon Rafkind committed
1
#!/usr/bin/perl -wT
2
#
3
# Copyright (c) 2008-2018 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 $FSCK	= "/sbin/e2fsck";
130
my $FSCKUFS	= "/sbin/fsck.ufs";
131
my $debug  = 0;
132
my $lockdebug = 1;
133
134
135
136
137
138
139
140
141
142
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"
143

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

151
152
153
154
155
156
157
158
159
160
161
162
#
# 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;

163
164
165
166
167
168
169
170
171
172
173
174
#
# 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.
Mike Hibler's avatar
Mike Hibler committed
175
176
177
178
#	-T: Put out a timestamp if there has been no previous output
#	    for at least 10 seconds.
#	-L: In conjunction with -T, the timestamp message includes how
#	    long it has been since the last output.
179
180
181
182
183
#	-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";
Mike Hibler's avatar
Mike Hibler committed
184
my $CAPTUREOPTS	= "-i -C -L -T 10 -R 2000";
185

Mike Hibler's avatar
Mike Hibler committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#
# 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; }
208

209
210
211
212
213
214
215
216
##
## Randomly chosen convention section
##

# global lock
my $GLOBAL_CONF_LOCK = "xenconf";

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

# where all our config files go
231
232
my $VMS    = "/var/emulab/vms";
my $VMDIR  = "$VMS/vminfo";
233
234
my $XENDIR = "/var/xen";

235
# Extra space for capture/restore.
236
my $EXTRAFS = "/capture";
237

238
# Extra space for image metadata between reloads.
Leigh B Stoller's avatar
Leigh B Stoller committed
239
my $METAFS = "/metadata";
240
241
# So we can ask this from outside;
sub METAFS()  { return $METAFS; }
Leigh B Stoller's avatar
Leigh B Stoller committed
242

243
244
245
# Extra space for vminfo (/var/emulab/vms) between reloads.
my $INFOFS = "/vminfo";

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

##
## Indefensible, arbitrary constant section
##

# Minimum memory for dom0
my $MIN_MB_DOM0MEM = 256;

Mike Hibler's avatar
Mike Hibler committed
258
#
259
# Minimum acceptible size (in GB) of LVM VG for domUs.
Mike Hibler's avatar
Mike Hibler committed
260
261
262
263
264
265
#
# 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;
266

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

Leigh B Stoller's avatar
Leigh B Stoller committed
297
298
299
300
301
302
303
304
305
306
307
# 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;

308
309
310
# Striping
my $STRIPE_COUNT   = 1;

311
312
313
# Setup a RAID10 underneath the LVM
my $LVM_RAID = SHAREDHOST() ? 1 : 0;

314
315
316
# Avoid using SSDs unless there are only SSDs
my $LVM_AVOIDSSD = 1;

317
318
319
# Whether or not to use only unpartitioned (unused) disks to form the Xen VG.
my $LVM_FULLDISKONLY = 0;

320
321
# Whether or not to use partitions only when they are big.
my $LVM_ONLYLARGEPARTS = 1;
322
my $LVM_LARGEPARTPCT = 10;
323
324
325

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

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

336
337
my $ISREMOTENODE = REMOTEDED();
my $BRIDGENAME   = "xenbr0";
338
my $VIFROUTING   = ((-e "$ETCDIR/xenvifrouting") ? 1 : 0);
339

340
341
my $TMCD_PORT	 = 7777;

342
343
344
345
346
#
# Information about the running Xen hypervisor
#
my %xeninfo = ();

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

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

    while (<XM>) {
	    chomp;
	    /^(\S+)\s*:\s+(.*)$/;
	    $xeninfo{$1} = $2;
    }
    
    close XM;
}
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
#
# 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;
497
	    } elsif ($cpus <= 2 || $disks <= 2 || $ram <= 2048) {
498
499
500
501
502
503
504
505
506
		$MAXCONCURRENT = 3;
	    } else {
		$MAXCONCURRENT = 5;
	    }
	}
    }
    print STDERR "Limiting to $MAXCONCURRENT concurrent vnode creations.\n";
}

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

    makeIfaceMaps();
    makeBridgeMaps();
513

Mike Hibler's avatar
Mike Hibler committed
514
515
516
517
518
519
    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`;
    }
520
521
522
    if ($toolstack =~ /xl$/) {
	$XM = "/usr/sbin/xl";
    }
523
    getXenInfo();
524

Mike Hibler's avatar
Mike Hibler committed
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
    # 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;
	}
    }

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

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

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

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

    return "image+" . $imagename;
}
575

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	    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;
	}

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

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

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

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

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

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

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

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

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

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

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

Mike Hibler's avatar
Mike Hibler committed
1042
1043
    TBDebugTimeStamp("  releasing global lock")
	if ($lockdebug);
1044
    TBScriptUnlock();
1045
1046
1047
1048
1049
    # 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
1050
    return 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
1051
1052
1053
bad:
    TBScriptUnlock();
    return -1;
Jon Rafkind's avatar
Jon Rafkind committed
1054
1055
}

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

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

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

1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
    #
    # 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
1109
    if (CreateVnodeLock() != 0) {
1110
	fatal("CreateVnodeLock()");
Leigh B Stoller's avatar
Leigh B Stoller committed
1111
1112
1113
1114
1115
1116
    }

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

1129
1130
    #
    # No image specified, use a default based on the dom0 OS.
1131
    # XXX this option no longer works, you must specify an OSID.
1132
1133
    #
    if (!defined($imagename)) {
1134
1135
1136
	fatal("xen_vnodeCreate: ".
	      "no longer support default image for vnodes, ".
	      "must specify an OSID");
1137
    }
1138
1139
1140
1141
1142
    elsif (!defined($raref)) {
	#
	# Boot existing image. The base volume has to exist, since we do
	# not have any reload info to get it.
	#
1143
	$lvname = ImageLVName($imagename);
1144
	if (!lvmFindVolume($lvname)) {
1145
	    TBScriptUnlock();
1146
1147
1148
	    fatal("xen_vnodeCreate: ".
		  "cannot find logical volume for $lvname, and no reload info");
	}
1149
    }
1150
    else {
1151
	$lvname = ImageLVName($imagename);
1152
1153
1154
	$inreload = 1;

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

1156
	# Tell stated we are getting ready for a reload
1157
	libutil::setState("RELOADSETUP");
1158
1159
1160
1161
1162
1163
1164

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

Mike Hibler's avatar
Mike Hibler committed
1167
	if (createImageDisk($imagename, $vnode_id, $raref, $dothinlv)) {
1168
1169
	    # XXX not strictly necessary since our caller will send TBFAILED
	    libutil::setState("RELOADFAILED");
1170
	    TBScriptUnlock();
1171
1172
1173
	    fatal("xen_vnodeCreate: ".
		  "cannot create logical volume for $imagename");
	}
1174
1175
    }

Leigh B Stoller's avatar
Leigh B Stoller committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
    #
    # Load this from disk.
    #
    if (!defined($imagemetadata)) {
	if (LoadImageMetadata($imagename, \$imagemetadata)) {
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: ".
		  "cannot load image metadata for $imagename");
	}
    }

1187
    #
1188
    # See if the image is really a package.
1189
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
1190
1191
1192
1193
1194
    if (exists($imagemetadata->{'ISPACKAGE'}) && $imagemetadata->{'ISPACKAGE'}){
	my $imagepath = lvmVolumePath($lvname);
	# In case of reboot.
	mysystem("mkdir -p /mnt/$imagename")
	    if (! -e "/mnt/$imagename");
1195
1196
	mysystem("mount $imagepath /mnt/$imagename")
	    if (! -e "/mnt/$imagename/.mounted");
1197

1198
1199
1200
1201
1202
	mysystem2("$RESTOREVM -t $VMDIR/$vnode_id $vnode_id /mnt/$imagename");
	if ($?) {
	    TBScriptUnlock();
	    fatal("xen_vnodeCreate: ".
		  "cannot restore logical volumes from $imagename");
1203
	}
1204
1205
	if ($inreload) {
	    libutil::setState("RELOADDONE");
1206
1207
1208
	    # XXX why do we need to wait for this to take effect?
	    print "waiting 4 sec after asserting RELOADDONE...\n"
		if ($sleepdebug);
1209
1210
	    sleep(4);
	}
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
	
	#
	# 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;
1232
1233
1234
1235
1236
1237
	#
	# 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.
	#
1238
1239
1240
1241
1242
	if (exists($attributes->{'XEN_EXTRAFS'})) {
	    my $dsize   = $attributes->{'XEN_EXTRAFS'};
	    my $auxchar = ord('c');
	    my @stanzas = ();
	    
1243
	    my $dpre = "xvd";
1244
1245
	    foreach my $disk (keys(%{$private->{'disks'}})) {
		my ($lvname,$vndisk,$vdisk) = @{$private->{'disks'}->{$disk}};
1246
1247
1248
1249
1250
		if ($vdisk =~ /^(sd)(\w)$/ || $vdisk =~ /^(xvd)(\w)$/ ||
		    $vdisk =~ /^(hd)(\w)$/) {
		    $dpre = $1;
		    $auxchar = ord($2)
			if (ord($2) > $auxchar);
1251
1252
1253
1254
		}
		# Generate a new set of stanzas. see below.
		push(@stanzas, "'phy:$vndisk,$vdisk,w'");
	    }
1255
	    my $vdisk = $dpre .	chr($auxchar);
1256
1257
	    my $auxlvname = "${vnode_id}.${vdisk}";
	    
1258
	    if (!lvmFindVolume($auxlvname)) {
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
		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);
1272
1273
1274

	    # Cause we have no idea.
	    $private->{'os'} = "other";
1275
	}
1276
	
Mike Hibler's avatar
Mike Hibler committed
1277
1278
	TBDebugTimeStamp("  releasing image lock")
	    if ($lockdebug);