libreboot.pm.in 25.6 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2006 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# All rights reserved.
#
# 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;
26
use libtblog;
27 28 29 30 31 32 33 34 35 36
use English;

#
# Configure variables
#
my $TB		= "@prefix@";
my $CLIENT_BIN  = "@CLIENT_BINDIR@";
my $BOSSNODE    = "@BOSSNODE@";

#
37 38
# The number of nodes we reboot at a time and the time to wait between batches. 
# The batch size determines the degree of parallelism.
39 40
#
my $BATCHCOUNT  = 12;
41 42 43 44 45 46 47 48 49
my $BATCHSLEEP	= 5;

#
# Default reboot waittime.
# If the user doesn't specify, we use this historic value.
#
# XXX should come from DB.
#
my $MAXWAITTIME	= (6 * 60);
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use event;
use POSIX qw(strftime);
use IO::Handle;
use Fcntl;

# External Programs
my $ssh		= "$TB/bin/sshtb -n";
my $power	= "$TB/bin/power";
my $ipod	= "$TB/sbin/apod";
my $vnodesetup	= "$TB/sbin/vnode_setup";
my $bisend      = "$TB/sbin/bootinfosend";
my $logfile	= "$TB/log/power.log";
my $ping	= "/sbin/ping";
my $reboot      = "$TB/bin/node_reboot";

# Locals
my $debug       = 0;
my %children    = ();

#
# The actual library function. 
#
sub nodereboot($$)
{
    my ($args, $result) = @_;
82 83 84 85 86 87 88 89 90 91
    my @nodes       = @{ $args->{'nodelist'}};

    #
    # Start a new logging sub-process
    #
    my $old_env = \%ENV;
    local %ENV;
    copy_hash %ENV, $old_env;
    tblog_sub_process("reboot", @nodes);

92 93 94 95 96 97 98 99 100 101 102

    $debug = $args->{'debug'}
        if (exists($args->{'debug'}));

    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'})) {
103
	    tberror "Must be root when using library!";
104 105 106 107 108 109 110 111
	    return -1;
	}
	print STDERR "reboot: no privs; invoking real nodereboot script!\n"
	    if ($debug);
	return nodereboot_exec($args, $result);
    }

    if (!defined($args->{'nodelist'})) {
112
	tberror "Must supply a node list!";
113 114 115
	return -1;
    }
    my $powercycle  = 0;
116
    my $rebootmode  = 0;
117
    my $waitmode    = 0;
118
    my $waittime    = $MAXWAITTIME;
119 120 121
    my $realmode    = 1;
    my $killmode    = 0;
    my $freemode    = 0;
122
    my $prepare     = 0;
123 124 125 126 127
    my $reconfig    = 0;
    my $asyncmode   = 0;
    my $pipemode    = 0;

    $powercycle  = $args->{'powercycle'} if (exists($args->{'powercycle'}));
128
    $rebootmode  = $args->{'rebootmode'} if (exists($args->{'rebootmode'}));
129
    $waitmode    = $args->{'waitmode'}   if (exists($args->{'waitmode'}));
130
    $waittime    = $args->{'waittime'}   if (exists($args->{'waittime'}));
131 132 133
    $realmode    = $args->{'realmode'}   if (exists($args->{'realmode'}));
    $killmode    = $args->{'killmode'}   if (exists($args->{'killmode'}));
    $freemode    = $args->{'freemode'}   if (exists($args->{'freemode'}));
134
    $prepare     = $args->{'prepare'}    if (exists($args->{'prepare'}));
135 136 137 138 139 140 141 142 143 144 145 146 147 148
    $reconfig    = $args->{'reconfig'}   if (exists($args->{'reconfig'}));
    $asyncmode   = $args->{'asyncmode'}  if (exists($args->{'asyncmode'}));

    #
    # 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 {
149
	    tberror "Bad pipeno in environment: $pipemode!";
150 151 152 153 154 155 156 157 158
	    return -1;
	}
    }

    #
    # Verify permission to reboot these nodes.
    #
    if ($UID && !TBAdmin($UID) &&
	! TBNodeAccessCheck($UID, TB_NODEACCESS_REBOOT, @nodes)) {
159
	tberror "You do not have permission to reboot some of the nodes!";
160 161 162 163 164 165 166
	return -1;
    }

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

167 168 169 170 171 172 173 174 175 176 177 178 179 180
    # 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) {
	my $qr = DBQueryFatal("select nt.isrebootable from " .
	    "nodes as n, node_types as nt " .
	    "where n.node_id=\"$node\" and " .
	    "n.type = nt.type");
	my ($rebootable) = $qr->fetchrow_array();
	push(@temp,$node) if $rebootable;
    }
    @nodes = @temp;
    # END XXX

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    #
    # 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 = ();

    foreach my $node (@nodes) {
	my ($jailed, $plab);

	# All nodes start out as being successful; altered later as needed.
	$result->{$node} = 0;

	if (TBIsNodeVirtual($node, \$jailed, \$plab)) {
	    if (! $jailed && ! $plab) {
		print "reboot ($node): Skipping old style virtual node\n";
		next;
	    }
	    my $pnode;

	    if (! TBPhysNodeID($node, \$pnode)) {
204
	        tberror "$node: No physical node!";
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
		return -1;
	    }
	    $virtnodes{$node} = $pnode;
	}
	else {
	    $realnodes{$node} = $node;
	}
    }
    for my $node ( keys(%virtnodes) ) {
	my $pnode = $virtnodes{$node};

	if (defined($realnodes{$pnode})) {
	    print "reboot ($node): Dropping since its host $pnode will reboot\n";
	    delete($virtnodes{$node});
	}
    }
    if (! keys(%realnodes) && ! keys(%virtnodes)) {
	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)) {
261
	    tberror "creating pipe: $!";
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
	    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}")) {
288
	    tberror "reopening pipe: $!";
289 290 291 292 293 294 295 296 297
	    return -1;
	}
	CHILD_WRITER->autoflush(1);

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

    #
298 299 300 301 302 303 304 305 306
    # 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).
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    #
    while (@sortednodes) {
	my @batch     = ();
	my $i         = 0;

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

	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.
	    #
	    info("*** reboot: Powercyle mode: power cycle ".join(" ",@batch));
	    if (PowerCycle(@batch)) {
326
		tberror "Powercyle failed for " . join(" ",@batch);
327 328 329 330 331 332 333 334 335 336 337 338
		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 ) {
339
		$pids{$node} = RebootNode($node, $reconfig,
340
					  $killmode, $rebootmode, $prepare);
341 342 343 344 345 346 347 348 349 350 351
	    }
	}

	#
	# 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) {
	    print "reboot: Pausing to give some nodes time to reboot\n"
		if ($debug);
352
	    sleep($BATCHSLEEP);
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
	}
    }

    #
    # Wait for all the reboot children to exit before continuing.
    #
    my @needPowercycle = ();
    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);
	    }
381
	    elsif ($mypid != 0 && $?) {
382 383
		$failed++;
		$result->{$node} = -1;
384
		tberror "Failed ($?)!";
385 386 387 388 389 390 391 392 393 394 395 396
	    }
	    else {
		print STDOUT "reboot ($node): Successful!\n";
	    }
	}
    }

    #
    # Power cycle nodes that couldn't be brought down any other way
    #
    if (@needPowercycle) {
	if (PowerCycle(@needPowercycle)) {
397
	    tberror "Powercyle failed for " . join(" ",@needPowercycle);
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	    foreach my $node (@needPowercycle) {
		$result->{$node} = -1;
		$failed++;
	    }
	}
    }

    #
    # Now do vnodes. Do these serially for now (simple).
    #
    for my $node ( sort(keys(%virtnodes)) ) {
	my $pnode = $virtnodes{$node};

	if (RebootVNode($node, $pnode)) {
	    $failed++;
	    $result->{$node} = -1;
414
	    tberror "$node: Reboot failed (on $pnode)";
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
	}
	else {
	    print STDOUT "reboot ($node): rebooting (on $pnode).\n";
	}
    }

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

	print STDOUT "reboot: Waiting for nodes to come up.\n";

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

	foreach my $node (sort(@nodes)) {
434 435
	    my $actual_state;
	    
436 437 438 439 440 441
	    #
	    # Skip if something failed earlier.
	    #
	    next
		if ($result->{node});
	    
442
	    if (!TBNodeStateWait($node, $waitstart, $waittime, \$actual_state,
443 444 445 446 447 448 449
				 (TBDB_NODESTATE_TBFAILED,
				  TBDB_NODESTATE_ISUP))) {
		if ($actual_state eq TBDB_NODESTATE_ISUP) {
		    print STDOUT "reboot ($node): alive and well.\n";
		    SetNodeBootStatus($node, NODEBOOTSTATUS_OKAY);
		    next;
		}
450
		tberror "$node reported a TBFAILED event.";
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
	    }
	    SetNodeBootStatus($node, NODEBOOTSTATUS_FAILED);
	    $result->{$node} = -1;
	    $failed++;
	}
    }
 done:    
    print "reboot: Done. There were $failed failures.\n";

    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 {
481
    my ($pc, $reconfig, $killmode, $rebootmode, $prepare) = @_;
482 483
    my ($status, $syspid, $mypid, $didipod, $nodestate);

484 485 486 487 488 489 490 491
    #
    # Start a new logging sub-process
    #
    my $old_env = \%ENV;
    local %ENV;
    copy_hash %ENV, $old_env;
    tblog_sub_process("reboot_node", $pc);

492 493 494 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 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    if ($reconfig) {
	print "reboot ($pc): Attempting to reconfigure ...\n";
    }
    else {
	print "reboot ($pc): Attempting to reboot ...\n";
    }

    # 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.
    #
    if (! TBGetNodeEventState($pc, \$nodestate)) {
	info("$pc has no event state: power cycle");
	print STDERR "*** reboot ($pc): no event state; will power cycle.\n"
	    if $debug;
	
	# Signal to the called that the node needs to be power cycled
	return -2;
    }
    if ($nodestate eq TBDB_NODESTATE_PXEWAIT() ||
	$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) {
	    info("$pc: in $nodestate: but power cycling in killmode");
	    print STDERR "reboot ($pc): in $nodestate, ".
		"but power cycling in killmode.\n" if $debug;
	    
	    # Signal to the caller that the node needs to be power cycled
	    return -2;
	}

	#
	# The aux program sends the event to stated ...
	#
538
	my $reqarg = ($rebootmode ? "-r" : "-q");
539
	my $optarg = ($debug ? "-dd" : "");
540
	
541 542
	print STDERR "reboot ($pc): in $nodestate: sending wakeup command.\n"
	    if $debug;
543
	system("$bisend $optarg $reqarg $pc");
544 545
	if ($?) {
	    info("$pc: PXEWAKEUP failed ... power cycle");
546
	    tbnotice "$pc: PXEWAKEUP failed; will power cycle.\n";
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
	    
	    # 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.
    #
568
    if (! DoesPing($pc, 0)) {
569
	info("$pc appears dead: power cycle");
570
	tbnotice "$pc appears dead; will power cycle.";
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
	
	# 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.
    #
    print STDERR "reboot ($pc): Trying ssh.\n" if $debug;

    #
    # 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); };
	    alarm 20;
	    waitpid($syspid, 0);
	    alarm 0;

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

	    #
	    # Any failure, revert to plain reboot below.
	    #
	    if (! $?) {
		$UID = $oldUID;
		exit(0);
	    }
	}
	else {
	    exec("$ssh -host $pc ".
		 "/usr/local/etc/emulab/rc/rc.bootsetup -b reconfig");
	    exit(0);
	}
    }

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
    #
    # 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";
	    }
	}
    }

655 656 657 658 659 660 661 662
    #
    # 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) {
663 664
	my $timedout = 0;
	local $SIG{ALRM} = sub { kill("TERM", $syspid); $timedout = 1; };
665
	alarm 20;;
666 667 668 669 670 671 672 673 674 675
	waitpid($syspid, 0);
	alarm 0;

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

	#
676 677 678 679 680 681 682
	# 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.
683
	#
684 685 686
	if ($timedout) {
	    print STDERR "*** reboot ($pc): wedged.\n" if $debug;
	    info("$pc: ssh reboot failed (hung) ... sending ipod");
687 688 689 690 691 692 693 694 695 696 697
	    print STDERR "*** reboot ($pc): Trying Ping-of-Death.\n" if $debug;

	    system("$ipod $pc");
	    $didipod = 1;
	}
	else {
	    info("$pc: ssh reboot ($?)");
	    $didipod = 0;
	}
    }
    else {
698 699 700 701 702
	my $cmd = "/sbin/reboot";
	$cmd = "'/usr/local/etc/emulab/reboot_prepare || $cmd'"
	    if ($prepare);
	
	exec("$ssh -host $pc $cmd");
703 704 705 706 707 708 709 710 711 712
	exit(0);
    }

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

    #
713 714 715
    # 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.
716
    #
717
    if (WaitTillDead($pc, ($prepare ? 200 : 30)) == 0) {
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
	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) {
	info("$pc: reboot failed ... sending ipod");
	$UID = 0;
	system("$ipod $pc");
	$UID = $oldUID;
735
	if (WaitTillDead($pc, 20) == 0) {
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 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 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
	    my $state = TBDB_NODESTATE_SHUTDOWN;
	    TBSetNodeEventState($pc,$state);
	    exit(0);
	}
    }

    info("$pc: ipod failed ... power cycle");
    print STDERR "*** reboot ($pc): Still running; will power cycle.\n"
	if $debug;
    exit(2);
}

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

    print STDOUT "reboot ($vnode): Rebooting (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.
    #
    $syspid = fork();

    if ($syspid) {
	local $SIG{ALRM} = sub { kill("TERM", $syspid); };
	alarm 20;
	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);
    }
    #
    # Must change our real UID to root so that ssh will work.
    #
    $UID = 0;

    exec("$ssh -host $vnode $CLIENT_BIN/vnodesetup -r -j $vnode");
    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;
}

#
# Wait until a machine stops returning ping packets.
#
sub WaitTillDead {
817
    my ($pc, $waittime) = @_;
818 819 820 821 822 823 824 825

    print STDERR "reboot ($pc): Waiting to die off.\n" if $debug;

    #
    # 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.
    #
826 827
    for (my $i = 0; $i < $waittime; $i++) {
	if (! DoesPing($pc, $i)) {
828 829 830 831 832 833 834 835 836 837 838 839 840
	    print STDERR "reboot ($pc): Died off.\n" if $debug;
	    return 0;
	}
    }
    print STDERR "reboot ($pc): still alive.\n" if $debug;
    return 1;
}

#
# Returns 1 if host is responding to pings, 0 otherwise
# This routine is NOT allowed to do any DB queries!
#
sub DoesPing {
841
    my ($pc, $index) = @_;
842 843 844 845 846 847 848 849 850 851 852 853 854 855
    my $status;
    my $saveuid;

    $saveuid = $UID;
    $UID = 0;
    system("$ping -q -i 0.25 -c 8 -t 2 $pc >/dev/null 2>&1");
    $UID = $saveuid;
    $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.
    #
856
    print STDERR "reboot ($pc): $ping $index returned $status\n" if $debug;
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    if ($status) {
	return 0;
    }
    return 1;
}


sub info($) {
    my $message = shift;
    # Print out log entries like this:
    # Sep 20 09:36:00 $message
    open(LOG,">> $logfile");
    print LOG strftime("%b %e %H:%M:%S",localtime)." $message\n";
    close(LOG);
}

#
# 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})) {
884
	tberror "No such child pid $childpid!";
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
	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 {
900
	    tberror "Improper response from child: $_";
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
	}
    }
    
    #
    # 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'});
931 932
    $cmdline .= " -b"
	if (exists($args->{'rebootmode'}) && $args->{'rebootmode'});
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
    $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'});
    $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)) {
951
	tberror "creating pipe: $!";
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 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 998
	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;