libvnode_openvz.pm 61.3 KB
Newer Older
1
#!/usr/bin/perl -w
2
3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2008-2012 University of Utah and the Flux Group.
5
6
7
8
9
10
11
# All rights reserved.
#
# Implements the libvnode API for OpenVZ support in Emulab.
#
package libvnode_openvz;
use Exporter;
@ISA    = "Exporter";
12
@EXPORT = qw( vz_init vz_setDebug
13
14
              vz_rootPreConfig vz_rootPreConfigNetwork vz_rootPostConfig 
              vz_vnodeCreate vz_vnodeDestroy vz_vnodeState 
15
              vz_vnodeBoot vz_vnodeHalt vz_vnodeReboot 
16
              vz_vnodePreConfig vz_vnodeUnmount vz_vnodeTearDown
17
18
              vz_vnodePreConfigControlNetwork vz_vnodePreConfigExpNetwork 
              vz_vnodeConfigResources vz_vnodeConfigDevices
19
              vz_vnodePostConfig vz_vnode vz_vnodeExec
20
21
22
23
24
25
26
27
28
            );

%ops = ( 'init' => \&vz_init,
	 'setDebug' => \&vz_setDebug,
	 'rootPreConfig' => \&vz_rootPreConfig,
	 'rootPreConfigNetwork' => \&vz_rootPreConfigNetwork,
	 'rootPostConfig' => \&vz_rootPostConfig,
	 'vnodeCreate' => \&vz_vnodeCreate,
	 'vnodeDestroy' => \&vz_vnodeDestroy,
29
	 'vnodeTearDown' => \&vz_vnodeTearDown,
30
31
32
	 'vnodeState' => \&vz_vnodeState,
	 'vnodeBoot' => \&vz_vnodeBoot,
	 'vnodeHalt' => \&vz_vnodeHalt,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
33
	 'vnodeUnmount' => \&vz_vnodeUnmount,
34
	 'vnodeReboot' => \&vz_vnodeReboot,
35
	 'vnodeExec' => \&vz_vnodeExec,
36
37
38
39
40
41
42
43
44
45
46
	 'vnodePreConfig' => \&vz_vnodePreConfig,
	 'vnodePreConfigControlNetwork' => \&vz_vnodePreConfigControlNetwork,
	 'vnodePreConfigExpNetwork' => \&vz_vnodePreConfigExpNetwork,
	 'vnodeConfigResources' => \&vz_vnodeConfigResources,
	 'vnodeConfigDevices' => \&vz_vnodeConfigDevices,
	 'vnodePostConfig' => \&vz_vnodePostConfig,
    );


use strict;
use English;
47
48
BEGIN { @AnyDBM_File::ISA = qw(DB_File GDBM_File NDBM_File) }
use AnyDBM_File;
49
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
50
use Socket;
51
52
53
54

# Pull in libvnode
require "/etc/emulab/paths.pm"; import emulabpaths;
use libvnode;
55
use libtestbed;
56
use libsetup;
57

58
59
60
61
62
63
64
65
66
67
#
# Turn off line buffering on output
#
$| = 1;

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

David Johnson's avatar
David Johnson committed
68
my $defaultImage = "emulab-default";
69

70
my $DOLVM = 1;
71
72
73
74
75
my $DOLVMDEBUG = 0;
my $LVMDEBUGOPTS = "-vvv -dddddd";

my $DOVZDEBUG = 0;
my $VZDEBUGOPTS = "--verbose";
76

77
78
my $GLOBAL_CONF_LOCK = "vzconf";

79
80
sub VZSTAT_RUNNING() { return "running"; }
sub VZSTAT_STOPPED() { return "stopped"; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
81
sub VZSTAT_MOUNTED() { return "mounted"; }
82
83
84
85

my $VZCTL  = "/usr/sbin/vzctl";
my $VZLIST = "/usr/sbin/vzlist";
my $IFCONFIG = "/sbin/ifconfig";
86
my $NETSTAT  = "/bin/netstat";
87
88
89
90
91
my $ROUTE = "/sbin/route";
my $BRCTL = "/usr/sbin/brctl";
my $IPTABLES = "/sbin/iptables";
my $MODPROBE = "/sbin/modprobe";
my $RMMOD = "/sbin/rmmod";
92
my $VLANCONFIG = "/sbin/vconfig";
93
my $IP = "/sbin/ip";
94
95
96
97
98

my $VZRC   = "/etc/init.d/vz";
my $MKEXTRAFS = "/usr/local/etc/emulab/mkextrafs.pl";

my $CTRLIPFILE = "/var/emulab/boot/myip";
99
my $IMQDB      = "/var/emulab/db/imqdb";
100
101
# The kernel will auto create up to 1024 IMQs
my $MAXIMQ     = 1024;
102
103
104
105
106

my $CONTROL_IFNUM  = 999;
my $CONTROL_IFDEV  = "eth${CONTROL_IFNUM}";
my $EXP_BASE_IFNUM = 0;

107
108
109
110
111
my $RTDB           = "/var/emulab/db/rtdb";
my $RTTABLES       = "/etc/iproute2/rt_tables";
# Temporary; later kernel version increases this.
my $MAXROUTETTABLE = 255;

112
113
114
115
116
my $debug = 0;

# XXX needs lifting up
my $JAILCTRLNET = "172.16.0.0";
my $JAILCTRLNETMASK = "255.240.0.0";
117

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
my $USE_NETEM = 0;
my $USE_MACVLAN = 0;

#
# If we are using a modern kernel, use netem instead of our own plr/delay
# qdiscs (which are no longer maintained as of 11/2011).
#
my ($kmaj,$kmin,$kpatch) = libvnode::getKernelVersion();
print STDERR "Got Linux kernel version numbers $kmaj $kmin $kpatch\n";
if ($kmaj >= 2 && $kmin >= 6 && $kpatch >= 32) {
    print STDERR "Using Linux netem instead of custom qdiscs.\n";
    $USE_NETEM = 1;
    print STDERR "Using Linux macvlan instead of OpenVZ veths.\n";
    $USE_MACVLAN = 1;
}

134
135
136
137
138
139
140
141
142
#
# Helpers.
#
sub findControlNet();
sub makeIfaceMaps();
sub makeBridgeMaps();
sub findIface($);
sub findMac($);
sub editContainerConfigFile($$);
143
144
145
146
sub InitializeRouteTable();
sub AllocateRouteTable($);
sub LookupRouteTable($);
sub FreeRouteTable($);
147
148
149
150
sub vmexists($);
sub vmstatus($);
sub vmrunning($);
sub vmstopped($);
151
152
sub GClvm($);
sub GCbridge($);
153
154
155
156
157
158
159
160

#
# Initialize the lib (and don't use BEGIN so we can do reinit).
#
sub vz_init {
    makeIfaceMaps();
    makeBridgeMaps();

161
162
163
    #
    # Turn off LVM if already using a /vz mount.
    #
164
    if (-e "/vz/.nolvm" || -e "/vz.save/.nolvm" || -e "/.nolvm") {
165
	$DOLVM = 0;
166
	mysystem("/sbin/dmsetup remove_all");
167
    }
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

    #
    # Enable/disable LVM debug options.
    #
    if (-e "/vz/.lvmdebug" || -e "/vz.save/.lvmdebug" || -e "/.lvmdebug") {
	$DOLVMDEBUG = 1;
    }
    if (!$DOLVMDEBUG) {
	$LVMDEBUGOPTS = "";
    }

    #
    # Enable/disable VZ debug options.
    #
    if (-e "/vz/.vzdebug" || -e "/vz.save/.vzdebug" || -e "/.vzdebug") {
	$DOVZDEBUG = 1;
    }
    if (!$DOVZDEBUG) {
	$VZDEBUGOPTS = "";
    }

189
190
191
192
193
194
195
    return 0;
}

#
# Prepare the root context.  Run once at boot.
#
sub vz_rootPreConfig {
196
197
198
199
200
201
202
    #
    # Only want to do this once, so use file in /var/run, which
    # is cleared at boot.
    #
    return 0
	if (-e "/var/run/openvz.ready");

203
    if ((my $locked = TBScriptLock($GLOBAL_CONF_LOCK,
204
				   TBSCRIPTLOCK_GLOBALWAIT(), 900)) 
205
206
207
208
209
210
	!= TBSCRIPTLOCK_OKAY()) {
	return 0
	    if ($locked == TBSCRIPTLOCK_IGNORE());
	print STDERR "Could not get the vzinit lock after a long time!\n";
	return -1;
    }
211
212
213
214
215
    # we must have the lock, so if we need to return right away, unlock
    if (-e "/var/run/openvz.ready") {
        TBScriptUnlock();
        return 0;
    }
216
217
    mysystem("$VZRC stop");
    
218
    # make sure filesystem is setup 
219
    if ($DOLVM) {
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
	# be ready to snapshot later on...
	open(FD, "gunzip -c /proc/config.gz |");
	my $snapshot = "n";
	while (my $line = <FD>) {
	    if ($line =~ /^CONFIG_DM_SNAPSHOT=([yYmM])/) {
		$snapshot = $1;
		last;
	    }
	}
	close(FD);
	if ($snapshot eq 'n' || $snapshot eq 'N') {
	    print STDERR "ERROR: this kernel does not support LVM snapshots!\n";
	    TBScriptUnlock();
	    return -1;
	}
	elsif ($snapshot eq 'm' || $snapshot eq 'M') {
	    mysystem("$MODPROBE dm-snapshot");
	}

239
	if (system("vgs $LVMDEBUGOPTS | grep -E -q '^[ ]+openvz.*\$'")) {
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
	    my $blockdevs = "";
	    my %devs = libvnode::findSpareDisks();
	    my $totalSize = 0;
	    foreach my $dev (keys(%devs)) {
		if (defined($devs{$dev}{"size"})) {
		    $blockdevs .= " /dev/$dev";
		    $totalSize += $devs{$dev}{"size"};
		}
		else {
		    foreach my $part (keys(%{$devs{$dev}})) {
			$blockdevs .= " /dev/${dev}${part}";
			$totalSize += $devs{$dev}{$part}{"size"};
		    }
		}
	    }

	    if ($blockdevs eq '') {
		die "findSpareDisks found no disks, can't use LVM!\n";
	    }
		    
260
261
	    mysystem("pvcreate $LVMDEBUGOPTS $blockdevs");
	    mysystem("vgcreate $LVMDEBUGOPTS openvz $blockdevs");
262
	}
263
264
	# make sure our volumes are active -- they seem to become inactive
	# across reboots
265
	mysystem("vgchange $LVMDEBUGOPTS -a y openvz");
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281

	#
	# If we reload the partition, the logical volumes will still
	# exist but /vz will be empty. We need to recreate /vz when
	# this happens.
	#
	# XXX eventually could move this into its own logical volume, but
	# we don't ever know how many images we'll have to store.
	#
	if (! -e "/vz/template") {
	    mysystem("rm -rf /vz/*")
		if (-e "/vz");
	    mysystem("mkdir /vz")
		if (! -e "/vz");
	    mysystem("cp -pR /vz.save/* /vz/");
	}
282
    }
283
    else {
Mike Hibler's avatar
Mike Hibler committed
284
285
286
287
288
	#
	# We need to create a local filesystem.
	# First see if the "extra" filesystem has already been created,
	# Emulab often mounts it as /local for various purposes.
	#
289
	# about the funny quoting: don't ask... emacs perl mode foo.
290
	if (!system('grep -q '."'".'^/dev/.*/local.*\$'."'".' /etc/fstab')) {
Mike Hibler's avatar
Mike Hibler committed
291
292
293
294
295
296
297
298
299
300
301
	    # local filesystem already exists, just create a subdir
	    if (! -d "/local/vz") {
		mysystem("$VZRC stop");
		mysystem("mkdir /local/vz");
		mysystem("cp -pR /vz.save/* /local/vz/");
		mysystem("touch /local/vz/.nolvm");
	    }
	    if (-e "/vz") {
		mysystem("rm -rf /vz");
		mysystem("ln -s /local/vz /vz");
	    }
302
	}
Mike Hibler's avatar
Mike Hibler committed
303
304
	else {
	    # about the funny quoting: don't ask... emacs perl mode foo.
305
	    if (system('grep -q '."'".'^/dev/.*/vz.*\$'."'".' /etc/fstab')) {
Mike Hibler's avatar
Mike Hibler committed
306
307
308
309
310
311
312
313
314
315
316
		mysystem("$VZRC stop");
		mysystem("rm -rf /vz")
		    if (-e "/vz");
		mysystem("mkdir /vz");
		mysystem("$MKEXTRAFS -f /vz");
		mysystem("cp -pR /vz.save/* /vz/");
		mysystem("touch /vz/.nolvm");
	    }
	    if (system('mount | grep -q \'on /vz\'')) {
		mysystem("mount /vz");
	    }
317
	}
318
319
    }

320
321
322
323
324
325
    # We need to increase the size of the net.core.netdev_max_backlog 
    # sysctl var in the root context; not sure to what amount, or exactly 
    # why though.  Perhaps there is too much contention when handling enqueued
    # packets on the veths?
    mysystem("sysctl -w net.core.netdev_max_backlog=2048");

326
327
328
329
330
331
332
333
334
335
336
337
338
339
    #
    # Ryan figured this one out. It was causing 75% packet loss on
    # gre tunnels. 
    #
    # According to Ryan: 'loose' mode just ensures that
    # the sender's IP is reachable by at least one interface, whereas
    # 'strict' mode requires that it be reachable via the interface
    # the packet was received on. This is why the ARP request from
    # the host was being dropped; the sending IP was only reachable
    # via veth999, not the internal greX interface where the request
    # was received.
    #
    mysystem("sysctl -w net.ipv4.conf.default.rp_filter=0");

340
341
342
343
344
345
346
347
348
    # make sure the initscript is going...
    if (system("$VZRC status 2&>1 > /dev/null")) {
	mysystem("$VZRC start");
    }

    # get rid of this simple container device support
    if (!system('lsmod | grep -q vznetdev')) {
	system("$RMMOD vznetdev");
    }
349

350
351
352
353
354
355
356
357
358
359
360
361
    if ($USE_MACVLAN) {
	#
	# If we build dummy shortbridge nets atop either a physical
	# device, or atop a dummy device, load these!
	#
	mysystem("$MODPROBE macvlan");
	mysystem("$MODPROBE dummy");
    }
    else {
	# this is what we need for veths
	mysystem("$MODPROBE vzethdev");
    }
362

Leigh B. Stoller's avatar
Leigh B. Stoller committed
363
364
365
    # For tunnels
    mysystem("$MODPROBE ip_gre");

366
367
368
    # For VLANs
    mysystem("$MODPROBE 8021q");

369
370
    # we need this stuff for traffic shaping -- only root context can
    # modprobe, for now.
371
372
373
374
375
376
377
    if (!$USE_NETEM) {
	mysystem("$MODPROBE sch_plr");
	mysystem("$MODPROBE sch_delay");
    }
    else {
	mysystem("$MODPROBE sch_netem");
    }
378
379
    mysystem("$MODPROBE sch_htb");

380
381
382
383
384
385
386
387
388
389
390
391
    # make sure our network hooks are called
    if (system('grep -q -e EXTERNAL_SCRIPT /etc/vz/vznet.conf')) {
	if (! -e '/etc/vz/vznet.conf') {
	    open(FD,">/etc/vz/vznet.conf") 
		or die "could not open /etc/vz/vznet.conf: $!";
	    print FD "#!/bin/bash\n";
	    print FD "\n";
	    close(FD);
	}
	mysystem("echo 'EXTERNAL_SCRIPT=\"/usr/local/etc/emulab/vznetinit-elab.sh\"' >> /etc/vz/vznet.conf");
    }

392
393
394
395
    #
    # XXX all this network config stuff should be done in PreConfigNetwork,
    # but we can't rmmod the IMQ module to change the config, so no point.
    #
396
    mysystem("$MODPROBE imq");
397
398
    mysystem("$MODPROBE ipt_IMQ");

399
    # Create a DB to manage them. 
400
401
402
    my %MDB;
    if (!dbmopen(%MDB, $IMQDB, 0660)) {
	print STDERR "*** Could not create $IMQDB\n";
403
	TBScriptUnlock();
404
405
406
	return -1;
    }
    for (my $i = 0; $i < $MAXIMQ; $i++) {
407
408
	$MDB{"$i"} = ""
	    if (!exists($MDB{"$i"}));
409
410
    }
    dbmclose(%MDB);
411

412
413
414
415
416
    if (InitializeRouteTables()) {
	print STDERR "*** Could not initialize routing table DB\n";
	TBScriptUnlock();
	return -1;
    }
417
418
    mysystem("touch /var/run/openvz.ready");
    TBScriptUnlock();
419
420
421
422
423
424
425
426
    return 0;
}

#
# Prepare any network stuff in the root context on a global basis.  Run once
# at boot, or at reconfigure.  For openvz, this consists of creating bridges
# and configuring them as necessary.
#
427
428
# NOTE: This function must clean up any side effects if it fails partway.
#
429
sub vz_rootPreConfigNetwork {
430
431
    my ($vnode_id, undef, $vnconfig, $private) = @_;
    
432
    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
433
434
435
	print STDERR "Could not get the vznetwork lock after a long time!\n";
	return -1;
    }
436

437
438
439
440
    # Do this again after lock.
    makeIfaceMaps();
    makeBridgeMaps();
    
441
442
    my @node_ifs = @{ $vnconfig->{'ifconfig'} };
    my @node_lds = @{ $vnconfig->{'ldconfig'} };
443

444
445
446
447
448
449
450
    # setup forwarding on ctrl net -- NOTE that iptables setup to do NAT
    # actually happens per vnode now.
    my ($iface,$ip,$netmask,$maskbits,$network,$mac) = findControlNet();
    mysystem("echo 1 > /proc/sys/net/ipv4/conf/$iface/forwarding");
    # XXX only needed for fake mac hack, which should go away someday
    mysystem("echo 1 > /proc/sys/net/ipv4/conf/$iface/proxy_arp");

451
452
    #
    # If we're using veths, figure out what bridges we need to make:
453
454
455
    # we need a bridge for each physical iface that is a multiplex pipe,
    # and one for each VTAG given PMAC=none (i.e., host containing both sides
    # of a link, or an entire lan).
456
    #
457
    my %brs = ();
458
459
460
461
    my $prefix = "br.";
    if ($USE_MACVLAN) {
	$prefix = "mvsw.";
    }
462
463
    {
	foreach my $ifc (@node_ifs) {
464
465
	    next if (!$ifc->{ISVIRT});

466
467
468
469
470
471
472
	    if ($ifc->{ITYPE} eq "loop") {
		my $vtag  = $ifc->{VTAG};

		#
		# No physical device. Its a loopback (trivial) link/lan
		# All we need is a common bridge to put the veth ifaces into.
		#
473
		my $brname = "${prefix}$vtag";
474
475
476
477
		$brs{$brname}{ENCAP} = 0;
		$brs{$brname}{SHORT} = 0;
	    }
	    elsif ($ifc->{ITYPE} eq "vlan") {
478
479
		my $iface = $ifc->{IFACE};
		my $vtag  = $ifc->{VTAG};
480
481
		my $vdev  = "${iface}.${vtag}";

482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
		if (! -d "/sys/class/net/$vdev") {
		    mysystem2("$VLANCONFIG set_name_type DEV_PLUS_VID_NO_PAD");
		    mysystem2("$VLANCONFIG add $iface $vtag");
		    goto bad
			if ($?);
		    mysystem2("$VLANCONFIG set_name_type VLAN_PLUS_VID_NO_PAD");
		    mysystem2("$IFCONFIG $vdev up");
		    makeIfaceMaps();

		    #
		    # We leave this behind in case of failure and at
		    # teardown since it is possibly a shared device, and
		    # it is difficult to tell if another vnode is using it.
		    # Leaving it behind is harmless, I think.
		    #
		}
498

499
		my $brname = "${prefix}$vdev";
500
501
502
503
504
		$brs{$brname}{ENCAP} = 1;
		$brs{$brname}{SHORT} = 0;
		$brs{$brname}{PHYSDEV} = $vdev;
	    }
	    elsif ($ifc->{PMAC} eq "none") {
505
		my $brname = "${prefix}" . $ifc->{VTAG};
506
507
508
509
510
511
512
513
514
515
516
517
		# if no PMAC, we don't need encap on the bridge
		$brs{$brname}{ENCAP} = 0;
		# count up the members so we can figure out if this is a shorty
		if (!exists($brs{$brname}{MEMBERS})) {
		    $brs{$brname}{MEMBERS} = 0;
		}
		else {
		    $brs{$brname}{MEMBERS}++;
		}
	    }
	    else {
		my $iface = findIface($ifc->{PMAC});
518
		my $brname = "${prefix}$iface";
519
520
521
522
523
524
525
		$brs{$brname}{ENCAP} = 1;
		$brs{$brname}{SHORT} = 0;
		$brs{$brname}{PHYSDEV} = $iface;
	    }
	}
    }

526
527
528
529
530
531
    #
    # Make bridges and add phys ifaces.
    #
    # Or, in the macvlan case, create a dummy device if there is no
    # underlying physdev to "host" the macvlan.
    #
532
533
534
535
536
537
538
539
540
541
542
543
    foreach my $k (keys(%brs)) {
	# postpass to setup SHORT if only two members and no PMAC
	if (exists($brs{$k}{MEMBERS})) {
	    if ($brs{$k}{MEMBERS} == 2) {
		$brs{$k}{SHORT} = 1;
	    }
	    else {
		$brs{$k}{SHORT} = 0;
	    }
	    $brs{$k}{MEMBERS} = undef;
	}

544
545
546
	if (!$USE_MACVLAN) {
	    # building bridges is an important activity
	    if (! -d "/sys/class/net/$k/bridge") {
547
548
549
550
551
		mysystem2("$BRCTL addbr $k");
		goto bad
		    if ($?);
		# record bridge created.
		$private->{'bridges'}->{$k} = $k;
552
553
	    }
	    # repetitions of this should not hurt anything
554
	    mysystem2("$IFCONFIG $k 0 up");
555
556
557
	}

	if (exists($brs{$k}{PHYSDEV})) {
558
	    if (!$USE_MACVLAN) {
559
560
561
		# make sure this iface isn't already part of another bridge;
		# if it it is, remove it from there first and add to
		# this bridge.
562
563
		my $obr = findBridge($brs{$k}{PHYSDEV});
		if (defined($obr)) {
564
565
566
		    mysystem2("$BRCTL delif " . $obr . " " .$brs{$k}{PHYSDEV});
		    goto bad
			if ($?);
567
568
569
		    # rebuild hashes
		    makeBridgeMaps();
		}
570
571
572
573
574
		mysystem2("$BRCTL addif $k $brs{$k}{PHYSDEV}");
		goto bad
		    if ($?);
		# record iface added to bridge 
		$private->{'bridgeifaces'}->{$k}->{$brs{$k}{PHYSDEV}} = $k;
575
	    }
576
577
578
579
	}
	elsif ($USE_MACVLAN
	       && ! -d "/sys/class/net/$k") {
	    # need to create a dummy device to "host" the macvlan ports
580
581
582
583
584
	    mysystem2("$IP link add name $k type dummy");
	    goto bad
		if ($?);
	    # record dummy created
	    $private->{'dummys'}->{$k} = $k;
585
586
587
	}
    }

588
    #
589
    # Use the IMQDB to reserve the devices to the container. We have the lock.
590
    #
591
592
593
    my %MDB;
    if (!dbmopen(%MDB, $IMQDB, 0660)) {
	print STDERR "*** Could not create $IMQDB\n";
594
	goto bad;
595
596
    }
    my $i = 0;
597
598
    {
        foreach my $ldc (@node_lds) {
599
	    if ($ldc->{"TYPE"} eq 'duplex') {
600
601
602
603
		while ($i < $MAXIMQ) {
		    my $current = $MDB{"$i"};

		    if (!defined($current) ||
604
605
			$current eq "" || $current eq $vnode_id) {
			$MDB{"$i"} = $vnode_id;
606
			$i++;
607
608
			# Record imq in use
			$private->{'imqs'}->{"$i"} = $i;
609
610
611
612
613
614
			last;
		    }
		    $i++;
		}
		if ($i == $MAXIMQ) {
		    print STDERR "*** No more IMQs\n";
615
616
		    dbmclose(%MDB);
		    goto bad;
617
		}
618
619
	    }
	}
620
621
622
	# Clear anything else this node is using; no longer needed.
	for (my $j = $i; $j < $MAXIMQ; $j++) {
	    my $current = $MDB{"$j"};
623

624
625
626
	    if (!defined($current)) {
		$MDB{"$j"} = $current = "";
	    }
627
	    if ($current eq $vnode_id) {
628
		$MDB{"$j"} = "";
629
630
631
	    }
	}
    }
632
633
    dbmclose(%MDB);
    TBScriptUnlock();
634
    return 0;
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691

  bad:
    #
    # Unwind anything we did.
    #
    if ($USE_MACVLAN) {
	# Remove interfaces we *added* to bridges.
	if (exists($private->{'bridgeifaces'})) {
	    foreach my $brname (keys(%{ $private->{'bridgeifaces'} })) {
		my $ref = $private->{'bridgeifaces'}->{$brname};

		foreach my $iface (keys(%{ $ref })) {
		    mysystem2("$BRCTL delif $brname $iface");
		    delete($ref->{$brname}->{$iface})
			if (! $?);
 		}
	    }
	}
	# Delete bridges we *created* 
	if (exists($private->{'bridges'})) {
	    foreach my $brname (keys(%{ $private->{'bridges'} })) {
		mysystem2("$IFCONFIG $brname down");
		# We can delete this cause we still have the lock and
		# no one else got a chance to add to it. 
		mysystem2("$BRCTL delbr $brname");		
		delete($private->{'bridges'}->{$brname})
		    if (! $?);
	    }
	}
    }
    else {
	# Delete the dummy macvlan thingies we created.
	if (exists($private->{'dummys'})) {
	    # We can delete this cause we have the lock and no one else got
	    # a chance to use the dummy.
	    foreach my $brname (keys(%{ $private->{'dummys'} })) {
		mysystem2("$IP link del dev $brname");
		delete($private->{'dummys'}->{$brname})
		    if ($?);
	    }
	}
    }
    # Undo the IMQs
    if (exists($private->{'imqs'})) {
	if (!dbmopen(%MDB, $IMQDB, 0660)) {
	    print STDERR "*** Could not open $IMQDB\n";
	    goto badbad;
	}
	foreach my $i (keys(%{ $private->{'imqs'} })) {
	    $MDB{"$i"} = "";
	    delete($private->{'imqs'}->{"$i"});
	}
	dbmclose(%MDB);
    }
  badbad:
    TBScriptUnlock();
    return -1;
692
693
694
}

sub vz_rootPostConfig {
695
    # Locking, if this ever does something?
696
697
698
699
700
701
702
    return 0;
}

#
# Create an OpenVZ container to host a vnode.  Should be called only once.
#
sub vz_vnodeCreate {
703
704
705
    my ($vnode_id, undef, $vnconfig, $private) = @_;
    my $image = $vnconfig->{'image'};
    my $reload_args_ref = $vnconfig->{'reloadinfo'};
706
707
708
709
710
711
712
713
714
715
716
717
718

    my $vmid;
    if ($vnode_id =~ /^\w+\d+\-(\d+)$/) {
	$vmid = $1;
    }
    else {
	fatal("vz_vnodeCreate: bad vnode_id $vnode_id!");
    }

    if (!defined($image) || $image eq '') {
	$image = $defaultImage;
    }

719
    my $imagelockpath = "/var/emulab/db/openvz.image.$image.ready";
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
    my $imagelockname = "vzimage.$image";
    my $imagepath = "/vz/template/cache/${image}.tar.gz";

    my %reload_args;
    if (defined($reload_args_ref)) {
	%reload_args = %$reload_args_ref;

	# Tell stated via tmcd
	libvnode::setState("RELOADSETUP");

	#
	# So, we are reloading this vnode (and maybe others).  Need to grab
	# the global lock for this image, check if we really need to download
	# the image based on the mtime for the currently cached image (if there
	# is one), if there is old image state, move out of the way, then
	# download the new image.  State to move out of teh way for an old
	# image is the ready file, the image file, lvm "root" devices that we
	# previously had built still-live VMs out of (we need to rename them),
	# and finally, garbage collecting unused "root" devices.  
	#
	# Note that we need to be really careful with the last item -- we 
	# only GC if our create has happened successfully, and we take the 
	# global image GC lock to do so.  This may race due to the nature 
	# of global locks and result in not all old devices getting reaped, 
	# but oh well.  Best effort for now.
	#
	if ((my $locked = TBScriptLock($imagelockname,
				       TBSCRIPTLOCK_GLOBALWAIT(), 1800))
	    != TBSCRIPTLOCK_OKAY()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
749
750
	    print STDERR
		"Could not get the $imagelockname lock after a long time!\n";
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
	    return -1;
	}

	# do we have the right image file already?
	my $incache = 0;
	if (-e $imagepath) {
	    my (undef,undef,undef,undef,undef,undef,undef,undef,undef,
		$mtime,undef,undef,undef) = stat($imagepath);
	    if ("$mtime" eq $reload_args{"IMAGEMTIME"}) {
		$incache = 1;
	    }
	    else {
		print "mtimes for $imagepath differ: local $mtime, server " . 
		    $reload_args{"IMAGEMTIME"} . "\n";
		unlink($imagepath);
	    }
	}

	if (!$incache && $DOLVM) {
	    # did we create an lvm device for the old image at some point?
	    # (i.e., does the image lock file exist?)
	    if (-e $imagelockpath) {
773
774
		# Remove the readyfile; no longer ready. 
		unlink($imagelockpath);
775
776
777
778
779
780
781
782
783
784
785
786
	    }
	}
	elsif (!$incache && -e $imagelockpath) {
	    # now we can remove the readyfile
	    unlink($imagelockpath);
	}

	# Tell stated via tmcd
	libvnode::setState("RELOADING");

	if (!$incache) {
	    # Now we just download the file, then let create do its normal thing
787
	    my $dret = libvnode::downloadImage($imagepath,0,$reload_args_ref);
788
789
790
791
792
793
794

	    # reload has finished, file is written... so let's set its mtime
	    utime(time(),$reload_args{"IMAGEMTIME"},$imagepath);
	}

	TBScriptUnlock();
    }
795
796
797
798
799
800
801
802
803
804
805
806
807
808
    elsif ($image eq $defaultImage && -e $imagelockpath) {
	#
        # Image already unpacked, but lets see if the tarball changed.
	#
	my (undef,undef,undef,undef,undef,undef,undef,undef,undef,
	    $mtime1,undef,undef,undef) = stat($imagepath);
	my (undef,undef,undef,undef,undef,undef,undef,undef,undef,
	    $mtime2,undef,undef,undef) = stat($imagelockpath);

	if ($mtime1 > $mtime2) {
	    print STDERR "Default image $imagepath appears to be newer\n";
	    unlink($imagelockpath);
	}
    }
809

810
    my $createArg = "";
811
812
813
    if ((my $locked = TBScriptLock($imagelockname,
				   TBSCRIPTLOCK_GLOBALWAIT(), 1800))
	!= TBSCRIPTLOCK_OKAY()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
814
815
	print STDERR
	    "Could not get the $imagelockname lock after a long time!\n";
816
817
	return -1;
    }
818
    if ($DOLVM) {
819
	my $MIN_ROOT_LVM_VOL_SIZE = 2 * 2048;
820
	my $MAX_ROOT_LVM_VOL_SIZE = 8 * 1024;
821
	my $MIN_SNAPSHOT_VOL_SIZE = 512;
822
	my $MAX_SNAPSHOT_VOL_SIZE = 8 * 1024;
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844

	# XXX size our snapshots to assume 50 VMs on the node.
	my $MAX_NUM_VMS = 50;

	# figure out how big our volumes should be based on the volume
	# group size
	my $vgSize;
	my $rootSize = $MAX_ROOT_LVM_VOL_SIZE;
	my $snapSize = $MAX_SNAPSHOT_VOL_SIZE;

	open (VFD,"vgdisplay openvz |")
	    or die "popen(vgdisplay openvz): $!";
	while (my $line = <VFD>) {
	    chomp($line);
	    if ($line =~ /^\s+VG Size\s+(\d+[\.\d]*)\s+(\w+)/) {
		# convert to MB
		if ($2 eq "GB") {    $vgSize = $1 * 1024; }
		elsif ($2 eq "TB") { $vgSize = $1 * 1024 * 1024; }
		elsif ($2 eq "PB") { $vgSize = $1 * 1024 * 1024 * 1024; }
		elsif ($2 eq "MB") { $vgSize = $1 + 0; }
		elsif ($2 eq "KB") { $vgSize = $1 / 1024; }
		last;
845
	    }
846
847
848
849
	}
	close(VFD);

	if (defined($vgSize)) {
850
	    $vgSize /= $MAX_NUM_VMS;
851
852
853

	    if ($vgSize < $MIN_ROOT_LVM_VOL_SIZE) {
		$rootSize = int($MIN_ROOT_LVM_VOL_SIZE);
854
	    }
855
856
	    elsif ($vgSize < $MAX_ROOT_LVM_VOL_SIZE) {
		$rootSize = int($vgSize);
857
	    }
858
859
860
861
862
863
864
865
	    if ($vgSize < $MIN_SNAPSHOT_VOL_SIZE) {
		$snapSize = int($MIN_SNAPSHOT_VOL_SIZE);
	    }
	    elsif ($vgSize < $MAX_SNAPSHOT_VOL_SIZE) {
		$snapSize = int($vgSize);
	    }
	}

866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
	#
	# Lastly, allow the server to override the snapshot size,
	# although we enforce the minimum, and do not allow it to be
	# greater then the underlying size since that would break things.
	#
	if (exists($vnconfig->{'config'}->{'VDSIZE'})) {
	    #
	    # Value in MB.
	    #
	    my $vdsize = $vnconfig->{'config'}->{'VDSIZE'};

	    $snapSize = $vdsize
		if ($vdsize > $MIN_SNAPSHOT_VOL_SIZE &&
		    $vdsize <= $rootSize);
	}

882
883
884
885
886
887
888
	print STDERR "Using LVM with root size $rootSize MB, snapshot size $snapSize MB.\n";

	# we must have the lock, so if we need to return right away, unlock
	if (-e $imagelockpath) {
	    TBScriptUnlock();
	}
	else {
889
890
891
892
893
894
895
896
897
898
899
900
901
902
	    #
	    # If there is already a logical device for this image, then
	    # need to GC or rename it (might be in use). Note that a
	    # reload of the partition will cause the lock files to get
	    # deleted, which results in some needless work (recreating
	    # the lvm even if it did not change), but I do not see a
	    # way to stamp the lvm itself so that we can determine its
	    # creation date. Besides, it is an atypical case.
	    #
	    if (system("lvdisplay /dev/openvz/$image >& /dev/null") == 0) {
		if (GClvm("$image")) {
		    fatal("Could not GC or rename $image");
		}
	    }
903
904
905
	    print "Creating LVM core logical device for image $image\n";

	    # ok, create the lvm logical volume for this image.
906
	    mysystem("lvcreate $LVMDEBUGOPTS -L${rootSize}M -n $image openvz");
907
908
909
910
911
912
913
914
915
916
917
	    mysystem("mkfs -t ext3 /dev/openvz/$image");
	    mysystem("mkdir -p /tmp/mnt/$image");
	    mysystem("mount /dev/openvz/$image /tmp/mnt/$image");
	    mysystem("mkdir -p /tmp/mnt/$image/root /tmp/mnt/$image/private");
	    mysystem("tar -xzf $imagepath -C /tmp/mnt/$image/private");
	    mysystem("umount /tmp/mnt/$image");

	    # ok, we're done
	    mysystem("mkdir -p /var/emulab/run");
	    mysystem("touch $imagelockpath");
	    TBScriptUnlock();
918
919
	}

920
	#
921
	# Now take a snapshot of this image's logical device
922
923
924
925
926
927
928
929
930
931
932
933
934
	#
	# As above, a partition reload will make it appear that the
	# container does not exist, when in fact the lvm really does
	# and we want to reuse it, not create another one. 
	#
	if (system("lvdisplay /dev/openvz/$vnode_id >& /dev/null")) {
	    mysystem("lvcreate $LVMDEBUGOPTS ".
		     "  -s -L${snapSize}M -n $vnode_id /dev/openvz/$image");
	}
	mysystem("mkdir -p /mnt/$vnode_id")
	    if (! -e "/mnt/$vnode_id");
	mysystem("mount /dev/openvz/$vnode_id /mnt/$vnode_id")
	    if (! -e "/mnt/$vnode_id/private");
935
936
937
938

	$createArg = "--private /mnt/$vnode_id/private" . 
	    " --root /mnt/$vnode_id/root --nofs yes";
    }
939
940
941
942
943
944
945
946
947
948
    else {
	TBScriptUnlock();
    }

    if (defined($reload_args_ref)) {
	# Tell stated via tmcd
	libvnode::setState("RELOADDONE");
	sleep(4);
	libvnode::setState("SHUTDOWN");
    }
949

950
    # build the container
951
    mysystem("$VZCTL $VZDEBUGOPTS create $vmid --ostemplate $image $createArg");
952
953

    # make sure bootvnodes actually starts things up on boot, not openvz
954
    mysystem("$VZCTL $VZDEBUGOPTS set $vmid --onboot no --name $vnode_id --save");
955

956
    # set some resource limits:
957
    my %deflimits = ( "diskinodes" => "unlimited:unlimited",
958
		      "diskspace" => "unlimited:unlimited",
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
		      "numproc" => "unlimited:unlimited",
		      "numtcpsock" => "unlimited:unlimited",
		      "numothersock" => "unlimited:unlimited",
		      "vmguarpages" => "unlimited:unlimited",
		      "kmemsize" => "unlimited:unlimited",
		      "tcpsndbuf" => "unlimited:unlimited",
		      "tcprcvbuf" => "unlimited:unlimited",
		      "othersockbuf" => "unlimited:unlimited",
		      "dgramrcvbuf" => "unlimited:unlimited",
		      "oomguarpages" => "unlimited:unlimited",
		      "lockedpages" => "unlimited:unlimited",
		      "privvmpages" => "unlimited:unlimited",
		      "shmpages" => "unlimited:unlimited",
		      "numfile" => "unlimited:unlimited",
		      "numflock" => "unlimited:unlimited",
		      "numpty" => "unlimited:unlimited",
		      "numsiginfo" => "unlimited:unlimited",
		      #"dcachesize" => "unlimited:unlimited",
		      "numiptent" => "unlimited:unlimited",
		      "physpages" => "unlimited:unlimited",
		      #"cpuunits" => "unlimited",
		      "cpulimit" => "0",
		      "cpus" => "unlimited",
		      "meminfo" => "none",
	);
    my $savestr = "";
    foreach my $k (keys(%deflimits)) {
	$savestr .= " --$k $deflimits{$k}";
    }
988
    mysystem("$VZCTL $VZDEBUGOPTS set $vmid $savestr --save");
989

990
991
992
    # XXX give them cap_net_admin inside containers... necessary to set
    # txqueuelen on devices inside the container.  This may have other
    # undesireable side effects, but need it for now.
993
    mysystem("$VZCTL $VZDEBUGOPTS set $vmid --capability net_admin:on --save");
994

995
996
997
998
999
1000
    #
    # Make some directories in case the guest doesn't have them -- the elab
    # mount and umount vz scripts need them to be there!
    #
    my $privroot = "/vz/private/$vnode_id";
    if ($DOLVM) {
For faster browsing, not all history is shown. View entire blame