libvnode.pm 13.3 KB
Newer Older
1
#!/usr/bin/perl -wT
2
#
3
# Copyright (c) 2008-2013 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
34
35
            );

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

41
42
43
44
45
46
47
#
# 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";

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

51
my $debug = 0;
52

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

59
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
#
# 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;
    }
89

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    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";

    # Retry a few times cause of iptables locking stupidity.
    for (my $i = 0; $i < 10; $i++) {
	system("$IPTABLES -v -t nat -$op PREROUTING -p $protocol -d $ext_ip ".
	       "--dport $ext_port -j DNAT ".
	       "--to-destination $int_ip:$int_port");
	
	if ($? == 0) {
	    return 0;
	}
	sleep(2);
    }

    # Operation failed after multiple retries - return error
    print STDERR "WARNING: forwardPort: Failed to manipulate NAT after ".
	         "several attempts!\n";
    return -1;
}

sub removePortForward($) {
    my $ref = shift;
    forwardPort($ref,1)
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
}

#
# A spare disk or disk partition is one whose partition ID is 0 and is not
# mounted and is not in /etc/fstab AND is larger than 8GB.  Yes, this means 
# it's possible that we might steal partitions that are in /etc/fstab by 
# UUID -- oh well.
#
# 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.
#
sub findSpareDisks() {
    my %retval = ();
    my %mounts = ();
    my %ftents = ();

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

    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]+)$/) {
	    if (!defined($mounts{"/dev/$2"}) && !defined($ftents{"/dev/$2"})) {
		$retval{$2}{"size"} = $BLKSIZE * $1;
	    }
	}
	elsif ($line =~ /^\s*\d+\s+\d+\s+(\d+)\s+([a-zA-Z]+)(\d+)$/) {
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
	    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};
184
185
		}
	    }
186
187
	    if (!defined($mounts{"/dev/$dev$part"}) 
		&& !defined($ftents{"/dev/$dev$part"})) {
188
189

		# try checking its ext2 label
190
		my @outlines = `dumpe2fs -h /dev/$dev$part 2>&1`;
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
		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
209
		my $output = `sfdisk --print-id /dev/$dev $part`;
210
		chomp($output);
211
212
		if ($?) {
		    print STDERR "WARNING: findSpareDisks: error running 'sfdisk --print-id /dev/$dev $part': $! ... ignoring /dev/$dev$part\n";
213
		}
214
215
		elsif ($output eq "0") {
		    $retval{$dev}{"$part"}{"size"} = $BLKSIZE * $1;
216
217
218
219
220
221
222
223
224
225
226
227
228
229
		}
	    }
	}
    }
    foreach my $k (keys(%retval)) {
	if (scalar(keys(%{$retval{$k}})) == 0) {
	    delete $retval{$k};
	}
    }
    close(PFD);

    return %retval;
}

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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) {
257
258
259
	next
	    if ($iface =~ /^ifb/ || $iface =~ /^imq/);
	
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
	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);
275
	$mac = lc($mac);
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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
	$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
343
344
345
346
347
348
349
350
351
sub existsIface($) {
    my $iface = shift;

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

    return 0;
}

352
353
354
355
sub findIface($) {
    my $mac = shift;

    $mac =~ s/://g;
356
    $mac = lc($mac);
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
    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) {
385
	if ($line =~ /^([\w\d\-\.]+)\s+/) {
386
387
388
389
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
	    $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;
}

435
436
437
438
439
#
# Since (some) vnodes are imageable now, we provide an image fetch
# mechanism.  Caller provides an imagepath for frisbee, and a hash of args that
# comes directly from loadinfo.
#
440
441
sub downloadImage($$$$) {
    my ($imagepath,$todisk,$nodeid,$reload_args_ref) = @_;
442
443
444
445
446
447

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

    my $addr = $reload_args_ref->{"ADDR"};
    my $FRISBEE = "/usr/local/etc/emulab/frisbee";
448
    my $IMAGEUNZIP = "/usr/local/bin/imageunzip";
449

450
451
452
    if (!defined($addr) || $addr eq "") {
	# frisbee master server world
	my ($server, $imageid);
453
454
	my $proxyopt  = "";
	my $todiskopt = "";
455
456
457
458
459
460
461

	if ($reload_args_ref->{"SERVER"} =~ /^(\d+\.\d+\.\d+\.\d+)$/) {
	    $server = $1;
	}
	if ($reload_args_ref->{"IMAGEID"} =~ /^([-\d\w]+),([-\d\w]+),([-\d\w]+)$/) {
	    $imageid = "$1/$3";
	}
462
	if (SHAREDHOST()) {
463
464
	    $proxyopt = "-P $nodeid";
	}
465
466
467
	if (!$todisk) {
	    $todiskopt = "-N";
	}
468
	if ($server && $imageid) {
469
	    mysystem2("$FRISBEE -f -M 64 $proxyopt $todiskopt ".
470
		     "         -S $server -B 30 -F $imageid $imagepath");
471
472
	    return -1
		if ($?);
473
474
475
476
477
478
479
	}
	else {
	    print STDERR "Could not parse frisbee loadinfo\n";
	    return -1;
	}
    }
    elsif ($addr =~/^(\d+\.\d+\.\d+\.\d+):(\d+)$/) {
480
481
482
	my $mcastaddr = $1;
	my $mcastport = $2;

483
	mysystem2("$FRISBEE -f -M 64 -m $mcastaddr -p $mcastport $imagepath");
484
485
	return -1
	    if ($?);
486
487
    }
    elsif ($addr =~ /^http/) {
488
	if ($todisk) {
489
	    mysystem("wget -nv -N -P -O - '$addr' | ".
490
		     "$IMAGEUNZIP -f -W 32 - $imagepath");
491
492
493
	} else {
	    mysystem("wget -nv -N -P -O $imagepath '$addr'");
	}
494
495
496
497
498
    }

    return 0;
}

499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
#
# 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;
}

514
515
516
517
518
519
520
#
# Create an extra FS using an LVM.
#
sub createExtraFS($$$)
{
    my ($path, $vgname, $size) = @_;
    
521
522
523
524
525
526
    if (! -e $path) {
	system("mkdir $path") == 0
	    or return -1;
    }
    return 0
	if (-e "$path/.mounted");
527
    
528
529
530
531
532
533
534
535
536
537
    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;

538
	system("mke2fs -j -q $lvpath") == 0
539
540
541
542
543
544
545
	    or return -1;
    }
    if (! -e "$path/.mounted") {
	system("mount $lvpath $path") == 0
	    or return -1;
    }
    system("touch $path/.mounted");
546

547
548
549
550
    if (system("egrep -q -s '^${lvpath}' /etc/fstab")) {
	system("echo '$lvpath $path ext3 defaults 0 0' >> /etc/fstab")
	    == 0 or return -1;
    }
551
552
553
    return 0;
}

554
555
556
557
558
559
560
#
# Figure out the size of the LVM.
#
sub lvSize($)
{
    my ($device) = @_;
    
561
    my $lv_size = `lvs -o lv_size --noheadings --units k --nosuffix $device`;
562
563
564
565
566
567
568
569
570
    return undef
	if ($?);
    
    chomp($lv_size);
    $lv_size =~ s/^\s+//;
    $lv_size =~ s/\s+$//;
    return $lv_size;
}

571
#
572
573
# Life's a rich picnic.  And all that.
1;