libreboot.pm.in 33.5 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2000-2018 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 30 31 32 33 34 35 36 37 38 39 40 41 42
#
# node reboot library. Basically the backend to the node_reboot script, but
# also used where we need finer control of rebooting nodes (and failure).
#
# XXX Only suitable for scripts that are already setuid and have not
# dropped privs by the time they call into nodereboot(). I think this
# makes the library somewhat useless.
#
package libreboot;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( nodereboot nodereboot_wait );

# Must come after package declaration!
use lib '@prefix@/lib';
use libdb;
43
use libtblog_simple;
44 45 46 47 48 49 50 51
use English;

#
# Configure variables
#
my $TB		= "@prefix@";
my $CLIENT_BIN  = "@CLIENT_BINDIR@";
my $BOSSNODE    = "@BOSSNODE@";
52 53
my $PGENISUPPORT= @PROTOGENI_SUPPORT@;

54
#
55
# The number of nodes we reboot at a time and the time to wait between batches.
56
# The batch size determines the degree of parallelism.
57 58
#
my $BATCHCOUNT  = 12;
59 60
my $BATCHSLEEP	= 5;

61 62 63 64 65 66 67 68 69 70 71 72 73 74
#
# Various timeouts that really should come from the DB.
#
# These determine the max time per-node that we take to attempt to effect
# a reboot short of power cycling (i.e., the time spent in RebootNode):
#
# node is in PXEWAIT, returns after sending a PXEWAKEUP ("immediately").
# node does not ping, returns after 2 seconds.
# node is pingable and ssh is running, returns after between
#   2 and ($REBOOTTIMO + $PINGWAIT) seconds.
# ssh reboot fails but ipod works, returns after between
#   ($REBOOTTIMO + $PINGWAIT) and ($REBOOTTIMO + 2 * $PINGWAIT) seconds.
# unresponsive to ipod, returns after ($REBOOTTIMO + 2 * $PINGWAIT) seconds.
#
Mike Hibler's avatar
Mike Hibler committed
75
# With current settings, this is between "immediately" and 80 seconds
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
# per node. In the common cases where nodes are in PXEWAIT, alive and
# well (ssh running), or completely dead it takes around 10 seconds max.
# Ironically, the slowest case if for the "alive and well" scenario where
# we have to wait for the node to stop pinging, which means after it has
# shutdown all services and reached the point where it shuts down network
# interfaces.
#

#
# SSH timeouts.
# Connection timeout value should be less than the reboot/reconfig values,
# since the latter two are for the entire operation. Set to zero to not
# have a connect timeout (the historic case).
#
my $CONNECTTIMO		= 10;
my $REBOOTTIMO		= 20;
my $REBOOTVNODETIMO	= 30;
my $RECONFIGTIMO	= 30;

95 96 97 98 99
#
# Default reboot waittime.
# If the user doesn't specify, we use this historic value.
#
my $MAXWAITTIME	= (6 * 60);
100

101 102 103 104
#
# Wait times for a node to stop pinging.
# Both regular case and when the prepare script has to be run.
#
Mike Hibler's avatar
Mike Hibler committed
105
my $PINGWAIT	= 30;
106 107
my $PREPAREWAIT	= 200;

108 109 110 111 112
#
# Testbed Support libraries
#
use libdb;
use libtestbed;
113
use User;
114 115 116 117 118 119 120
use event;
use POSIX qw(strftime);
use IO::Handle;
use Fcntl;

# External Programs
my $ssh		= "$TB/bin/sshtb -n";
121 122 123
if ($CONNECTTIMO) {
    $ssh .= " -o ConnectTimeout=$CONNECTTIMO";
}
124 125 126
my $power	= "$TB/bin/power";
my $vnodesetup	= "$TB/sbin/vnode_setup";
my $bisend      = "$TB/sbin/bootinfosend";
127
my $logfile	= "$TB/log/reboot.log";
128 129 130 131 132
my $ping	= "/sbin/ping";
my $reboot      = "$TB/bin/node_reboot";

# Locals
my $debug       = 0;
133
my $silent      = 0;
134 135 136 137 138 139 140 141
my %children    = ();

#
# The actual library function. 
#
sub nodereboot($$)
{
    my ($args, $result) = @_;
142
    my @nodes       = @{ $args->{'nodelist'}};
143
    my %nodeobjects = ();	# Not in the mood to rewrite this function.
144

145 146 147 148 149
    # Reset our few globals.
    $debug    = 0;
    $silent   = 0;
    %children = ();
    
150 151
    $debug = $args->{'debug'}
        if (exists($args->{'debug'}));
152 153
    $silent = $args->{'silent'}
        if (exists($args->{'silent'}));
154 155 156 157 158 159 160 161

    if ($EUID != 0) {
	#
	# Use the exec version, but only if we do not already have
	# a pipeno in the environment, which would indicate a loop
	# caused by installing improperly.
	#
	if (exists($ENV{'REBOOTPIPENO'})) {
162
	    tberror "Must be root when using library!";
163 164 165 166 167 168 169 170
	    return -1;
	}
	print STDERR "reboot: no privs; invoking real nodereboot script!\n"
	    if ($debug);
	return nodereboot_exec($args, $result);
    }

    if (!defined($args->{'nodelist'})) {
171
	tberror "Must supply a node list!";
172 173 174
	return -1;
    }
    my $powercycle  = 0;
175
    my $rebootmode  = 0;
176
    my $waitmode    = 0;
177
    my $waittime    = $MAXWAITTIME;
178 179 180
    my $realmode    = 1;
    my $killmode    = 0;
    my $freemode    = 0;
181
    my $prepare     = 0;
182 183 184
    my $reconfig    = 0;
    my $asyncmode   = 0;
    my $pipemode    = 0;
185
    my $force       = 0;
186 187

    $powercycle  = $args->{'powercycle'} if (exists($args->{'powercycle'}));
188
    $rebootmode  = $args->{'rebootmode'} if (exists($args->{'rebootmode'}));
189
    $waitmode    = $args->{'waitmode'}   if (exists($args->{'waitmode'}));
190
    $waittime    = $args->{'waittime'}   if (exists($args->{'waittime'}));
191 192 193
    $realmode    = $args->{'realmode'}   if (exists($args->{'realmode'}));
    $killmode    = $args->{'killmode'}   if (exists($args->{'killmode'}));
    $freemode    = $args->{'freemode'}   if (exists($args->{'freemode'}));
194
    $prepare     = $args->{'prepare'}    if (exists($args->{'prepare'}));
195 196
    $reconfig    = $args->{'reconfig'}   if (exists($args->{'reconfig'}));
    $asyncmode   = $args->{'asyncmode'}  if (exists($args->{'asyncmode'}));
197
    $force       = $args->{'force'}      if (exists($args->{'force'}));
198 199 200 201 202 203 204 205 206 207 208 209

    #
    # If pipeno is specified in the environment, we write the results to
    # that pipe.
    # 
    if (exists($ENV{'REBOOTPIPENO'})) {
	$pipemode = $ENV{'REBOOTPIPENO'};

	if ($pipemode =~ /^(\d+)$/) {
	    $pipemode = $1;
	}
	else {
210
	    tberror "Bad pipeno in environment: $pipemode!";
211 212 213 214 215 216 217 218 219
	    return -1;
	}
    }

    #
    # Verify permission to reboot these nodes.
    #
    if ($UID && !TBAdmin($UID) &&
	! TBNodeAccessCheck($UID, TB_NODEACCESS_REBOOT, @nodes)) {
220
	tberror "You do not have permission to reboot some of the nodes!";
221 222 223 224 225 226 227
	return -1;
    }

    # Locals.
    my %pids	 = ();
    my $failed   = 0;

228 229 230 231
    # XXX - Wisconsin hack to avoid rebooting routers - this needs to be
    # replaced with the node_capabilities stuff or similar.
    my @temp = ();
    foreach my $node (@nodes) {
232 233
	my $nodeobject = Node->Lookup($node);
	my $rebootable = $nodeobject->rebootable();
234

235
	$nodeobjects{$node} = $nodeobject;
236
	push(@temp,$node) if ($rebootable || $force);
237 238 239 240
    }
    @nodes = @temp;
    # END XXX

241 242 243 244 245 246 247 248 249
    #
    # VIRTNODE HACK: Virtual nodes are special. We can reboot jailed
    # vnodes, but not old style (non-jail). Also, if we are going to
    # reboot the physical node that a vnode is on, do not bother with
    # rebooting the vnode since it will certainly get rebooted anyway!
    #
    my %realnodes = ();
    my %virtnodes = ();

250 251 252 253 254 255 256
    #
    # Geni node reboot/wait is optimized inside libGeni, so keep them
    # separate. Both real and virtual; libGeni treats them the same
    # since the Protogeni interface makes no distinction.
    #
    my %geninodes = ();

257
    foreach my $node (@nodes) {
258 259 260 261 262 263 264 265 266 267
	my $nodeobj = $nodeobjects{$node};
	if (!defined($nodeobj)) {
	    tbdie("Could not map $node to its object");
	}
	my $jailed     = $nodeobj->jailflag();
	my $plab       = $nodeobj->isplabdslice();
	my $pnode      = $nodeobj->phys_nodeid();
	my $geninode   = $nodeobj->isfednode();
	my $rebootable = $nodeobj->rebootable();
	
268 269 270
	# All nodes start out as being successful; altered later as needed.
	$result->{$node} = 0;

271 272 273 274 275
	if ($geninode) {
	    $geninodes{$node} = $nodeobj;
	}
	elsif ($nodeobj->isvirtnode()) {
	    if (!$jailed && !$plab && !$rebootable) {
276 277 278
		print "reboot ($node): Skipping old style virtual node\n";
		next;
	    }
279
	    if (!defined($pnode)) {
280
	        tberror "$node: No physical node!";
281 282 283 284 285 286 287 288 289 290 291 292
		return -1;
	    }
	    $virtnodes{$node} = $pnode;
	}
	else {
	    $realnodes{$node} = $node;
	}
    }
    for my $node ( keys(%virtnodes) ) {
	my $pnode = $virtnodes{$node};

	if (defined($realnodes{$pnode})) {
Leigh Stoller's avatar
Leigh Stoller committed
293 294
	    print "reboot: Dropping $node since its host $pnode will reboot\n"
		if (!$silent);
295 296 297
	    delete($virtnodes{$node});
	}
    }
298
    if (! (keys(%realnodes) || keys(%virtnodes) || keys(%geninodes))) {
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
	print "reboot: No nodes to reboot.\n";
	return 0;
    }
    my @sortednodes = sort(keys(%realnodes));

    #
    # This stuff is incomplete and non-functional.
    # 
    if (!$realmode) {
	EventSendFatal(host      => $BOSSNODE ,
		       objtype   => TBDB_TBEVENT_COMMAND ,
		       eventtype => TBDB_COMMAND_REBOOT ,
		       objname   => join(",", @sortednodes));
	# In here we can do some output to tell the user what's going on.
	if ($waitmode) {
	    # Wait for [SHUTDOWN,ISUP]
	}
	else {
	    # Wait for [SHUTDOWN]
	}
	return 0;
    }

    #
    # This is somewhat hackish. To promote parallelism, we want to fork off
    # the reboot from the parent so it can do other things.  The problem is
    # how to return status via the results vector. Well, lets do it with
    # some simple IPC. Since the results vector is simply a hash of node
    # name to an integer value, its easy to pass that back.
    #
    # We return the pid to the caller, which it can wait on either directly
    # or by calling back into this library if it wants to actually get the
    # results from the child!
    #
    if ($asyncmode) {
	#
	# Create a pipe to read back results from the child we will create.
	#
	if (! pipe(PARENT_READER, CHILD_WRITER)) {
338
	    tberror "creating pipe: $!";
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
	    return -1;
	}
	CHILD_WRITER->autoflush(1);

	if (my $childpid = fork()) {
	    close(CHILD_WRITER);
	    $children{$childpid} = [ *PARENT_READER, $result ];
	    return $childpid;
	}
	#
	# Child keeps going. 
	#
	close(PARENT_READER);
	TBdbfork();

	print STDERR "reboot: Running in asyncmode.\n"
	    if ($debug);
    }
    elsif ($pipemode) {
	#
	# We were invoked with an FD already opened to write the results to.
	# See nodereboot_exec() below. The operation from here is basically
	# the same as in asyncmode, but we do not need to create the pipe,
	# but rather just write the results to the pipe we got. 
	#
	if (! open(CHILD_WRITER, ">>&=${pipemode}")) {
365
	    tberror "reopening pipe: $!";
366 367 368 369 370 371 372 373
	    return -1;
	}
	CHILD_WRITER->autoflush(1);

	print STDERR "reboot: Running in pipemode ($pipemode).\n"
	    if ($debug);
    }

374 375 376 377
    #
    # Fire off the geninode reboots. 
    #
    if (keys(%geninodes)) {
378 379
	require libGeni;
	
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	my $this_user = User->ThisUser();
	if (!defined($this_user)) {
	    tbdie("Could not determine current user for libGeni\n");
	}
	if (libGeni::RestartNodes($this_user, $debug, values(%geninodes))) {
	    tbdie("Could not restart protogeni nodes\n");
	}
	#
	# We always do a wait for geni nodes since for nodes in "basic"
	# cooked mode, nothing will be reporting a state change from the
	# node. We have to go poll it to make sure that the node is alive,
	# and so we can report ISUP for it. This is a bit of a violation of
	# the default reboot model, which is fire and forget when waitmode
	# is not set, but no way around it.
	#
	if (libGeni::WaitForNodes($this_user, $debug,
				  undef, values(%geninodes))) {
	    tbdie("Error in waiting for protogeni nodes\n");
	}
    }

401
    #
402 403 404 405 406 407 408 409 410
    # We do not want lots of nodes all rebooting at the same time, it puts
    # a strain on UDP-based PXE/DHCP/TFTP protocols.  So we group them in
    # batches and wait a short time between batches.
    #
    # Currently batches are organized by increasing node order.  In the
    # future we may want to batch based on power controllers; e.g. either
    # reboot all nodes on a power controller at once or AVOID rebooting
    # all nodes on a power controller at once (if controller cannot handle
    # max surge of all attached nodes).
411 412 413 414 415 416 417 418 419 420 421
    #
    while (@sortednodes) {
	my @batch     = ();
	my $i         = 0;

	while ($i < $BATCHCOUNT && @sortednodes > 0) {
	    my $node = shift(@sortednodes);
	    push(@batch, $node);
	    $i++;
	}

Mike Hibler's avatar
Mike Hibler committed
422 423
	info("BATCH: ". ($powercycle ? "power cycling " : "rebooting ").
	     join(" ", @batch));
424 425 426 427 428 429 430
	if ($powercycle) {
	    #
	    # In powercyle mode, call the power program for the whole
	    # batch, and continue on. We do not wait for them to go down or
	    # reboot.
	    #
	    if (PowerCycle(@batch)) {
431 432
		tberror "Powercycle failed for one or more of " .
		    join(" ",@batch);
433 434 435 436 437 438 439 440 441 442 443 444
		foreach my $node (@batch) {
		    $result->{$node} = -1;
		    $failed++;
		}
	    }
	}
	else {
	    #
	    # Fire off a reboot process so that we can overlap them all.
	    # We need the pid so we can wait for them all before preceeding.
	    #
	    foreach my $node ( @batch ) {
445
		$pids{$node} = RebootNode($nodeobjects{$node}, $reconfig,
446
					  $killmode, $rebootmode, $prepare);
447 448 449 450 451 452 453 454 455
	    }
	}

	#
	# If there are more nodes to go, then lets pause a bit so that we
	# do not get a flood of machines coming up all at the same exact
	# moment.
	#
	if (@sortednodes) {
Mike Hibler's avatar
Mike Hibler committed
456
	    info("BATCH: pausing for ${BATCHSLEEP}s");
457
	    sleep($BATCHSLEEP);
458 459 460 461 462 463 464
	}
    }

    #
    # Wait for all the reboot children to exit before continuing.
    #
    my @needPowercycle = ();
465
    my @needPowerOn = ();
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    if (scalar(keys(%pids))) {
	foreach my $node (sort(keys(%realnodes))) {
	    my $mypid     = $pids{$node};
	    my $status;

	    #
	    # Child may have avoided the fork, and returned status directly.
	    # Flip it and apply the same test.
	    #
	    if ($mypid <= 0) {
		$status = -$mypid;
	    }
	    else {
		waitpid($mypid, 0);
		$status = $? >> 8;
	    }

	    if ($status == 2) {
		# Child signaled to us that this node needs a power cycle
		push(@needPowercycle, $node);
	    }
487 488 489 490
            elsif ($status == 3) {
                # Child signaled to us that this node needs to be powered on
                push(@needPowerOn, $node);
            }
491
	    elsif ($mypid != 0 && $?) {
492 493
		$failed++;
		$result->{$node} = -1;
494
		tberror "Failed ($?)!";
495 496
	    }
	    else {
497 498
		print STDOUT "reboot ($node): Successful!\n"
		    if (!$silent);
499 500 501 502 503 504 505 506 507
	    }
	}
    }

    #
    # Power cycle nodes that couldn't be brought down any other way
    #
    if (@needPowercycle) {
	if (PowerCycle(@needPowercycle)) {
508 509
	    tberror "Powercycle failed for one or more of " .
		join(" ",@needPowercycle);
510 511 512 513 514 515 516
	    foreach my $node (@needPowercycle) {
		$result->{$node} = -1;
		$failed++;
	    }
	}
    }

517 518 519 520 521 522 523 524 525 526 527 528 529
    #
    # Power on nodes that were turned off
    #
    if (@needPowerOn) {
	if (PowerOn(@needPowerOn)) {
	    tberror "Power on failed for " . join(" ",@needPowerOn);
	    foreach my $node (@needPowerOn) {
		$result->{$node} = -1;
		$failed++;
	    }
	}
    }
    
530 531 532 533 534 535
    #
    # Now do vnodes. Do these serially for now (simple).
    #
    for my $node ( sort(keys(%virtnodes)) ) {
	my $pnode = $virtnodes{$node};

536
	if (RebootVNode($nodeobjects{$node}, $pnode, $reconfig)) {
537 538
	    $failed++;
	    $result->{$node} = -1;
539
	    tberror "$node: Reboot failed (on $pnode)";
540 541
	}
	else {
Leigh Stoller's avatar
Leigh Stoller committed
542 543
	    print STDOUT "reboot ($node): rebooting (on $pnode).\n"
		if (!$silent);
544 545 546 547 548 549 550 551 552
	}
    }

    #
    # Wait for nodes to reboot. We wait only once, no reboots.
    #
    if ($waitmode) {
	my $waitstart = time;

553
	print STDOUT "reboot: Waiting (${waittime}s) for nodes to come up.\n"
554
	    if (!$silent);
555 556 557 558 559

	# Wait for events to filter through stated! If we do not wait, then we
	# could see nodes still in ISUP.
	sleep(2);

560 561 562 563 564 565 566 567 568 569 570
	#
	# States that signify that the reboot stage is done.
	# For normal reboots this means either that the node came
	# or correctly (ISUP) or not (TBFAILED). However, for a reloading
	# node there is no ISUP, it either got into the reloading process
	# (RELOAD/RELOADING) or it didn't (no explicit report).
	#
	my @waitstates = (TBDB_NODESTATE_TBFAILED,
			  TBDB_NODESTATE_ISUP,
			  TBDB_NODEOPMODE_RELOAD."/".TBDB_NODESTATE_RELOADING);

571
	foreach my $node (sort(@nodes)) {
572 573
	    my $actual_state;
	    
574 575 576 577 578 579
	    #
	    # Skip if something failed earlier.
	    #
	    next
		if ($result->{node});
	    
580 581 582 583 584 585 586 587
	    if (!TBNodeStateWait($node, $waitstart, $waittime,
				 \$actual_state, @waitstates)) {
		if ($actual_state ne TBDB_NODESTATE_TBFAILED) {
		    if ($actual_state eq TBDB_NODESTATE_ISUP) {
			print STDOUT "reboot ($node): alive and well.\n";
		    } else {
			print STDOUT "reboot ($node): alive and reloading.\n";
		    }
588
		    Node::SetBootStatus($node, NODEBOOTSTATUS_OKAY);
589 590
		    next;
		}
591
		tberror "$node reported a TBFAILED event.";
592
	    }
593
	    Node::SetBootStatus($node, NODEBOOTSTATUS_FAILED);
594 595 596 597 598
	    $result->{$node} = -1;
	    $failed++;
	}
    }
 done:    
599 600
    print "reboot: Done. There were $failed failures.\n"
	if (!$silent);
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622

    if ($asyncmode || $pipemode) {
	#
	# We are a child. Send back the results to the parent side
	# and *exit* with status instead of returning it.
	# 
	foreach my $node (keys(%{ $result })) {
	    my $status = $result->{$node};

	    print CHILD_WRITER "$node,$status\n";
	}
	close(CHILD_WRITER);
	exit($failed);
    }
    return $failed;
}

#
# Reboot a node in a child process. Return the pid to the parent so
# that it can wait on all the children later.
#
sub RebootNode {
623
    my ($nodeobject, $reconfig, $killmode, $rebootmode, $prepare) = @_;
Mike Hibler's avatar
Mike Hibler committed
624
    my ($status, $syspid, $mypid, $nodestate);
625
    my $pc = $nodeobject->node_id();
626 627

    if ($reconfig) {
628 629
	print "reboot ($pc): Attempting to reconfigure ...\n"
	    if (!$silent);
630 631
    }
    else {
632 633
	print "reboot ($pc): Attempting to reboot ...\n"
	    if (!$silent);
634 635 636 637 638 639 640 641 642 643 644 645 646 647
    }

    # Report some activity into last_ext_act
    TBActivityReport($pc);

    #
    # Is the node in PXEWAIT? If so we want to wake it up so that it can
    # query bootinfo and do what it is supposed to do, without a real reboot.
    # We send the initial wakeup from here, but let stated deal with it
    # failing (timeout) and resending it. That means we could be called
    # with the node in PXEWAKEUP, so send it another wakeup. The point is that
    # stated is controlling the timeouts. Eventually stated gives up and uses
    # the -k option to force a power cycle.
    #
648
    if ($nodeobject->GetEventState(\$nodestate)) {
Mike Hibler's avatar
Mike Hibler committed
649
	info("*** $pc: no event state, power cycling");
650 651 652 653 654
	
	# Signal to the called that the node needs to be power cycled
	return -2;
    }
    if ($nodestate eq TBDB_NODESTATE_PXEWAIT() ||
655
	$nodestate eq TBDB_NODESTATE_PXELIMBO() ||
656 657 658 659 660 661 662
	$nodestate eq TBDB_NODESTATE_PXEWAKEUP()) {
	#
	# In killmode, we do not want to bother with sending a wakeup event.
	# Just do the power cycle. This is used to unstick a machine that
	# is in waitmode, but not responding to the wakeups.
	#
	if ($killmode) {
Mike Hibler's avatar
Mike Hibler committed
663
	    info("$pc: in $nodestate, but power cycling in killmode");
664 665 666 667 668
	    
	    # Signal to the caller that the node needs to be power cycled
	    return -2;
	}

669 670 671 672 673 674 675
	my $whol = 0;
	if ($nodeobject->NodeAttribute("wakeonlan_afterpower", \$whol) == 0) {
	    if ($whol) {
		$nodeobject->SimpleWOL();
	    }
	}
	
676 677 678
	#
	# The aux program sends the event to stated ...
	#
679
	my $reqarg = ($rebootmode ? "-r" : "-q");
Mike Hibler's avatar
Mike Hibler committed
680 681
	#my $optarg = ($debug ? "-dd" : "");
	my $optarg = "";
682
	
Mike Hibler's avatar
Mike Hibler committed
683
	info("$pc: in $nodestate, sending PXEWAKEUP");
684
	system("$bisend $optarg $reqarg $pc");
685
	if ($?) {
Mike Hibler's avatar
Mike Hibler committed
686
	    info("$pc: PXEWAKEUP failed, power cycling");
687
	    tbnotice "$pc: PXEWAKEUP failed; will power cycle.\n";
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
	    
	    # Signal to the caller that the node needs to be power cycled
	    return -2;
	}
	return 0;
    }

    #
    # Do the rest in a child process. After the fork, we do the ping test
    # before we reconnect to the DB. This cuts down on the flurry of connects
    # by a bunch of children (ping will take a moment to run).
    #
    $mypid = fork();
    if ($mypid) {
	return $mypid;
    }

    #
    # See if the machine is pingable. If its not pingable, then we just
    # power cycle the machine rather than wait for ssh to time out.
    #
709
    if (! DoesPing($pc, 0, 1)) {
710
        if ($nodestate eq TBDB_NODESTATE_POWEROFF) {
Mike Hibler's avatar
Mike Hibler committed
711
            info("$pc: powered off, will power on");
712 713 714
            tbnotice "$pc powered off; will power on.";
            exit(3);
        }
Mike Hibler's avatar
Mike Hibler committed
715
	info("$pc: appears dead, power cycle");
716
	tbnotice "$pc appears dead; will power cycle.";
717 718 719 720 721 722 723 724 725 726
	
	# Signal to the parent that the node needs to be power cycled
	exit(2);
    }
    TBdbfork();

    #
    # Machine is pingable at least. Try to reboot it gracefully,
    # or power cycle anyway if that does not work.
    #
Mike Hibler's avatar
Mike Hibler committed
727
    info("$pc: trying ssh ".($reconfig ? "reconfig" : "reboot"));
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

    #
    # Must change our real UID to root so that ssh will work. We save the old
    # UID so that we can restore it after we finish the ssh
    #
    my $oldUID = $UID;
    $UID = 0;

    #
    # If doing a reconfig, first try that in a child.
    #
    if ($reconfig) {
	TBSetNodeEventState($pc, "RECONFIG");
	$syspid = fork();

	if ($syspid) {
	    local $SIG{ALRM} = sub { kill("TERM", $syspid); };
745
	    alarm $RECONFIGTIMO;
746 747 748 749 750 751 752
	    waitpid($syspid, 0);
	    alarm 0;

	    #
	    # The ssh can return non-zero exit status, but still have worked.
	    # FreeBSD for example.
	    #
753
	    my $stat = $?;
Mike Hibler's avatar
Mike Hibler committed
754
	    info("$pc: reconfig returned ".($stat >> 8));
755 756 757 758

	    #
	    # Any failure, revert to plain reboot below.
	    #
759
	    if ($stat == 0) {
760 761 762 763 764 765 766 767 768 769 770
		$UID = $oldUID;
		exit(0);
	    }
	}
	else {
	    exec("$ssh -host $pc ".
		 "/usr/local/etc/emulab/rc/rc.bootsetup -b reconfig");
	    exit(0);
	}
    }

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    #
    # If any of the node's subnodes are being reloaded, wait for the operation
    # to finish before doing the reboot.
    #
    my @subnodes = TBNodeSubNodes($pc);
    foreach my $subnode (@subnodes) {
	my $opmode;
	
	if (TBGetNodeOpMode($subnode, \$opmode) &&
	    defined($opmode) &&
	    (($opmode eq TBDB_NODEOPMODE_RELOADING) ||
	     ($opmode eq TBDB_NODEOPMODE_RELOAD) ||
	     ($opmode eq TBDB_NODEOPMODE_RELOADMOTE))) {
	    my $startwait = time;
	    my $actual_state;

	    print "reboot ($pc): waiting for subnode '$subnode' to finish ".
		"reloading...\n";
	    sleep(5);
	    if (TBNodeStateWait($subnode,
				$startwait,
				(60*10),
				\$actual_state,
				(TBDB_NODESTATE_TBFAILED,
				 TBDB_NODESTATE_ISUP))) {
		print "reboot ($pc): subnode has not finished reloading, ".
		    "rebooting anyways...\n";
	    }
	}
    }

Mike Hibler's avatar
Mike Hibler committed
802 803
    my $didipod = 0;

804 805 806 807 808 809 810 811
    #
    # 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.
    #
    $syspid = fork();

    if ($syspid) {
812 813
	my $timedout = 0;
	local $SIG{ALRM} = sub { kill("TERM", $syspid); $timedout = 1; };
814
	alarm $REBOOTTIMO;
815 816
	waitpid($syspid, 0);
	alarm 0;
817
	my $stat = $? >> 8;
818 819

	#
820 821 822 823 824 825 826
	# We used to special case $?==256 here as meaning "ssh is not running"
	# but relying on any return code here is dubious.  Too much depends on
	# the timing of the reboot operation on the client.  So we just check
	# for a self-induced timeout here and immediately send a PoD in that
	# case.  Otherwise, we assume the reboot happened and we will catch
	# our error below if the node does not stop pinging within a couple
	# of seconds.
827
	#
828
	if ($timedout) {
Mike Hibler's avatar
Mike Hibler committed
829
	    info("$pc: ssh reboot hung, sending ipod");
830

831 832 833
	    if ($nodeobject->SendApod(1) == 0) {
		$didipod = 1;
	    }
834
	}
835 836 837 838
	#
	# The ssh can return non-zero exit status, but still have worked.
	# FreeBSD for example.
	#
839
	else {
Mike Hibler's avatar
Mike Hibler committed
840
	    info("$pc: ssh reboot returned $stat");
841 842 843
	}
    }
    else {
844 845 846 847 848
	my $cmd = "/sbin/reboot";
	$cmd = "'/usr/local/etc/emulab/reboot_prepare || $cmd'"
	    if ($prepare);
	
	exec("$ssh -host $pc $cmd");
849 850 851 852 853 854 855 856 857 858
	exit(0);
    }

    #
    # Restore the old UID so that scripts run from this point on get the
    # user's real UID
    #
    $UID = $oldUID;

    #
859 860 861
    # Okay, before we try IPoD or power cycle lets really make sure we need to.
    # We wait a while for the node to stop responding to pings, and if it never
    # goes silent, whack it with a bigger stick.
862
    #
863 864 865 866 867
    # We need to give shared hosts a chance to stop their containers.
    # The standard pingwait is too small. 
    #
    my $wtime = ($prepare ||
		 $nodeobject->sharing_mode() ? $PREPAREWAIT : $PINGWAIT);
Mike Hibler's avatar
Mike Hibler committed
868
    info("$pc: waiting ${wtime}s for reboot");
869
    if (WaitTillDead($pc, $wtime) == 0) {
Mike Hibler's avatar
Mike Hibler committed
870
	info("$pc: rebooted");
871 872 873 874 875 876 877 878 879 880 881 882 883
	my $state = TBDB_NODESTATE_SHUTDOWN;
	TBSetNodeEventState($pc,$state);
	exit(0);
    }

    #
    # Haven't yet tried an ipod, try that and wait again.
    # This further slows down reboot but is probably worth it
    # since this should be a rare case (reboot says it worked but
    # node doesn't reboot) and is vital if the nodes have no
    # power cycle capability to fall back on.
    #
    if (! $didipod) {
Mike Hibler's avatar
Mike Hibler committed
884
	info("$pc: ssh reboot failed, sending ipod");
885
	$UID = 0;
886
	my $rv = $nodeobject->SendApod(1);
887
	$UID = $oldUID;
888
	if ($rv == 0) {
Mike Hibler's avatar
Mike Hibler committed
889
	    info("$pc: waiting ${PINGWAIT}s for ipod");
890
	    if (WaitTillDead($pc, $PINGWAIT) == 0) {
Mike Hibler's avatar
Mike Hibler committed
891
		info("$pc: rebooted");
892 893 894 895
		my $state = TBDB_NODESTATE_SHUTDOWN;
		TBSetNodeEventState($pc,$state);
		exit(0);
	    }
896 897 898
	}
    }

Mike Hibler's avatar
Mike Hibler committed
899
    info("$pc: ipod failed, power cycling");
900 901 902 903 904 905
    exit(2);
}

#
# Reboot a vnode in a child process, and wait for it.
#
906 907
sub RebootVNode($$$) {
    my ($nodeobj, $pnode, $reconfig) = @_;
908 909
    my $syspid;

910 911 912 913
    my $vnode      = $nodeobj->node_id();
    my $jailed     = $nodeobj->jailflag();
    my $plab       = $nodeobj->isplabdslice();
    my $geninode   = $nodeobj->isfednode();
914
    my $oldUID     = $UID;
915

916 917 918 919 920 921 922 923
    if ($reconfig) {
	print "reboot ($vnode): Attempting to reconfigure.\n"
	    if (!$silent);
    }
    else {
	print STDOUT "reboot ($vnode): Rebooting (on $pnode).\n"
	    if (!$silent);
    }
924 925

    #
926 927
    # For reconfig, we might need to fall back to reboot, so need
    # another child.
928
    #
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    if ($jailed && $reconfig) {
	TBSetNodeEventState($vnode, "RECONFIG");
	my $reconpid = fork();

	if ($reconpid) {
	    local $SIG{ALRM} = sub { kill("TERM", $reconpid); };
	    alarm $RECONFIGTIMO;
	    waitpid($reconpid, 0);
	    alarm 0;

	    #
	    # The ssh can return non-zero exit status, but still have worked.
	    # FreeBSD for example.
	    #
	    my $stat = $?;
	    info("$vnode: reconfig returned ".($stat >> 8));

	    #
	    # Any failure, revert to plain reboot below.
	    #
	    if ($stat == 0) {
		exit(0);
	    }
	}
	else {
	    # Must change our real UID to root so that ssh will work.
	    $UID = 0;

	    exec("$ssh -host $vnode ".
		 "/usr/local/etc/emulab/rc/rc.bootsetup -b reconfig");
	    exit(0);
	}
    }
962

963 964 965 966 967 968 969 970 971
    #
    # 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.
    #
    $syspid = fork();

    if ($syspid) {
	local $SIG{ALRM} = sub { kill("TERM", $syspid); };
972
	alarm $REBOOTVNODETIMO;
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
	waitpid($syspid, 0);
	alarm 0;
	my $exitstatus = $?;

	#
	# The ssh can return non-zero exit status, but still have worked.
	# FreeBSD for example.
	#
	print STDERR "*** reboot ($vnode): returned $exitstatus.\n" if $debug;

	#
	# Look for setup failure, reported back through ssh.
	#
	if ($exitstatus) {
	    if ($exitstatus == 256) {
		print STDERR "*** reboot ($vnode): $pnode is not running sshd.\n"
		    if $debug;
	    }
	    elsif ($exitstatus == 15) {
		print STDERR "*** reboot ($vnode): $pnode is wedged.\n"
		    if $debug;
	    }
	}
	return($exitstatus);
    }
998

999
    my $addargs = "-t ";	# Turn on timestamps.
1000 1001 1002 1003
    if ($plab) {
	$addargs .= "-p ";
    }
    elsif ($jailed) {
1004 1005
	# Use virtual control net routes. 
	$addargs .= "-jV ";
1006
    }
1007 1008 1009
    else {
	$addargs .= "-i ";
    }	
1010

1011 1012 1013 1014 1015
    #
    # Must change our real UID to root so that ssh will work.
    #
    $UID = 0;

Leigh Stoller's avatar
Leigh Stoller committed
1016
    exec("$ssh -host $pnode $CLIENT_BIN/vnodesetup -r $addargs $vnode");
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    exit(0);
}

#
# Power cycle a PC using the testbed power program.
#
sub PowerCycle {
    my @pcs = @_;

    my $pcstring = join(" ",@pcs);

    system("$power cycle $pcstring");
    return $? >> 8;
}

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
#
# Power on a PC using the testbed power program.
#
sub PowerOn {
    my @pcs = @_;
    
    my $pcstring = join(" ",@pcs);

    system("$power on $pcstring");
    return $? >> 8;
}

1044 1045 1046 1047
#
# Wait until a machine stops returning ping packets.
#
sub WaitTillDead {
1048
    my ($pc, $waittime) = @_;
1049

1050
    print STDERR "reboot ($pc): Waiting to die off.\n" if $debug > 1;
1051 1052 1053 1054 1055 1056

    #
    # Sigh, a long ping results in the script waiting until all the
    # packets are sent from all the pings, before it will exit. So,
    # loop doing a bunch of shorter pings.
    #
1057 1058 1059 1060
    # Note that each call to DoesPing takes about two seconds.
    #
    my $iters = int(($waittime + 1) / 2);
    for (my $i = 0; $i < $iters; $i++) {
1061
	if (! DoesPing($pc, $i, 0)) {
1062
	    print STDERR "reboot ($pc): Died off.\n" if $debug > 1;
1063 1064 1065
	    return 0;
	}
    }
Mike Hibler's avatar
Mike Hibler committed
1066 1067
    print STDERR "reboot ($pc): still alive after $waittime seconds.\n"
	if $debug > 1;
1068 1069 1070 1071
    return 1;
}

#
1072 1073
# Returns 1 if host is responding to pings, 0 otherwise.
# Pings for roughly two seconds.
1074
# If $immediate is set, return after the first successful ping.
1075 1076 1077
# This routine is NOT allowed to do any DB queries!
#
sub DoesPing {
1078
    my ($pc, $index, $immediate) = @_;
1079 1080 1081
    my $status;
    my $saveuid;

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
    #
    # We fork/exec rather than system() for two reasons.
    # One, is so that we don't have to flip the UID back and forth in
    # the parent, and two, so that we can throw away stdout/stderr without
    # an extra level of "sh -c" to setup redirection (">/dev/null 2>&1").
    #
    # XXX I am not sure either of these is particularly compelling,
    # but when we can have literally hundreds of pending nodereboots
    # outstanding at any time, it might matter.
    #
    my $child = fork();
    if ($child == 0) {
	my $args = "-q -i 0.25 -c 9 -t 2";
	$args .= " -o" if ($immediate);

	# get rid of output that -q doesn't
	open(STDOUT, ">/dev/null");
	open(STDERR, ">&STDOUT");

	$UID = 0;
	exec("$ping $args $pc");
	exit(1);
    }
    waitpid($child, 0);
1106 1107 1108 1109 1110 1111 1112
    $status = $? >> 8;

    #
    # Ping returns 0 if any packets are returned. Returns 2 if pingable
    # but no packets are returned. Other non-zero error codes indicate
    # other problems.  Any non-zero return indicates "not pingable" to us.
    #
1113
    print STDERR "reboot ($pc): $ping $index returned $status\n" if $debug > 1;
1114 1115 1116 1117 1118 1119 1120 1121
    if ($status) {
	return 0;
    }
    return 1;
}

sub info($) {
    my $message = shift;
Mike Hibler's avatar
Mike Hibler committed
1122 1123

    # Time stamp log messages like:
1124
    # Sep 20 09:36:00 $message
Mike Hibler's avatar
Mike Hibler committed
1125 1126
    my $tstamp = strftime("%b %e %H:%M:%S", localtime);

1127
    open(LOG,">> $logfile");
Mike Hibler's avatar
Mike Hibler committed
1128
    print LOG "$tstamp $message\n";
1129
    close(LOG);
Mike Hibler's avatar
Mike Hibler committed
1130 1131

    print STDERR "$message\n" if ($debug);
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
}

#
# This gets called in the parent, to wait for an async reboot that was
# launched earlier (asyncmode). The child will print the results back
# on the the pipe that was opened between the parent and child. They
# are stuffed into the original results array.
#
sub nodereboot_wait($)
{
    my ($childpid) = @_;

    if (!exists($children{$childpid})) {
1145
	tberror "No such child pid $childpid!";
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
	return -1;
    }
    my ($PARENT_READER, $result) = @{ $children{$childpid}};

    #
    # Read back the results.
    # 
    while (<$PARENT_READER>) {
	chomp($_);

	if ($_ =~ /^([-\w]+),([-\d])+$/) {
	    $result->{$1} = $2;
	    print STDERR "reboot ($1): child returned $2 status.\n";
	}
	else {
1161
	    tberror "Improper response from child: $_";
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
	}
    }
    
    #
    # And get the actual exit status.
    # 
    waitpid($childpid, 0);
    return $? >> 8;
}

#
# Okay, this is horrible! We cannot include this library into non-setuid
# scripts cause a lot of this stuff needs to be run as root. So provide an
# interface that is equiv to the library interface above, but which execs
# an instance of node_reboot and waits for the results.
#
sub nodereboot_exec($$)
{
    my ($args, $result) = @_;
    my $asyncmode = 0;

    #
    # Create a suitable command line from arg hash.
    #
    my $cmdline = "";

    $cmdline .= "-d"
	if (exists($args->{'debug'}) && $args->{'debug'});
    $cmdline .= " -f"
	if (exists($args->{'powercycle'}) && $args->{'powercycle'});
1192 1193
    $cmdline .= " -b"
	if (exists($args->{'rebootmode'}) && $args->{'rebootmode'});
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    $cmdline .= " -w"
	if (exists($args->{'waitmode'}) && $args->{'waitmode'});
    $cmdline .= " -r"
	if (exists($args->{'realmode'}) && $args->{'realmode'});
    $cmdline .= " -k"
	if (exists($args->{'killmode'}) && $args->{'killmode'});
    $cmdline .= " -a"
	if (exists($args->{'freemode'}) && $args->{'freemode'});
    $cmdline .= " -c"
	if (exists($args->{'reconfig'}) && $args->{'reconfig'});
1204 1205
    $cmdline .= " -W$args->{waittime}"
	if (exists($args->{'waittime'}) && $args->{'waittime'});
1206 1207
    $cmdline .= " -F"
	if (exists($args->{'force'}));
1208 1209 1210 1211 1212 1213 1214 1215
    $cmdline .= " @{ $args->{'nodelist'}}";
    
    $asyncmode = $args->{'asyncmode'} if (exists($args->{'asyncmode'}));
	    
    #
    # Create a pipe to read back results from the child we will create.
    #
    if (! pipe(PARENT_READER, CHILD_WRITER)) {
1216
	tberror "creating pipe: $!";
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	return -1;
    }
    CHILD_WRITER->autoflush(1);

    #
    # ACK! Perl defaults to close-on-exec? Why is that?
    # 
    fcntl(CHILD_WRITER, F_SETFD, 0);

    if (my $childpid = fork()) {
	close(CHILD_WRITER);

	#
	# Save the info we need for calling nodereboot_wait() above.
	# 
	$children{$childpid} = [ *PARENT_READER, $result ];

	#
	# If asyncmode we return right away. The caller will need to
	# use the nodereboot_wait() routine above.
	#
	if ($asyncmode) {
	    return $childpid;
	}

	#
	# Block waiting.
	#
	return nodereboot_wait($childpid);
    }
    close(PARENT_READER);

    #
    # Pass the fd number to the child.
    # 
    $ENV{'REBOOTPIPENO'} = fileno(CHILD_WRITER);
   
    #
    # Child execs the instance of node_reboot, with an extra open fd.
    #
    exec("$reboot $cmdline");
    die("Could not exec $reboot!");
    
}

# _Always_ make sure that this 1 is at the end of the file...
1;