stated.in 62.8 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
# Copyright (c) 2000-2016 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 B. Stoller's avatar
Leigh B. 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 60 61 62
#
# XXX if bootinfo is not sending the BOOTING event, then dhcpd is sending them
# and we have to watch out for spurrious BOOTING events caused by a node
# making runtime dhcp calls (e.g., it is running dhclient).
#
my $BIEVENTS = @BOOTINFO_EVENTS@;

Robert Ricci's avatar
Robert Ricci committed
63 64 65 66
$| = 1;

use event;
use libdb;
67
use Node;
68
use OSImage;
Robert Ricci's avatar
Robert Ricci committed
69
use libtestbed;
70
use TimeoutQueue;
Robert Ricci's avatar
Robert Ricci committed
71
use Getopt::Std;
72
#use strict;
Robert Ricci's avatar
Robert Ricci committed
73
use English;
Mac Newbold's avatar
Mac Newbold committed
74 75
use POSIX;			# for strftime, and sigprocmask and friends
use Fcntl;			# file constants for pidfile
76 77
use POSIX ":sys_wait_h";
use IO::Poll qw(POLLIN);
78
use POSIX qw(:errno_h);
Mac Newbold's avatar
Mac Newbold committed
79

80 81 82 83 84 85
#
# Set this non-zero if you want to send mail on abnormal stated events.
# Otherwise we just log them to $MAILFILE.
#
my $SPAMME = 0;

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

Mike Hibler's avatar
Mike Hibler committed
97 98 99
# 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.
100
my $maxpasttimeout = -(7 * 24 * 60 * 60);	# 1 week
Mike Hibler's avatar
Mike Hibler committed
101

102 103 104
# Handling of SECVIOLATIONS, eventually controlled by a sitevar
my $soft_secviolation = 1;

105 106 107
# Command line opts.
my $dbtag = "";
my $debug = 0;
108 109
my $server = "localhost";
my $port   = @BOSSEVENTPORT@;
110 111
my $lockfile;
my $pidfile;
112
my $eventchild;
113

Robert Ricci's avatar
Robert Ricci committed
114 115 116
# Process command-line arguments

sub usage {
Mac Newbold's avatar
Mac Newbold committed
117
    print << "END";
118
Usage: $0 [-h] [-d] [-s server] [-p port] [-t dbtag]
119
-h              This message
120 121
-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
122 123
-s server       Use specified server, instead of this site's bossnode
-p port	        Use specified port
124
Send SIGHUP to reload database state, or SIGUSR1 to restart completely.
Robert Ricci's avatar
Robert Ricci committed
125
END
126
    exit(1);
Robert Ricci's avatar
Robert Ricci committed
127 128
}

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

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

Mac Newbold's avatar
Mac Newbold committed
139 140 141 142 143 144
if ($opt{h}) {
    exit &usage;
}
if (@ARGV) {
    exit &usage;
}
Robert Ricci's avatar
Robert Ricci committed
145

Mac Newbold's avatar
Mac Newbold committed
146 147 148 149 150 151
if ($opt{s}) {
    $server = $opt{s};
}
if ($opt{p}) {
    $port = $opt{p};
}
152 153 154
if ($opt{t}) {
    $dbtag = $opt{t};
}
Mac Newbold's avatar
Mac Newbold committed
155 156 157
if ($opt{d}) {
    $debug = 1;
}
Robert Ricci's avatar
Robert Ricci committed
158

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

187 188
# Special PXEBOOT state machine that all local nodes use.
my $PXEKERNEL	 = "PXEKERNEL";
189

190 191
# Even special-er SECUREBOOT state machine that local nodes may use.
my $SECUREBOOT	 = "SECUREBOOT";
192

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

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    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
231
    if (TBBackGround($LOGFILE)) {
Mac Newbold's avatar
Mac Newbold committed
232 233
	exit(0);
    }
234
    TBdbfork();
Robert Ricci's avatar
Robert Ricci committed
235
}
236 237 238 239 240 241 242 243 244

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
245

246 247 248
# Change my $0 so that it is easier to see in a ps/top
$0 = "$0";

249 250 251 252 253
#
# Start up the event system interface.
#
if (StartEvents() != 0) {
    fatal("Error starting events");
Robert Ricci's avatar
Robert Ricci committed
254
}
255 256
# We want to exit on any warning. 
$SIG{__WARN__} = sub { print STDERR $_[0]; exit(-1); };
Robert Ricci's avatar
Robert Ricci committed
257 258 259

# Read in the pre-existing node states, and timeout and valid transition
# information from the database
260 261 262 263
my %timeouts  = getTimeouts();
my %valid     = getValid();
my %modeTrans = getModeTrans();
my %triggers  = getTriggers();
264
my %nodes     = readStates();
265
my %timeouttag= ();
266
if ($debug) { qshow(); }
Robert Ricci's avatar
Robert Ricci committed
267 268 269

# Gets set if a reload of state from the database should happen.
my $do_reload = 0;
270
my $do_reopen = 0;
271 272
my $sigrestart= 0;
my $sigcleanup= 0;
273
my $exiting   = 0;
Robert Ricci's avatar
Robert Ricci committed
274 275 276 277

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

Mac Newbold's avatar
Mac Newbold committed
281
# Set up other signals.
282 283 284 285 286
$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
287

288 289 290
# Track if I handled an event or not
my $event_count = 0;

291 292
# Control how long I block while waiting for events
my $blockwait=0;
293
my $nextdeadline=0;
294 295
my $mailqueue=0;

296 297 298 299 300
notify("Stated starting up\n");

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

355
# Now, we just poll for events, and watch for timeouts
Robert Ricci's avatar
Robert Ricci committed
356
while (1) {
Mac Newbold's avatar
Mac Newbold committed
357
    my $now = time();
358 359 360 361
    my ($deadline,$node);

    # Check for nodes that have passed their timeout
    if (!qhead($deadline,$node)) {
362
	info("HEAD: $node in ".($deadline-$now).", queue=".qsize()."\n");
363 364
	while ($now >= $deadline && $node ne "") {
	    qpop($deadline,$node);
365
	    info("POP: $node in ".($deadline-$now).", queue=".qsize()."\n");
366 367 368 369 370 371 372 373 374 375 376 377 378
	    #
	    # 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}));
	    }
379 380 381 382
	    if (0) { qshow(); }
	    if (qhead($deadline,$node)) {
		$deadline=0; $node="";
	    }
383
	}
384 385
    } else {
	$deadline=0;
386
    }
387
    $nextdeadline = $deadline;
388

Mac Newbold's avatar
Mac Newbold committed
389 390 391 392
    if ($do_reload || ($now - $last_reload > $reload_time)) {
	reload();
	$do_reload = 0;
    }
Mac Newbold's avatar
Mac Newbold committed
393

Mike Hibler's avatar
Mike Hibler committed
394 395 396 397 398
    if (qsize()==0) {
	$blockwait=1;
	debug("---Blocking wait okay---\n");
    }

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

402 403
    if ($sigrestart) { restart(); }
    if ($sigcleanup) { cleanup(); }
404 405 406 407 408 409 410
    if ($do_reopen)  {
	ReOpenLog($LOGFILE);
	if (! kill('USR2', $eventchild)) {
	    fatal("Could not signal(USR2) event reader child\n");
	}
	$do_reopen = 0;
    }
411
    process_event_queue;
Robert Ricci's avatar
Robert Ricci committed
412 413
}

Mac Newbold's avatar
Mac Newbold committed
414 415
exit(0);

Robert Ricci's avatar
Robert Ricci committed
416
# Read the current states of nodes from the database
417
sub readStates(;@) {
Mac Newbold's avatar
Mac Newbold committed
418
    my %oldnodes = @_;
Mike Hibler's avatar
Mike Hibler committed
419
    my $now = time();
Mac Newbold's avatar
Mac Newbold committed
420 421

    # Guard against undefined variable warnings
422
    if (! %oldnodes) {
Mac Newbold's avatar
Mac Newbold committed
423 424
	%oldnodes = ();
    }
425

Mac Newbold's avatar
Mac Newbold committed
426 427 428
    #debug("readStates called\n");
    my $result = DBQueryFatal("SELECT node_id, eventstate, " .
			      "state_timestamp, op_mode, " .
429
			      "op_mode_timestamp, stated_tag FROM nodes ".
430
			      "where node_id not like 'sh%'");
Mac Newbold's avatar
Mac Newbold committed
431 432

    my %nodes;
433
    while (my ($node_id, $state, $timestamp, $mode, $mode_timestamp, $tag)
Mac Newbold's avatar
Mac Newbold committed
434
	   = $result->fetchrow()) {
435 436 437 438 439 440 441 442 443 444 445
	$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
446

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

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

Mac Newbold's avatar
Mac Newbold committed
483 484 485 486 487
    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
488 489 490 491 492 493
}

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

Mac Newbold's avatar
Mac Newbold committed
498
    my %valid;
499
    while (my ($mode, $state1, $state2) = $result->fetchrow()) {
Mac Newbold's avatar
Mac Newbold committed
500 501 502
	$valid{$mode}{$state1}{$state2} = 1;
    }
    return %valid;
Robert Ricci's avatar
Robert Ricci committed
503 504
}

505 506 507 508 509 510 511 512
#
# Check if a transition is valid. Actually, it is a check for an invalid
# transition.
#
sub IsValidTransition($$$)
{
    my ($mode, $oldstate, $newstate) = @_;

513 514 515 516 517 518 519 520 521 522 523
    # 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;
    }
524

525 526 527 528 529 530 531 532 533
    # 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;
534 535
}

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

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

564 565
    debug("anymode ==> '$TBANYMODE'\n");

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

Mac Newbold's avatar
Mac Newbold committed
597 598
    # Grab per-node triggers (including any-mode)
    $result =
599
      DBQueryFatal("SELECT node_id, op_mode, state, `trigger` " .
600 601 602 603 604 605
		   "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
606
    }
607

Mac Newbold's avatar
Mac Newbold committed
608 609
    debug(hash_recurse(%t));

Mac Newbold's avatar
Mac Newbold committed
610
    return %t;
611 612
}

Robert Ricci's avatar
Robert Ricci committed
613 614 615 616
#
# Gets called for every event that we recieve
#
sub handleEvent($$$) {
617
    my ($objtype,$objname,$eventtype) = @_;
Mac Newbold's avatar
Mac Newbold committed
618
    $event_count++;
Mac Newbold's avatar
Mac Newbold committed
619

620
    #
Mac Newbold's avatar
Mac Newbold committed
621 622 623
    # 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.
624
    #
625
    if ($dbtag eq "") {
626 627
	debug("Got an event: ($objtype,$objname,$eventtype)\n");
    }
Mac Newbold's avatar
Mac Newbold committed
628 629 630 631

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

635 636 637 638 639 640 641
	#
	# 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
642
	    # churning via reload(). Bad.
643
	    if (! defined($nodes{$node})) {
644 645 646 647
		notify("Got $objtype/$eventtype for nonexistent $node!\n");
		return;
	    }
	}
Mac Newbold's avatar
Mac Newbold committed
648

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

    #
    # 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.)
    #
670 671 672
    if ($dbtag ne "") {
	debug("Got an event: ($objtype,$objname,$eventtype)\n");
    }
Mac Newbold's avatar
Mac Newbold committed
673 674 675

 SWITCH: for ($objtype) {

Mac Newbold's avatar
Mac Newbold committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689
	(/$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;
	};
690 691 692 693
	(/$TBCOMMAND/) && do {
	    handleCommand($objname,$eventtype);
	    last;
	};
694

Mac Newbold's avatar
Mac Newbold committed
695
    }
696 697 698 699 700

}

sub stateTransition($$) {

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

703 704
    # Check for invalid transitions
    my ($oldstate, $mode);
705 706 707
    $oldstate = $nodes{$node}{state};
    $mode     = $nodes{$node}{mode};

708
    if ($oldstate && $mode && !IsValidTransition($mode,$oldstate,$newstate)) {
709
	notify("Invalid transition for node $node from $mode/$oldstate " .
710
	       "to $newstate\n");
711
	
712 713 714 715 716 717 718 719 720 721 722
	#
	# XXX hack ignore spurious BOOTING transitions caused by dhcp
	#
	if (!$BIEVENTS &&
	    $mode eq TBDB_NODEOPMODE_NORMALv2 &&
	    $oldstate eq TBDB_NODESTATE_ISUP &&
	    $newstate eq TBDB_NODESTATE_BOOTING) {
	    notify("$node: Ignored spurious BOOTING transition\n");
	    return;
	}

723 724 725 726 727 728
	#
	# 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) {
729 730 731
            $newstate = TBDB_NODESTATE_SECVIOLATION;
            notify("Moving $node to $newstate because it's in $mode\n");
        }
732
    }
733

734 735 736 737 738
    #
    # Nodes that are in the SECVIOLATION state are not allowed to leave!
    #
    if ($oldstate eq TBDB_NODESTATE_SECVIOLATION &&
	$newstate ne TBDB_NODESTATE_SECVIOLATION) {
739
	#
740 741 742
	# 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.
743 744 745
	#
	# XXX DEBUG ONLY!
	# 
746 747
	if ($soft_secviolation &&
	    ($newstate eq TBDB_NODESTATE_SHUTDOWN ||
748
	     $newstate eq TBDB_NODESTATE_POWEROFF ||
749 750
	     $newstate eq TBDB_NODESTATE_GPXEBOOTING)) {
	    notify("$node allowed to transition: SECVIOLATION => $newstate\n");
751 752 753 754
	} else {
	    notify("$node tried to leave SECVIOLATION (to $newstate)\n");
	    $newstate = TBDB_NODESTATE_SECVIOLATION;
	}
755
    }
Robert Ricci's avatar
Robert Ricci committed
756

757 758 759 760
    my $now = time();
    $nodes{$node}{state}     = $newstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{notified}  = 0;
761

762 763 764
    info("$node: $mode/$oldstate => $mode/$newstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$newstate', " .
		 "state_timestamp='$now' WHERE node_id='$node'");
765

766 767 768 769
    # 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:/) {
770
        debug("TimeoutTag = '$timeout_tag{$node}'\n");
771
	my ($str,$cmd) = split(":",$timeout_tag{$node});
772
	debug("str=$str\tcmd=$cmd\tTBREBOOT=$TBREBOOT\tstate=$newstate\n");
773
	if ($cmd eq $TBREBOOT) {
774
	    if ($newstate eq TBDB_NODESTATE_SHUTDOWN ) {
775 776 777
		info("$node: $TBREBOOT success\n");
		# Timeout will get cleared below by setTimeout call
	    } else {
778 779
		notify("$node: $TBREBOOT in progress, but got state ".
		       "$newstate instead of ".TBDB_NODESTATE_SHUTDOWN."!\n");
780 781 782 783 784
	    }
	#} elsif ($cmd eq $FOO ) {
	    # Add more here...
	} else {
	    notify("$node: Unknown command timeout '$timeout_tag{$node}' ".
785
		   "found at $mode/$newstate\n");
786 787 788
	}
    }

789 790 791 792 793
    #
    # 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.
    #
794 795
    setTimeout($mode,$newstate,$node,$now);

Mac Newbold's avatar
Mac Newbold committed
796 797 798 799 800 801 802
    # 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 = $_;
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
	    /^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
820
	    /^$PXEBOOT$/ && do {
821
		#
Mac Newbold's avatar
Mac Newbold committed
822 823 824 825 826 827 828 829 830 831 832 833
		# 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.
834
		#
Mac Newbold's avatar
Mac Newbold committed
835 836 837 838
		# 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.
839
		#
Mac Newbold's avatar
Mac Newbold committed
840 841 842 843
		debug("Running $PXEBOOT trigger\n");
		if ($mode ne $PXEKERNEL) {
		    opModeTransition($node, $PXEKERNEL, 1);
		    $mode=$PXEKERNEL;
844
		}
Mac Newbold's avatar
Mac Newbold committed
845 846
		next;
	    };
847 848 849 850 851 852
	    /^$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.
853
		#
854 855 856
		# To differentiate BOOT from LOAD:
		# if next_op_mode is SECURELOAD, goto SECURELOAD
		# else if mode/state is SECURELOAD/SHUTDOWN, goto SECURELOAD
857
		# else if mode/state is SECURELOAD/REBOOTING, goto SECURELOAD
858
		# else goto SECUREBOOT.
859
		#
860 861 862 863
		# The SHUTDOWN case handles os_load.
		# The REBOOT case handles the forced reboot following PXEWAIT
		# (inflicted by bootinfo--see bootinfo_mysql.c).
		#
864 865 866 867
		my $query_result =
		    DBQueryWarn("select next_op_mode from nodes ".
				"where node_id='$node'");
		my ($nextmode) = $query_result->fetchrow();
868 869 870
		if (!$nextmode) {
		    $nextmode = $mode;
		}
871
		info("Running $SECUREBOOT trigger with $nextmode/$oldstate\n");
872
		if ($nextmode ne TBDB_NODEOPMODE_SECURELOAD ||
873 874
		    ($oldstate ne TBDB_NODESTATE_SHUTDOWN &&
		     $oldstate ne TBDB_NODESTATE_REBOOTING)) {
875 876 877 878 879 880
		    $nextmode = TBDB_NODEOPMODE_SECUREBOOT;
		}
		if ($mode ne $nextmode) {
		    info("$node: Forcing mode transition to $nextmode!\n");
		    opModeTransition($node, $nextmode, 1);
		    $mode=$nextmode;
881 882 883
		}
		next;
	    };
Mac Newbold's avatar
Mac Newbold committed
884 885 886 887 888
	    /^$BOOTING$/ && do {
		#
		# See if we are in the right mode/osid.
		#
		my ($bootosid,$bootopmode) = TBBootWhat($node, $debug);
889 890 891 892 893 894 895
		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;
		}
896

897 898 899 900 901 902 903
		# 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
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
		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 {
940 941
			my $str = "$node running $bootosid in ".
			  "mode $mode instead of mode $bootopmode!\n";
Mac Newbold's avatar
Mac Newbold committed
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
			
			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;
	    };
968 969 970 971
	    /^CHECKPORTREG$/ && do {
		CheckPortRegistration($node);
		next;
	    };
972 973 974 975 976 977
	    /^$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;
	    };
978
	    /^$TBRESET$/ && do {
979 980 981
		# We successfully booted, so clear some flags
		$nodes{$node}{noretry}   = 0;
		$nodes{$node}{timedout}  = 0;
982 983 984 985
		# 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();
986 987 988 989 990 991 992
		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) {
993 994
		    handleCtrlEvent($node,$trig);
		}
995 996 997 998 999
		# XXX tmp hack
		elsif ($mode eq "WIMRELOAD") {
		    info("$node: RESET in WIMRELOAD, but osid=defosid=$osid\n");
		    handleCtrlEvent($node,$trig);
		}
1000 1001
		next;
	    };
1002
	    (/^$TBRELOADDONEV1$/ || /^$TBRELOADDONEV2$/) && do {
1003 1004 1005
		handleCtrlEvent($node,$trig);
		next;
	    };
1006 1007 1008 1009 1010 1011 1012 1013
	    /^$TBISUP$/ && do {
		info("$node: Triggered $TBISUP\n");
		EventSendWarn(host      => $BOSSNODE ,
			      objtype   => TBDB_TBEVENT_NODESTATE ,
			      eventtype => TBDB_NODESTATE_ISUP ,
			      objname   => $node);
		next;
	    };
1014
	    (/^$TBREBOOT$/ || /^$TBPOWERCYCLE$/ || /^$TBPOWEROFF$/) && do {
1015
		handleCommand($node,$trig);
1016 1017 1018
		next;
	    };
            (/^EMAILNOTIFY$/) && do {
1019 1020
		my $msg = "$node entered state $mode/$newstate from " .
		    "$mode/$oldstate";
1021
		my $dest = $REALTBOPS;
1022
		if ($newstate eq TBDB_NODESTATE_SECVIOLATION) {
1023 1024 1025 1026 1027 1028 1029 1030
		    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.";
		    }
1031
		}
1032 1033
		SENDMAIL($dest, "STATED: $node entered state $newstate",
			 $msg, "Stated Daemon <".$TBOPS.">");
1034
		next;
1035
            };
1036 1037
	    /^RELOADOLDMFS$/ && do {
		my $frisbee_osid = TBNodeDiskloadOSID($node);
1038 1039
		my $osimage = OSImage->Lookup($frisbee_osid);
		my $frisbee_name = (defined($osimage) ?
Leigh B Stoller's avatar
Leigh B Stoller committed
1040
				    $osimage->osname() : $frisbee_osid);
1041 1042 1043 1044 1045 1046 1047 1048 1049
		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;
	    };
1050
	    notify("Unknown trigger '$trig' for $node in $mode/$newstate!\n");
1051
	}
Mac Newbold's avatar
Mac Newbold committed
1052 1053 1054 1055 1056 1057 1058
	# 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);
	}
1059
    }
1060

1061 1062 1063 1064 1065 1066 1067 1068
    # 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
1069 1070 1071
	} else {
	    debug("No next mode.\n");
	}
1072 1073
    }
}
1074

1075
sub opModeTransition($$;$) {
Mac Newbold's avatar
Mac Newbold committed
1076

1077 1078
    my ($node,$newmode,$force) = @_;
    if (!defined($force)) { $force = 0; }
1079
    my $mode = $nodes{$node}{mode};
Mac Newbold's avatar
Mac Newbold committed
1080

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

1084
    # Check for invalid transitions
1085
    my ($oldstate, $nextstate);
1086 1087
    $oldstate = $nodes{$node}{state};

1088
    if (defined($modeTrans{"$mode:$oldstate"}) || $force) {
1089 1090 1091 1092 1093
	#
	# 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"})) {
1094 1095 1096 1097 1098
	    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);
1099 1100 1101 1102 1103
	    if ($debug) {
		print STDERR "Valid transitions from $mode/$oldstate are:\n";
		foreach my $k (sort keys %trans) {
		    print STDERR "$k => $trans{$k}\n";
		}
1104 1105 1106
	    }
	    if (defined($trans{$newmode})) {
		$nextstate=$trans{$newmode};
1107 1108 1109 1110
		if ($force) {
		    info("$node: opMode force changing state along with mode\n");
		}
	    } elsif (!$force) {
1111 1112 1113
		notify("Invalid mode transition for $node from ".
		       "$mode/$oldstate to $newmode!\n");
	    }
1114 1115
	}
    } else {
1116
	notify("Invalid mode transition for $node from $mode/$oldstate: ".
1117 1118
	       "Not a valid mode transition state!\n");
    }
Mac Newbold's avatar
Mac Newbold committed
1119 1120 1121
    if (!$nextstate) {
	$nextstate=$oldstate;
    }
Mac Newbold's avatar
Mac Newbold committed
1122

1123 1124 1125 1126 1127 1128
    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
1129

1130
    info("$node: $mode/$oldstate => $newmode/$nextstate\n");
1131 1132 1133 1134 1135 1136 1137 1138 1139
    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
1140 1141 1142 1143

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

1144 1145 1146 1147
}

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

1149 1150 1151
    info("$node: CtrlEvent: $event\n");

    #
1152
    # stated should use the node objects.
1153 1154 1155
    # XXX but since it largely doesn't, we need to make sure to sync up here.
    #
    my $nodeobj = Node->LookupSync($node);
1156
    if (!defined($nodeobj)) {
1157
	info("$node: CtrlEvent: could not lookup node object, event ignored!\n");
1158 1159
	return;
    }
1160

Mac Newbold's avatar