stated.in 46.5 KB
Newer Older
Robert Ricci's avatar
Robert Ricci committed
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2 3
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2006 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5 6 7
# All rights reserved.
#

Robert Ricci's avatar
Robert Ricci committed
8 9 10
#
# stated - A daemon to monitor the states of nodes in the testbed. Recives
# state change notification through the event system, and writes the new
Mac Newbold's avatar
Mac Newbold committed
11
# state into the database. Also watches for invalid transitions, timeouts,
12
# and performs other state-related control functions.
Robert Ricci's avatar
Robert Ricci committed
13 14 15 16
#
# Send it a HUP signal to get it to reload the timeout and transition
# information. Periodically reloads this information regardless, though.
#
17
# Will restart when sent SIGUSR1, by exec'ing its executable again.
Robert Ricci's avatar
Robert Ricci committed
18
#
19

Robert Ricci's avatar
Robert Ricci committed
20 21
# Configure variables
use lib '@prefix@/lib';
22
my $TB = "@prefix@";
23
my $REALTB = "/usr/testbed"; # So we know if we're the "real" stated or not
Robert Ricci's avatar
Robert Ricci committed
24
my $BOSSNODE = "@BOSSNODE@";
25
my $TBOPS = "@TBSTATEDEMAIL@";
26
my $REALTBOPS = "@TBOPSEMAIL@";
27
my $TBDBNAME = "@TBDBNAME@";
28
my $REALTBDBNAME = "tbdb"; # So we know if we're using the "real" db
29
my $osselect = "$TB/bin/os_select";
30
my $nodereboot = "$TB/bin/node_reboot";
31
my $rebootlog  = "$TB/log/nodereboot.log";
32
my $power = "$TB/bin/power";
33
my $apod = "$TB/sbin/apod";
34
my $TBLOG = "@TBLOGFACIL@";
Robert Ricci's avatar
Robert Ricci committed
35 36 37 38 39 40

$| = 1;

use event;
use libdb;
use libtestbed;
41
use TimeoutQueue;
Robert Ricci's avatar
Robert Ricci committed
42
use Getopt::Std;
43
#use strict;
Robert Ricci's avatar
Robert Ricci committed
44
use English;
Mac Newbold's avatar
Mac Newbold committed
45 46
use POSIX;			# for strftime, and sigprocmask and friends
use Fcntl;			# file constants for pidfile
Mac Newbold's avatar
Mac Newbold committed
47 48 49 50 51
use Sys::Syslog;
# Important note about syslog: It defaults to using an inet socket,
# but 'syslogd -s' (the default) doesn't listen for one. So either
# run syslogd without -s, or use setlogsock('unix') before openlog.
# (To get setlocksock: 'use Sys::Syslog qw(:DEFAULT setlogsock);' )
Robert Ricci's avatar
Robert Ricci committed
52

Mac Newbold's avatar
Mac Newbold committed
53
# Do lots of db retries before we fail and die
54
$libdb::DBQUERY_MAXTRIES = 100;
Mac Newbold's avatar
Mac Newbold committed
55

56 57 58 59 60
# Set up some notification throttling
my $mailgap = 15;		# in seconds
my $lastmail = time() - $mailgap + 2; # Send a digest of startup msgs after 2s.
my %msgs = ();

Mac Newbold's avatar
Mac Newbold committed
61
# Number of iterations (roughly, seconds) after which we'll reload
Robert Ricci's avatar
Robert Ricci committed
62 63
# information from the database. This is so we don't end up with information
# that's _too_ out of sync.
64
my $reload_time = 600;
65
my $last_reload = time;
Robert Ricci's avatar
Robert Ricci committed
66

67 68 69 70
# Command line opts.
my $dbtag = "";
my $debug = 0;
my $nolog = 0;
71 72
my $server = "localhost";
my $port   = @BOSSEVENTPORT@;
73 74 75
my $lockfile;
my $pidfile;

Robert Ricci's avatar
Robert Ricci committed
76 77 78
# Process command-line arguments

sub usage {
Mac Newbold's avatar
Mac Newbold committed
79
    print << "END";
80
Usage: $0 [-h] [-d] [-s server] [-p port] [-t dbtag]
81
-h              This message
82 83 84
-d              Turn on debugging output, and do not go into the background
-l              Do not use syslog; send output to stderr. Use with -d only
-t tag          Use only those nodes with matching tag in nodes table
Robert Ricci's avatar
Robert Ricci committed
85 86
-s server       Use specified server, instead of this site's bossnode
-p port	        Use specified port
87
Send SIGHUP to reload database state, or SIGUSR1 to restart completely.
Robert Ricci's avatar
Robert Ricci committed
88
END
89
    exit(1);
Robert Ricci's avatar
Robert Ricci committed
90 91
}

Mac Newbold's avatar
Mac Newbold committed
92
# Only root should run this - it won't work when run as a user...
93
# (Or, let an admin run it if it isn't the real one in /usr/testbed/ )
94
if ($UID && ( $TB eq $REALTB || ! TBAdmin($UID) ) ) {
Mac Newbold's avatar
Mac Newbold committed
95 96 97
    die("Only root can run this script!\n");
}

98
my @args = @ARGV;    # save a copy for restart before we mess with them.
Robert Ricci's avatar
Robert Ricci committed
99
my %opt = ();
100
if (!getopts("ds:p:ht:l",\%opt)) { usage(); }
Robert Ricci's avatar
Robert Ricci committed
101

Mac Newbold's avatar
Mac Newbold committed
102 103 104 105 106 107
if ($opt{h}) {
    exit &usage;
}
if (@ARGV) {
    exit &usage;
}
Robert Ricci's avatar
Robert Ricci committed
108

Mac Newbold's avatar
Mac Newbold committed
109 110 111 112 113 114
if ($opt{s}) {
    $server = $opt{s};
}
if ($opt{p}) {
    $port = $opt{p};
}
115 116 117 118 119 120 121 122
if ($opt{l}) {
    usage()
	if (! $opt{d});
    $nolog = 1;
}
if ($opt{t}) {
    $dbtag = $opt{t};
}
Mac Newbold's avatar
Mac Newbold committed
123 124 125
if ($opt{d}) {
    $debug = 1;
}
Robert Ricci's avatar
Robert Ricci committed
126

127
# Grab some constants into variables
128
my $TBANYMODE    = TBDB_NODEOPMODE_ANY;
129 130
my $TBRESET      = TBDB_TBCONTROL_RESET;
my $TBTIMEOUT    = TBDB_TBCONTROL_TIMEOUT;
Mac Newbold's avatar
Mac Newbold committed
131 132 133
my $PXEBOOT      = TBDB_TBCONTROL_PXEBOOT;
my $BOOTING      = TBDB_TBCONTROL_BOOTING;
my $CHECKGENISUP = TBDB_TBCONTROL_CHECKGENISUP;
134 135 136
my $TBNOTIMEOUT  = TBDB_NO_STATE_TIMEOUT;
my $TBNODESTATE  = TBDB_TBEVENT_NODESTATE;
my $TBNODEOPMODE = TBDB_TBEVENT_NODEOPMODE;
137 138 139 140 141 142
my $TBCONTROL    = TBDB_TBEVENT_CONTROL;
my $TBCOMMAND    = TBDB_TBEVENT_COMMAND;
my $TBREBOOT     = TBDB_COMMAND_REBOOT;
my $TBPOWEROFF   = TBDB_COMMAND_POWEROFF;
my $TBPOWERON    = TBDB_COMMAND_POWERON;
my $TBPOWERCYCLE = TBDB_COMMAND_POWERCYCLE;
143
my $TBISUP       = TBDB_NODESTATE_ISUP;
144 145 146
my $PXEWAIT      = TBDB_NODESTATE_PXEWAIT;
my $PXEWAKEUP    = TBDB_NODESTATE_PXEWAKEUP;
my $PXEBOOTING   = TBDB_NODESTATE_PXEBOOTING;
147 148
my $TBRELOADDONEV1    = TBDB_TBCONTROL_RELOADDONE;
my $TBRELOADDONEV2    = TBDB_TBCONTROL_RELOADDONE_V2;
149 150 151 152
my $TBTIMEOUTREBOOT   = TBDB_STATED_TIMEOUT_REBOOT;
my $TBTIMEOUTNOTIFY   = TBDB_STATED_TIMEOUT_NOTIFY;
my $TBTIMEOUTCMDRETRY = TBDB_STATED_TIMEOUT_CMDRETRY;
my $TB_OSID_MBKERNEL  = TB_OSID_MBKERNEL;
153

154 155
# Special PXEBOOT state machine that all local nodes use.
my $PXEKERNEL	 = "PXEKERNEL";
156

157 158 159 160 161 162 163 164 165 166 167 168 169
# Protos.
sub debug(@);
sub fatal($);
sub notify($;$);
sub info($;$);
sub getTimeouts();
sub getValid();
sub getModeTrans();
sub getTriggers();
sub readStates(;@);
sub handleCtrlEvent($$);
sub reload();
    
170 171 172
if (!$debug) {
    if ( $TB eq $REALTB ) {
	$pidfile = "/var/run/stated.pid";
Mac Newbold's avatar
Mac Newbold committed
173
    } else {
174
	$pidfile = "$TB/locks/stated.pid";
Mac Newbold's avatar
Mac Newbold committed
175
    }
176
    debug("Using pidfile $pidfile\n");
Mac Newbold's avatar
Mac Newbold committed
177

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    if (-e $pidfile) {
	my $otherpid = `cat $pidfile`;
	my $running = `ps -auxww | grep $otherpid | grep -v grep`;
	if ($running ne "") {
	    fatal("Lockfile $pidfile exists, and process $otherpid appears ".
		  "to be running.\n");
	} else {
	    notify("Lockfile exists, but process $otherpid appears to be dead".
		   "\n".
		   "Removing lock file...\n");
	}
	system("rm $pidfile") &&
	    fatal("Couldn't remove $pidfile: $? $!\n");
    }
    # Background
Mac Newbold's avatar
Mac Newbold committed
193 194 195 196
    # We use syslog, so redirect the output to nothing
    if (TBBackGround("/dev/null")) {
	exit(0);
    }
Robert Ricci's avatar
Robert Ricci committed
197
}
Mac Newbold's avatar
Mac Newbold committed
198
# set up syslog
199 200 201 202 203 204 205 206 207 208 209 210
if (! $nolog) {
    openlog("stated","pid",$TBLOG);
}

if (defined($pidfile)) {
    sysopen(PIDFILE, $pidfile, O_WRONLY | O_EXCL | O_CREAT) ||
	fatal("Couldn't create '$pidfile': $? $!\n");
    print PIDFILE "$$";
    close PIDFILE;
    # If I make it to here, I'll need to clean up the lock file
    $lockfile = $pidfile;
}
Robert Ricci's avatar
Robert Ricci committed
211

212 213 214
# Change my $0 so that it is easier to see in a ps/top
$0 = "$0";

Robert Ricci's avatar
Robert Ricci committed
215
my $URL = "elvin://$server";
Mac Newbold's avatar
Mac Newbold committed
216 217 218
if ($port) {
    $URL .= ":$port";
}
Robert Ricci's avatar
Robert Ricci committed
219

Mac Newbold's avatar
Mac Newbold committed
220
# Connect to the event system, and subscribe the the events we want
Robert Ricci's avatar
Robert Ricci committed
221
my $handle = event_register($URL,0);
Mac Newbold's avatar
Mac Newbold committed
222 223 224
if (!$handle) {
    fatal("Unable to register with event system\n");
}
Robert Ricci's avatar
Robert Ricci committed
225 226

my $tuple = address_tuple_alloc();
Mac Newbold's avatar
Mac Newbold committed
227 228 229
if (!$tuple) {
    fatal("Could not allocate an address tuple\n");
}
Robert Ricci's avatar
Robert Ricci committed
230

231 232 233
%$tuple = ( objtype => join(",",
			    $TBNODESTATE, $TBNODEOPMODE,
			    $TBCONTROL, $TBCOMMAND) );
234

Robert Ricci's avatar
Robert Ricci committed
235
if (!event_subscribe($handle,\&handleEvent,$tuple)) {
Mac Newbold's avatar
Mac Newbold committed
236
    fatal("Could not subscribe to events\n");
Robert Ricci's avatar
Robert Ricci committed
237 238 239 240
}

# Read in the pre-existing node states, and timeout and valid transition
# information from the database
241 242 243 244
my %timeouts  = getTimeouts();
my %valid     = getValid();
my %modeTrans = getModeTrans();
my %triggers  = getTriggers();
245
my %nodes     = readStates();
246
my %timeouttag= ();
247
if ($debug) { qshow(); }
Robert Ricci's avatar
Robert Ricci committed
248 249 250

# Gets set if a reload of state from the database should happen.
my $do_reload = 0;
251 252
my $sigrestart= 0;
my $sigcleanup= 0;
Robert Ricci's avatar
Robert Ricci committed
253 254 255 256

# Make the daemon reload database state on a sighup - but I'm worried
# about what would happen if we tried to do this mid-loop. So, we'll
# just set a flag and do it when we're done with our current pass.
257 258
$SIG{HUP}  = sub { info("SIGHUP - Reloading DB state\n"); $do_reload = 1; };

Mac Newbold's avatar
Mac Newbold committed
259
# Set up other signals.
260 261 262 263 264 265 266
$SIG{USR1} = \&restart_wrap;
$SIG{USR2} = \&cleanup_wrap;
$SIG{INT}  = \&cleanup_wrap;
$SIG{QUIT} = \&cleanup_wrap;
$SIG{ABRT} = \&cleanup_wrap;
$SIG{TERM} = \&cleanup_wrap;
$SIG{KILL} = \&cleanup_wrap;
Robert Ricci's avatar
Robert Ricci committed
267

268 269 270
# Track if I handled an event or not
my $event_count = 0;

271 272
# Control how long I block while waiting for events
my $blockwait=0;
273
my $nextdeadline=0;
274 275
my $mailqueue=0;

276 277 278 279 280
notify("Stated starting up\n");

sub process_event_queue() {
    $event_count=0;
    my $lastcount=-1;
281 282 283 284 285 286 287 288 289 290 291 292 293
    my $wait;
    my $now = time();
    debug("Polling - mq=$mailqueue bw=$blockwait\n");
    if ( $mailqueue == 0) {
	# no messages waiting...
	if ($blockwait) {
	    # we can wait a long time - nothing else will happen
	    # until we get an event, or get woken up by a signal
	    $wait = 600;
	} else {
	    # only wait until the next deadline...
	    if ($nextdeadline > 0) {
		$wait = $nextdeadline - $now;
294 295
	    } else {
		$wait = 0;
296 297 298 299 300
	    }
	}
    } else {
	# mail is waiting. Only block until it is time to send it.
	$wait = $lastmail + $mailgap - $now;
Mac Newbold's avatar
Mac Newbold committed
301
	debug("Now $now, mailgap $mailgap, last $lastmail ==> wait $wait\n");
302 303 304
    }
    if ($wait < 0) { debug("Wait was $wait!\n"); $wait=0; }
    my $finish = $now + $wait;
Mac Newbold's avatar
Mac Newbold committed
305 306
    while (($event_count != $lastcount || $wait > 0) &&
	   !($sigrestart || $sigcleanup || $do_reload)) {
307
	$lastcount = $event_count;
Mac Newbold's avatar
Mac Newbold committed
308 309
	# Don't block if we got a signal!
	if ($wait<=0 || $sigrestart || $sigcleanup || $do_reload) {
310 311
	    event_poll($handle);
	} else {
312
	    #debug("Using blocking event poll - $wait seconds\n");
313 314 315 316 317
	    # timeout param is in milliseconds, so multiply
	    event_poll_blocking($handle, $wait*1000);
	    $now = time();
	    # subtract seconds elapsed from my wait time
	    $wait = $finish - $now;
318
	    #debug("Finished blocking event poll - $wait seconds remain\n");
319
	    if ($event_count > 0 &&
Mac Newbold's avatar
Mac Newbold committed
320 321
		(qsize() > 0 || $mailqueue ||
		 $sigrestart || $sigcleanup || $do_reload)) {
322 323 324 325 326 327 328
		$blockwait=0;
		$wait=0;
		#debug("Cancelling wait - timeouts/msgs waiting, or HUP'd\n");
		#debug("---End Blocking Wait ---\n");
	    }
	}
	#debug("Wait is $wait\n");
329 330
    }
    if ($event_count > 0) {
Mac Newbold's avatar
Mac Newbold committed
331
	debug("Handled $event_count event(s).\n");
332 333
    }
}
Robert Ricci's avatar
Robert Ricci committed
334

335
# Now, we just poll for events, and watch for timeouts
Robert Ricci's avatar
Robert Ricci committed
336
while (1) {
Mac Newbold's avatar
Mac Newbold committed
337
    my $now = time();
338 339 340 341
    my ($deadline,$node);

    # Check for nodes that have passed their timeout
    if (!qhead($deadline,$node)) {
342
	info("HEAD: $node in ".($deadline-$now).", queue=".qsize()."\n");
343 344
	while ($now >= $deadline && $node ne "") {
	    qpop($deadline,$node);
345
	    info("POP: $node in ".($deadline-$now).", queue=".qsize()."\n");
346
	    handleCtrlEvent($node,$TBTIMEOUT);
347 348 349 350
	    if (0) { qshow(); }
	    if (qhead($deadline,$node)) {
		$deadline=0; $node="";
	    }
351
	}
352 353
    } else {
	$deadline=0;
354
    }
355
    $nextdeadline = $deadline;
356

357 358 359 360
    if (qsize()==0) {
	$blockwait=1;
	debug("---Blocking wait okay---\n");
    }
Mac Newbold's avatar
Mac Newbold committed
361

Mac Newbold's avatar
Mac Newbold committed
362 363 364 365
    if ($do_reload || ($now - $last_reload > $reload_time)) {
	reload();
	$do_reload = 0;
    }
Mac Newbold's avatar
Mac Newbold committed
366

Mac Newbold's avatar
Mac Newbold committed
367 368
    # Send any messages in the queue if it is time
    notify("",1);
Mac Newbold's avatar
Mac Newbold committed
369

370 371 372
    if ($sigrestart) { restart(); }
    if ($sigcleanup) { cleanup(); }

373
    process_event_queue;
Robert Ricci's avatar
Robert Ricci committed
374 375
}

Mac Newbold's avatar
Mac Newbold committed
376 377
exit(0);

Robert Ricci's avatar
Robert Ricci committed
378
# Read the current states of nodes from the database
379
sub readStates(;@) {
Mac Newbold's avatar
Mac Newbold committed
380 381 382
    my %oldnodes = @_;

    # Guard against undefined variable warnings
383
    if (! %oldnodes) {
Mac Newbold's avatar
Mac Newbold committed
384 385
	%oldnodes = ();
    }
386

Mac Newbold's avatar
Mac Newbold committed
387 388 389
    #debug("readStates called\n");
    my $result = DBQueryFatal("SELECT node_id, eventstate, " .
			      "state_timestamp, op_mode, " .
390
			      "op_mode_timestamp, stated_tag FROM nodes ".
391
			      "where node_id not like 'sh%'");
Mac Newbold's avatar
Mac Newbold committed
392 393

    my %nodes;
394
    while (my ($node_id, $state, $timestamp, $mode, $mode_timestamp, $tag)
Mac Newbold's avatar
Mac Newbold committed
395
	   = $result->fetchrow()) {
396 397 398 399 400 401 402 403 404 405 406
	$nodes{$node_id}{"tag"} = (defined($tag) ? $tag : "");

	if ($dbtag ne "" && $dbtag eq $nodes{$node_id}{"tag"}) {
	    info("This stated will work on $node_id\n");
	}
	if ($dbtag eq "" && $dbtag ne $nodes{$node_id}{"tag"}) {
	    info("This stated will *NOT* work on $node_id\n");
	}
	if ($dbtag ne $nodes{$node_id}{"tag"}) {
	    remTimeout($node_id);
	}
Mac Newbold's avatar
Mac Newbold committed
407

408
	#
Mac Newbold's avatar
Mac Newbold committed
409 410 411 412
	# If there's an entry in oldnodes for this node, and it
	# hasn't changed state or time, use the old entry (so that
	# we don't lose information about which nodes we've already
	# notified the ops about, etc.)
413
	#
Mac Newbold's avatar
Mac Newbold committed
414 415 416 417 418
	if ($oldnodes{$node_id} && $state && $timestamp &&
	    ($oldnodes{$node_id}{state} eq $state) &&
	    ($oldnodes{$node_id}{mode} eq $mode) &&
	    ($oldnodes{$node_id}{timestamp} == $timestamp)) {
	    $nodes{$node_id} = $oldnodes{$node_id};
419
	} else {
Mac Newbold's avatar
Mac Newbold committed
420 421 422 423
	    $nodes{$node_id}{state}          = $state;
	    $nodes{$node_id}{timestamp}      = $timestamp;
	    $nodes{$node_id}{mode}           = $mode;
	    $nodes{$node_id}{mode_timestamp} = $mode_timestamp;
424 425 426
	    $nodes{$node_id}{notified}       = 0;
	    $nodes{$node_id}{timedout}       = 0;
	    $nodes{$node_id}{noretry}        = 0;
427
	    # Is there a timeout? If so, set it up!
428 429 430
	    if ($dbtag eq $nodes{$node_id}{"tag"}) {
		setTimeout($mode,$state,$node_id,$timestamp);
	    }
431
	}
Mac Newbold's avatar
Mac Newbold committed
432 433
    }
    return %nodes;
Robert Ricci's avatar
Robert Ricci committed
434 435 436 437 438 439
}

#
# Read timeouts for various states from the database
#
sub getTimeouts() {
Mac Newbold's avatar
Mac Newbold committed
440 441 442
    #debug("getTimeouts called\n");
    my $result = DBQueryFatal("SELECT op_mode, state, timeout, action " .
			      "FROM state_timeouts");
Robert Ricci's avatar
Robert Ricci committed
443

Mac Newbold's avatar
Mac Newbold committed
444 445 446 447 448
    my %timeouts;
    while (my ($op_mode, $state, $timeout, $action) = $result->fetchrow()) {
	$timeouts{$op_mode}{$state} = [ $timeout, $action ];
    }
    return %timeouts;
Robert Ricci's avatar
Robert Ricci committed
449 450 451 452 453 454
}

#
# Read the list of valid state transitions from the database
#
sub getValid() {
Mac Newbold's avatar
Mac Newbold committed
455 456 457
    #debug("getValid called\n");
    my $result = DBQueryFatal("SELECT op_mode, state1, state2 " .
			      "FROM state_transitions");
Robert Ricci's avatar
Robert Ricci committed
458

Mac Newbold's avatar
Mac Newbold committed
459 460 461 462 463
    my %valid;
    while (my ($mode,$state1, $state2) = $result->fetchrow()) {
	$valid{$mode}{$state1}{$state2} = 1;
    }
    return %valid;
Robert Ricci's avatar
Robert Ricci committed
464 465
}

466 467 468 469
#
# Read the list of valid mode transitions from the database
#
sub getModeTrans() {
Mac Newbold's avatar
Mac Newbold committed
470
    #debug("getModeTrans called\n");
Mac Newbold's avatar
Mac Newbold committed
471
    my $result =
Mac Newbold's avatar
Mac Newbold committed
472 473 474 475 476 477 478 479 480 481 482
      DBQueryFatal("SELECT op_mode1, state1, op_mode2, state2 " .
		   "FROM mode_transitions order by op_mode1,state1");

    my %modeTrans;
    while (my ($mode1,$state1, $mode2, $state2) = $result->fetchrow()) {
	if (!defined($modeTrans{"$mode1:$state1"})) {
	    $modeTrans{"$mode1:$state1"}= ["$mode2:$state2"];
	} else {
	    my @l = @{$modeTrans{"$mode1:$state1"}};
	    push(@l, "$mode2:$state2");
	    $modeTrans{"$mode1:$state1"}= \@l;
483
	}
Mac Newbold's avatar
Mac Newbold committed
484 485
    }
    return %modeTrans;
486 487 488 489 490 491
}

#
# Read the list of states which trigger an action
#
sub getTriggers() {
492
    debug("getTriggers called\n");
Mac Newbold's avatar
Mac Newbold committed
493

494 495
    debug("anymode ==> '$TBANYMODE'\n");

Mac Newbold's avatar
Mac Newbold committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    # A note about triggers:
    #
    # "per-node" triggers only affect their specific node in a
    # particular mode/state, and are run first of all. "global"
    # triggers are triggers for a given mode/state that affect all
    # nodes, and are run after any per-node triggers. "Any-mode"
    # triggers are tied to a state, and occur in that state in any
    # mode. The any-mode triggers are over-ridden by global triggers,
    # and if an "Any-mode" trigger for state XYZ exists as well as a
    # global trigger for mode FOOBAR state XYZ, then when I arrive in
    # XYZ any per-node triggers will be run. Then, if I'm in mode
    # FOOBAR, only the global trigger will run. If I'm in any other
    # mode, only the any-mode trigger will run.

    # (our "*" is stored as $TBANYMODE)
    # Per-node triggers have a specific node_id
    # Global triggers have "*" as the node_id
    # Any-mode triggers have "*" as the mode, and can be global or per-node

    # Grab global triggers (including any-mode)
    my $result =
Mac Newbold's avatar
Mac Newbold committed
517
      DBQueryFatal("SELECT op_mode, state, trigger " .
518 519
		   "FROM state_triggers where node_id='$TBANYMODE' ".
		   "order by op_mode,state");
Mac Newbold's avatar
Mac Newbold committed
520
    my %t;
521
    while (my ($mode, $state, $trig) = $result->fetchrow()) {
Mac Newbold's avatar
Mac Newbold committed
522 523 524
	my @trigs = split(/\s*,\s*/,$trig);
	$t{"$mode:$state"} = \@trigs;
	debug("trig($mode:$state)\t => ".join(',',@trigs)."\n");
525 526
    }

Mac Newbold's avatar
Mac Newbold committed
527 528
    # Grab per-node triggers (including any-mode)
    $result =
529 530 531 532 533 534 535
      DBQueryFatal("SELECT node_id, op_mode, state, trigger " .
		   "FROM state_triggers where node_id!='$TBANYMODE' ".
		   "order by op_mode,state");
    while (my ($n, $mode, $state, $trig) = $result->fetchrow()) {
	my @trigs = split(/\s*,\s*/,$trig);
	$t{"$n:$mode:$state"} = \@trigs;
	debug("trig($n:$mode:$state)\t => ".join(',',@trigs)."\n");
Mac Newbold's avatar
Mac Newbold committed
536
    }
537

Mac Newbold's avatar
Mac Newbold committed
538 539
    debug(hash_recurse(%t));

Mac Newbold's avatar
Mac Newbold committed
540
    return %t;
541 542
}

Robert Ricci's avatar
Robert Ricci committed
543 544 545 546
#
# Gets called for every event that we recieve
#
sub handleEvent($$$) {
Mac Newbold's avatar
Mac Newbold committed
547 548 549 550 551 552
    my ($handle,$notification,$data) = @_;
    my $objtype = event_notification_get_objtype($handle,$notification);
    my $objname = event_notification_get_objname($handle,$notification);
    my $eventtype = event_notification_get_eventtype($handle,$notification);

    $event_count++;
Mac Newbold's avatar
Mac Newbold committed
553

554
    #
Mac Newbold's avatar
Mac Newbold committed
555 556 557
    # For readability, only do this on the main stated. This will print all
    # events, which gets cumbersome with debugging versions, so we'll print
    # only applicable events in debug versions, after we decide they apply.
558
    #
559
    if ($dbtag eq "") {
560 561
	debug("Got an event: ($objtype,$objname,$eventtype)\n");
    }
Mac Newbold's avatar
Mac Newbold committed
562 563 564 565

    #
    # Check to see if another instance is supposed to be handling this node
    #
566 567
    if ($objtype ne $TBCOMMAND) {
	my $node = $objname;
Mac Newbold's avatar
Mac Newbold committed
568

569 570 571 572 573 574 575
	#
	# If we have never seen this node, reload.
	#
	if (! defined($nodes{$node})) {
	    reload();

	    # Still not defined, someone screwed up! This could end up
Mac Newbold's avatar
Mac Newbold committed
576
	    # churning via reload(). Bad.
577
	    if (! defined($nodes{$node})) {
578 579 580 581
		notify("Got $objtype/$eventtype for nonexistent $node!\n");
		return;
	    }
	}
Mac Newbold's avatar
Mac Newbold committed
582

583 584
	#
	# If a stated_tag was specified on the command line, ignore those
Mac Newbold's avatar
Mac Newbold committed
585
	# nodes that do not match.
586
	#
Mac Newbold's avatar
Mac Newbold committed
587
	#debug("dbtag='$dbtag', node $node='".$nodes{$node}{"tag"}."'\n");
588 589 590 591 592 593 594 595 596 597
	if ($dbtag ne $nodes{$node}{"tag"}) {
	    # Record when main stated ignores a node.
	    info("Got $objtype/$eventtype for $node, which is not mine\n")
		if ($dbtag eq "");
	    return;
	}
	if (!checkDBRedirect($node)) {
	    info("Got $objtype/$eventtype for $node, which is not mine\n");
	    return;
	}
Mac Newbold's avatar
Mac Newbold committed
598
    }
Mac Newbold's avatar
Mac Newbold committed
599 600 601 602 603

    #
    # If this is a debugging version, then this event is for one of my
    # nodes, so I can print out the event now. (Main version prints earlier.)
    #
604 605 606
    if ($dbtag ne "") {
	debug("Got an event: ($objtype,$objname,$eventtype)\n");
    }
Mac Newbold's avatar
Mac Newbold committed
607 608 609

 SWITCH: for ($objtype) {

Mac Newbold's avatar
Mac Newbold committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623
	(/$TBNODESTATE/) && do {
	    stateTransition($objname,$eventtype);
	    last;
	};
	(/$TBNODEOPMODE/) && do {
	    opModeTransition($objname,$eventtype);
	    notify("Use of deprecated event TBNODEOPMODE:\n".
		   "$objname->$eventtype\n");
	    last;
	};
	(/$TBCONTROL/) && do {
	    handleCtrlEvent($objname,$eventtype);
	    last;
	};
624 625 626 627
	(/$TBCOMMAND/) && do {
	    handleCommand($objname,$eventtype);
	    last;
	};
628

Mac Newbold's avatar
Mac Newbold committed
629
    }
630 631 632 633 634

}

sub stateTransition($$) {

635
    my ($node,$newstate) = @_;
Robert Ricci's avatar
Robert Ricci committed
636

637 638
    # Check for invalid transitions
    my ($oldstate, $mode);
639 640 641
    $oldstate = $nodes{$node}{state};
    $mode     = $nodes{$node}{mode};

642 643 644
    if ($oldstate && $mode && $valid{$mode} && $valid{$mode}{$oldstate} &&
	!$valid{$mode}{$oldstate}{$newstate}) {
	notify("Invalid transition for node $node from $mode/$oldstate " .
645
	       "to $newstate\n");
646
    }
Robert Ricci's avatar
Robert Ricci committed
647

648 649 650 651
    my $now = time();
    $nodes{$node}{state}     = $newstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{notified}  = 0;
652

653 654 655
    info("$node: $mode/$oldstate => $mode/$newstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$newstate', " .
		 "state_timestamp='$now' WHERE node_id='$node'");
656

657 658 659 660
    # Before we set the timeout (overwriting any current ones), we need
    # to check if we had a pending command
    if (qfind($node) &&
	$timeout_tag{$node} =~ /^$TBCOMMAND:/) {
661
        debug("TimeoutTag = '$timeout_tag{$node}'\n");
662
	my ($str,$cmd) = split(":",$timeout_tag{$node});
663
	debug("str=$str\tcmd=$cmd\tTBREBOOT=$TBREBOOT\tstate=$newstate\n");
664
	if ($cmd eq $TBREBOOT) {
665
	    if ($newstate eq TBDB_NODESTATE_SHUTDOWN ) {
666 667 668
		info("$node: $TBREBOOT success\n");
		# Timeout will get cleared below by setTimeout call
	    } else {
669 670
		notify("$node: $TBREBOOT in progress, but got state ".
		       "$newstate instead of ".TBDB_NODESTATE_SHUTDOWN."!\n");
671 672 673 674 675
	    }
	#} elsif ($cmd eq $FOO ) {
	    # Add more here...
	} else {
	    notify("$node: Unknown command timeout '$timeout_tag{$node}' ".
676
		   "found at $mode/$newstate\n");
677 678 679
	}
    }

680 681 682 683 684
    #
    # Check if this state has a timeout, and if so, put it in the queue.
    # Note that any opmode transition below will replace (or remove) this
    # timeout if appropriate.
    #
685 686
    setTimeout($mode,$newstate,$node,$now);

Mac Newbold's avatar
Mac Newbold committed
687 688 689 690 691 692 693
    # Check if this state has any triggers
    my @nodetrigs = GetNodeTriggerList($node,$mode,$newstate,1);
    my @trigs = GetNodeTriggerList($node,$mode,$newstate);
    if (@trigs > 0) {
	debug("Running triggers: ".join("/",@trigs)."\n");
	foreach ( @trigs) {
	    my $trig = $_;
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
	    /^SCRIPT:([-\w\/]+)$/ && do {
		#
		# Run a script. No arguments at the moment.
		#
		my $script = $1;

		#
		# If the path is absolute, run it. Otherwise it has to
		# come from the sbin directory.
		#
		if (! ($script =~ /^\//)) {
		    $script = "$TB/sbin/$script";
		}
		info("$node: Running $script.\n");
		system("$script &");
		next;
	    };
Mac Newbold's avatar
Mac Newbold committed
711
	    /^$PXEBOOT$/ && do {
712
		#
Mac Newbold's avatar
Mac Newbold committed
713 714 715 716 717 718 719 720 721 722 723 724
		# See if we jumped into the PXEBOOT kernel. Bootinfo
		# will send PXEBOOTING every time a node contacts it,
		# which is our indicator that the node is in the first
		# phase of booting. At this point we want to switch
		# state machines since the entire boot process is
		# governed by a single state machine that is
		# independent of the OS that the node will eventually
		# boot.  Rather then encode that in each state
		# machine, we use a special machine with a defined
		# entrypoint (PXEBOOTING) and a defined exitpoint
		# (BOOTING). See below for where we jump back out of
		# this state machine.
725
		#
Mac Newbold's avatar
Mac Newbold committed
726 727 728 729
		# Jumped in. We need to change the opmode so that
		# the state transitions are legal. We do not
		# bother to save the old opmode since we can
		# figure it out later when we leave.
730
		#
Mac Newbold's avatar
Mac Newbold committed
731 732 733 734 735
		debug("Running $PXEBOOT trigger\n");
		if ($mode ne $PXEKERNEL) {
		    info("$node: Forcing mode transition into $PXEKERNEL!\n");
		    opModeTransition($node, $PXEKERNEL, 1);
		    $mode=$PXEKERNEL;
736
		}
Mac Newbold's avatar
Mac Newbold committed
737 738 739 740 741 742 743
		next;
	    };
	    /^$BOOTING$/ && do {
		#
		# See if we are in the right mode/osid.
		#
		my ($bootosid,$bootopmode) = TBBootWhat($node, $debug);
744

Mac Newbold's avatar
Mac Newbold committed
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
		info("$node: BootWhat says $bootosid (mode $bootopmode).\n");
		DBQueryFatal("update nodes set osid='$bootosid' ".
			     "where node_id='$node'");

		if ($bootopmode ne $mode) {
		    if ($mode eq $PXEKERNEL) {
			#
			# If we came from PXE boot, then we have to
			# jump out of the PXEKERNEL state machine into
			# whatever state machine is current for the
			# node. Since we came through bootinfo, we
			# know that the node is doing what it is
			# supposed to, and that this change matches
			# what the node is booting.
			#
			info("$node: Forcing mode transition out of $PXEKERNEL!\n");
			opModeTransition($node, $bootopmode, 1);
			$mode=$bootopmode;
		    }
		    elsif ($oldstate eq TBDB_NODESTATE_ISUP) {
			#
			# Skipped SHUTDOWN, which could result in a
			# missed opmode transition. Can this really
			# happen anymore?
			#
			info("$node: Came from ISUP! ".
			     "Checking for mode transition\n");
			my $query_result =
			  DBQueryWarn("select next_op_mode from nodes ".
				      "where node_id='$node'");
			my ($nextmode) = $query_result->fetchrow();
			if ($nextmode) {
			    info("$node: Forcing mode transition!\n");
			    opModeTransition($node, $nextmode, 1);
			    $mode=$nextmode;
			}
		    }
		    else {
			my $str = "$node is running $bootosid, but in ".
			  "mode $mode\ninstead of mode $bootopmode!\n";
			
			if ($bootopmode eq "RELOAD") {
			    #
			    # For now, only force if we're going into
			    # reload mode, so we don't get stuck
			    # looping in reloading.  Can this happen
			    # anymore?
			    #
			    DBQueryFatal("UPDATE nodes SET ".
					 "op_mode='$bootopmode', ".
					 "op_mode_timestamp=".
					 "unix_timestamp(now()) ".
					 "WHERE node_id='$node'");
			    $nodes{$node}{mode} = $bootopmode;
			    $nodes{$node}{mode_timestamp} = $now;
			    $str .= "Forced op_mode to $bootopmode.\n";
			}
			notify($str);
		    }
		}
		next;
	    };
	    /^$CHECKGENISUP$/ && do {
		checkGenISUP($node);
		next;
	    };
811
	    /^$TBRESET$/ && do {
812 813 814
		# We successfully booted, so clear some flags
		$nodes{$node}{noretry}   = 0;
		$nodes{$node}{timedout}  = 0;
815 816 817 818 819 820 821 822 823
		# Check if we really need to do a reset
		my $r = DBQueryWarn("select osid,def_boot_osid from nodes ".
				    "where node_id='$node'");
		my ($osid,$defosid) = $r->fetchrow();
		if ($osid ne $defosid) {
		    handleCtrlEvent($node,$trig);
		}
		next;
	    };
824
	    (/^$TBRELOADDONEV1$/ || /^$TBRELOADDONEV2$/) && do {
825 826 827
		handleCtrlEvent($node,$trig);
		next;
	    };
828 829 830 831 832 833 834 835
	    /^$TBISUP$/ && do {
		info("$node: Triggered $TBISUP\n");
		EventSendWarn(host      => $BOSSNODE ,
			      objtype   => TBDB_TBEVENT_NODESTATE ,
			      eventtype => TBDB_NODESTATE_ISUP ,
			      objname   => $node);
		next;
	    };
836 837 838 839
	    (/^$TBPOWERCYCLE$/) && do {
		handleCommand($node,$TBPOWERCYCLE);
		next;
	    };
840
	    notify("Unknown trigger '$trig' for $node in $mode/$newstate!\n");
841
	}
Mac Newbold's avatar
Mac Newbold committed
842 843 844 845 846 847 848
	# Clear any of the node triggers that we ran.
	# (Don't clear all of them, because some of the triggers we ran
	# may have caused others to be set, and we don't want to nuke them.)
	if (@nodetrigs > 0) {
	    debug("Clearing node triggers: ".join("/",@nodetrigs)."\n");
	    ClearNodeTrigger($node,$mode,$newstate,@nodetrigs);
	}
849
    }
850

851 852 853 854 855 856 857 858
    # Check if this state can trigger a mode transition
    if (defined($modeTrans{"$mode:$newstate"})) {
	info("$node: Checking for mode transition\n");
	my $r = DBQueryWarn("select next_op_mode from nodes ".
			    "where node_id='$node'");
	my ($nextmode) = $r->fetchrow();
	if ($nextmode) {
	    opModeTransition($node,$nextmode);
Mac Newbold's avatar
Mac Newbold committed
859 860 861
	} else {
	    debug("No next mode.\n");
	}
862 863
    }
}
864

865
sub opModeTransition($$;$) {
Mac Newbold's avatar
Mac Newbold committed
866

867 868
    my ($node,$newmode,$force) = @_;
    if (!defined($force)) { $force = 0; }
Mac Newbold's avatar
Mac Newbold committed
869

870
    info("$node: Mode change to $newmode requested ($force)\n");
Mac Newbold's avatar
Mac Newbold committed
871

872 873
    # Check for invalid transitions
    my ($oldstate, $mode, $nextstate);
874 875 876
    $oldstate = $nodes{$node}{state};
    $mode     = $nodes{$node}{mode};

877
    if (defined($modeTrans{"$mode:$oldstate"}) || $force) {
878
	if (!$force) {
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
	    debug("Mode Transition check:\n");
	    my $translist = join(",",@{$modeTrans{"$mode:$oldstate"}});
	    #debug("translist=$translist\n");
	    #debug("splitlist=".join(", ",split(/[:,]/,$translist))."\n");
	    my %trans = split(/[:,]/,$translist);
	    debug("Valid transitions from $mode/$oldstate are:\n");
	    foreach my $k (sort keys %trans) {
		debug("$k => $trans{$k}\n");
	    }
	    if (defined($trans{$newmode})) {
		$nextstate=$trans{$newmode};
	    } else {
		notify("Invalid mode transition for $node from ".
		       "$mode/$oldstate to $newmode!\n");
	    }
894 895
	}
    } else {
896
	notify("Invalid mode transition for $node from $mode/$oldstate: ".
897 898
	       "Not a valid mode transition state!\n");
    }
Mac Newbold's avatar
Mac Newbold committed
899 900 901
    if (!$nextstate) {
	$nextstate=$oldstate;
    }
Mac Newbold's avatar
Mac Newbold committed
902

903 904 905 906 907 908
    my $now = time();
    $nodes{$node}{state}     = $nextstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{mode}           = $newmode;
    $nodes{$node}{mode_timestamp} = $now;
    $nodes{$node}{notified}       = 0;
Mac Newbold's avatar
Mac Newbold committed
909

910 911 912 913 914
    info("$node: $mode/$oldstate => $newmode/$nextstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$nextstate', ".
		 "next_op_mode='', op_mode='$newmode', ".
		 "state_timestamp='$now', ".
		 "op_mode_timestamp='$now' WHERE node_id='$node'");
Mac Newbold's avatar
Mac Newbold committed
915 916 917 918

    # Check if this state has a timeout, and if so, put it in the queue
    setTimeout($newmode,$nextstate,$node,$now);

919 920 921 922
}

sub handleCtrlEvent($$) {
    my ($node,$event) = @_;
923

924
    info("CtrlEvent: $node, $event\n");
925

926 927
    foreach ($event) {
	/^$TBRESET$/ && do {
928 929
	    #
	    # Clear next_boot_path with os_select.
Mac Newbold's avatar
Mac Newbold committed
930
	    #
931
	    $cmd = "$osselect -d -c -1 $node";
932
	    system($cmd) and
933
		notify("$node/$event: Could not clear next_boot_path!\n");
Mac Newbold's avatar
Mac Newbold committed
934 935

	    info("Performed $TBRESET for $node\n");
936 937
	    next;
	};
938
	(/^$TBRELOADDONEV1$/ || /^$TBRELOADDONEV2$/) && do {
939 940 941 942 943 944 945
	    info("Clearing reload info for $node\n");
	    DBQueryFatal("delete from current_reloads where node_id='$node'");
	    my ($pid,$eid);
	    NodeidToExp($node,\$pid,\$eid);
	    if (($pid eq NODERELOADING_PID) && ($eid eq NODERELOADING_EID)) {
		DBQueryFatal("delete from scheduled_reloads ".
			     "where node_id='$node'");
946
		DBQueryFatal("delete from reserved where node_id='$node'");
947 948
		TBSetNodeHistory($node, TB_NODEHISTORY_OP_FREE,
				 $UID, $pid, $eid);
949
		info("Released $node from $pid/$eid\n");
950
	    }
951 952 953 954 955
	    if ($event eq $TBRELOADDONEV2) {
		info("Sending an apod to $node\n");
		system("$apod $node") == 0 or
		    notify("Could not apod $node after $TBRELOADDONEV2!\n");
	    }
956 957 958
	    next;
	};
	/^$TBTIMEOUT$/ && do {
959 960 961 962
	    my ($mode,$state) = split(":",$timeout_tag{$node});
	    delete($timeout_tag{$node});
	    my $curstate = $nodes{$node}{state};
	    my $curmode = $nodes{$node}{mode};
963
	    my ($timeout,$action);
964 965 966 967 968
	    if (!defined($nodes{$node}{notified})) {
		$nodes{$node}{notified}=0;
	    }
	    $nodes{$node}{notified}++;
	    my $notified = $nodes{$node}{notified};
969 970
	    $nodes{$node}{timedout}++;
	    my $timedout = $nodes{$node}{timedout};
971 972 973 974
	    if ($mode && $state && $timeouts{$mode} &&
		$timeouts{$mode}{$state}) {
		($timeout, $action) = @{$timeouts{$mode}{$state}};
	    }
975 976
	    if ($mode eq $TBCOMMAND) {
		# It is a command, not a true state
977
		if ($action eq $TBTIMEOUTCMDRETRY) {
978
		    # Retry the command
979
		    notify("$node: Command $state, retry #$timedout\n");
980
		    # notify in case we get in a retry loop...
981
		    handleCommand($node,$state,$timedout,1);
982 983 984 985 986 987
		} else {
		    notify("$node: Unknown timeout action for ".
			   "$mode/$state: '$action'\n");
		}
		next;
	    }
988 989 990 991 992 993 994

	    #
	    # Trash. This stuff should not be encoded this way, but I have
	    # no idea how timeouts, TBCOMMAND, and actions interact.
	    #
	    if ($curstate eq $PXEWAKEUP) {
		my $optarg = ($debug ? "-d " : "");
Mac Newbold's avatar
Mac Newbold committed
995

996 997
		if ($timedout < 3) {
		    #
Mac Newbold's avatar
Mac Newbold committed
998 999
		    # Try again.
		    #
1000 1001 1002 1003 1004 1005
		    info("Node $node has timed out $timedout times in ".
			 "$PXEWAKEUP!\n".
			 "Sending it a another wakeup command\n");
		}
		else {
		    #
Mac Newbold's avatar
Mac Newbold committed
1006 1007
		    # Failed too many times, power cycle instead.
		    #
1008 1009 1010 1011 1012 1013 1014 1015 1016
		    notify("Node $node has timed out $timedout times in ".
			   "$PXEWAKEUP!\n".
			   "Sending it a reboot command\n");
		    $optarg .= "-k";
		}
		my $cmd = "$nodereboot -r $optarg $node";
		debug("$cmd\n");
		system("date 2>&1 >> $rebootlog");
		system("$cmd 2>&1 >> $rebootlog &") and
1017
		    notify("$PXEWAKEUP retry: ".
1018 1019 1020 1021 1022
			   "Command '$cmd' failed, error $?: $!\n");

		next;
	    }

1023 1024 1025 1026 1027 1028
	    info("Node $node has timed out in state $mode/$state".
		 ($action ne "" ? "\n\tRequested action $action." : "").
		 "\n");

	    foreach ($action) {
		/^$TBTIMEOUTREBOOT/ && do {
1029 1030 1031 1032 1033
		    if ($timedout>3) {
			# We've tried too many times...
			notify("Node $node has timed out too many times!\n".
			       "Giving up until it boots sucessfully.\n");
			$nodes{$node}{noretry} = 1;
1034
		    } else {
1035 1036 1037 1038 1039 1040
			# XXX Temporary!  For now notify instead of
			# really rebooting, until the timeout/retry
			# stuff is gone from os_setup and os_load
			notify("Node $node has timed out in state ".
			       "$mode/$state - REBOOT requested\n");
			#handleCommand($node,$TBREBOOT,$timedout,1);
1041 1042 1043 1044 1045 1046 1047
		    }
		    last; };
		/^$TBTIMEOUTNOTIFY/ && do {
		    notify("Node $node has timed out in state $mode/$state\n");
		    last; };
		notify("$node: Unknown Timeout Action: $action\n");
	    }
1048 1049
	    next;
	};
1050
	notify("$node: Unknown CtrlEvent: $event\n");
1051 1052
    }
}
Robert Ricci's avatar
Robert Ricci committed
1053

1054 1055
sub handleCommand($$;$$) {
    my ($params,$command,$retry,$force) = @_;
1056
    if (!defined($retry)) { $retry=0; }
1057
    if (!defined($force)) { $force=0; }
1058 1059 1060 1061 1062 1063 1064 1065

    info("Command: $params, $command (attempt $retry)\n");

    # XXX - Right now we skip the checkDBRedirect calls for our
    # TBCOMMAND events, since they may have a list of nodes in them.
    # We may need to do it here (while iterating over the list), or
    # make some other fix up in handleEvent.

1066
    if ($command eq $TBREBOOT && $retry >=4) {
1067 1068
	announce("Node $params has tried rebooting $retry times and has \n".
		 "still not been successful. Please look into it soon.\n".
1069 1070 1071
	"" );#	 "In the meantime, $params will be powered off.\n");
	# Just return...
	return 0;
1072
	# change my command to poweroff.
1073
	#$command = $TBPOWEROFF;
1074 1075 1076 1077 1078 1079
    }

    foreach ($command) {
	/^$TBREBOOT$/ && do {
	    # For reboot, the params is a comma-separated list of nodes
	    my @nodes = split(",",$params);
1080 1081 1082 1083 1084 1085 1086 1087

	    # Check if any of these are in the middle of things and
	    # shouldn't be rebooted.
	    if (!$force) {
		foreach $n ( 0 .. $#nodes ) {
		    $node = $nodes[$n];
		    debug("Checking rebooting: $node, $nodes{$node}, ".
			  "$nodes{$node}{state}, $nodes{$node}{noretry}\n");
1088 1089
		    if (($nodes{$node}{state} ne TBDB_NODESTATE_ISUP) &&
			(!$nodes{$node}{noretry}) ) {
1090
			# This node shouldn't be rebooted now...
1091 1092
			# XXX Send feedback here somehow!

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
			info("$node: Trying to reboot too soon! Skipping.\n");
			# Cut it out of the list
			debug("Nodelist before ==> ".join(" ",@nodes)."\n");
			splice(@nodes,$n,1);
			debug("Nodelist after  ==> ".join(" ",@nodes)."\n");
		    }
		}
		if (@nodes == 0) { next; }
	    }

1103 1104 1105 1106 1107
	    my $nodelist=join(" ",@nodes);
	    info("Rebooting nodes: $nodelist\n");
	    # Permissions were checked in order to send the message,
	    # so we don't need to do any fancy stuff here.

1108
	    my $cmd = "$nodereboot -r $nodelist";
1109
	    my $redir = " 2>&1 >> $rebootlog &";
1110 1111 1112
	    debug("$cmd $redir\n");
	    system("date $redir");
	    system($cmd.$redir) and
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
	      notify("$params/$command: ".
		     "Command '$cmd' failed, error $?: $!\n");

	    # Set up a timeout, so we retry if we don't get SHUTDOWN in time
	    foreach $node (@nodes) {
		# Note: This will replace any state timeouts currently in
		# the queue. But here that's okay because we're expecting
		# to see another transition really soon anyway.
		setTimeout($TBCOMMAND,$command,$node,time());
	    }

	    info("Performed $command for $params\n");
	    next;
	};
	(/^$TBPOWEROFF$/ || /^$TBPOWERON$/ || /^$TBPOWERCYCLE$/) && do {
	    # For power, the params is a comma-separated list of nodes
	    my @nodes = split(",",$params);
	    my $nodelist=join(" ",@nodes);
	    my %funcmap = ( $TBPOWERCYCLE => "cycle",
			    $TBPOWERON    => "on",
			    $TBPOWEROFF   => "off");
	    my $func = $funcmap{$command};
1135
	    info("Sending power $func for nodes: $nodelist\n");
1136 1137 1138 1139
	    # Permissions were checked in order to send the message,
	    # so we don't need to do any fancy stuff here.

	    my $cmd = "$power $func $nodelist &";
1140 1141
	    debug("$cmd\n") and
	    system($cmd) and
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	      notify("$params/$command: ".
		     "Command '$cmd' failed, error $?: $!\n");

	    info("Performed $command for $params\n");
	    next;
	};
	notify("$params: Unknown Command: $command\n");
    }
}

1152 1153 1154 1155
#
# Check if we need to generate an ISUP
#
sub checkGenISUP($) {
Mac Newbold's avatar
Mac Newbold committed
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    my ($node) = @_;
    debug("$node: Checking ISUP Generation\n");
    my $r = DBQueryWarn("select osfeatures from nodes as n ".
			"left join os_info as o on o.osid=n.osid ".
			"where node_id='$node' and osfeatures is not null");
    my $osfeatures="";
    # If we don't get anything back, assume it has no features.
    if ($r->num_rows() > 0) {
	($osfeatures) = $r->fetchrow();
    }
Mac Newbold's avatar
Mac Newbold committed
1166

Mac Newbold's avatar
Mac Newbold committed
1167 1168 1169 1170 1171 1172
    my @features = split(",",$osfeatures);
    # Make sure features I care about are defined
    my %can=("ping"=>0, "isup"=>0);
    foreach my $f (@features) {
	$can{"\L$f"}=1;	# make sure it's all lowercase
    }
Mac Newbold's avatar
Mac Newbold committed
1173

Mac Newbold's avatar
Mac Newbold committed
1174 1175
    # If os will send ISUP on its own, do nothing here.
    if ($can{"isup"}) {
Mac Newbold's avatar
Mac Newbold committed
1176
	debug("$node: Will send own ISUP\n");
Mac Newbold's avatar
Mac Newbold committed
1177 1178
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
1179

Mac Newbold's avatar
Mac Newbold committed
1180 1181 1182 1183 1184 1185
    # If os doesn't support isup but can ping, fork and ping it every
    # few seconds and send isup when it pings, or timeout after too long.
    if ($can{"ping"}) {
	debug("$node: Needs to be pinged - calling eventping\n");
	system("$TB/sbin/eventping $node &");
	return 0;
1186
    }
Mac Newbold's avatar
Mac Newbold committed
1187

Mac Newbold's avatar
Mac Newbold committed
1188
    # If os doesn't support ping or isup, stated sends ISUP just after
Mac Newbold's avatar
Mac Newbold committed
1189 1190 1191 1192 1193 1194 1195
    # the node gets to BOOTING (a bit early, but the best we can do)

    debug("$node: OS doesn't ping - sending ISUP\n");
    EventSendWarn(host      => $BOSSNODE ,
		  objtype   => TBDB_TBEVENT_NODESTATE ,
		  eventtype => TBDB_NODESTATE_ISUP ,
		  objname   => $node);
Robert Ricci's avatar
Robert Ricci committed
1196 1197
}

1198 1199 1200 1201
# Figure out if this node belongs to us (ie. if it's using our database.)
# Returns 1 if it does, 0 if not
sub checkDBRedirect($) {

Mac Newbold's avatar
Mac Newbold committed
1202
    my ($node) = @_;
1203