libvnode.pm 15.2 KB
Newer Older
1
#!/usr/bin/perl -wT
2
#
3
# Copyright (c) 2008-2014 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
# General vnode setup routines and helpers (Linux)
25
26
27
28
#
package libvnode;
use Exporter;
@ISA    = "Exporter";
29
@EXPORT = qw( makeIfaceMaps makeBridgeMaps
Leigh B Stoller's avatar
Leigh B Stoller committed
30
	      findControlNet existsIface findIface findMac
31
	      existsBridge findBridge findBridgeIfaces
32
              downloadImage getKernelVersion createExtraFS
33
              forwardPort removePortForward lvSize DoIPtables restartDHCP
34
35
            );

36
use Data::Dumper;
37
38
use libutil;
use libgenvnode;
39
use libsetup;
40
use libtestbed;
41

42
43
44
45
46
47
48
#
# Magic control network config parameters.
#
my $PCNET_IP_FILE   = "/var/emulab/boot/myip";
my $PCNET_MASK_FILE = "/var/emulab/boot/mynetmask";
my $PCNET_GW_FILE   = "/var/emulab/boot/routerip";

49
50
# Other local constants
my $IPTABLES   = "/sbin/iptables";
51

52
my $debug = 0;
53

54
55
56
57
58
59
sub setDebug($) {
    $debug = shift;
    print "libvnode: debug=$debug\n"
	if ($debug);
}

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#
# Setup (or teardown) a port forward according to input hash containing:
# * ext_ip:   External IP address traffic is destined to
# * ext_port: External port traffic is destined to
# * int_ip:   Internal IP address traffic is redirected to
# * int_port: Internal port traffic is redirected to
#
# 'protocol' - a string; either "tcp" or "udp"
# 'remove'   - a boolean indicating whether or not to do a teardown.
#
# Side effect: uses iptables command to manipulate NAT.
#
sub forwardPort($;$) {
    my ($ref, $remove) = @_;
    
    my $int_ip   = $ref->{'int_ip'};
    my $ext_ip   = $ref->{'ext_ip'};
    my $int_port = $ref->{'int_port'};
    my $ext_port = $ref->{'ext_port'};
    my $protocol = $ref->{'protocol'};

    if (!(defined($int_ip) && 
	  defined($ext_ip) && 
	  defined($int_port) &&
	  defined($ext_port) && 
	  defined($protocol))
	) {
	print STDERR "WARNING: forwardPort: parameters missing!";
	return -1;
    }
90

91
92
93
94
95
96
97
98
    if ($protocol !~ /^(tcp|udp)$/) {
	print STDERR "WARNING: forwardPort: Unknown protocol: $protocol\n";
	return -1;
    }
    
    # Are we removing or adding the rule?
    my $op = (defined($remove) && $remove) ? "D" : "A";

99
100
101
102
103
104
105
106
107
108
109
110
111
112
    return -1
	if (DoIPtables("-v -t nat -$op PREROUTING -p $protocol -d $ext_ip ".
		       "--dport $ext_port -j DNAT ".
		       "--to-destination $int_ip:$int_port"));
    return 0;
}

#
# Oh jeez, iptables is about the dumbest POS I've ever seen; it fails
# if you run two at the same time. So we have to serialize the calls.
# The problem is that XEN also manipulates things, and so it is hard
# to get a perfect lock. So, we do our best and if it fails sleep for
# a couple of seconds and try again. 
#
113
sub DoIPtables(@)
114
{
115
    my (@rules) = @_;
116

117
118
119
120
    if (TBScriptLock("iptables", 0, 900) != TBSCRIPTLOCK_OKAY()) {
	print STDERR "Could not get the iptables lock after a long time!\n";
	return -1;
    }
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    foreach my $rule (@rules) {
	my $retries = 5;
	my $status  = 0;
	while ($retries > 0) {
	    mysystem2("$IPTABLES $rule");
	    $status = $?;
	    last
		if (!$status || $status >> 8 != 4);
	    print STDERR "will retry in a couple of seconds ...\n";
	    sleep(2);
	    $retries--;
	}
	# Operation failed - return error
	if (!$retries || $status) {
	    TBScriptUnlock();
	    return -1;
	}
138
    }
139
140
    TBScriptUnlock();
    return 0;
141
142
143
144
}

sub removePortForward($) {
    my $ref = shift;
145
    return forwardPort($ref,1);
146
147
148
149
}

#
# A spare disk or disk partition is one whose partition ID is 0 and is not
150
151
152
# mounted and is not in /etc/fstab AND is >= the specified minsize (in MiB).
# Yes, this means it's possible that we might steal partitions that are
# in /etc/fstab by UUID -- oh well.
153
154
155
156
157
#
# This function returns a hash of device name => part number => size (bytes);
# note that a device name => size entry is filled IF the device has no
# partitions.
#
158
159
160
sub findSpareDisks($) {
    my ($minsize) = @_;

161
162
163
164
165
166
167
    my %retval = ();
    my %mounts = ();
    my %ftents = ();

    # /proc/partitions prints sizes in 1K phys blocks
    my $BLKSIZE = 1024;

168
169
170
    # convert minsize to 1K blocks
    $minsize *= 1024;

171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    open (MFD,"/proc/mounts") 
	or die "open(/proc/mounts): $!";
    while (my $line = <MFD>) {
	chomp($line);
	if ($line =~ /^([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+/) {
	    $mounts{$1} = $2;
	}
    }
    close(MFD);

    open (FFD,"/etc/fstab") 
	or die "open(/etc/fstab): $!";
    while (my $line = <FFD>) {
	chomp($line);
	if ($line =~ /^([^\s]+)\s+([^\s]+)/) {
	    $ftents{$1} = $2;
	}
    }
    close(FFD);

    open (PFD,"/proc/partitions") 
	or die "open(/proc/partitions): $!";
    while (my $line = <PFD>) {
	chomp($line);
	if ($line =~ /^\s*\d+\s+\d+\s+(\d+)\s+([a-zA-Z]+)$/) {
196
197
	    if (!defined($mounts{"/dev/$2"}) && !defined($ftents{"/dev/$2"}) &&
		$1 >= $minsize) {
198
199
200
201
		$retval{$2}{"size"} = $BLKSIZE * $1;
	    }
	}
	elsif ($line =~ /^\s*\d+\s+\d+\s+(\d+)\s+([a-zA-Z]+)(\d+)$/) {
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
	    my ($dev,$part) = ($2,$3);

	    # XXX don't include extended partitions (the reason is to filter
	    # out pseudo partitions that linux creates for bsd disklabel 
	    # slices -- we don't want to use those!
	    # 
	    # (of course, a much better approach would be to check if a 
	    # partition is contained within another and not use it.)
	    next 
		if ($part > 4);

	    if (exists($retval{$dev}{"size"})) {
		delete $retval{$dev}{"size"};
		if (scalar(keys(%{$retval{$dev}})) == 0) {
		    delete $retval{$dev};
217
218
		}
	    }
219
220
	    if (!defined($mounts{"/dev/$dev$part"}) 
		&& !defined($ftents{"/dev/$dev$part"})) {
221
222

		# try checking its ext2 label
223
		my @outlines = `dumpe2fs -h /dev/$dev$part 2>&1`;
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
		if (!$?) {
		    my ($uuid,$label);
		    foreach my $line (@outlines) {
			if ($line =~ /^Filesystem UUID:\s+([-\w\d]+)/) {
			    $uuid = $1;
			}
			elsif ($line =~ /^Filesystem volume name:\s+([-\/\w\d]+)/) {
			    $label = $1;
			}
		    }
		    if ((defined($uuid) && defined($ftents{"UUID=$uuid"}))
			|| (defined($label) && defined($ftents{"LABEL=$label"})
			    && $ftents{"LABEL=$label"} eq $label)) {
			next;
		    }
		}

		# one final check: partition id
242
		my $output = `sfdisk --print-id /dev/$dev $part`;
243
		chomp($output);
244
245
		if ($?) {
		    print STDERR "WARNING: findSpareDisks: error running 'sfdisk --print-id /dev/$dev $part': $! ... ignoring /dev/$dev$part\n";
246
		}
247
		elsif ($output eq "0" && $1 >= $minsize) {
248
		    $retval{$dev}{"$part"}{"size"} = $BLKSIZE * $1;
249
250
251
252
253
254
255
256
257
258
259
260
261
262
		}
	    }
	}
    }
    foreach my $k (keys(%retval)) {
	if (scalar(keys(%{$retval{$k}})) == 0) {
	    delete $retval{$k};
	}
    }
    close(PFD);

    return %retval;
}

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
my %if2mac = ();
my %mac2if = ();
my %ip2if = ();
my %ip2mask = ();
my %ip2net = ();
my %ip2maskbits = ();

#
# Grab iface, mac, IP info from /sys and /sbin/ip.
#
sub makeIfaceMaps()
{
    # clean out anything
    %if2mac = ();
    %mac2if = ();
    %ip2if = ();
    %ip2net = ();
    %ip2mask = ();
    %ip2maskbits = ();

    my $devdir = '/sys/class/net';
    opendir(SD,$devdir) 
	or die "could not find $devdir!";
    my @ifs = grep { /^[^\.]/ && -f "$devdir/$_/address" } readdir(SD);
    closedir(SD);

    foreach my $iface (@ifs) {
290
291
292
	next
	    if ($iface =~ /^ifb/ || $iface =~ /^imq/);
	
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
	if ($iface =~ /^([\w\d\-_]+)$/) {
	    $iface = $1;
	}
	else {
	    next;
	}

	open(FD,"/sys/class/net/$iface/address") 
	    or die "could not open /sys/class/net/$iface/address!";
	my $mac = <FD>;
	close(FD);
	next if (!defined($mac) || $mac eq '');

	$mac =~ s/://g;
	chomp($mac);
308
	$mac = lc($mac);
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
	$if2mac{$iface} = $mac;
	$mac2if{$mac} = $iface;

	# also find ip, ugh
	my $pip = `ip addr show dev $iface | grep 'inet '`;
	chomp($pip);
	if ($pip =~ /^\s+inet\s+(\d+\.\d+\.\d+\.\d+)\/(\d+)/) {
	    my $ip = $1;
	    $ip2if{$ip} = $iface;
	    my @ip = split(/\./,$ip);
	    my $bits = int($2);
	    my @netmask = (0,0,0,0);
	    my ($idx,$counter) = (0,8);
	    for (my $i = $bits; $i > 0; --$i) {
		--$counter;
		$netmask[$idx] += 2 ** $counter;
		if ($counter == 0) {
		    $counter = 8;
		    ++$idx;
		}
	    }
	    my @network = ($ip[0] & $netmask[0],$ip[1] & $netmask[1],
			   $ip[2] & $netmask[2],$ip[3] & $netmask[3]);
	    $ip2net{$ip} = join('.',@network);
	    $ip2mask{$ip} = join('.',@netmask);
	    $ip2maskbits{$ip} = $bits;
	}
    }

    if ($debug > 1) {
	print STDERR "makeIfaceMaps:\n";
	print STDERR "if2mac:\n";
	print STDERR Dumper(%if2mac) . "\n";
	#print STDERR "mac2if:\n";
	#print STDERR Dumper(%mac2if) . "\n";
	print STDERR "ip2if:\n";
	print STDERR Dumper(%ip2if) . "\n";
	print STDERR "\n";
    }

    return 0;
}

#
# Find control net iface info.  Returns:
# (iface_name,IP,IPmask,IPmaskbits,IPnet,MAC,GW)
#
sub findControlNet()
{
    my $ip = (-r $PCNET_IP_FILE) ? `cat $PCNET_IP_FILE` : "0";
    chomp($ip);
    if ($ip =~ /^(\d+\.\d+\.\d+\.\d+)$/) {
	$ip = $1;
    } else {
	die "Could not find valid control net IP (no $PCNET_IP_FILE?)";
    }
    my $gw = (-r $PCNET_GW_FILE) ? `cat $PCNET_GW_FILE` : "0";
    chomp($gw);
    if ($gw =~ /^(\d+\.\d+\.\d+\.\d+)$/) {
	$gw = $1;
    } else {
	die "Could not find valid control net GW (no $PCNET_GW_FILE?)";
    }
    return ($ip2if{$ip}, $ip, $ip2mask{$ip}, $ip2maskbits{$ip}, $ip2net{$ip},
	    $if2mac{$ip2if{$ip}}, $gw);
}

Leigh B Stoller's avatar
Leigh B Stoller committed
376
377
378
379
380
381
382
383
384
sub existsIface($) {
    my $iface = shift;

    return 1
        if (exists($if2mac{$iface}));

    return 0;
}

385
386
387
388
sub findIface($) {
    my $mac = shift;

    $mac =~ s/://g;
389
    $mac = lc($mac);
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
    return $mac2if{$mac}
        if (exists($mac2if{$mac}));

    return undef;
}

sub findMac($) {
    my $iface = shift;

    return $if2mac{$iface}
        if (exists($if2mac{$iface}));

    return undef;
}

my %bridges = ();
my %if2br = ();

sub makeBridgeMaps() {
    # clean out anything...
    %bridges = ();
    %if2br = ();

    my @lines = `brctl show`;
    # always get rid of the first line -- it's the column header 
    shift(@lines);
    my $curbr = '';
    foreach my $line (@lines) {
418
	if ($line =~ /^([\w\d\-\.]+)\s+/) {
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
	    $curbr = $1;
	    $bridges{$curbr} = [];
	}
	if ($line =~ /^[^\s]+\s+[^\s]+\s+[^\s]+\s+([\w\d\-\.]+)$/ 
	    || $line =~ /^\s+([\w\d\-\.]+)$/) {
	    push @{$bridges{$curbr}}, $1;
	    $if2br{$1} = $curbr;
	}
    }

    if ($debug > 1) {
	print STDERR "makeBridgeMaps:\n";
	print STDERR "bridges:\n";
	print STDERR Dumper(%bridges) . "\n";
	print STDERR "if2br:\n";
	print STDERR Dumper(%if2br) . "\n";
	print STDERR "\n";
    }

    return 0;
}

sub existsBridge($) {
    my $bname = shift;

    return 1
        if (exists($bridges{$bname}));

    return 0;
}

sub findBridge($) {
    my $iface = shift;

    return $if2br{$iface}
        if (exists($if2br{$iface}));

    return undef;
}

sub findBridgeIfaces($) {
    my $bname = shift;

    return @{$bridges{$bname}}
        if (exists($bridges{$bname}));

    return undef;
}

468
469
#
# Since (some) vnodes are imageable now, we provide an image fetch
470
471
# mechanism.  Caller provides an imagepath for frisbee, and a hash of
# args that comes directly from loadinfo.
472
#
473
474
sub downloadImage($$$$) {
    my ($imagepath,$todisk,$nodeid,$reload_args_ref) = @_;
475
476
477
478
479

    return -1 
	if (!defined($imagepath) || !defined($reload_args_ref));

    my $addr = $reload_args_ref->{"ADDR"};
480
    my $FRISBEE = "/usr/local/bin/frisbee";
481
    my $IMAGEUNZIP = "/usr/local/bin/imageunzip";
482
    my $command = "";
483
484
485
486
    # Backwards compat.
    if (! -e $FRISBEE) {
	$FRISBEE = "/usr/local/etc/emulab/frisbee";
    }
487

488
489
490
    if (!defined($addr) || $addr eq "") {
	# frisbee master server world
	my ($server, $imageid);
491
492
	my $proxyopt  = "";
	my $todiskopt = "";
493
494
495
496

	if ($reload_args_ref->{"SERVER"} =~ /^(\d+\.\d+\.\d+\.\d+)$/) {
	    $server = $1;
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
497
	if ($reload_args_ref->{"IMAGEID"} =~
498
	    /^([-\d\w]+),([-\d\w]+),([-\d\w\.:]+)$/) {
499
500
	    $imageid = "$1/$3";
	}
501
	if (SHAREDHOST()) {
502
503
	    $proxyopt = "-P $nodeid";
	}
504
505
506
	if (!$todisk) {
	    $todiskopt = "-N";
	}
507
	if ($server && $imageid) {
508
509
	    $command = "$FRISBEE -f -M 64 $proxyopt $todiskopt ".
		"         -S $server -B 30 -F $imageid $imagepath";
510
511
512
513
514
515
516
	}
	else {
	    print STDERR "Could not parse frisbee loadinfo\n";
	    return -1;
	}
    }
    elsif ($addr =~/^(\d+\.\d+\.\d+\.\d+):(\d+)$/) {
517
518
519
	my $mcastaddr = $1;
	my $mcastport = $2;

520
	$command = "$FRISBEE -f -M 64 -m $mcastaddr -p $mcastport $imagepath";
521
522
    }
    elsif ($addr =~ /^http/) {
523
	if ($todisk) {
524
525
526
527
528
	    $command = "wget -nv -N -O - '$addr' | ".
		"$IMAGEUNZIP -f -W 32 - $imagepath";
	}
	else {
	    $command = "wget -nv -N -O $imagepath '$addr'";
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
    print STDERR $command . "\n";
    
    #
    # Run the command protected by an alarm to avoid trying forever,
    # as frisbee is prone to doing.
    #
    my $childpid = fork();
    if ($childpid) {
	local $SIG{ALRM} = sub { kill("TERM", $childpid); };
	alarm 60 * 30;
	waitpid($childpid, 0);
	my $stat = $?;
	alarm 0;

	if ($stat) {
	    print STDERR "  returned $stat ... \n";
	    return -1;
	}
	return 0;
    }
    else {
	#
	# We have blocked most signals in mkvnode, including TERM.
	#
	local $SIG{TERM} = 'DEFAULT';
	exec($command);
	exit(1);
    }
559
560
}

561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
#
# Get kernel (major,minor,patchlevel) version tuple.
#
sub getKernelVersion()
{
    my $kernvers = `cat /proc/sys/kernel/osrelease`;
    chomp $kernvers;

    if ($kernvers =~ /^(\d+)\.(\d+)\.(\d+)/) {
	return ($1,$2,$3);
    }

    return undef;
}

576
577
578
579
580
581
582
#
# Create an extra FS using an LVM.
#
sub createExtraFS($$$)
{
    my ($path, $vgname, $size) = @_;
    
583
584
585
586
587
588
    if (! -e $path) {
	system("mkdir $path") == 0
	    or return -1;
    }
    return 0
	if (-e "$path/.mounted");
589
    
590
591
592
593
594
595
596
597
598
599
    my $lvname;
    if ($path =~ /\/(.*)$/) {
	$lvname = $1;
    }
    my $lvpath = "/dev/$vgname/$lvname";
    my $exists = `lvs --noheadings -o origin $lvpath > /dev/null 2>&1`;
    if ($?) {
	system("lvcreate -n $lvname -L $size $vgname") == 0
	    or return -1;

600
	system("mke2fs -j -q $lvpath") == 0
601
602
603
604
605
606
607
	    or return -1;
    }
    if (! -e "$path/.mounted") {
	system("mount $lvpath $path") == 0
	    or return -1;
    }
    system("touch $path/.mounted");
608

609
610
611
612
    if (system("egrep -q -s '^${lvpath}' /etc/fstab")) {
	system("echo '$lvpath $path ext3 defaults 0 0' >> /etc/fstab")
	    == 0 or return -1;
    }
613
614
615
    return 0;
}

616
617
618
619
620
621
622
#
# Figure out the size of the LVM.
#
sub lvSize($)
{
    my ($device) = @_;
    
623
    my $lv_size = `lvs -o lv_size --noheadings --units k --nosuffix $device`;
624
625
626
627
628
629
630
631
632
    return undef
	if ($?);
    
    chomp($lv_size);
    $lv_size =~ s/^\s+//;
    $lv_size =~ s/\s+$//;
    return $lv_size;
}

633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
sub restartDHCP()
{
    my $dhcpd_service = 'dhcpd';
    if (-f '/etc/init/isc-dhcp-server.conf') {
        $dhcpd_service = 'isc-dhcp-server';
    }

    # make sure dhcpd is running
    if (-x '/sbin/initctl') {
        # Upstart
        if (mysystem2("/sbin/initctl restart $dhcpd_service") != 0) {
            mysystem2("/sbin/initctl start $dhcpd_service");
        }
    } else {
        #sysvinit
        mysystem2("/etc/init.d/$dhcpd_service restart");
    }
}

652
#
653
654
# Life's a rich picnic.  And all that.
1;