libvnode_openvz.pm 39.7 KB
Newer Older
1
2
3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2008-2010 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 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
16
              vz_vnodePreConfig vz_vnodeUnmount
17
18
              vz_vnodePreConfigControlNetwork vz_vnodePreConfigExpNetwork 
              vz_vnodeConfigResources vz_vnodeConfigDevices
19
              vz_vnodePostConfig vz_vnodeExec
20
21
22
23
24
25
26
27
28
29
30
31
            );

%ops = ( 'init' => \&vz_init,
	 'setDebug' => \&vz_setDebug,
	 'rootPreConfig' => \&vz_rootPreConfig,
	 'rootPreConfigNetwork' => \&vz_rootPreConfigNetwork,
	 'rootPostConfig' => \&vz_rootPostConfig,
	 'vnodeCreate' => \&vz_vnodeCreate,
	 'vnodeDestroy' => \&vz_vnodeDestroy,
	 'vnodeState' => \&vz_vnodeState,
	 'vnodeBoot' => \&vz_vnodeBoot,
	 'vnodeHalt' => \&vz_vnodeHalt,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
32
	 'vnodeUnmount' => \&vz_vnodeUnmount,
33
	 'vnodeReboot' => \&vz_vnodeReboot,
34
	 'vnodeExec' => \&vz_vnodeExec,
35
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;
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
47
use Socket;
48
49
50
51

# Pull in libvnode
require "/etc/emulab/paths.pm"; import emulabpaths;
use libvnode;
52
use libtestbed;
53

54
55
56
57
58
59
60
61
62
63
#
# 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
64
my $defaultImage = "emulab-default";
65

66
67
my $DOLVM = 1;

68
69
my $GLOBAL_CONF_LOCK = "vzconf";

70
71
sub VZSTAT_RUNNING() { return "running"; }
sub VZSTAT_STOPPED() { return "stopped"; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
72
sub VZSTAT_MOUNTED() { return "mounted"; }
73
74
75
76
77
78
79
80
81

my $VZCTL  = "/usr/sbin/vzctl";
my $VZLIST = "/usr/sbin/vzlist";
my $IFCONFIG = "/sbin/ifconfig";
my $ROUTE = "/sbin/route";
my $BRCTL = "/usr/sbin/brctl";
my $IPTABLES = "/sbin/iptables";
my $MODPROBE = "/sbin/modprobe";
my $RMMOD = "/sbin/rmmod";
82
my $VLANCONFIG = "/sbin/vconfig";
83
84
85
86
87

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

my $CTRLIPFILE = "/var/emulab/boot/myip";
88
my $IMQDB      = "/var/emulab/db/imqdb";
89
my $MAXIMQ     = 64;
90
91
92
93
94
95
96
97
98
99

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

my $debug = 0;

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

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#
# Helpers.
#
sub findControlNet();
sub makeIfaceMaps();
sub makeBridgeMaps();
sub findIface($);
sub findMac($);
sub editContainerConfigFile($$);

sub vmexists($);
sub vmstatus($);
sub vmrunning($);
sub vmstopped($);

#
# Initialize the lib (and don't use BEGIN so we can do reinit).
#
sub vz_init {
    my ($pnode_id,) = @_;

    makeIfaceMaps();
    makeBridgeMaps();

125
126
127
128
129
130
    #
    # Turn off LVM if already using a /vz mount.
    #
    if (-e "/vz/.nolvm") {
	$DOLVM = 0;
    }
131
132
133
134
135
136
137
    return 0;
}

#
# Prepare the root context.  Run once at boot.
#
sub vz_rootPreConfig {
138
139
140
141
142
143
144
    #
    # 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");

145
    if ((my $locked = TBScriptLock($GLOBAL_CONF_LOCK,
146
				   TBSCRIPTLOCK_GLOBALWAIT(), 900)) 
147
148
149
150
151
152
	!= TBSCRIPTLOCK_OKAY()) {
	return 0
	    if ($locked == TBSCRIPTLOCK_IGNORE());
	print STDERR "Could not get the vzinit lock after a long time!\n";
	return -1;
    }
153
154
155
156
157
    # we must have the lock, so if we need to return right away, unlock
    if (-e "/var/run/openvz.ready") {
        TBScriptUnlock();
        return 0;
    }
158

159
    # make sure filesystem is setup 
160
    if ($DOLVM) {
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
	# 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");
	}

180
	if (system('vgs | grep -E -q '."'".'^[ ]+openvz.*$'."'")) {
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
	    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";
	    }
		    
	    mysystem("pvcreate $blockdevs");
	    mysystem("vgcreate openvz $blockdevs");
203
204
205
206
207
208
209
210
211

	    # XXX eventually could move this into its own logical volume, but
	    # we don't ever know how many images we'll have to store.
	    mysystem("$VZRC stop");
	    mysystem("rm -rf /vz")
		if (-e "/vz");
	    mysystem("mkdir /vz");
	    mysystem("cp -pR /vz.save/* /vz/");
	}
212
213
214
215

	# make sure our volumes are active -- they seem to become inactive
	# across reboots
	mysystem("vgchange -a y openvz");
216
    }
217
218
219
220
221
222
223
224
225
    else {
	# about the funny quoting: don't ask... emacs perl mode foo.
	if (system('grep -q '."'".'^/dev/.*/vz.*$'."'".' /etc/fstab')) {
	    mysystem("$VZRC stop");
	    mysystem("rm -rf /vz")
		if (-e "/vz");
	    mysystem("mkdir /vz");
	    mysystem("$MKEXTRAFS -f /vz");
	    mysystem("cp -pR /vz.save/* /vz/");
226
	    mysystem("touch /vz/.nolvm");
227
228
229
230
	}
	if (system('mount | grep -q \'on /vz\'')) {
	    mysystem("mount /vz");
	}
231
232
    }

233
234
235
236
237
238
    # 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");

239
240
241
242
243
244
245
246
247
    # 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");
    }
248

249
250
251
    # this is what we need for veths
    mysystem("$MODPROBE vzethdev");

Leigh B. Stoller's avatar
Leigh B. Stoller committed
252
253
254
    # For tunnels
    mysystem("$MODPROBE ip_gre");

255
256
257
    # For VLANs
    mysystem("$MODPROBE 8021q");

258
259
260
261
262
263
    # we need this stuff for traffic shaping -- only root context can
    # modprobe, for now.
    mysystem("$MODPROBE sch_plr");
    mysystem("$MODPROBE sch_delay");
    mysystem("$MODPROBE sch_htb");

264
265
266
267
268
269
270
271
272
273
274
275
    # 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");
    }

276
277
278
279
    #
    # 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.
    #
280

281
    # Ug, pre-create a bunch of imq devices, since adding new ones
282
283
284
285
286
287
288
289
290
291
292
    # does not work right yet.
    mysystem("$MODPROBE imq numdevs=$MAXIMQ");
    mysystem("$MODPROBE ipt_IMQ");

    # Create a DB to manage them.
    my %MDB;
    if (!dbmopen(%MDB, $IMQDB, 0660)) {
	print STDERR "*** Could not create $IMQDB\n";
	return -1;
    }
    for (my $i = 0; $i < $MAXIMQ; $i++) {
293
294
	$MDB{"$i"} = ""
	    if (!exists($MDB{"$i"}));
295
296
297
298
299
    }
    dbmclose(%MDB);

    mysystem("touch /var/run/openvz.ready");
    TBScriptUnlock();
300
301
302
303
304
305
306
307
308
    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.
#
sub vz_rootPreConfigNetwork {
309
    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
310
311
312
	print STDERR "Could not get the vznetwork lock after a long time!\n";
	return -1;
    }
313

314
315
316
317
    # Do this again after lock.
    makeIfaceMaps();
    makeBridgeMaps();
    
318
    my ($node_ifs,$node_ifsets,$node_lds) = @_;
319

320
321
322
323
324
325
326
    # 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");

327
328
329
330
331
332
333
334
335
    # figure out what bridges we need to make:
    # 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).
    my %brs = ();
    foreach my $node (keys(%$node_ifs)) {
	foreach my $ifc (@{$node_ifs->{$node}}) {
	    next if (!$ifc->{ISVIRT});

336
337
338
339
340
341
342
343
344
345
346
347
	    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.
		#
		my $brname = "br$vtag";
		$brs{$brname}{ENCAP} = 0;
		$brs{$brname}{SHORT} = 0;
	    }
	    elsif ($ifc->{ITYPE} eq "vlan") {
348
349
		my $iface = $ifc->{IFACE};
		my $vtag  = $ifc->{VTAG};
350
351
352
		my $vdev  = "${iface}.${vtag}";

		system("$VLANCONFIG set_name_type DEV_PLUS_VID_NO_PAD");
353
		system("$VLANCONFIG add $iface $vtag");
354
		system("$VLANCONFIG set_name_type VLAN_PLUS_VID_NO_PAD");
355
356
357
358
359
360
361
362
		system("$IFCONFIG $vdev up");

		my $brname = "pbr$vdev";
		$brs{$brname}{ENCAP} = 1;
		$brs{$brname}{SHORT} = 0;
		$brs{$brname}{PHYSDEV} = $vdev;
	    }
	    elsif ($ifc->{PMAC} eq "none") {
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
		my $brname = "br" . $ifc->{VTAG};
		# 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});
		my $brname = "pbr$iface";
		$brs{$brname}{ENCAP} = 1;
		$brs{$brname}{SHORT} = 0;
		$brs{$brname}{PHYSDEV} = $iface;
	    }
	}
    }

    # actually make bridges and add phys ifaces
    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;
	}

	# building bridges is an important activity
398
	if (! -d "/sys/class/net/$k/bridge") {
399
400
401
402
403
404
405
406
407
408
409
	    mysystem("$BRCTL addbr $k");
	}
	# repetitions of this should not hurt anything
	mysystem("$IFCONFIG $k 0 up");

	# XXX here we would normally config the bridge to encapsulate or
	# act in short mode

	if (exists($brs{$k}{PHYSDEV})) {
	    # 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.
410
411
412
	    my $obr = findBridge($brs{$k}{PHYSDEV});
	    if (defined($obr)) {
		mysystem("$BRCTL delif " . $obr . " " .$brs{$k}{PHYSDEV});
413
414
415
416
417
418
419
		# rebuild hashes
		makeBridgeMaps();
	    }
	    mysystem("$BRCTL addif $k $brs{$k}{PHYSDEV}");
	}
    }

420
421
422
423
424
425
426
427
    # Use the IMQDB to reserve the devices to the container. We have the lock.
    my %MDB;
    if (!dbmopen(%MDB, $IMQDB, 0660)) {
	print STDERR "*** Could not create $IMQDB\n";
	TBScriptUnlock();
	return -1;
    }
    my $i = 0;
428
429
430
    foreach my $node (keys(%$node_lds)) {
        foreach my $ldc (@{$node_lds->{$node}}) {
	    if ($ldc->{"TYPE"} eq 'duplex') {
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
		while ($i < $MAXIMQ) {
		    my $current = $MDB{"$i"};

		    if (!defined($current) ||
			$current eq "" || $current eq $node) {
			$MDB{"$i"} = $node;
			$i++;
			last;
		    }
		    $i++;
		}
		if ($i == $MAXIMQ) {
		    print STDERR "*** No more IMQs\n";
		    TBScriptUnLock();
		    return -1;
		}
447
448
	    }
	}
449
450
451
	# Clear anything else this node is using; no longer needed.
	for (my $j = $i; $j < $MAXIMQ; $j++) {
	    my $current = $MDB{"$j"};
452

453
454
455
456
457
	    if (!defined($current)) {
		$MDB{"$j"} = $current = "";
	    }
	    if ($current eq $node) {
		$MDB{"$j"} = "";
458
459
460
	    }
	}
    }
461
    dbmclose(%MDB);
462

463
    TBScriptUnlock();
464
465
466
467
    return 0;
}

sub vz_rootPostConfig {
468
    # Locking, if this ever does something?
469
470
471
472
473
474
475
    return 0;
}

#
# Create an OpenVZ container to host a vnode.  Should be called only once.
#
sub vz_vnodeCreate {
476
    my ($vnode_id,$image,$reload_args_ref) = @_;
477
478
479
480
481
482
483
484
485
486
487
488
489

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

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
    my $imagelockpath = "/var/emulab/run/openvz.image.$image.ready";
    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()) {
#	    return 0
#		if ($locked == TBSCRIPTLOCK_IGNORE());
	    print STDERR "Could not get the $imagelockname lock after a long time!\n";
	    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) {
		# if there's already a logical device for this image...
		my $sysret = system("lvdisplay /dev/openvz/$image >& /dev/null");
		if (!$sysret) {
		    my $rand = int(rand(100000));
		    my @outlines = system("lvs --noheadings");
		    my $found = 0;
		    while (!$found) {
			foreach my $line (@outlines) {
			    if ($line =~ /^\s*([-_\d\w]+)\.(\d+)\s+openvz/) {
				if ($rand == $2) {
				    $found = 1;
				    last;
				}
			    }
			}
			if ($found) {
			    $found = 0;
			    $rand = int(rand(100000));
			    @outlines = system("lvs --noheadings");
			}
			else {
			    $found = 1;
			}
		    }

		    # rename nicely works even when snapshots exist
		    mysystem("lvrename /dev/openvz/$image" . 
			     " /dev/openvz/$image.$rand");

		    # now we can remove the readyfile
		    unlink($imagelockpath);
		}
	    }
	}
	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
589
	    my $dret = libvnode::downloadImage($imagepath,0,$reload_args_ref);
590
591
592
593
594
595
596
597

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

	TBScriptUnlock();
    }

598
    my $createArg = "";
599
600
601
602
603
604
605
606
    if ((my $locked = TBScriptLock($imagelockname,
				   TBSCRIPTLOCK_GLOBALWAIT(), 1800))
	!= TBSCRIPTLOCK_OKAY()) {
#	return 0
#	    if ($locked == TBSCRIPTLOCK_IGNORE());
	print STDERR "Could not get the $imagelockname lock after a long time!\n";
	return -1;
    }
607
    if ($DOLVM) {
608
	my $MIN_ROOT_LVM_VOL_SIZE = 1024;
609
	my $MAX_ROOT_LVM_VOL_SIZE = 8 * 1024;
610
	my $MIN_SNAPSHOT_VOL_SIZE = 512;
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
	my $MAX_SNAPSHOT_VOL_SIZE = $MAX_ROOT_LVM_VOL_SIZE;

	# 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;
634
	    }
635
636
637
638
639
640
641
642
	}
	close(VFD);

	if (defined($vgSize)) {
	    $vgSize /= 50;

	    if ($vgSize < $MIN_ROOT_LVM_VOL_SIZE) {
		$rootSize = int($MIN_ROOT_LVM_VOL_SIZE);
643
	    }
644
645
	    elsif ($vgSize < $MAX_ROOT_LVM_VOL_SIZE) {
		$rootSize = int($vgSize);
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
	    if ($vgSize < $MIN_SNAPSHOT_VOL_SIZE) {
		$snapSize = int($MIN_SNAPSHOT_VOL_SIZE);
	    }
	    elsif ($vgSize < $MAX_SNAPSHOT_VOL_SIZE) {
		$snapSize = int($vgSize);
	    }
	}

	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 {
	    print "Creating LVM core logical device for image $image\n";

	    # ok, create the lvm logical volume for this image.
	    mysystem("lvcreate -L${rootSize}M -n $image openvz");
	    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();
677
678
679
	}

	# Now take a snapshot of this image's logical device
680
	mysystem("lvcreate -s -L${snapSize}M -n $vnode_id /dev/openvz/$image");
681
682
683
684
685
686
	mysystem("mkdir -p /mnt/$vnode_id");
	mysystem("mount /dev/openvz/$vnode_id /mnt/$vnode_id");

	$createArg = "--private /mnt/$vnode_id/private" . 
	    " --root /mnt/$vnode_id/root --nofs yes";
    }
687
688
689
690
691
692
693
694
695
696
    else {
	TBScriptUnlock();
    }

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

698
    # build the container
699
    mysystem("$VZCTL create $vmid --ostemplate $image $createArg");
700
701
702
703

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

704
    # set some resource limits:
705
    my %deflimits = ( "diskinodes" => "unlimited:unlimited",
706
		      "diskspace" => "unlimited:unlimited",
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
		      "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}";
    }
    mysystem("$VZCTL set $vmid $savestr --save");

738
739
740
741
742
    # 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.
    mysystem("$VZCTL set $vmid --capability net_admin:on --save");

743
744
745
746
747
748
749
750
751
752
    #
    # 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) {
	$privroot = "/mnt/$vnode_id/private";
    }
    mysystem("mkdir -p $privroot/var/emulab/boot/");

753
754
755
756
757
758
759
    # NOTE: we can't ever umount the LVM logical device because vzlist can't
    # return status appropriately if a VM's root and private areas don't
    # exist.
    if (0 && $DOLVM) {
	mysystem("umount /mnt/$vnode_id");
    }

760
761
762
763
764
765
    return $vmid;
}

sub vz_vnodeDestroy {
    my ($vnode_id,$vmid) = @_;

766
767
768
769
    if ($DOLVM) {
	mysystem("umount /mnt/$vnode_id");
	mysystem("lvremove -f /dev/openvz/$vnode_id");
    }
770
    mysystem("$VZCTL destroy $vnode_id");
771
772
773
774
775
776
777
    return -1
	if ($?);

    #
    # Clear the IMQ reservations. Must lock since IMQDB is a shared
    # resource.
    #
778
    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
	print STDERR "Could not get the vzpreconfig lock after a long time!\n";
	return -1;
    }
    my %MDB;
    if (!dbmopen(%MDB, $IMQDB, 0660)) {
	print STDERR "*** Could not open $IMQDB\n";
	TBScriptUnlock();
	return -1;
    }
    for (my $i = 0; $i < $MAXIMQ; $i++) {
	next
	    if ($MDB{"$i"} ne $vnode_id);
	$MDB{"$i"} = "";
    }
    dbmclose(%MDB);
    TBScriptUnlock();
    return 0;
}

sub vz_vnodeExec {
    my ($vnode_id,$vmid,$command) = @_;

801
802
    # Note: do not use mysystem here since that exits.
    system("$VZCTL exec2 $vnode_id $command");
803

804
    return $?;
805
806
807
808
809
}

sub vz_vnodeState {
    my ($vnode_id,$vmid) = @_;

810
811
812
813
814
815
816
817
818
819
820
821
822
    # Sometimes if the underlying filesystems are not mounted, we might get 
    # no status even though the vnode has been created (currently, this will
    # only happen with LVM)... since the openvz utils seem to need to see the
    # vnode filesystem in order to work properly, which is sensible).
    if ($DOLVM) {
	if (-e "/etc/vz/conf/$vmid.conf" && -e "/dev/openvz/$vnode_id"
	    && ! -e "/mnt/$vnode_id/private") {
	    print "Trying to mount LVM logical device for vnode $vnode_id: ";
	    mysystem("mount /dev/openvz/$vnode_id /mnt/$vnode_id");
	    print "done.\n";
	}
    }

823
    my $status = vmstatus($vmid);
824

825
826
827
828
829
830
    if ($status eq 'running') {
	return VNODE_STATUS_RUNNING();
    }
    elsif ($status eq 'stopped') {
	return VNODE_STATUS_STOPPED();
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
831
832
833
    elsif ($status eq 'mounted') {
	return VNODE_STATUS_MOUNTED();
    }
834
835
836
837
838
839
840

    return VNODE_STATUS_UNKNOWN();
}

sub vz_vnodeBoot {
    my ($vnode_id,$vmid) = @_;

841
842
843
844
    if ($DOLVM) {
	system("mount /dev/openvz/$vnode_id /mnt/$vnode_id");
    }

845
846
847
848
849
850
851
852
853
854
855
856
857
    mysystem("$VZCTL start $vnode_id");

    return 0;
}

sub vz_vnodeHalt {
    my ($vnode_id,$vmid) = @_;

    mysystem("$VZCTL stop $vnode_id");

    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
858
859
860
861
862
863
864
865
sub vz_vnodeUnmount {
    my ($vnode_id,$vmid) = @_;

    mysystem("$VZCTL umount $vnode_id");

    return 0;
}

866
867
868
869
870
871
872
873
874
sub vz_vnodeReboot {
    my ($vnode_id,$vmid) = @_;

    mysystem("$VZCTL restart $vnode_id");

    return 0;
}

sub vz_vnodePreConfig {
875
    my ($vnode_id,$vmid,$callback) = @_;
876

877
878
879
880
881
882
    # Make sure we're mounted so that vzlist and friends work; see NOTE about
    # mounting LVM logical devices above.
    if ($DOLVM) {
	system("mount /dev/openvz/$vnode_id /mnt/$vnode_id");
    }

883
    #
884
885
886
    # Look and see if this node already has imq devs mapped into it -- if
    # those match the ones in the IMQDB, do nothing, else fixup. Must lock
    # since IMQDB is a shared resource.
887
    #
888
    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
889
890
891
892
893
894
895
896
	print STDERR "Could not get the vzpreconfig lock after a long time!\n";
	return -1;
    }
    my %MDB;
    if (!dbmopen(%MDB, $IMQDB, 0660)) {
	print STDERR "*** Could not open $IMQDB\n";
	TBScriptUnlock();
	return -1;
897
    }
898
899
900
901
902
    my %devs = ();

    for (my $i = 0; $i < $MAXIMQ; $i++) {
	next
	    if ($MDB{"$i"} ne $vnode_id);
903

904
	$devs{"imq$i"} = 1;
905
906
907
908
    }
    dbmclose(%MDB);
    TBScriptUnlock();
    
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
    my $existing = `sed -n -r -e 's/NETDEV="(.*)"/\1/p' /etc/vz/conf/$vmid.conf`;
    chomp($existing);
    foreach my $dev (split(/,/,$existing)) {
	if (!exists($devs{$dev})) {
	    # needs deleting
	    $devs{$dev} = 0;
	}
	else {
	    # was already mapped, leave alone
	    $devs{$dev} = undef;
	}
    }

    foreach my $dev (keys(%devs)) {
	if ($devs{$dev} == 1) {
	    mysystem("$VZCTL set $vnode_id --netdev_add $dev --save");
	}
	elsif ($devs{$dev} == 0) {
	    mysystem("$VZCTL set $vnode_id --netdev_del $dev --save");
	}
    }
930
931
932
933
934
935
936
    #
    # Make sure container is mounted before calling the callback.
    #
    my $status = vmstatus($vmid);
    my $didmount = 0;
    if ($status ne 'running' && $status ne 'mounted') {
	mysystem("$VZCTL mount $vnode_id");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
937
	$didmount = 1;
938
    }
939
940
941
942
943
    my $privroot = "/vz/private/$vmid";
    if ($DOLVM) {
	$privroot = "/mnt/$vnode_id/private";
    }
    my $ret = &$callback("$privroot");
944
945
946
947
    if ($didmount) {
	mysystem("$VZCTL umount $vnode_id");
    }
    return $ret;
948
949
950
951
952
953
954
955
956
}

#
# Preconfigure the control net interface; special case of vnodeConfigInterfaces.
#
sub vz_vnodePreConfigControlNetwork {
    my ($vnode_id,$vmid,$ip,$mask,$mac,$gw,
	$vname,$longdomain,$shortdomain,$bossip) = @_;

957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
    # setup iptables on real ctrl net
    my ($ciface,$cip,$cnetmask,$cmaskbits,$cnetwork,$cmac) = findControlNet();

    my @ipa = map { int($_); } split(/\./,$ip);
    my @maska = map { int($_); } split(/\./,$mask);
    my @neta = ($ipa[0] & $maska[0],$ipa[1] & $maska[1],
		$ipa[2] & $maska[2],$ipa[3] & $maska[3]);
    my $net = join('.',@neta);

    # If the SNAT rule is there, probably we're good.
    if (system('iptables -t nat -L POSTROUTING' . 
	       ' | grep -q -e \'^SNAT.* ' . $net . '\'')) {
	mysystem("$MODPROBE ip_nat");
	mysystem("$IPTABLES -t nat -A POSTROUTING" . 
		 " -s $net/$mask" . 
		 " -d $cnetwork/$cnetmask -j ACCEPT");
	mysystem("$IPTABLES -t nat -A POSTROUTING" . 
		 " -s $net/$mask" . 
		 " -d $net/$mask -j ACCEPT");
	mysystem("$IPTABLES -t nat -A POSTROUTING" . 
		 " -s $net/$mask" . 
		 " -o $ciface -j SNAT --to-source $cip");
    }

981
982
983
984
985
986
987
988
989
990
    # Make sure we're mounted so that vzlist and friends work; see NOTE about
    # mounting LVM logical devices above.
    if ($DOLVM) {
	system("mount /dev/openvz/$vnode_id /mnt/$vnode_id");
    }

    my $privroot = "/vz/private/$vmid";
    if ($DOLVM) {
	$privroot = "/mnt/$vnode_id/private";
    }
991
992
993
994
995
996
997
998
999
1000

    # add the control net iface
    my $cnet_veth = "veth${vmid}.${CONTROL_IFNUM}";
    my $cnet_mac = macAddSep($mac);
    my $ext_vethmac = $cnet_mac;
    if ($ext_vethmac =~ /^(00:00)(.*)$/) {
	$ext_vethmac = "00:01$2";
    }

    #
For faster browsing, not all history is shown. View entire blame