vnode_setup.in 16.5 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2 3 4

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2008 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
6 7
# All rights reserved.
#
8 9 10 11 12 13 14 15 16 17 18 19 20
use English;
use Getopt::Std;

#
# Set up the vnode state on a virtual (multiplexed) node.
#
# XXX - This script should only be run from os_setup!
#
# The output is all jumbled together since the updates are issued in parallel.
# Might be a pain when debugging. 
# 
sub usage()
{
21
    print STDOUT "Usage: vnode_setup [-f] [-k] [-j] [-p] [-n <numbatch>] [-w <wait_time>] <pid> <eid> [node ...]\n";
22 23
    exit(-1);
}
24
my  $optlist = "fdkjpn:w:";
25 26 27 28 29 30 31 32 33 34

#
# We don't want to run this script unless its the real version.
# That is, it must be setuid root. 
#
if ($EUID != 0) {
    die("*** $0:\n".
	"    Must be root! Maybe its a development version?\n");
}

35 36 37 38 39 40 41
#
# Configure variables
#
my $TB		= "@prefix@";
my $TESTMODE    = @TESTMODE@;
my $TBOPS       = "@TBOPSEMAIL@";
my $TBLOGS      = "@TBLOGSEMAIL@";
42
my $CLIENT_BIN  = "@CLIENT_BINDIR@";
43
my $PGENISUPPORT= @PROTOGENI_SUPPORT@;
44

45
my $SAVEUID     = $UID;
46 47 48 49 50
my $ssh		= "$TB/bin/sshtb -n";
my $debug       = 0;
my $force       = 0;
my $failed      = 0;
my $killmode    = 0;
51 52
my $jailonly    = 0;
my $plabonly    = 0;
Kirk Webb's avatar
Kirk Webb committed
53
my $numbatch    = 10;
Kirk Webb's avatar
Kirk Webb committed
54
my $childwait   = 120;
55 56 57 58 59 60 61 62
my $dbuid;

#
# Load the Testbed support stuff. 
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
63 64 65
use libtblog;
use Experiment;
use Node;
66 67 68
if ($PGENISUPPORT) {
    require GeniEmulab;
}
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

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

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
85
if (@ARGV < 2) {
86 87 88 89 90 91 92 93 94 95 96
    usage();
}
if (defined($options{"f"})) {
    $force = 1;
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"k"})) {
    $killmode = 1;
}
97 98 99 100 101 102
if (defined($options{"j"})) {
    $jailonly = 1;
}
if (defined($options{"p"})) {
    $plabonly = 1;
}
Kirk Webb's avatar
Kirk Webb committed
103 104 105 106 107 108 109 110
if (defined($options{"n"})) {
    if ($options{"n"} =~ /^(\d+)$/) {
        $numbatch = $1;
    }
    else {
        die ("*** Bad data in numbatch: $options{'n'}");
    }
}
Kirk Webb's avatar
Kirk Webb committed
111 112 113 114 115 116 117 118
if (defined($options{"w"})) {
    if ($options{"w"} =~ /^(\d+)$/) {
        $childwait = $1;
    }
    else {
        die ("*** Bad data in wait_time: $options{'w'}");
    }
}
Kirk Webb's avatar
Kirk Webb committed
119

120 121
my $pid   = shift(@ARGV);
my $eid   = shift(@ARGV);
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

#
# Untaint the arguments.
#
if ($pid =~ /^([-\@\w]+)$/) {
    $pid = $1;
}
else {
    die("*** Bad data in pid: $pid\n");
}	
if ($eid =~ /^([-\@\w]+)$/) {
    $eid = $1;
}
else {
    die("*** Bad data in eid: $eid\n");
}

139
if ($plabonly && $jailonly) {
140 141 142 143 144 145 146 147 148 149 150 151 152
    tbdie("*** '-j' and '-p' are mutually exclusive.");
}

#
# Verify user and get his DB uid and other info for later.
#
my $this_user = User->ThisUser();
if (!defined($this_user) && $UID) {
    tbdie("You ($UID) do not exist!");
}
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    tbdie("Could not locate object for experiment $pid/$eid");
153 154
}

155
#
156 157
# Verify permission to muck with this experiment. Note that this script
# is run as root from the plab monitor daemon.
158
#
159 160 161
if (defined($this_user) && !$this_user->IsAdmin() &&
    !$experiment->AccessCheck($this_user, TB_EXPT_DESTROY)) {
    tbdie("You do not have permission to mess with $pid/$eid!");
162 163 164
}

#
165
# Get the list of nodes in this experiment.
166
#
167
my @nodes = $experiment->NodeList(1);
168
if (! @nodes) {
169
    tbwarn("No allocated nodes in experiment $pid/$eid.");
170
    exit(0);
171
}
172 173

# Nodes on the command line. Operate only on this set.
174 175 176 177 178 179 180 181 182 183 184 185 186 187
if (@ARGV) {
    my %fulllist = ();

    # Temporary hash list for searching.
    foreach my $node ( @nodes ) {
	$fulllist{$node} = 1;
    }
    @nodes = ();

    foreach my $node ( @ARGV ) {
	if ($node =~ /^([-\@\w]+)$/) {
	    $node = $1;

	    if (!defined($fulllist{$node})) {
188
		tbdie("Node $node is not allocated to $pid/$eid!");
189 190 191
	    }
	}
	else {
192
	    tbdie("Bad node name: $node.");
193 194 195 196
	}
	push(@nodes, $node);
    }
}
197
my $exptstate = $experiment->state();
198 199 200

# Just the vnodes mam.
foreach my $node (@nodes) {
201
    my $mode = ($killmode ? "teardown" : "setup");
202 203 204 205
    
    my $nodeobj = Node->Lookup($node);
    if (!defined($nodeobj)) {
	tbdie("Could not map $node to its object");
206
    }
207 208 209 210 211 212 213 214 215 216
    my $jailed     = $nodeobj->jailflag();
    my $plab       = $nodeobj->isplabdslice();
    my $remote     = $nodeobj->isremotenode();
    my $pnode      = $nodeobj->phys_nodeid();
    my $allocstate = $nodeobj->allocstate();
    my $geninode   = $nodeobj->isfednode();

    next
	if (!$nodeobj->isvirtnode());

217
    if (($plabonly || $jailonly) and 
218 219
        !(($plabonly && $plab) || ($jailonly && (($jailed || $remote) 
						 && !$plab)))) {
220 221
        next;
    }
222 223
    if (!defined($pnode)) {
	tbdie("No physical node for $node!");
224
    }
225

226 227 228
    #
    # On remote nodes, or when forcemode is on, always do the deed.
    # Otherwise, look at experiment state.
229 230
    #
    if (!$force) {
231 232 233 234
	if ($exptstate eq EXPTSTATE_SWAPPING) {
	    #
	    # When swapping, local vnodes go down with the physnode.
	    #
235
	    if (! $remote) {
236 237 238 239
		print "$node will $mode with local node $pnode.\n";
		next;
	    }
	    elsif ($allocstate eq TBDB_ALLOCSTATE_DOWN) {
240 241 242 243 244 245 246
		if (!$plab) {
		    print "$node failed to boot; skipping $mode.\n";
		    next;
		}
		# Plab nodes need to be cleaned up.
		print "$node failed to boot; changing to cleanup.\n";
		$mode = "cleanup";
247
	    }
248
	}
249 250
	elsif ($exptstate eq EXPTSTATE_ACTIVATING ||
	       $exptstate eq EXPTSTATE_MODIFY_RESWAP) {
251
	    #
252 253 254 255 256 257 258 259 260 261 262
	    # The allocstate determines if the vnode actually needs to
	    # be setup or torndown. Note that a failed experiment will
	    # cause a bunch of vnodes to be torndown, while in the
	    # ACTIVATING state. See os_setup and assign_wrapper; the
	    # idea is to avoid doing setup/teardown up vnodes on
	    # machines that are rebooting anyway, or that failed.
	    # Complicated by modify which could add/subtract a vnode on
	    # an existing machine, but not reboot the machine. Note that
	    # free (now unused) vnodes will land in RES_TEARDOWN. It is
	    # assumed that these booted okay, and need to be torndown,
	    # even though they are not RES_READY.
263
	    #
264
	    if (! $remote) {
265 266
		if ($killmode) {
		    if ($allocstate eq TBDB_ALLOCSTATE_DOWN) {
267 268 269 270
			print "$node failed to boot; skipping $mode.\n";
			next;
		    }
		    elsif ($allocstate eq TBDB_ALLOCSTATE_RES_INIT_CLEAN()) {
271 272 273
			print "$node never booted; skipping $mode.\n";
			next;
		    }
274 275 276 277
		    elsif ($allocstate eq TBDB_ALLOCSTATE_RES_READY()) {
			print "$node will $mode with local node $pnode.\n";
			next;
		    }
278 279
		}
		elsif ($allocstate eq TBDB_ALLOCSTATE_RES_READY()) {
280
		    print "$node is already setting up on local node $pnode\n";
281 282 283
		    next;
		}
	    }
284 285
	    else {
		if ($killmode) {
286 287 288
		    if ($allocstate eq TBDB_ALLOCSTATE_DEAD) {
			# plab only. See below.
			print "$node failed to initialize; skipping $mode.\n";
289 290
			next;
		    }
291 292 293 294 295 296 297 298 299
		    elsif ($allocstate eq TBDB_ALLOCSTATE_DOWN) {
			if (!$plab) {
			    print "$node failed to boot; skipping $mode.\n";
			    next;
			}
			# Plab nodes need to be cleaned up.
			print "$node failed to boot; changing to cleanup.\n";
			$mode = "cleanup";
		    }
300 301 302 303
		    elsif ($allocstate eq TBDB_ALLOCSTATE_RES_INIT_CLEAN()) {
			print "$node never booted; skipping $mode.\n";
			next;
		    }
304
		}
305 306
		elsif ($allocstate eq TBDB_ALLOCSTATE_RES_READY()) {
		    print "$node is already set up on remote node $pnode\n";
307 308
		    next;
		}
309
		elsif ($allocstate eq TBDB_ALLOCSTATE_RES_INIT_DIRTY()) {
310
		    print "$node needs a reboot on remote node $pnode\n";
311 312
		    $mode = "reboot";
		}
313 314 315 316 317 318 319
		elsif ($allocstate eq TBDB_ALLOCSTATE_RES_RECONFIG()) {
		    print "$node needs a reconfig on remote node $pnode\n";
		    # We do not actually reconfig virtual nodes; just
		    # reboot them. Might reconfig someday, in which case
		    # this would move up into os_setup.
		    $mode = "reboot";
		}
320 321 322 323 324 325 326 327 328 329 330 331 332
		elsif ($plab && $allocstate eq TBDB_ALLOCSTATE_RES_INIT_CLEAN()) {
		    # This is a special case.  If we reuse one of the plab 
		    # nodes, but use a different vname in the topo, there will
		    # be an entry in the database and a slice will be reserved
		    # because it's never torn down.  However, we need to 
		    # skip plabnode alloc and go straight to vnodesetup.
		    #
		    # BUT, we only can do this if the sliver entry is already
		    # in the database!
		    # Also note that this could eventually cause problems
		    # if there is a mistaken sliver entry in the DB.

		    $res = DBQueryFatal(
333 334 335 336 337 338 339
			"select ps.slicename,psn.node_id".
			" from plab_slices as ps" . 
			" left join plab_slice_nodes as psn" . 
			"   on (ps.slicename=psn.slicename" . 
			"       and ps.plc_idx=psn.plc_idx)" . 
			" where ps.pid='$pid' and ps.eid='$eid'" . 
                        "   and psn.node_id='$node'");
340 341 342 343 344 345 346
		    if ($res->numrows == 1) {
			# node exists; change mode to resetup
			$mode = "resetup";
			print "Doing a resetup on '$node'\n";
		    }
		    
		}
347 348
	    }
	}
349 350 351 352 353 354
    }

    #
    # When setting up a vnode, force its event state into SHUTDOWN since
    # no telling what its initial state is. 
    # 
Kirk Webb's avatar
Kirk Webb committed
355 356
    # XXX: Don't we always want to set this?
    #
357
    if ($mode eq "teardown" || $mode eq "reboot") {
358
	$nodeobj->SetEventState(TBDB_NODESTATE_SHUTDOWN);
359
    }
360 361

    #
362 363
    # Put this into the list of calls we have to make in the next loop
    #
364
    push @vnodes, [$nodeobj, $mode];
365 366 367

}

368

369 370
my $children = 0;
my %child_vnodes = ();
Kirk Webb's avatar
Kirk Webb committed
371 372
print "vnode_setup running at parallelization: $numbatch ". 
    "wait_time: $childwait\n";
373 374
while (1) {

Kirk Webb's avatar
Kirk Webb committed
375
    # Space out the invocation of child processes a little.
Kirk Webb's avatar
Kirk Webb committed
376
    sleep(1);
Kirk Webb's avatar
Kirk Webb committed
377

378 379 380 381 382 383 384
    #
    # We're done when we've hit the last vnode, and we've outlived all of our
    # children
    #
    if ((!@vnodes) && ($children == 0)) {
	last;
    }
385

386 387 388
    #
    # There are more free slots
    #
Kirk Webb's avatar
Kirk Webb committed
389
    if (($children < $numbatch) && @vnodes) {
390 391 392 393
	#
	# Look for a vnode that is not on a pnode we're already working on
	# 
	# XXX - do this!
394 395 396 397 398 399 400 401

	my ($nodeobj, $mode) = @{pop @vnodes};
	my $vnode    = $nodeobj->node_id();
	my $jailed   = $nodeobj->jailflag();
	my $plab     = $nodeobj->isplabdslice();
	my $remote   = $nodeobj->isremotenode();
	my $pnode    = $nodeobj->phys_nodeid();
	my $geni     = $nodeobj->isfednode();
402 403 404 405 406 407 408 409 410 411 412 413 414 415
    
	print STDOUT "Doing $mode of vnode $vnode on $pnode ...\n";

	#
	# Run an ssh command in a child process, protected by an alarm to
	# ensure that the ssh is not hung up forever if the machine is in some
	# funky state.
	# 
	my $syspid = fork();

	if ($syspid) {
	    #
	    # Just keep track of it, we'll wait for it finish down below
	    #
416
	    $child_vnodes{$syspid} = [$nodeobj, $mode, time()];
417 418
	    $children++;
	} else {
419 420
	    TBdbfork();	# So we get the event system fork too ...
	    
421
            my $exval = 0;
422 423 424
	    # Must change our real UID to root so that ssh will work.
	    $UID = 0;

425
	    if ($mode eq "setup" && ($plab || !$jailed || $geni)) {
Kirk Webb's avatar
Kirk Webb committed
426 427 428
                # Make sure vnode is in the proper state before trying to
                # bring it up.
                # XXX: do this for all vnodes (see above)?
429 430 431 432 433 434 435 436
                $nodeobj->SetEventState(TBDB_NODESTATE_SHUTDOWN);
		if ($geni) {
		    $UID  = $SAVEUID;
		    $EUID = $UID;
		    $exval = GeniEmulab->StartSlivers($experiment,
						      [ $nodeobj ]);
		}
		elsif ($plab) {
437 438 439 440 441 442 443 444 445 446 447 448 449 450
		    if (TBForkCmd("$TB/sbin/plabnode ". 
				  ($force ? "-f" : "").
				  " alloc $pid $eid $vnode", 1)) {
			print STDERR "*** $0:\n" .
			    "    Plab node allocation failed\n";
			# Should check DB state instead.
			exit(99);
		    }
		}
		else {
		    if (TBForkCmd("$ssh -host $pnode $CLIENT_BIN/vnodesetup ".
				  " -i $vnode", 1)) {
			exit(99);
		    }
451
		}
452
                # Make sure the system knows we now have state on the node!
453
		$nodeobj->SetAllocState(TBDB_ALLOCSTATE_RES_INIT_DIRTY);
454
	    }
455
	    
456 457 458 459 460 461 462
	    if ($geni && ($mode eq "teardown" || $mode eq "cleanup")) {
		$nodeobj->SetEventState(TBDB_NODESTATE_SHUTDOWN);
		$UID  = $SAVEUID;
		$EUID = $UID;
		$exval = GeniEmulab->DestroySlivers($experiment, [ $nodeobj ]);
	    }
	    elsif (!($plab && ($mode eq "cleanup" || $mode eq "teardown"))
463
		&& !($mode eq "setup" && $remote && !$plab)) {
464 465 466 467
		# Cleanup is used only on plab nodes.
		# Don't try to teardown plab vnodes; it's just asking for
		# trouble as the shutdown may hang or take too long.  It's
		# best to simply try and free the vserver below.
468 469
		my $args = (($mode eq "teardown") ? "-k " :
			    ($mode eq "reboot" ? "-r " : " "));
470
		$args   .= ($jailed   ? "-j " : ($plab ? "-p " : "-i "));
471
		$args   .= "$vnode ";
472
		
473 474 475 476 477 478
		# If it's a plab node, we must ssh to the vnode, not pnode.
		my $pnodeOrVnode = $pnode;
		if ($plab) {
		    $pnodeOrVnode = $vnode;
		}
		$exval = TBForkCmd("$ssh -host $pnodeOrVnode ".
479 480 481 482 483
                                 "$CLIENT_BIN/vnodesetup $args",1);
            }

            # Free the plab node lease if necessary.
            if ($plab && ($mode eq "teardown" || $mode eq "cleanup")) {
484
		$nodeobj->SetEventState(TBDB_NODESTATE_SHUTDOWN);
485 486 487 488 489
                exec("$TB/sbin/plabnode free $pid $eid $vnode");
                die("*** $0:\n".
                    "    exec failed!\n");
            }
	    exit($exval);
490 491 492 493 494 495 496 497 498 499 500
	}
    } else {
	#
	# We have too many of the little rugrats, wait for one to die
	#

	#
	# Set up a timer - we want to kill processes after they hit 120 seconds
	# old (not much of a life, is it?), so we find the first one marked for
	# death.
	#
501
	my $oldest;
502
	my $oldestpid = 0;
Kirk Webb's avatar
Kirk Webb committed
503
        my $oldestvnode = "";
504
	while (my ($pid, $aref) = each %child_vnodes) {
505 506
	    my ($nodeobj, $mode, $birthtime) = @$aref;
	    my $vnode = $nodeobj->node_id();
507
	    if ((!$oldestpid) || ($birthtime < $oldest)) {
508 509
		$oldest = $birthtime;
		$oldestpid = $pid;
Kirk Webb's avatar
Kirk Webb committed
510
                $oldestvnode = $vnode;
511 512 513 514 515 516 517 518 519 520 521
	    }
	}

	#
	# Sanity check
	#
	if (!$oldest) {
	    die "*** $0\n".
	    	"Uh oh, I have no children left, something is wrong!\n";
	}

522
	#
Kirk Webb's avatar
Kirk Webb committed
523
	# If the oldest has already expired, just kill it off right now, and go
524 525 526
	# back around the loop
	#
	my $now = time();
Kirk Webb's avatar
Kirk Webb committed
527
	my $waittime = ($oldest + $childwait) - time();
528

529
	#
Kirk Webb's avatar
Kirk Webb committed
530
	# Kill off the oldest if it gets too old while we're waiting.
531
	#
Kirk Webb's avatar
Kirk Webb committed
532 533
        my $childpid = -1;
        my $exitstatus = -1;
534

Kirk Webb's avatar
Kirk Webb committed
535 536 537 538 539 540 541 542 543
        eval {
            local $SIG{ALRM} = sub { die "alarm clock" };

            if ($waittime <= 0) {
                print "*** $0: timeout waiting for vnode: $oldestvnode\n";
                kill("TERM",$oldestpid);
            } else {
                alarm($waittime);
            }
544

Kirk Webb's avatar
Kirk Webb committed
545 546 547 548 549 550 551
            $childpid = wait();
            alarm 0;
            $exitstatus = $?;
        };
        if ($@) {
            die unless $@ =~ /alarm clock/;
            next;
552 553
        }

554 555 556 557 558 559 560 561 562 563 564 565 566
	#
	# Another sanity check
	#
	if ($childpid < 0) {
	    die "*** $0\n".
	    	"wait() returned <0, something is wrong!\n";
	}

	#
	# Look up to see what vnode, etc. this was associated with - if we
	# don't know about this child, ignore it
	#
	my $aref = $child_vnodes{$childpid};
567 568 569 570
	next unless @$aref;	
	my ($nodeobj, $mode, $birthtime) = @$aref;
	my $vnode = $nodeobj->node_id();
	my $pnode = $nodeobj->phys_nodeid();	
571 572 573
	$children--;
	delete $child_vnodes{$childpid};

574
	#
575
	# Look for setup failure, reported back through ssh.
576
	# 
577
	if ($exitstatus) {
578 579
	    print STDERR "vnode $vnode $mode on $pnode returned $?.\n"
		if $debug;
580

581
	    if ($exitstatus == 256) {
582
		print STDERR "$vnode is not running sshd.\n" if $debug;
583 584
	    }
	    elsif ($exitstatus == 15) {
585
		print STDERR "$vnode is wedged.\n" if $debug;
586
	    }
587 588 589
	    elsif ($exitstatus >> 8 == 99) {
		print STDERR "$vnode did not allocate properly.\n" if $debug;
	    }
590

591 592
	    push @failed_nodes, [$vnode, $pnode, $mode, $exitstatus];
	    
593 594
	    warn("*** $0:\n".
		 "    Virtual node $vnode $mode failure!\n");
595
	}
596

597
	if ($nodeobj->isplabdslice()) {
598 599 600 601 602 603 604 605
	    #
	    # If the node was in the setup process, then mark its allocstate
	    # as down so os_setup knows not to bother waiting for it. DEAD
	    # is a temp state, different then DOWN. It indicates the node
	    # was never instantiated (important distinction for plab). 
	    #
	    if ($exitstatus &&
		(($mode eq "setup") || ($mode eq "reboot"))) {
606
		$nodeobj->SetAllocState(TBDB_ALLOCSTATE_DEAD());
607 608
	    }
	}
609 610 611
    }
}

612 613 614 615 616 617
#
# In force node, do not bother with this other stuff. 
#
exit(scalar(@failed_nodes))
    if ($force);

618 619 620 621 622 623
#
# Send mail to testbed-ops about failed nodes
#
if (@failed_nodes) { 
    my $failed_lines = join("\n",map { join("\t",@{$_}) } @failed_nodes);
    SENDMAIL($TBOPS, "Virtual Node failure for $pid/$eid",
624 625 626
	     "The following virtual nodes failed: \n" .
	     "vnode\t\tpnode\tmode\texit status\n" .
	     $failed_lines);
627 628
}

629 630 631 632 633 634
if ($killmode) {
    print STDOUT "Vnode teardown finished.\n";
}
else {
    print STDOUT "Vnode setup initiated on all nodes ...\n";
}
635
exit(0);