mkvnode.pl 14.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
# Copyright (c) 2009 University of Utah and the Flux Group.
# All rights reserved.
#
use strict;
use Getopt::Std;
use English;
use Errno;
use POSIX qw(strftime);
12
use POSIX ":sys_wait_h";
13 14 15 16 17 18 19
use Data::Dumper;

#
# The corollary to mkjail.pl in the freebsd directory ...
#
sub usage()
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
20
    print "Usage: mkvnode [-d] vnodeid\n" . 
21 22 23 24 25 26 27 28
          "  -d   Debug mode.\n" .
          "";
    exit(1);
}
my $optlist  = "d";
my $debug    = 1;
my $leaveme  = 0;
my $cleaning = 0;
29
my $rebooting= 0;
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
my $vnodeid;

#
# Turn off line buffering on output
#
$| = 1;

# Drag in path stuff so we can find emulab stuff.
BEGIN { require "/etc/emulab/paths.pm"; import emulabpaths; }

#
# Load the OS independent support library. It will load the OS dependent
# library and initialize itself. 
# 
use libsetup;
use libtmcc;
use libtestbed;
47
use liblocsetup;
48 49 50 51 52 53 54
    
# Pull in libvnode
use libvnode;

# Helpers
sub MyFatal($);
sub safeLibOp($$$$;@);
55
sub Cleanup(); 
56 57 58 59

# Locals
my $CTRLIPFILE = "/var/emulab/boot/myip";
my $VMPATH     = "/var/emulab/vms";
60 61
my $IPTABLES   = "/sbin/iptables";
	    
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 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 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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
# hah, this is funny... emacs perl mode will not properly indent unless
# I throw this extra block in.  Woo!
{
    if (defined($options{"d"})) {
	$debug = 1;
    }
}
usage()
    if (@ARGV != 1);
$vnodeid = $ARGV[0];

#
# Must be root.
# 
if ($UID != 0) {
    die("*** $0:\n".
	"    Must be root to run this script!\n");
}

# Tell the library what vnode we are messing with.
libsetup_setvnodeid($vnodeid);

#
# Turn on debug timestamps if desired.
#
if ($debug) {
    TBDebugTimeStampsOn();
}

#
# XXX: for now, support only a single vnode type per phys node.  This is bad,
# but it's the current assumption.  For now, we also assume the nodetype since
# we only have pcvm.  Later, we need to get this info from tmcd so we know 
# lib to load.
#
my @nodetypes = ( GENVNODETYPE() );

#
# We go through this crap so that we can pull in multiple packages implementing
# the libvnode API so they (hopefully) won't step on our namespace too much.
#
my %libops = ();
foreach my $type (@nodetypes) {
    if ($type =~ /^([\w\d\-]+)$/) {
	$type = $1;
    }
    # load lib and initialize it
    my %ops;
    eval "use libvnode_$type; %ops = %libvnode_${type}::ops";
    if ($@) {
	die "while trying to load 'libvnode_$type': $@";
    }
    if (0 && $debug) {
	print "%ops($type):\n" . Dumper(%ops);
    }
    $libops{$type} = \%ops;
    if ($debug) {
	$libops{$type}{'setDebug'}->(1);
    }
    $libops{$type}{'init'}->()
}
if ($debug) {
    print "GENVNODETYPE " . GENVNODETYPE() . "\n";
    print "libops:\n" . Dumper(%libops);
}

#
# Need the domain, but no conistent way to do it. Ask tmcc for the
# boss node and parse out the domain. 
#
my $DOMAINNAME = tmccbossname();
die("Could not get bossname from tmcc!")
    if (!defined($DOMAINNAME));

if ($DOMAINNAME =~ /^[-\w]+\.(.*)$/) {
    $DOMAINNAME = $1;
}
else {
    die("Could not parse domain name!");
}

#
# Need the bossip, which we get from virthost emulab boot dir:
#
my $BOSSIP = `cat $BOOTDIR/bossip`;
chomp($BOSSIP);
if ($BOSSIP !~ /^\d+\.\d+\.\d+\.\d+$/) {
    die "Bad bossip '$BOSSIP' in $BOOTDIR/bossip!";
}

#
# In most cases, the vnodeid directory will have been created by the
# caller, and a config file possibly dropped in.  When debugging, we
# have to create it here.
# 
chdir($VMPATH) or
    die("Could not chdir to $VMPATH: $!\n");

if (! -e $vnodeid) {
    mkdir($vnodeid, 0770) or
	fatal("Could not mkdir $vnodeid in $VMPATH: $!");
}
my $VNDIR = "$VMPATH/$vnodeid";

my ($pid, $eid, $vname) = check_nickname();
my %vnconfig;
getgenvnodeconfig(\%vnconfig) == 0
    or fatal("Could not get vnode config for $vnodeid");

# XXX: need to do this for each type encountered! Only happens once.
my $vmtype = GENVNODETYPE();
TBDebugTimeStamp("starting $vmtype rootPreConfig()")
    if ($debug);
$libops{GENVNODETYPE()}{'rootPreConfig'}->();
TBDebugTimeStamp("finished $vmtype rootPreConfig()")
    if ($debug);

# Link and linkdelay stuff we need in the root context.
my %ifconfigs = ();
my %ldconfigs = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
190
my %tunconfig = ();
191 192
my @tmp1;
my @tmp2;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
193
my $tmp3;
194 195 196 197 198 199 200 201 202

fatal("getifconfig($vnodeid): $!")
    if (getifconfig(\@tmp1));
$ifconfigs{$vnodeid} = \@tmp1;

fatal("getlinkdelayconfig($vnodeid): $!") 
    if (getlinkdelayconfig(\@tmp2));
$ldconfigs{$vnodeid} = \@tmp2;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
203 204 205 206
fatal("gettunnelconfig($vnodeid): $!")
    if (gettunnelconfig(\$tmp3));
$tunconfig{$vnodeid} = $tmp3;

207 208 209 210
if ($debug) {
    print "vnconfig:\n" . Dumper(%vnconfig);
    print "ifconfig:\n" . Dumper(%ifconfigs);
    print "ldconfig:\n" . Dumper(%ldconfigs);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
211
    print "tunconfig:\n" . Dumper(%tunconfig);
212 213 214 215 216 217 218 219 220 221 222
}

TBDebugTimeStamp("starting $vmtype rootPreConfigNetwork")
    if ($debug);
$libops{GENVNODETYPE()}{'rootPreConfigNetwork'}->(\%ifconfigs,{},\%ldconfigs)
    == 0 or fatal("rootPreConfigNetwork failed!");
TBDebugTimeStamp("finished $vmtype rootPreConfigNetwork")
    if ($debug);

my ($vmid,$ret,$err);

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
#
# see if we 1) are supposed to be "booting" into the reload mfs, and 2) if
# we have loadinfo.  Need both to reload!
#
my $reload = 0;
my @results = ();
fatal("getbootwhat($vnodeid): $!") 
    if (getbootwhat(\@results));
if (scalar(@results)) {
    if (defined($results[0]->{"WHAT"}) 
	&& $results[0]->{"WHAT"} =~ /frisbee-pcvm/) {
	#
	# Ok, we're reloading, using the fake frisbee pcvm mfs.
	#
	$reload = 1;
    }
}

my $image;
if ($reload) {
    @results = ();
    fatal("getloadinfo($vnodeid): $!") 
	if (getloadinfo(\@results));
    if (!scalar(@results)) {
	fatal("vnode $vnodeid in reloading, but got no loadinfo!");
    }
    else {
	if ($results[0]->{"IMAGEID"} =~ /^([-\d\w]+),([-\d\w]+),([-\d\w]+)$/) {
	    $image = "$1-$2-$3";
	}
	else {
	    fatal("vnode $vnodeid in reloading, but got bogus IMAGEID " . 
		  $results[0]->{"IMAGEID"} . " from loadinfo!");
	}
    }
}

260 261 262 263 264 265 266 267 268 269
#
# If this file exists, we are rebooting an existing container.
#
if (! -e "$VNDIR/vnode.info") {
    #
    # XXX XXX XXX: need to get this from tmcd!
    # NOTE: we first put the type into vndb so that the create call can go!
    #
    $vmtype = GENVNODETYPE();

270 271 272 273 274 275 276 277 278 279
    if ($reload) {
	# OP: create
	($ret,$err) = safeLibOp($vnodeid,'vnodeCreate',0,0,$vnodeid,
				$image,$results[0]);
    }
    else {
	# OP: create
	($ret,$err) = safeLibOp($vnodeid,'vnodeCreate',0,0,$vnodeid);
    }

280 281 282 283 284 285 286
    if ($err) {
	MyFatal("vnodeCreate failed");
    }
    $vmid = $ret;

    mysystem("echo '$vmid $vmtype' > $VNDIR/vnode.info");
    mysystem("echo '$vnodeid' > $VMPATH/vnode.$vmid");
287 288 289

    # bootvnodes wants this to be here...
    mysystem("mkdir -p /var/emulab/jails/$vnodeid");
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
}
else {
    my $str = `cat $VNDIR/vnode.info`;
    chomp($str);
    ($vmid, $vmtype) = ($str =~ /^(\d*) (\w*)$/);

    MyFatal("Cannot determine vmid/from $VNDIR/vnode.info")
	if (!(defined($vmid) && defined($vmtype)));
    
    ($ret,$err) = safeLibOp($vnodeid,'vnodeState',1,0,$vnodeid,$vmid);
    if ($err) {
	MyFatal("Failed to get status for $vnodeid: $err");
    }
    if ($ret ne VNODE_STATUS_STOPPED()) {
	MyFatal("vnode $vnodeid not stopped, no booting!");
    }
306
    $rebooting = 1;
307 308
}

309 310 311 312 313 314 315 316 317 318
my $cnet_mac = ipToMac($vnconfig{'CTRLIP'});
my $ext_ctrlip = `cat $CTRLIPFILE`;
chomp($ext_ctrlip);
if ($ext_ctrlip !~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) {
    # cannot/should not really go on if this happens.
    MyFatal("error prior to vnodePreConfigControlNetwork($vnodeid): " . 
	    " could not find valid ip in $CTRLIPFILE!");
}
my $longdomain = "${eid}.${pid}.${DOMAINNAME}";

319 320 321 322 323 324 325 326
#
# Call back to do things to the container before it boots.
#
sub callback($)
{
    my ($path) = @_;

    if (SHAREDHOST()) {
327
	if (0 && !$rebooting &&
328
	    system("/bin/cp -f ".
329 330 331 332
		   "$TMGROUP $TMPASSWD $TMSHADOW $TMGSHADOW $path/etc") != 0) {
	    return -1;
	}
    }
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    #
    # Set up sshd port to listen on. If the vnode has its own IP
    # then listen on both 22 and the per-vnode port.
    #
    if (system('grep -q -e EmulabJail $path/etc/ssh/sshd_config')) {
	if (exists($vnconfig{'SSHDPORT'}) && $vnconfig{'SSHDPORT'} ne "") {
	    my $sshdport = $vnconfig{'SSHDPORT'};

	    system("echo '# EmulabJail' >> $path/etc/ssh/sshd_config");
	    system("echo 'Port $sshdport' >> $path/etc/ssh/sshd_config");
	    if ($vnconfig{'CTRLIP'} ne $ext_ctrlip) {
		system("echo 'Port 22' >> $path/etc/ssh/sshd_config");
	    }
	}
    }
348 349 350
    return 0;
}

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
if ($rebooting && $reload) {
    #
    # vnode is already stopped due to state check above; now just remove it
    # and recreate it.
    #
    ($ret,$err) = safeLibOp($vnodeid,'vnodeDestroy',1,1,$vnodeid,$vmid);
    if ($err) {
	MyFatal("failed to destroy $vnodeid: $err");
    }

    # OP: create
    ($ret,$err) = safeLibOp($vnodeid,'vnodeCreate',0,0,$vnodeid,
			    $image,$results[0]);
    if ($err) {
	MyFatal("vnodeCreate failed during reboot-reload");
    }
}

369
# OP: preconfig
370
if (safeLibOp($vnodeid,'vnodePreConfig',1,1,$vnodeid,$vmid,\&callback)) {
371 372 373 374 375 376 377 378 379 380 381 382 383
    MyFatal("vnodePreConfig failed");
}

# OP: control net preconfig
if (safeLibOp($vnodeid,'vnodePreConfigControlNetwork',1,1,
	      $vnodeid,$vmid,$vnconfig{'CTRLIP'},
	      $vnconfig{'CTRLMASK'},$cnet_mac,
	      $ext_ctrlip,$vname,$longdomain,$DOMAINNAME,$BOSSIP)) {
    MyFatal("vnodePreConfigControlNetwork failed");
}

# OP: exp net preconfig
if (safeLibOp($vnodeid,'vnodePreConfigExpNetwork',1,1,$vnodeid,$vmid,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
384 385
	      $ifconfigs{$vnodeid},
	      $ldconfigs{$vnodeid},$tunconfig{$vnodeid})) {
386 387 388 389 390 391 392 393 394
    MyFatal("vnodePreConfigExpNetwork failed");
}
if (safeLibOp($vnodeid,'vnodeConfigResources',1,1,$vnodeid,$vmid)) {
    MyFatal("vnodeConfigResources failed");
}
if (safeLibOp($vnodeid,'vnodeConfigDevices',1,1,$vnodeid,$vmid)) {
    MyFatal("vnodeConfigDevices failed");
}

395 396 397 398 399 400 401 402 403 404 405
#
# Route to inner sshd
#
if (exists($vnconfig{'SSHDPORT'}) && $vnconfig{'SSHDPORT'} ne "") {
    my $sshdport = $vnconfig{'SSHDPORT'};
    my $ctrlip   = $vnconfig{'CTRLIP'};
	
    system("$IPTABLES -v -t nat -A PREROUTING -p tcp -d $ext_ctrlip ".
	   "--dport $sshdport -j DNAT --to-destination $ctrlip:$sshdport");
}

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 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 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
#
# Start the container. If all goes well, this will exit cleanly, with the
# it running in its new context. Still, lets protect it with a timer
# since it might get hung up inside and we do not want to get stuck here.
#
my $childpid = fork();
if ($childpid) {
    local $SIG{ALRM} = sub { kill("TERM", $childpid); };
    alarm 30;
    waitpid($childpid, 0);
    alarm 0;

    #
    # If failure then cleanup.
    #
    if ($?) {
	MyFatal("$vnodeid container startup exited with $?");
    }
}
else {
    $SIG{TERM} = 'DEFAULT';

    TBDebugTimeStamp("Starting the container")
	if ($debug);

    if (safeLibOp($vnodeid,'vnodeBoot',1,1,$vnodeid,$vmid)) {
	print STDERR "*** ERROR: vnodeBoot failed\n";
	exit(1);
    }
    TBDebugTimeStamp("Container has been started")
	if ($debug);
    exit(0);
}
if (safeLibOp($vnodeid,'vnodePostConfig',1,1,$vnodeid,$vmid)) {
    MyFatal("vnodePostConfig failed");
}
# XXX: need to do this for each type encountered!
TBDebugTimeStamp("starting $vmtype rootPostConfig()")
    if ($debug);
$libops{$vmtype}{'rootPostConfig'}->();
TBDebugTimeStamp("finished $vmtype rootPostConfig()")
    if ($debug);

# This is for vnodesetup
mysystem("touch $VNDIR/running");

#
# Install a signal handler to catch signals from vnodesetup.
#
sub handler ($) {
    my ($signame) = @_;
    
    $SIG{INT}  = 'IGNORE';
    $SIG{USR1} = 'IGNORE';
    $SIG{TERM} = 'IGNORE';
    $SIG{HUP}  = 'IGNORE';

    if ($signame eq 'USR1') {
	$leaveme = 1;
    }
    MyFatal("Caught a SIG${signame}! Killing the container ...");
}
$SIG{INT}  = \&handler;
$SIG{USR1} = \&handler;
$SIG{HUP}  = \&handler;
$SIG{TERM} = 'IGNORE';

#
# This loop is to catch when the container halts itself.
#
RUNNING: while (1) {
    $childpid = fork();
    if ($childpid) {
	while (1) {
	    my $kidpid = waitpid(-1, 0);

	    #
	    # container exec command returned.  See if it exited
	    # or if the sleep just ended.
	    #
	    if ($kidpid == $childpid) {
487 488 489 490 491 492
		# If the sleep exits, we are going to tear down the
		# VM, but leave it intact if it exited from within
		# (reboot from inside). Otherwise, we get our marching
		# orders from our parent (vnodesetup).
		$leaveme = 1
		    if (!$cleaning);
493 494 495 496 497 498 499 500
		last RUNNING;
	    }
	    else {
		print("Unknown child $kidpid exited with status $?!\n");
		last RUNNING;
	    }
	}
    } else {
501
	($ret,$err) = safeLibOp($vnodeid,'vnodeExec',
502
				1,1,$vnodeid,$vmid,"sleep 100000000");
503

504
	exit($ret);
505 506
    }
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
507
exit(Cleanup());
508 509 510 511 512 513 514 515 516 517 518 519 520

#
# Clean things up.
#
sub Cleanup()
{
    if ($cleaning) {
	die("*** $0:\n".
	    "    Oops, already cleaning!\n");
    }
    $cleaning = 1;

    # If the container was never built, there is nothing to do.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
521
    return 0
522 523
	if (! -e "$VNDIR/vnode.info" || !defined($vmid));

524 525 526 527 528 529 530 531
    if (exists($vnconfig{'SSHDPORT'}) && $vnconfig{'SSHDPORT'} ne "") {
	my $sshdport = $vnconfig{'SSHDPORT'};
	my $ctrlip   = $vnconfig{'CTRLIP'};
	
	system("$IPTABLES -v -t nat -D PREROUTING -p tcp -d $ext_ctrlip ".
	       "--dport $sshdport -j DNAT --to-destination $ctrlip:$sshdport");
    }

532 533 534 535 536
    # if not halted, try that first
    my ($ret,$err) = safeLibOp($vnodeid,'vnodeState',1,0,$vnodeid,$vmid);
    if ($err) {
	print STDERR "*** ERROR: vnodeState: ".
	    "failed to cleanup $vnodeid: $err\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
537
	return -1;
538
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
539
    if ($ret eq VNODE_STATUS_RUNNING()) {
540
	print STDERR "cleanup: $vnodeid not stopped, trying to halt it.\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
541 542 543 544 545 546
	($ret,$err) = safeLibOp($vnodeid,'vnodeHalt',1,1,$vnodeid,$vmid);
	if ($err) {
	    print STDERR "*** ERROR: vnodeHalt: ".
		"failed to halt $vnodeid: $err\n";
	    return -1;
	}
547
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
548 549 550 551 552 553 554 555 556 557
    elsif ($ret eq VNODE_STATUS_MOUNTED()) {
	print STDERR "cleanup: $vnodeid is mounted, trying to unmount it.\n";
	($ret,$err) = safeLibOp($vnodeid,'vnodeUnmount',1,1,$vnodeid,$vmid);
	if ($err) {
	    print STDERR "*** ERROR: vnodeUnmount: ".
		"failed to unmount $vnodeid: $err\n";
	    return -1;
	}
    }
    return 0
558 559 560 561 562 563
	if ($leaveme);

    # now destroy
    ($ret,$err) = safeLibOp($vnodeid,'vnodeDestroy',1,1,$vnodeid,$vmid);
    if ($err) {
	print STDERR "*** ERROR: failed to destroy $vnodeid: $err\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
564
	return -1;
565 566 567
    }
    unlink("$VNDIR/vnode.info");
    unlink("$VMPATH/vnode.$vmid");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
568
    return 0;
569 570 571 572 573 574 575 576 577 578 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 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
}
    
#
# Print error and exit.
#
sub MyFatal($)
{
    my ($msg) = @_;

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

#
# Helpers:
#
sub safeLibOp($$$$;@) {
    my ($vnode_id,$op,$autolog,$autoerr,@args) = @_;

    my $sargs = '';
    if (@args > 0) {
	$sargs = join(',',@args);
    }
    TBDebugTimeStamp("starting $vmtype $op($sargs)")
	if ($debug);
    my $ret = eval {
	$libops{$vmtype}{$op}->(@args);
    };
    my $err;
    if ($@) {
	$err = $@;
	if ($autolog) {
	    ;
	}
	TBDebugTimeStamp("failed $vmtype $op($sargs): $@")
	    if ($debug);
	return (-1,$err);
    }
    if ($autoerr && $ret) {
	$err = "$op($vnode_id) failed with exit code $ret!";
	if ($autolog) {
	    ;
	}
	TBDebugTimeStamp("failed $vmtype $op($sargs): exited with $ret")
	    if ($debug);
	return ($ret,$err);
    }

    TBDebugTimeStamp("finished $vmtype $op($sargs)")
	if ($debug);

    return $ret;
}