stated.in 61.4 KB
Newer Older
Robert Ricci's avatar
Robert Ricci committed
1
#!/usr/bin/perl -w
Leigh Stoller's avatar
Leigh Stoller committed
2
#
3
# Copyright (c) 2000-2014 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/>.
# 
# }}}
Leigh Stoller's avatar
Leigh Stoller committed
23 24
#

Robert Ricci's avatar
Robert Ricci committed
25 26 27
#
# 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
28
# state into the database. Also watches for invalid transitions, timeouts,
29
# and performs other state-related control functions.
Robert Ricci's avatar
Robert Ricci committed
30 31 32 33
#
# Send it a HUP signal to get it to reload the timeout and transition
# information. Periodically reloads this information regardless, though.
#
34
# Will restart when sent SIGUSR1, by exec'ing its executable again.
Robert Ricci's avatar
Robert Ricci committed
35
#
36

Robert Ricci's avatar
Robert Ricci committed
37 38
# Configure variables
use lib '@prefix@/lib';
39
my $TB = "@prefix@";
40
my $REALTB = "/usr/testbed"; # So we know if we're the "real" stated or not
Robert Ricci's avatar
Robert Ricci committed
41
my $BOSSNODE = "@BOSSNODE@";
42
my $TBOPS = "@TBSTATEDEMAIL@";
43
my $REALTBOPS = "@TBOPSEMAIL@";
44
my $TBDBNAME = "@TBDBNAME@";
45
my $REALTBDBNAME = "tbdb"; # So we know if we're using the "real" db
46
my $pxeselect = "$TB/bin/pxe_select";
47
my $osselect = "$TB/bin/os_select";
48
my $nodereboot = "$TB/bin/node_reboot";
49
my $rebootlog  = "$TB/log/nodereboot.log";
50
my $power = "$TB/bin/power";
51
my $apod = "$TB/sbin/apod";
52
my $TBLOG = "@TBLOGFACIL@";
53
my $LOGFILE = "$TB/log/stated.log";
54
my $MAILFILE = "$TB/log/stated-mail.log";
Robert Ricci's avatar
Robert Ricci committed
55 56 57 58 59

$| = 1;

use event;
use libdb;
60
use Node;
61
use OSinfo;
Robert Ricci's avatar
Robert Ricci committed
62
use libtestbed;
63
use TimeoutQueue;
Robert Ricci's avatar
Robert Ricci committed
64
use Getopt::Std;
65
#use strict;
Robert Ricci's avatar
Robert Ricci committed
66
use English;
Mac Newbold's avatar
Mac Newbold committed
67 68
use POSIX;			# for strftime, and sigprocmask and friends
use Fcntl;			# file constants for pidfile
69 70
use POSIX ":sys_wait_h";
use IO::Poll qw(POLLIN);
71
use POSIX qw(:errno_h);
Mac Newbold's avatar
Mac Newbold committed
72

73 74 75 76 77 78
#
# Set this non-zero if you want to send mail on abnormal stated events.
# Otherwise we just log them to $MAILFILE.
#
my $SPAMME = 0;

79 80 81 82 83
# 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
84
# Number of iterations (roughly, seconds) after which we'll reload
Robert Ricci's avatar
Robert Ricci committed
85 86
# information from the database. This is so we don't end up with information
# that's _too_ out of sync.
87
my $reload_time = 600;
88
my $last_reload = time;
Robert Ricci's avatar
Robert Ricci committed
89

Mike Hibler's avatar
Mike Hibler committed
90 91 92
# For startup and reload: maximum time in the past for which we will schedule
# a timeout. Anything older is assumed to be ancient history and is ignored.
# Note it is a negative value.
93
my $maxpasttimeout = -(7 * 24 * 60 * 60);	# 1 week
Mike Hibler's avatar
Mike Hibler committed
94

95 96 97
# Handling of SECVIOLATIONS, eventually controlled by a sitevar
my $soft_secviolation = 1;

98 99 100
# Command line opts.
my $dbtag = "";
my $debug = 0;
101 102
my $server = "localhost";
my $port   = @BOSSEVENTPORT@;
103 104
my $lockfile;
my $pidfile;
105
my $eventchild;
106

Robert Ricci's avatar
Robert Ricci committed
107 108 109
# Process command-line arguments

sub usage {
Mac Newbold's avatar
Mac Newbold committed
110
    print << "END";
111
Usage: $0 [-h] [-d] [-s server] [-p port] [-t dbtag]
112
-h              This message
113 114
-d              Turn on debugging output, and do not go into the background
-t tag          Use only those nodes with matching tag in nodes table
Robert Ricci's avatar
Robert Ricci committed
115 116
-s server       Use specified server, instead of this site's bossnode
-p port	        Use specified port
117
Send SIGHUP to reload database state, or SIGUSR1 to restart completely.
Robert Ricci's avatar
Robert Ricci committed
118
END
119
    exit(1);
Robert Ricci's avatar
Robert Ricci committed
120 121
}

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

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

Mac Newbold's avatar
Mac Newbold committed
132 133 134 135 136 137
if ($opt{h}) {
    exit &usage;
}
if (@ARGV) {
    exit &usage;
}
Robert Ricci's avatar
Robert Ricci committed
138

Mac Newbold's avatar
Mac Newbold committed
139 140 141 142 143 144
if ($opt{s}) {
    $server = $opt{s};
}
if ($opt{p}) {
    $port = $opt{p};
}
145 146 147
if ($opt{t}) {
    $dbtag = $opt{t};
}
Mac Newbold's avatar
Mac Newbold committed
148 149 150
if ($opt{d}) {
    $debug = 1;
}
Robert Ricci's avatar
Robert Ricci committed
151

152
# Grab some constants into variables
153
my $TBANYMODE    = TBDB_NODEOPMODE_ANY;
154
my $TBPXERESET   = TBDB_TBCONTROL_PXERESET;
155 156
my $TBRESET      = TBDB_TBCONTROL_RESET;
my $TBTIMEOUT    = TBDB_TBCONTROL_TIMEOUT;
Mac Newbold's avatar
Mac Newbold committed
157 158 159
my $PXEBOOT      = TBDB_TBCONTROL_PXEBOOT;
my $BOOTING      = TBDB_TBCONTROL_BOOTING;
my $CHECKGENISUP = TBDB_TBCONTROL_CHECKGENISUP;
160 161 162
my $TBNOTIMEOUT  = TBDB_NO_STATE_TIMEOUT;
my $TBNODESTATE  = TBDB_TBEVENT_NODESTATE;
my $TBNODEOPMODE = TBDB_TBEVENT_NODEOPMODE;
163 164 165 166 167 168
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;
169
my $TBISUP       = TBDB_NODESTATE_ISUP;
170 171 172
my $PXEWAIT      = TBDB_NODESTATE_PXEWAIT;
my $PXEWAKEUP    = TBDB_NODESTATE_PXEWAKEUP;
my $PXEBOOTING   = TBDB_NODESTATE_PXEBOOTING;
173 174
my $TBRELOADDONEV1    = TBDB_TBCONTROL_RELOADDONE;
my $TBRELOADDONEV2    = TBDB_TBCONTROL_RELOADDONE_V2;
175 176 177 178
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;
179

180 181
# Special PXEBOOT state machine that all local nodes use.
my $PXEKERNEL	 = "PXEKERNEL";
182

183 184
# Even special-er SECUREBOOT state machine that local nodes may use.
my $SECUREBOOT	 = "SECUREBOOT";
185

186 187 188 189
# Protos.
sub debug(@);
sub fatal($);
sub notify($;$);
190
sub info($);
191 192 193 194 195 196 197
sub getTimeouts();
sub getValid();
sub getModeTrans();
sub getTriggers();
sub readStates(;@);
sub handleCtrlEvent($$);
sub reload();
198 199
sub StartEvents();
sub PollEvents($$);
200
    
201 202 203
if (!$debug) {
    if ( $TB eq $REALTB ) {
	$pidfile = "/var/run/stated.pid";
Mac Newbold's avatar
Mac Newbold committed
204
    } else {
205
	$pidfile = "$TB/locks/stated.pid";
Mac Newbold's avatar
Mac Newbold committed
206
    }
207
    debug("Using pidfile $pidfile\n");
Mac Newbold's avatar
Mac Newbold committed
208

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    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
224
    if (TBBackGround($LOGFILE)) {
Mac Newbold's avatar
Mac Newbold committed
225 226
	exit(0);
    }
227
    TBdbfork();
Robert Ricci's avatar
Robert Ricci committed
228
}
229 230 231 232 233 234 235 236 237

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
238

239 240 241
# Change my $0 so that it is easier to see in a ps/top
$0 = "$0";

242 243 244 245 246
#
# Start up the event system interface.
#
if (StartEvents() != 0) {
    fatal("Error starting events");
Robert Ricci's avatar
Robert Ricci committed
247
}
248 249
# We want to exit on any warning. 
$SIG{__WARN__} = sub { print STDERR $_[0]; exit(-1); };
Robert Ricci's avatar
Robert Ricci committed
250 251 252

# Read in the pre-existing node states, and timeout and valid transition
# information from the database
253 254 255 256
my %timeouts  = getTimeouts();
my %valid     = getValid();
my %modeTrans = getModeTrans();
my %triggers  = getTriggers();
257
my %nodes     = readStates();
258
my %timeouttag= ();
259
if ($debug) { qshow(); }
Robert Ricci's avatar
Robert Ricci committed
260 261 262

# Gets set if a reload of state from the database should happen.
my $do_reload = 0;
263
my $do_reopen = 0;
264 265
my $sigrestart= 0;
my $sigcleanup= 0;
266
my $exiting   = 0;
Robert Ricci's avatar
Robert Ricci committed
267 268 269 270

# 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.
271
$SIG{HUP}  = sub { info("SIGHUP - Reloading DB state\n"); $do_reload = 1; };
272
$SIG{USR2} = sub { info("SIGUSR2 - Reopening logfile\n"); $do_reopen = 1; };
273

Mac Newbold's avatar
Mac Newbold committed
274
# Set up other signals.
275 276 277 278 279
$SIG{USR1} = \&restart_wrap;
$SIG{INT}  = \&cleanup_wrap;
$SIG{QUIT} = \&cleanup_wrap;
$SIG{ABRT} = \&cleanup_wrap;
$SIG{TERM} = \&cleanup_wrap;
Robert Ricci's avatar
Robert Ricci committed
280

281 282 283
# Track if I handled an event or not
my $event_count = 0;

284 285
# Control how long I block while waiting for events
my $blockwait=0;
286
my $nextdeadline=0;
287 288
my $mailqueue=0;

289 290 291 292 293
notify("Stated starting up\n");

sub process_event_queue() {
    $event_count=0;
    my $lastcount=-1;
294 295
    my $wait;
    my $now = time();
Mike Hibler's avatar
Mike Hibler committed
296
    debug("Polling at $now - mq=$mailqueue bw=$blockwait ndl=$nextdeadline\n");
297 298 299 300 301 302 303 304 305 306
    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;
307 308
	    } else {
		$wait = 0;
309 310 311 312 313
	    }
	}
    } else {
	# mail is waiting. Only block until it is time to send it.
	$wait = $lastmail + $mailgap - $now;
Mac Newbold's avatar
Mac Newbold committed
314
	debug("Now $now, mailgap $mailgap, last $lastmail ==> wait $wait\n");
315 316 317
    }
    if ($wait < 0) { debug("Wait was $wait!\n"); $wait=0; }
    my $finish = $now + $wait;
Mac Newbold's avatar
Mac Newbold committed
318
    while (($event_count != $lastcount || $wait > 0) &&
319
	   !($sigrestart || $sigcleanup || $do_reload || $do_reopen)) {
320
	$lastcount = $event_count;
Mac Newbold's avatar
Mac Newbold committed
321
	# Don't block if we got a signal!
322
	if ($wait<=0 || $sigrestart || $sigcleanup || $do_reload || $do_reopen) {
323
	    PollEvents(0, 0);
324
	} else {
325
	    #debug("Using blocking event poll - $wait seconds\n");
326
	    # timeout param is in milliseconds, so multiply
327
	    PollEvents(1, $wait);
328 329 330
	    $now = time();
	    # subtract seconds elapsed from my wait time
	    $wait = $finish - $now;
331
	    #debug("Finished blocking event poll - $wait seconds remain\n");
332
	    if ($event_count > 0 &&
Mac Newbold's avatar
Mac Newbold committed
333
		(qsize() > 0 || $mailqueue ||
334
		 $sigrestart || $sigcleanup || $do_reload || $do_reopen)) {
335 336 337 338 339 340 341
		$blockwait=0;
		$wait=0;
		#debug("Cancelling wait - timeouts/msgs waiting, or HUP'd\n");
		#debug("---End Blocking Wait ---\n");
	    }
	}
	#debug("Wait is $wait\n");
342 343
    }
    if ($event_count > 0) {
Mac Newbold's avatar
Mac Newbold committed
344
	debug("Handled $event_count event(s).\n");
345 346
    }
}
Robert Ricci's avatar
Robert Ricci committed
347

348
# Now, we just poll for events, and watch for timeouts
Robert Ricci's avatar
Robert Ricci committed
349
while (1) {
Mac Newbold's avatar
Mac Newbold committed
350
    my $now = time();
351 352 353 354
    my ($deadline,$node);

    # Check for nodes that have passed their timeout
    if (!qhead($deadline,$node)) {
355
	info("HEAD: $node in ".($deadline-$now).", queue=".qsize()."\n");
356 357
	while ($now >= $deadline && $node ne "") {
	    qpop($deadline,$node);
358
	    info("POP: $node in ".($deadline-$now).", queue=".qsize()."\n");
359 360 361 362 363 364 365 366 367 368 369 370 371
	    #
	    # If the node is no longer in the nodes array, it was most
	    # likely a dynamic virtual node which is now gone. Ignore.
	    # Need to look at reload() to see if we can catch this earlier. 
	    #
	    if (exists($nodes{$node})) {
		handleCtrlEvent($node,$TBTIMEOUT);
	    }
	    else {
		info("POP: $node is no longer in the nodes array. Skipping\n");
		delete($timeout_tag{$node})
		    if (exists($timeout_tag{$node}));
	    }
372 373 374 375
	    if (0) { qshow(); }
	    if (qhead($deadline,$node)) {
		$deadline=0; $node="";
	    }
376
	}
377 378
    } else {
	$deadline=0;
379
    }
380
    $nextdeadline = $deadline;
381

Mac Newbold's avatar
Mac Newbold committed
382 383 384 385
    if ($do_reload || ($now - $last_reload > $reload_time)) {
	reload();
	$do_reload = 0;
    }
Mac Newbold's avatar
Mac Newbold committed
386

Mike Hibler's avatar
Mike Hibler committed
387 388 389 390 391
    if (qsize()==0) {
	$blockwait=1;
	debug("---Blocking wait okay---\n");
    }

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

395 396
    if ($sigrestart) { restart(); }
    if ($sigcleanup) { cleanup(); }
397 398 399 400 401 402 403
    if ($do_reopen)  {
	ReOpenLog($LOGFILE);
	if (! kill('USR2', $eventchild)) {
	    fatal("Could not signal(USR2) event reader child\n");
	}
	$do_reopen = 0;
    }
404
    process_event_queue;
Robert Ricci's avatar
Robert Ricci committed
405 406
}

Mac Newbold's avatar
Mac Newbold committed
407 408
exit(0);

Robert Ricci's avatar
Robert Ricci committed
409
# Read the current states of nodes from the database
410
sub readStates(;@) {
Mac Newbold's avatar
Mac Newbold committed
411
    my %oldnodes = @_;
Mike Hibler's avatar
Mike Hibler committed
412
    my $now = time();
Mac Newbold's avatar
Mac Newbold committed
413 414

    # Guard against undefined variable warnings
415
    if (! %oldnodes) {
Mac Newbold's avatar
Mac Newbold committed
416 417
	%oldnodes = ();
    }
418

Mac Newbold's avatar
Mac Newbold committed
419 420 421
    #debug("readStates called\n");
    my $result = DBQueryFatal("SELECT node_id, eventstate, " .
			      "state_timestamp, op_mode, " .
422
			      "op_mode_timestamp, stated_tag FROM nodes ".
423
			      "where node_id not like 'sh%'");
Mac Newbold's avatar
Mac Newbold committed
424 425

    my %nodes;
426
    while (my ($node_id, $state, $timestamp, $mode, $mode_timestamp, $tag)
Mac Newbold's avatar
Mac Newbold committed
427
	   = $result->fetchrow()) {
428 429 430 431 432 433 434 435 436 437 438
	$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
439

440
	#
Mac Newbold's avatar
Mac Newbold committed
441 442 443 444
	# 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.)
445
	#
Mac Newbold's avatar
Mac Newbold committed
446 447 448 449 450
	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};
451
	} else {
Mac Newbold's avatar
Mac Newbold committed
452 453 454 455
	    $nodes{$node_id}{state}          = $state;
	    $nodes{$node_id}{timestamp}      = $timestamp;
	    $nodes{$node_id}{mode}           = $mode;
	    $nodes{$node_id}{mode_timestamp} = $mode_timestamp;
456 457 458
	    $nodes{$node_id}{notified}       = 0;
	    $nodes{$node_id}{timedout}       = 0;
	    $nodes{$node_id}{noretry}        = 0;
459
	    # Is there a timeout? If so, set it up!
Mike Hibler's avatar
Mike Hibler committed
460
	    if (defined($timestamp) && $dbtag eq $nodes{$node_id}{"tag"}) {
461
		setTimeout($mode,$state,$node_id,$timestamp);
462
	    }
463
	}
Mac Newbold's avatar
Mac Newbold committed
464 465
    }
    return %nodes;
Robert Ricci's avatar
Robert Ricci committed
466 467 468 469 470 471
}

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

Mac Newbold's avatar
Mac Newbold committed
476 477 478 479 480
    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
481 482 483 484 485 486
}

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

Mac Newbold's avatar
Mac Newbold committed
491
    my %valid;
492
    while (my ($mode, $state1, $state2) = $result->fetchrow()) {
Mac Newbold's avatar
Mac Newbold committed
493 494 495
	$valid{$mode}{$state1}{$state2} = 1;
    }
    return %valid;
Robert Ricci's avatar
Robert Ricci committed
496 497
}

498 499 500 501 502 503 504 505
#
# Check if a transition is valid. Actually, it is a check for an invalid
# transition.
#
sub IsValidTransition($$$)
{
    my ($mode, $oldstate, $newstate) = @_;

506 507 508 509 510 511 512 513 514 515 516
    # If there are no transitions for mode, then all transitions are invalid.
    if (!exists($valid{$mode})) {
	return 0;
    }

    # See if there is a specific transition for mode/oldstate -> newstate
    if (exists($valid{$mode}{$oldstate}) &&
	exists($valid{$mode}{$oldstate}{$newstate}) &&
	$valid{$mode}{$oldstate}{$newstate} == 1) {
	return 1;
    }
517

518 519 520 521 522 523 524 525 526
    # See if there is a wildcard transition for mode/* -> newstate
    if (exists($valid{$mode}{"*"}) &&
	exists($valid{$mode}{"*"}{$newstate}) &&
	$valid{$mode}{"*"}{$newstate} == 1) {
	return 1;
    }

    # Otherwise, transition is invalid.
    return 0;
527 528
}

529 530 531 532
#
# Read the list of valid mode transitions from the database
#
sub getModeTrans() {
Mac Newbold's avatar
Mac Newbold committed
533
    #debug("getModeTrans called\n");
Mac Newbold's avatar
Mac Newbold committed
534
    my $result =
Mac Newbold's avatar
Mac Newbold committed
535 536 537 538 539 540 541 542 543 544 545
      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;
546
	}
Mac Newbold's avatar
Mac Newbold committed
547 548
    }
    return %modeTrans;
549 550 551 552 553 554
}

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

557 558
    debug("anymode ==> '$TBANYMODE'\n");

Mac Newbold's avatar
Mac Newbold committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    # 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 =
580
      DBQueryFatal("SELECT op_mode, state, `trigger` " .
581 582
		   "FROM state_triggers where node_id='$TBANYMODE' ".
		   "order by op_mode,state");
Mac Newbold's avatar
Mac Newbold committed
583
    my %t;
584
    while (my ($mode, $state, $trig) = $result->fetchrow()) {
Mac Newbold's avatar
Mac Newbold committed
585 586 587
	my @trigs = split(/\s*,\s*/,$trig);
	$t{"$mode:$state"} = \@trigs;
	debug("trig($mode:$state)\t => ".join(',',@trigs)."\n");
588 589
    }

Mac Newbold's avatar
Mac Newbold committed
590 591
    # Grab per-node triggers (including any-mode)
    $result =
592
      DBQueryFatal("SELECT node_id, op_mode, state, `trigger` " .
593 594 595 596 597 598
		   "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
599
    }
600

Mac Newbold's avatar
Mac Newbold committed
601 602
    debug(hash_recurse(%t));

Mac Newbold's avatar
Mac Newbold committed
603
    return %t;
604 605
}

Robert Ricci's avatar
Robert Ricci committed
606 607 608 609
#
# Gets called for every event that we recieve
#
sub handleEvent($$$) {
610
    my ($objtype,$objname,$eventtype) = @_;
Mac Newbold's avatar
Mac Newbold committed
611
    $event_count++;
Mac Newbold's avatar
Mac Newbold committed
612

613
    #
Mac Newbold's avatar
Mac Newbold committed
614 615 616
    # 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.
617
    #
618
    if ($dbtag eq "") {
619 620
	debug("Got an event: ($objtype,$objname,$eventtype)\n");
    }
Mac Newbold's avatar
Mac Newbold committed
621 622 623 624

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

628 629 630 631 632 633 634
	#
	# 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
635
	    # churning via reload(). Bad.
636
	    if (! defined($nodes{$node})) {
637 638 639 640
		notify("Got $objtype/$eventtype for nonexistent $node!\n");
		return;
	    }
	}
Mac Newbold's avatar
Mac Newbold committed
641

642 643
	#
	# If a stated_tag was specified on the command line, ignore those
Mac Newbold's avatar
Mac Newbold committed
644
	# nodes that do not match.
645
	#
Mac Newbold's avatar
Mac Newbold committed
646
	#debug("dbtag='$dbtag', node $node='".$nodes{$node}{"tag"}."'\n");
647 648 649 650 651 652 653 654 655 656
	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
657
    }
Mac Newbold's avatar
Mac Newbold committed
658 659 660 661 662

    #
    # 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.)
    #
663 664 665
    if ($dbtag ne "") {
	debug("Got an event: ($objtype,$objname,$eventtype)\n");
    }
Mac Newbold's avatar
Mac Newbold committed
666 667 668

 SWITCH: for ($objtype) {

Mac Newbold's avatar
Mac Newbold committed
669 670 671 672 673 674 675 676 677 678 679 680 681 682
	(/$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;
	};
683 684 685 686
	(/$TBCOMMAND/) && do {
	    handleCommand($objname,$eventtype);
	    last;
	};
687

Mac Newbold's avatar
Mac Newbold committed
688
    }
689 690 691 692 693

}

sub stateTransition($$) {

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

696 697
    # Check for invalid transitions
    my ($oldstate, $mode);
698 699 700
    $oldstate = $nodes{$node}{state};
    $mode     = $nodes{$node}{mode};

701
    if ($oldstate && $mode && !IsValidTransition($mode,$oldstate,$newstate)) {
702
	notify("Invalid transition for node $node from $mode/$oldstate " .
703
	       "to $newstate\n");
704
	
705 706 707 708 709 710
	#
	# Machines in the secure boot path are not allowed to jump
	# willy-nilly into unknown states.
	#
        if ($mode eq TBDB_NODEOPMODE_SECUREBOOT ||
	    $mode eq TBDB_NODEOPMODE_SECURELOAD) {
711 712 713
            $newstate = TBDB_NODESTATE_SECVIOLATION;
            notify("Moving $node to $newstate because it's in $mode\n");
        }
714
    }
715

716 717 718 719 720
    #
    # Nodes that are in the SECVIOLATION state are not allowed to leave!
    #
    if ($oldstate eq TBDB_NODESTATE_SECVIOLATION &&
	$newstate ne TBDB_NODESTATE_SECVIOLATION) {
721
	#
722 723 724
	# Allow transitions to SHUTDOWN/POWEROFF.
	# This allows someone to reboot (turn-off and back on) a node in
	# the SECVIOLATION state getting it back to MINIMAL/SHUTDOWN.
725 726 727
	#
	# XXX DEBUG ONLY!
	# 
728 729
	if ($soft_secviolation &&
	    ($newstate eq TBDB_NODESTATE_SHUTDOWN ||
730
	     $newstate eq TBDB_NODESTATE_POWEROFF ||
731 732
	     $newstate eq TBDB_NODESTATE_GPXEBOOTING)) {
	    notify("$node allowed to transition: SECVIOLATION => $newstate\n");
733 734 735 736
	} else {
	    notify("$node tried to leave SECVIOLATION (to $newstate)\n");
	    $newstate = TBDB_NODESTATE_SECVIOLATION;
	}
737
    }
Robert Ricci's avatar
Robert Ricci committed
738

739 740 741 742
    my $now = time();
    $nodes{$node}{state}     = $newstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{notified}  = 0;
743

744 745 746
    info("$node: $mode/$oldstate => $mode/$newstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$newstate', " .
		 "state_timestamp='$now' WHERE node_id='$node'");
747

748 749 750 751
    # 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:/) {
752
        debug("TimeoutTag = '$timeout_tag{$node}'\n");
753
	my ($str,$cmd) = split(":",$timeout_tag{$node});
754
	debug("str=$str\tcmd=$cmd\tTBREBOOT=$TBREBOOT\tstate=$newstate\n");
755
	if ($cmd eq $TBREBOOT) {
756
	    if ($newstate eq TBDB_NODESTATE_SHUTDOWN ) {
757 758 759
		info("$node: $TBREBOOT success\n");
		# Timeout will get cleared below by setTimeout call
	    } else {
760 761
		notify("$node: $TBREBOOT in progress, but got state ".
		       "$newstate instead of ".TBDB_NODESTATE_SHUTDOWN."!\n");
762 763 764 765 766
	    }
	#} elsif ($cmd eq $FOO ) {
	    # Add more here...
	} else {
	    notify("$node: Unknown command timeout '$timeout_tag{$node}' ".
767
		   "found at $mode/$newstate\n");
768 769 770
	}
    }

771 772 773 774 775
    #
    # 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.
    #
776 777
    setTimeout($mode,$newstate,$node,$now);

Mac Newbold's avatar
Mac Newbold committed
778 779 780 781 782 783 784
    # 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 = $_;
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
	    /^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
802
	    /^$PXEBOOT$/ && do {
803
		#
Mac Newbold's avatar
Mac Newbold committed
804 805 806 807 808 809 810 811 812 813 814 815
		# 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.
816
		#
Mac Newbold's avatar
Mac Newbold committed
817 818 819 820
		# 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.
821
		#
Mac Newbold's avatar
Mac Newbold committed
822 823 824 825
		debug("Running $PXEBOOT trigger\n");
		if ($mode ne $PXEKERNEL) {
		    opModeTransition($node, $PXEKERNEL, 1);
		    $mode=$PXEKERNEL;
826
		}
Mac Newbold's avatar
Mac Newbold committed
827 828
		next;
	    };
829 830 831 832 833 834
	    /^$SECUREBOOT$/ && do {
		#
		# Force machine into the SECUREBOOT/LOAD op_mode.
		# Currently triggered by receipt of GPXEBOOTING state.
		# This could come from any state as it just indicates that
		# a machine with a gPXE dongle has rebooted.
835
		#
836 837 838
		# To differentiate BOOT from LOAD:
		# if next_op_mode is SECURELOAD, goto SECURELOAD
		# else if mode/state is SECURELOAD/SHUTDOWN, goto SECURELOAD
839
		# else if mode/state is SECURELOAD/REBOOTING, goto SECURELOAD
840
		# else goto SECUREBOOT.
841
		#
842 843 844 845
		# The SHUTDOWN case handles os_load.
		# The REBOOT case handles the forced reboot following PXEWAIT
		# (inflicted by bootinfo--see bootinfo_mysql.c).
		#
846 847 848 849
		my $query_result =
		    DBQueryWarn("select next_op_mode from nodes ".
				"where node_id='$node'");
		my ($nextmode) = $query_result->fetchrow();
850 851 852
		if (!$nextmode) {
		    $nextmode = $mode;
		}
853
		info("Running $SECUREBOOT trigger with $nextmode/$oldstate\n");
854
		if ($nextmode ne TBDB_NODEOPMODE_SECURELOAD ||
855 856
		    ($oldstate ne TBDB_NODESTATE_SHUTDOWN &&
		     $oldstate ne TBDB_NODESTATE_REBOOTING)) {
857 858 859 860 861 862
		    $nextmode = TBDB_NODEOPMODE_SECUREBOOT;
		}
		if ($mode ne $nextmode) {
		    info("$node: Forcing mode transition to $nextmode!\n");
		    opModeTransition($node, $nextmode, 1);
		    $mode=$nextmode;
863 864 865
		}
		next;
	    };
Mac Newbold's avatar
Mac Newbold committed
866 867 868 869 870
	    /^$BOOTING$/ && do {
		#
		# See if we are in the right mode/osid.
		#
		my ($bootosid,$bootopmode) = TBBootWhat($node, $debug);
871 872 873 874 875 876 877
		if (!defined($bootosid)) {
		    info("$node: TBBootWhat say node doesn't exist!?");
		    next;
		} elsif ($bootosid == 0) {
		    info("$node: should be in PXEWAIT, why are we here?!");
		    next;
		}
878

879 880 881 882 883 884 885
		# XXX defensive programming, this happened once
		if (!defined($bootopmode)) {
		    info("$node: TBBootWhat did not return op_mode ".
			 "(osid=$bootosid)!? Remaining in $mode");
		    next;
		}

Mac Newbold's avatar
Mac Newbold committed
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
		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.
			#
			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) {
			    opModeTransition($node, $nextmode, 1);
			    $mode=$nextmode;
			}
		    }
		    else {
922 923
			my $str = "$node running $bootosid in ".
			  "mode $mode instead of mode $bootopmode!\n";
Mac Newbold's avatar
Mac Newbold committed
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
			
			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;
	    };
950 951 952 953
	    /^CHECKPORTREG$/ && do {
		CheckPortRegistration($node);
		next;
	    };
954 955 956 957 958 959
	    /^$TBPXERESET$/ && do {
		# We successfully booted, so reset one-shot PXEboot if any
		# Check if we really need to do a reset
		handleCtrlEvent($node,$trig);
		next;
	    };
960
	    /^$TBRESET$/ && do {
961 962 963
		# We successfully booted, so clear some flags
		$nodes{$node}{noretry}   = 0;
		$nodes{$node}{timedout}  = 0;
964 965 966 967
		# 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();
968 969 970 971 972 973 974
		if (! (defined($osid) && defined($defosid))) {
		    info("$node: osid not defined\n")
			if (!defined($osid));
		    info("$node: def_boot_osid not defined\n")
			if (!defined($defosid));
		}
		elsif ($osid ne $defosid) {
975 976
		    handleCtrlEvent($node,$trig);
		}
977 978 979 980 981
		# XXX tmp hack
		elsif ($mode eq "WIMRELOAD") {
		    info("$node: RESET in WIMRELOAD, but osid=defosid=$osid\n");
		    handleCtrlEvent($node,$trig);
		}
982 983
		next;
	    };
984
	    (/^$TBRELOADDONEV1$/ || /^$TBRELOADDONEV2$/) && do {
985 986 987
		handleCtrlEvent($node,$trig);
		next;
	    };
988 989 990 991 992 993 994 995
	    /^$TBISUP$/ && do {
		info("$node: Triggered $TBISUP\n");
		EventSendWarn(host      => $BOSSNODE ,
			      objtype   => TBDB_TBEVENT_NODESTATE ,
			      eventtype => TBDB_NODESTATE_ISUP ,
			      objname   => $node);
		next;
	    };
996
	    (/^$TBREBOOT$/ || /^$TBPOWERCYCLE$/ || /^$TBPOWEROFF$/) && do {
997
		handleCommand($node,$trig);
998 999 1000
		next;
	    };
            (/^EMAILNOTIFY$/) && do {
1001 1002
		my $msg = "$node entered state $mode/$newstate from " .
		    "$mode/$oldstate";
1003
		my $dest = $REALTBOPS;
1004
		if ($newstate eq TBDB_NODESTATE_SECVIOLATION) {
1005 1006 1007 1008 1009 1010 1011 1012
		    if ($soft_secviolation) {
			$msg .= "\n\nNode $node was allowed to continue.\n";
			$dest = $TBOPS;
		    } else {
			$msg .= "\n\nNode $node has been powered off.\n" .
			        "You must address the cause of the violation ".
				"and reset the eventstate before powering on.";
		    }
1013
		}
1014 1015
		SENDMAIL($dest, "STATED: $node entered state $newstate",
			 $msg, "Stated Daemon <".$TBOPS.">");
1016
		next;
1017
            };
1018 1019
	    /^RELOADOLDMFS$/ && do {
		my $frisbee_osid = TBNodeDiskloadOSID($node);
1020 1021 1022
		my $osinfo = OSinfo->Lookup($frisbee_osid);
		my $frisbee_name = (defined($osinfo) ?
				    $osinfo->osame() : $frisbee_osid);
1023 1024 1025 1026 1027 1028 1029 1030 1031
		my $msg = 
		    ("Attempted to load multiple images on $node using an old Frisbee MFS.\n".
		     "To make this work please update the $frisbee_name MFS image.\n");
		SENDMAIL($REALTBOPS,
			 "$frisbee_name Needs Updating",
			 $msg,
			 "Stated Daemon <".$TBOPS.">");
		next;
	    };
1032
	    notify("Unknown trigger '$trig' for $node in $mode/$newstate!\n");
1033
	}
Mac Newbold's avatar
Mac Newbold committed
1034 1035 1036 1037 1038 1039 1040
	# 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);
	}
1041
    }
1042

1043 1044 1045 1046 1047 1048 1049 1050
    # 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
1051 1052 1053
	} else {
	    debug("No next mode.\n");
	}
1054 1055
    }
}
1056

1057
sub opModeTransition($$;$) {
Mac Newbold's avatar
Mac Newbold committed
1058

1059 1060
    my ($node,$newmode,$force) = @_;
    if (!defined($force)) { $force = 0; }
1061
    my $mode = $nodes{$node}{mode};
Mac Newbold's avatar
Mac Newbold committed
1062

1063 1064
    info("$node: Mode change $mode => $newmode ".
	 ($force ? "forced" : "requested"). "\n");
Mac Newbold's avatar
Mac Newbold committed
1065

1066
    # Check for invalid transitions
1067
    my ($oldstate, $nextstate);
1068 1069
    $oldstate = $nodes{$node}{state};

1070
    if (defined($modeTrans{"$mode:$oldstate"}) || $force) {
1071 1072 1073 1074 1075
	#
	# If there is a next state associated with mode:oldstate, use it.
	# Otherwise we just remain in the old state.
	#
	if (defined($modeTrans{"$mode:$oldstate"})) {
1076 1077 1078 1079 1080
	    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);
1081 1082 1083 1084 1085
	    if ($debug) {
		print STDERR "Valid transitions from $mode/$oldstate are:\n";
		foreach my $k (sort keys %trans) {
		    print STDERR "$k => $trans{$k}\n";
		}
1086 1087 1088
	    }
	    if (defined($trans{$newmode})) {
		$nextstate=$trans{$newmode};
1089 1090 1091 1092
		if ($force) {
		    info("$node: opMode force changing state along with mode\n");
		}
	    } elsif (!$force) {
1093 1094 1095
		notify("Invalid mode transition for $node from ".
		       "$mode/$oldstate to $newmode!\n");
	    }
1096 1097
	}
    } else {
1098
	notify("Invalid mode transition for $node from $mode/$oldstate: ".
1099 1100
	       "Not a valid mode transition state!\n");
    }
Mac Newbold's avatar
Mac Newbold committed
1101 1102 1103
    if (!$nextstate) {
	$nextstate=$oldstate;
    }
Mac Newbold's avatar
Mac Newbold committed
1104

1105 1106 1107 1108 1109 1110
    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
1111

1112
    info("$node: $mode/$oldstate => $newmode/$nextstate\n");
1113 1114 1115 1116 1117 1118 1119 1120 1121
    my $nodeobj = Node->LookupSync($node);
    my %updates = ("eventstate"        => $nextstate,
		   "next_op_mode"      => '',
		   "op_mode"           => $newmode,
		   "state_timestamp"   => $now,
		   "op_mode_timestamp" => $now);
    if ($nodeobj->Update(\%updates)) {
	notify("Could not make op_mode transition to $newmode for $node!\n");
    }
Mac Newbold's avatar
Mac Newbold committed
1122 1123 1124 1125

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

1126 1127 1128 1129
}

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

1131 1132 1133
    info("$node: CtrlEvent: $event\n");

    #
1134
    # stated should use the node objects.
1135 1136 1137
    # XXX but since it largely doesn't, we need to make sure to sync up here.
    #
    my $nodeobj = Node->LookupSync($node);
1138
    if (!defined($nodeobj)) {
1139
	info("$node: CtrlEvent: could not lookup node object, event ignored!\n");
1140 1141
	return;
    }
1142

1143
    foreach ($event) {
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
	/^$TBPXERESET$/ && do {
	    #
	    # Clear next_pxe_boot_path with pxe_select.
	    #
	    # Note that this will recreate the DHCPD config file and HUP it.
	    # It will also ssh over to any subbosses and do the same.
	    # Thus there is lost of potential to get hung or take a long time.
	    #
	    $cmd = "$pxeselect -d -c -1 $node";
	    system($cmd) and
		notify("$node/$event: Could not clear next_pxe_boot_path!\n");

1156
	    info("$node: Performed $TBPXERESET\n");
Mike Hibler's avatar
Mike Hibler committed
1157
	    last;
1158
	};
1159
	/^$TBRESET$/ && do {
1160
	    # Clear next_boot_path.
1161
	    if ($nodeobj->OSSelect(undef, "next_boot_osid", 0) != 0) {
1162
		notify("$node/$event: Could not clear next_boot_path!\n");
1163
	    }
1164 1165
	    my ($bosid,$bopmode) = TBBootWhat($node, 0);
	    info("$node: $TBRESET done, bootwhat returns $bopmode,$bosid\n");
Mike Hibler's avatar
Mike Hibler committed
1166
	    last;
1167
	};
1168
	(/^$TBRELOADDONEV1$/ || /^$TBRELOADDONEV2$/) && do {
1169
	    info("$node: Clearing reload info\n");
1170 1171 1172 1173 1174 1175
	    $nodeobj->ClearCurrentReload();
	    $nodeobj->FlushReserved();
	    my $experiment = $nodeobj->Reservation();
	    if (defined($experiment) &&
		$experiment->pid() eq NODERELOADING_PID &&
		$experiment->eid() eq NODERELOADING_EID) {
1176
		$nodeobj->RemoveTaintState();
1177 1178 1179
		$nodeobj->ClearSchedReload();
		my $reserved_pid = $nodeobj->CheckPreReserve(1);
		if (defined($reserved_pid)) {
1180
		    info("$node: Setting pre reserve to $reserved_pid\n");
1181 1182 1183 1184
		}
		$nodeobj->ClearReservation();
		$nodeobj->SetNodeHistory(TB_NODEHISTORY_OP_FREE,
					 undef, $experiment);
1185
		info("$node: Released from $experiment\n");
1186 1187
	    } else {
		$nodeobj->SyncDiskPartitionTaintStates();
1188
	    }
1189
	    if ($event eq $TBRELOADDONEV2) {
1190 1191
		info("$node: Sending apod\n");
		if ($nodeobj->SendApod(1)) {
1192
		    notify("Could not apod $node after $TBRELOADDONEV2!\n");
1193
		}
1194
	    }
Mike Hibler's avatar
Mike Hibler committed
1195
	    last;
1196 1197
	};
	/^$TBTIMEOUT$/ && do {
1198 1199 1200 1201
	    my ($mode,$state) = split(":",$timeout_tag{$node});
	    delete($timeout_tag{$node});
	    my $curstate = $nodes{$node}{state};
	    my $curmode = $nodes{$node}{mode};
1202
	    my ($timeout,$action);
1203 1204 1205 1206 1207
	    if (!defined($nodes{$node}{notified})) {
		$nodes{$node}{notified}=0;
	    }
	    $nodes{$node}{notified}++;
	    my $notified = $nodes{$node}{notified};
1208 1209
	    $nodes{$node}{timedout}++;
	    my $timedout = $nodes{$node}{timedout};
1210 1211 1212 1213
	    if ($mode && $state && $timeouts{$mode} &&
		$timeouts{$mode}{$state}) {
		($timeout, $action) = @{$timeouts{$mode}{$state}};
	    }
1214 1215
	    if ($mode eq $TBCOMMAND) {
		# It is a command, not a true state
1216
		if ($action eq $TBTIMEOUTCMDRETRY) {
1217
		    # Retry the command
1218
		    notify("$node: Command $state, retry #$timedout\n");
1219
		    # notify in case we get in a retry loop...
1220
		    handleCommand($node,$state,$timedout,1);
1221 1222 1223 1224
		} else {
		    notify("$node: Unknown timeout action for ".
			   "$mode/$state: '$action'\n");
		}
Mike Hibler's avatar
Mike Hibler committed
1225
		last;
1226
	    }
1227 1228 1229 1230 1231 1232 1233

	    #
	    # 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
1234

1235 1236
		if ($timedout < 3) {
		    #
Mac Newbold's avatar
Mac Newbold committed
1237 1238
		    # Try again.
		    #
1239 1240 1241 1242 1243 1244
		    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
1245 1246
		    # Failed too many times, power cycle instead.
		    #
1247
		    notify("Node $node timed out $timedout times in ".
1248
			   "$PXEWAKEUP!\n".
1249
			   "Sending it a reboot command.\n");
1250 1251 1252 1253
		    $optarg .= "-k";
		}
		my $cmd = "$nodereboot -r $optarg $node";
		debug("$cmd\n");
1254
		system("(date; $cmd) >>$rebootlog 2>&1 &") and
1255
		    notify("$PXEWAKEUP retry: ".
1256 1257
			   "Command '$cmd' failed, error $?: $!\n");

Mike Hibler's avatar
Mike Hibler committed
1258
		last;
1259 1260
	    }

1261 1262 1263 1264 1265 1266
	    info("Node $node has timed out in state $mode/$state".
		 ($action ne "" ? "\n\tRequested action $action." : "").
		 "\n");

	    foreach ($action) {
		/^$TBTIMEOUTREBOOT/ && do {
1267 1268 1269 1270 1271
		    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;
1272
		    } else {
1273 1274 1275 1276 1277 1278
			# 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);
1279 1280 1281 1282 1283
		    }
		    last; };
		/^$TBTIMEOUTNOTIFY/ && do {
		    notify("Node $node has timed out in state $mode/$state\n");
		    last; };
1284 1285 1286 1287 1288
                /^STATE:([-\w\/]+)$/ && do {
                    my $newstate = $1;
                    # Force the node into a new state
                    stateTransition($node,$newstate);
                    last; };
1289 1290
		notify("$node: Unknown Timeout Action: $action\n");
	    }
Mike Hibler's avatar
Mike Hibler committed
1291
	    last;
1292
	};
1293
	notify("$node: Unknown CtrlEvent: $event\n");
1294 1295
    }
}
Robert Ricci's avatar
Robert Ricci committed
1296

1297 1298
sub handleCommand($$;$$) {
    my ($params,$command,$retry,$force) = @_;
1299
    if (!defined($retry)) { $retry=0; }
1300
    if (!defined($force)) { $force=0; }
1301 1302 1303 1304 1305 1306 1307 1308

    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.

1309
    if ($command eq $TBREBOOT && $retry >=4) {
1310 1311
	announce("Node $params has tried rebooting $retry times and has \n".
		 "still not been successful. Please look into it soon.\n".