libvnode.pm 13.7 KB
Newer Older
1
#!/usr/bin/perl -wT
2
#
3
# Copyright (c) 2008-2012 University of Utah and the Flux Group.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23
24
25
26
27
28
29
#
# Implements the libvnode API for OpenVZ support in Emulab.
#
package libvnode;
use Exporter;
@ISA    = "Exporter";
@EXPORT = qw( VNODE_STATUS_RUNNING VNODE_STATUS_STOPPED VNODE_STATUS_BOOTING 
30
              VNODE_STATUS_INIT VNODE_STATUS_STOPPING VNODE_STATUS_UNKNOWN
Leigh B. Stoller's avatar
Leigh B. Stoller committed
31
32
	      VNODE_STATUS_MOUNTED
              ipToMac macAddSep fatal mysystem mysystem2
33
	      makeIfaceMaps makeBridgeMaps
Leigh B Stoller's avatar
Leigh B Stoller committed
34
	      findControlNet existsIface findIface findMac
35
36
	      existsBridge findBridge findBridgeIfaces
              findVirtControlNet findDNS downloadImage setState
37
              getKernelVersion isRoutable findDomain createExtraFS
38
39
            );

40
use Data::Dumper;
41
use libtmcc;
42
use libsetup;
43
use Socket;
44

45
46
sub VNODE_STATUS_RUNNING() { return "running"; }
sub VNODE_STATUS_STOPPED() { return "stopped"; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
47
sub VNODE_STATUS_MOUNTED() { return "mounted"; }
48
sub VNODE_STATUS_BOOTING() { return "booting"; }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
49
50
sub VNODE_STATUS_INIT()    { return "init"; }
sub VNODE_STATUS_STOPPING(){ return "stopping"; }
51
52
sub VNODE_STATUS_UNKNOWN() { return "unknown"; }

53
54
55
56
57
58
59
60
61
62
63
64
#
# 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";
my $VCNET_NET	    = "172.16.0.0";
my $VCNET_MASK      = "255.240.0.0";
my $VCNET_GW	    = "172.16.0.1";

my $debug = 0;

65
66
sub mysystem($);

67
68
69
70
71
72
sub setDebug($) {
    $debug = shift;
    print "libvnode: debug=$debug\n"
	if ($debug);
}

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
119
120
121
122
123
124
125
126
sub setState($) {
    my ($state) = @_;

    libtmcc::tmcc(TMCCCMD_STATE(),"$state");
}

#
# 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+)$/) {
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
	    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};
142
143
		}
	    }
144
145
	    if (!defined($mounts{"/dev/$dev$part"}) 
		&& !defined($ftents{"/dev/$dev$part"})) {
146
147

		# try checking its ext2 label
148
		my @outlines = `dumpe2fs -h /dev/$dev$part 2>&1`;
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
		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
167
		my $output = `sfdisk --print-id /dev/$dev $part`;
168
		chomp($output);
169
170
		if ($?) {
		    print STDERR "WARNING: findSpareDisks: error running 'sfdisk --print-id /dev/$dev $part': $! ... ignoring /dev/$dev$part\n";
171
		}
172
173
		elsif ($output eq "0") {
		    $retval{$dev}{"$part"}{"size"} = $BLKSIZE * $1;
174
175
176
177
178
179
180
181
182
183
184
185
186
187
		}
	    }
	}
    }
    foreach my $k (keys(%retval)) {
	if (scalar(keys(%{$retval{$k}})) == 0) {
	    delete $retval{$k};
	}
    }
    close(PFD);

    return %retval;
}

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
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
257
258
259
260
261
262
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
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) {
	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);
	$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);
}

#
# Find virtual control net iface info.  Returns:
# (net,mask,GW)
#
sub findVirtControlNet()
{
    return ($VCNET_NET, $VCNET_MASK, $VCNET_GW);
}

Leigh B Stoller's avatar
Leigh B Stoller committed
306
307
308
309
310
311
312
313
314
sub existsIface($) {
    my $iface = shift;

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

    return 0;
}

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
sub findIface($) {
    my $mac = shift;

    $mac =~ s/://g;
    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) {
347
	if ($line =~ /^([\w\d\-\.]+)\s+/) {
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
	    $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;
}

397
398
399
400
401
#
# 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.
#
402
403
sub downloadImage($$$$) {
    my ($imagepath,$todisk,$nodeid,$reload_args_ref) = @_;
404
405
406
407
408
409

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

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

412
413
414
    if (!defined($addr) || $addr eq "") {
	# frisbee master server world
	my ($server, $imageid);
415
	my $proxyopt = "";
416
417
418
419
420
421
422

	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";
	}
423
	if (SHAREDHOST()) {
424
425
	    $proxyopt = "-P $nodeid";
	}
426
	if ($server && $imageid) {
427
	    mysystem2("$FRISBEE -M 64 $proxyopt ".
428
		     "         -S $server -B 30 -F $imageid $imagepath");
429
430
	    return -1
		if ($?);
431
432
433
434
435
436
437
	}
	else {
	    print STDERR "Could not parse frisbee loadinfo\n";
	    return -1;
	}
    }
    elsif ($addr =~/^(\d+\.\d+\.\d+\.\d+):(\d+)$/) {
438
439
440
	my $mcastaddr = $1;
	my $mcastport = $2;

441
	mysystem2("$FRISBEE -M 64 -m $mcastaddr -p $mcastport $imagepath");
442
443
	return -1
	    if ($?);
444
445
    }
    elsif ($addr =~ /^http/) {
446
	if ($todisk) {
447
448
	    mysystem("wget -nv -N -P -O - '$addr' | ".
		     "$IMAGEUNZIP -W 32 - $imagepath");
449
450
451
	} else {
	    mysystem("wget -nv -N -P -O $imagepath '$addr'");
	}
452
453
454
455
456
    }

    return 0;
}

457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
sub ipToMac($) {
    my $ip = shift;

    return sprintf("0000%02x%02x%02x%02x",$1,$2,$3,$4)
	if ($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);

    return undef;
}

sub macAddSep($;$) {
    my ($mac,$sep) = @_;
    if (!defined($sep)) {
	$sep = ":";
    }

    return "$1$sep$2$sep$3$sep$4$sep$5$sep$6"
	if ($mac =~ /^([0-9a-zA-Z]{2})([0-9a-zA-Z]{2})([0-9a-zA-Z]{2})([0-9a-zA-Z]{2})([0-9a-zA-Z]{2})([0-9a-zA-Z]{2})$/);

    return undef;
}

478
479
480
481
482
483
484
#
# XXX boss is the DNS server for everyone
#
sub findDNS($)
{
    my ($ip) = @_;

485
    my ($bossname,$bossip) = libtmcc::tmccbossinfo();
486
487
488
    if ($bossip =~ /^(\d+\.\d+\.\d+\.\d+)$/) {
	$bossip = $1;
    } else {
489
	die "Could not find boss IP address (tmccbossinfo failed?)";
490
491
492
493
494
    }

    return $bossip;
}

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
#
# Print error and exit.
#
sub fatal($)
{
    my ($msg) = @_;

    die("*** $0:\n".
	"    $msg\n");
}

#
# Run a command string, redirecting output to a logfile.
#
sub mysystem($)
{
    my ($command) = @_;

    if (1) {
	print STDERR "mysystem: '$command'\n";
    }

    system($command);
    if ($?) {
	fatal("Command failed: $? - $command");
    }
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
522
523
524
525
526
527
528
529
530
531
532
533
534
sub mysystem2($)
{
    my ($command) = @_;

    if (1) {
	print STDERR "mysystem: '$command'\n";
    }

    system($command);
    if ($?) {
	print STDERR "Command failed: $? - '$command'\n";
    }
}
535

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#
# 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;
}

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
#
# Is an IP routable?
#
sub isRoutable($)
{
    my ($IP)  = @_;
    my ($a,$b,$c,$d) = ($IP =~ /^(\d*)\.(\d*)\.(\d*)\.(\d*)/);

    #
    # These are unroutable:
    # 10.0.0.0        -   10.255.255.255  (10/8 prefix)
    # 172.16.0.0      -   172.31.255.255  (172.16/12 prefix)
    # 192.168.0.0     -   192.168.255.255 (192.168/16 prefix)
    #

    # Easy tests.
    return 0
	if (($a eq "10") ||
	    ($a eq "192" && $b eq "168"));

    # Lastly
    return 0
	if (inet_ntoa((inet_aton($IP) & inet_aton("255.240.0.0"))) eq
	    "172.16.0.0");

    return 1;
}

579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
#
# Get our domain
#
sub findDomain()
{
    import emulabpaths;

    return undef
	if (! -e "$BOOTDIR/mydomain");
    
    my $domain = `cat $BOOTDIR/mydomain`;
    chomp($domain);
    return $domain;
}

#
# Create an extra FS using an LVM.
#
sub createExtraFS($$$)
{
    my ($path, $vgname, $size) = @_;
    
    return
	if (-e $path);

    system("mkdir $path") == 0
	or return -1;
    
607
    system("lvcreate -n extrafs -L $size $vgname") == 0
608
609
610
611
612
613
614
615
616
617
618
619
620
621
	or return -1;

    system("mke2fs -j /dev/$vgname/extrafs") == 0
	or return -1;

    system("mount /dev/$vgname/extrafs $path") == 0
	or return -1;

    system("echo '/dev/$vgname/extrafs $path ext3 defaults 0 0' >> /etc/fstab")
	== 0 or return -1;

    return 0;
}

622
#
623
624
# Life's a rich picnic.  And all that.
1;