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

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

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

$| = 1;

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

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

54 55 56 57 58
# 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 = ();

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

65 66 67 68 69 70 71 72
# Command line opts.
my $dbtag = "";
my $debug = 0;
my $nolog = 0;
my ($server,$port);
my $lockfile;
my $pidfile;

Robert Ricci's avatar
Robert Ricci committed
73 74 75
# Process command-line arguments

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

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

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

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

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

126
# Grab some constants into variables
127
my $TBANYMODE    = TBDB_NODEOPMODE_ANY;
128 129 130 131 132 133
my $TBRESET      = TBDB_TBCONTROL_RESET;
my $TBRELOADDONE = TBDB_TBCONTROL_RELOADDONE;
my $TBTIMEOUT    = TBDB_TBCONTROL_TIMEOUT;
my $TBNOTIMEOUT  = TBDB_NO_STATE_TIMEOUT;
my $TBNODESTATE  = TBDB_TBEVENT_NODESTATE;
my $TBNODEOPMODE = TBDB_TBEVENT_NODEOPMODE;
134 135 136 137 138 139
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;
140
my $TBISUP       = TBDB_NODESTATE_ISUP;
141 142 143 144
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;
145

146 147 148
# This only gets used here, so it isn't in a lib constant.
my $TBFREENODE = "FREENODE";

149 150 151
if (!$debug) {
    if ( $TB eq $REALTB ) {
	$pidfile = "/var/run/stated.pid";
Mac Newbold's avatar
Mac Newbold committed
152
    } else {
153
	$pidfile = "$TB/locks/stated.pid";
Mac Newbold's avatar
Mac Newbold committed
154
    }
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    debug("Using pidfile $pidfile\n");
    
    if (-e $pidfile) {
	my $otherpid = `cat $pidfile`;
	my $running = `ps -auxww | grep $otherpid | grep -v grep`;
	if ($running ne "") {
	    fatal("Lockfile $pidfile exists, and process $otherpid appears ".
		  "to be running.\n");
	} else {
	    notify("Lockfile exists, but process $otherpid appears to be dead".
		   "\n".
		   "Removing lock file...\n");
	}
	system("rm $pidfile") &&
	    fatal("Couldn't remove $pidfile: $? $!\n");
    }
    # Background
Mac Newbold's avatar
Mac Newbold committed
172 173 174 175
    # We use syslog, so redirect the output to nothing
    if (TBBackGround("/dev/null")) {
	exit(0);
    }
Robert Ricci's avatar
Robert Ricci committed
176
}
Mac Newbold's avatar
Mac Newbold committed
177
# set up syslog
178 179 180 181 182 183 184 185 186 187 188 189
if (! $nolog) {
    openlog("stated","pid",$TBLOG);
}

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

191 192 193
# Change my $0 so that it is easier to see in a ps/top
$0 = "$0";

Robert Ricci's avatar
Robert Ricci committed
194
my $URL = "elvin://$server";
Mac Newbold's avatar
Mac Newbold committed
195 196 197
if ($port) {
    $URL .= ":$port";
}
Robert Ricci's avatar
Robert Ricci committed
198 199 200

# Connect to the event system, and subscribe the the events we want 
my $handle = event_register($URL,0);
Mac Newbold's avatar
Mac Newbold committed
201 202 203
if (!$handle) {
    fatal("Unable to register with event system\n");
}
Robert Ricci's avatar
Robert Ricci committed
204 205

my $tuple = address_tuple_alloc();
Mac Newbold's avatar
Mac Newbold committed
206 207 208
if (!$tuple) {
    fatal("Could not allocate an address tuple\n");
}
Robert Ricci's avatar
Robert Ricci committed
209

210 211 212
%$tuple = ( objtype => join(",",
			    $TBNODESTATE, $TBNODEOPMODE,
			    $TBCONTROL, $TBCOMMAND) );
213

Robert Ricci's avatar
Robert Ricci committed
214
if (!event_subscribe($handle,\&handleEvent,$tuple)) {
Mac Newbold's avatar
Mac Newbold committed
215
    fatal("Could not subscribe to events\n");
Robert Ricci's avatar
Robert Ricci committed
216 217 218 219
}

# Read in the pre-existing node states, and timeout and valid transition
# information from the database
220 221 222 223
my %timeouts  = getTimeouts();
my %valid     = getValid();
my %modeTrans = getModeTrans();
my %triggers  = getTriggers();
224
my %nodes     = readStates();
225
my %timeouttag= ();
226
if ($debug) { qshow(); }
Robert Ricci's avatar
Robert Ricci committed
227 228 229

# Gets set if a reload of state from the database should happen.
my $do_reload = 0;
230 231
my $sigrestart= 0;
my $sigcleanup= 0;
Robert Ricci's avatar
Robert Ricci committed
232 233 234 235

# 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.
236 237
$SIG{HUP}  = sub { info("SIGHUP - Reloading DB state\n"); $do_reload = 1; };

Mac Newbold's avatar
Mac Newbold committed
238
# Set up other signals.
239 240 241 242 243 244 245
$SIG{USR1} = \&restart_wrap;
$SIG{USR2} = \&cleanup_wrap;
$SIG{INT}  = \&cleanup_wrap;
$SIG{QUIT} = \&cleanup_wrap;
$SIG{ABRT} = \&cleanup_wrap;
$SIG{TERM} = \&cleanup_wrap;
$SIG{KILL} = \&cleanup_wrap;
Robert Ricci's avatar
Robert Ricci committed
246

247 248 249
# Track if I handled an event or not
my $event_count = 0;

250 251
# Control how long I block while waiting for events
my $blockwait=0;
252
my $nextdeadline=0;
253 254
my $mailqueue=0;

255 256 257 258 259
notify("Stated starting up\n");

sub process_event_queue() {
    $event_count=0;
    my $lastcount=-1;
260 261 262 263 264 265 266 267 268 269 270 271 272
    my $wait;
    my $now = time();
    debug("Polling - mq=$mailqueue bw=$blockwait\n");
    if ( $mailqueue == 0) {
	# no messages waiting...
	if ($blockwait) {
	    # we can wait a long time - nothing else will happen
	    # until we get an event, or get woken up by a signal
	    $wait = 600;
	} else {
	    # only wait until the next deadline...
	    if ($nextdeadline > 0) {
		$wait = $nextdeadline - $now;
273 274
	    } else {
		$wait = 0;
275 276 277 278 279
	    }
	}
    } else {
	# mail is waiting. Only block until it is time to send it.
	$wait = $lastmail + $mailgap - $now;
Mac Newbold's avatar
Mac Newbold committed
280
	debug("Now $now, mailgap $mailgap, last $lastmail ==> wait $wait\n");
281 282 283
    }
    if ($wait < 0) { debug("Wait was $wait!\n"); $wait=0; }
    my $finish = $now + $wait;
Mac Newbold's avatar
Mac Newbold committed
284 285
    while (($event_count != $lastcount || $wait > 0) &&
	   !($sigrestart || $sigcleanup || $do_reload)) {
286
	$lastcount = $event_count;
Mac Newbold's avatar
Mac Newbold committed
287 288
	# Don't block if we got a signal!
	if ($wait<=0 || $sigrestart || $sigcleanup || $do_reload) {
289 290 291 292 293 294 295 296
	    event_poll($handle);
	} else {
	    debug("Using blocking event poll - $wait seconds\n");
	    # timeout param is in milliseconds, so multiply
	    event_poll_blocking($handle, $wait*1000);
	    $now = time();
	    # subtract seconds elapsed from my wait time
	    $wait = $finish - $now;
Mac Newbold's avatar
Mac Newbold committed
297
	    debug("Finished blocking event poll - $wait seconds remain\n");
298
	    if ($event_count > 0 &&
Mac Newbold's avatar
Mac Newbold committed
299 300
		(qsize() > 0 || $mailqueue ||
		 $sigrestart || $sigcleanup || $do_reload)) {
301 302 303 304 305 306 307
		$blockwait=0;
		$wait=0;
		#debug("Cancelling wait - timeouts/msgs waiting, or HUP'd\n");
		#debug("---End Blocking Wait ---\n");
	    }
	}
	#debug("Wait is $wait\n");
308 309
    }
    if ($event_count > 0) {
Mac Newbold's avatar
Mac Newbold committed
310
	debug("Handled $event_count event(s).\n");
311 312
    }
}
Robert Ricci's avatar
Robert Ricci committed
313

314
# Now, we just poll for events, and watch for timeouts
Robert Ricci's avatar
Robert Ricci committed
315
while (1) {
Mac Newbold's avatar
Mac Newbold committed
316
    my $now = time();
317 318 319 320
    my ($deadline,$node);

    # Check for nodes that have passed their timeout
    if (!qhead($deadline,$node)) {
321
	info("HEAD: $node in ".($deadline-$now).", queue=".qsize()."\n");
322 323
	while ($now >= $deadline && $node ne "") {
	    qpop($deadline,$node);
324
	    info("POP: $node in ".($deadline-$now).", queue=".qsize()."\n");
325
	    handleCtrlEvent($node,$TBTIMEOUT);
326 327 328 329
	    if (0) { qshow(); }
	    if (qhead($deadline,$node)) {
		$deadline=0; $node="";
	    }
330
	}
331 332
    } else {
	$deadline=0;
333
    }
334
    $nextdeadline = $deadline;
335

336 337 338 339 340
    if (qsize()==0) {
	$blockwait=1;
	debug("---Blocking wait okay---\n");
    }
		
Mac Newbold's avatar
Mac Newbold committed
341 342 343 344
    if ($do_reload || ($now - $last_reload > $reload_time)) {
	reload();
	$do_reload = 0;
    }
Mac Newbold's avatar
Mac Newbold committed
345

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

349 350 351
    if ($sigrestart) { restart(); }
    if ($sigcleanup) { cleanup(); }

352
    process_event_queue;
Robert Ricci's avatar
Robert Ricci committed
353 354
}

Mac Newbold's avatar
Mac Newbold committed
355 356
exit(0);

Robert Ricci's avatar
Robert Ricci committed
357
# Read the current states of nodes from the database
358
sub readStates(;@) {
Mac Newbold's avatar
Mac Newbold committed
359 360 361 362 363 364
    my %oldnodes = @_;

    # Guard against undefined variable warnings
    if (! defined(%oldnodes)) {
	%oldnodes = ();
    }
365

Mac Newbold's avatar
Mac Newbold committed
366 367 368
    #debug("readStates called\n");
    my $result = DBQueryFatal("SELECT node_id, eventstate, " .
			      "state_timestamp, op_mode, " .
369
			      "op_mode_timestamp, stated_tag FROM nodes ".
370
			      "where node_id not like 'sh%'");
Mac Newbold's avatar
Mac Newbold committed
371 372

    my %nodes;
373
    while (my ($node_id, $state, $timestamp, $mode, $mode_timestamp, $tag)
Mac Newbold's avatar
Mac Newbold committed
374
	   = $result->fetchrow()) {
375 376 377 378 379 380 381 382 383 384 385 386
	$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);
	}
	
387
	#
Mac Newbold's avatar
Mac Newbold committed
388 389 390 391
	# 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.)
392
	#
Mac Newbold's avatar
Mac Newbold committed
393 394 395 396 397
	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};
398
	} else {
Mac Newbold's avatar
Mac Newbold committed
399 400 401 402
	    $nodes{$node_id}{state}          = $state;
	    $nodes{$node_id}{timestamp}      = $timestamp;
	    $nodes{$node_id}{mode}           = $mode;
	    $nodes{$node_id}{mode_timestamp} = $mode_timestamp;
403 404 405
	    $nodes{$node_id}{notified}       = 0;
	    $nodes{$node_id}{timedout}       = 0;
	    $nodes{$node_id}{noretry}        = 0;
406
	    # Is there a timeout? If so, set it up!
407 408 409
	    if ($dbtag eq $nodes{$node_id}{"tag"}) {
		setTimeout($mode,$state,$node_id,$timestamp);
	    }
410
	}
Mac Newbold's avatar
Mac Newbold committed
411 412
    }
    return %nodes;
Robert Ricci's avatar
Robert Ricci committed
413 414 415 416 417 418
}

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

Mac Newbold's avatar
Mac Newbold committed
423 424 425 426 427
    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
428 429 430 431 432 433
}

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

Mac Newbold's avatar
Mac Newbold committed
438 439 440 441 442
    my %valid;
    while (my ($mode,$state1, $state2) = $result->fetchrow()) {
	$valid{$mode}{$state1}{$state2} = 1;
    }
    return %valid;
Robert Ricci's avatar
Robert Ricci committed
443 444
}

445 446 447 448
#
# Read the list of valid mode transitions from the database
#
sub getModeTrans() {
Mac Newbold's avatar
Mac Newbold committed
449 450 451 452 453 454 455 456 457 458 459 460 461
    #debug("getModeTrans called\n");
    my $result = 
      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;
462
	}
Mac Newbold's avatar
Mac Newbold committed
463 464
    }
    return %modeTrans;
465 466 467 468 469 470
}

#
# Read the list of states which trigger an action
#
sub getTriggers() {
471 472 473 474 475
    debug("getTriggers called\n");
    
    debug("anymode ==> '$TBANYMODE'\n");

    # Grab global triggers
Mac Newbold's avatar
Mac Newbold committed
476 477
    my $result = 
      DBQueryFatal("SELECT op_mode, state, trigger " .
478 479
		   "FROM state_triggers where node_id='$TBANYMODE' ".
		   "order by op_mode,state");
Mac Newbold's avatar
Mac Newbold committed
480
    my %t;
481
    while (my ($mode, $state, $trig) = $result->fetchrow()) {
Mac Newbold's avatar
Mac Newbold committed
482
	$t{"$mode:$state"} = $trig;
483 484 485 486 487 488 489 490 491 492 493 494
	debug("trig($mode:$state)\t => $trig\n");
    }

    # Grab per-node triggers
    $result = 
      DBQueryFatal("SELECT node_id, op_mode, state, trigger " .
		   "FROM state_triggers where node_id!='$TBANYMODE' ".
		   "order by op_mode,state");
    while (my ($n, $mode, $state, $trig) = $result->fetchrow()) {
	my @trigs = split(/\s*,\s*/,$trig);
	$t{"$n:$mode:$state"} = \@trigs;
	debug("trig($n:$mode:$state)\t => ".join(',',@trigs)."\n");
Mac Newbold's avatar
Mac Newbold committed
495
    }
496

Mac Newbold's avatar
Mac Newbold committed
497
    return %t;
498 499
}

Robert Ricci's avatar
Robert Ricci committed
500 501 502 503
#
# Gets called for every event that we recieve
#
sub handleEvent($$$) {
Mac Newbold's avatar
Mac Newbold committed
504 505 506 507 508 509
    my ($handle,$notification,$data) = @_;
    my $objtype = event_notification_get_objtype($handle,$notification);
    my $objname = event_notification_get_objname($handle,$notification);
    my $eventtype = event_notification_get_eventtype($handle,$notification);

    $event_count++;
510 511 512 513 514 515 516
    
    #
    # For readability, only do this on the main stated.
    #
    if ($dbtag ne "") {
	debug("Got an event: ($objtype,$objname,$eventtype)\n");
    }
Mac Newbold's avatar
Mac Newbold committed
517 518 519 520

    #
    # Check to see if another instance is supposed to be handling this node
    #
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    if ($objtype ne $TBCOMMAND) {
	my $node = $objname;
	
	#
	# If we have never seen this node, reload.
	#
	if (! defined($nodes{$node})) {
	    reload();

	    # Still not defined, someone screwed up! This could end up
	    # churning via reload(). Bad. 
	    if (defined($nodes{$node})) {
		notify("Got $objtype/$eventtype for nonexistent $node!\n");
		return;
	    }
	}
	
	#
	# If a stated_tag was specified on the command line, ignore those
	# nodes that do not match. 
	#
	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
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    }
  SWITCH: for ($objtype) {
	
	(/$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;
	};
569 570 571 572
	(/$TBCOMMAND/) && do {
	    handleCommand($objname,$eventtype);
	    last;
	};
573

Mac Newbold's avatar
Mac Newbold committed
574
    }
575 576 577 578 579

}

sub stateTransition($$) {

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

582 583 584 585 586 587 588 589
    # Check for invalid transitions
    my ($oldstate, $mode);
    if ($nodes{$node}) {
	$oldstate = $nodes{$node}{state};
	$mode = $nodes{$node}{mode};
    } else {
	# Try reloading the cache once before we give up on this node
	reload();
590
	if ($nodes{$node}) {
591 592
	    $oldstate = $nodes{$node}{state};
	    $mode = $nodes{$node}{mode};
Robert Ricci's avatar
Robert Ricci committed
593
	} else {
594
	    notify("Got an event for a node ($node) I don't know about\n");
Robert Ricci's avatar
Robert Ricci committed
595
	}
596 597 598 599
    }
    if ($oldstate && $mode && $valid{$mode} && $valid{$mode}{$oldstate} &&
	!$valid{$mode}{$oldstate}{$newstate}) {
	notify("Invalid transition for node $node from $mode/$oldstate " .
600
	       "to $newstate\n");
601
    }
Robert Ricci's avatar
Robert Ricci committed
602

603 604 605 606
    my $now = time();
    $nodes{$node}{state}     = $newstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{notified}  = 0;
607

608 609 610
    info("$node: $mode/$oldstate => $mode/$newstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$newstate', " .
		 "state_timestamp='$now' WHERE node_id='$node'");
611

612 613 614 615
    # 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:/) {
616
        debug("TimeoutTag = '$timeout_tag{$node}'\n");
617
	my ($str,$cmd) = split(":",$timeout_tag{$node});
618
	debug("str=$str\tcmd=$cmd\tTBREBOOT=$TBREBOOT\tstate=$newstate\n");
619
	if ($cmd eq $TBREBOOT) {
620
	    if ($newstate eq TBDB_NODESTATE_SHUTDOWN ) {
621 622 623
		info("$node: $TBREBOOT success\n");
		# Timeout will get cleared below by setTimeout call
	    } else {
624 625
		notify("$node: $TBREBOOT in progress, but got state ".
		       "$newstate instead of ".TBDB_NODESTATE_SHUTDOWN."!\n");
626 627 628 629 630
	    }
	#} elsif ($cmd eq $FOO ) {
	    # Add more here...
	} else {
	    notify("$node: Unknown command timeout '$timeout_tag{$node}' ".
631
		   "found at $mode/$newstate\n");
632 633 634
	}
    }

635 636 637
    # Check if this state has a timeout, and if so, put it in the queue
    setTimeout($mode,$newstate,$node,$now);

638 639
    # Check if this is TBDB_NODESTATE_BOOTING , which has actions
    if ($newstate eq TBDB_NODESTATE_BOOTING) {
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
	# If I skipped shutdown, and came to booting directly from isup,
	# check for a mode transition so I don't miss one...
	if ($oldstate eq TBDB_NODESTATE_ISUP) {
	    info("$node: Came from ISUP! Checking for mode transition\n");
	    my $r = DBQueryWarn("select next_op_mode from nodes ".
				"where node_id='$node'");
	    my ($nextmode) = $r->fetchrow();
	    if ($nextmode) {
		# Force the transition even though it is illegal
		info("$node: Forcing mode transition!\n");
		opModeTransition($node,$nextmode,1);
		$mode=$nextmode;
	    } else {
		debug("No next mode.\n");
	    }
	}

	# Check if I'm in the right mode
658
	my $osid = TBBootWhat($node,$debug);
659 660
	my $os_op_mode = os_opmode($osid);
	info("$node: Current OS is '$osid', OS mode is '$os_op_mode'\n");
661
	DBQueryFatal("UPDATE nodes SET osid='$osid' WHERE node_id='$node'");
662
	if ($os_op_mode ne $mode) {
663 664
	    my $str = "Node $node is running OS '$osid' but in mode '$mode' ".
	      "instead of mode '$os_op_mode'!\n";
665 666 667
	    # For now, only force if we're going into reload mode, so we
	    # don't get stuck looping in reloading.
	    if ($os_op_mode eq "RELOAD") {
668 669 670 671 672 673 674 675 676
		DBQueryFatal("UPDATE nodes SET op_mode='$os_op_mode', ".
			     "op_mode_timestamp=unix_timestamp(now()) ".
			     "WHERE node_id='$node'");
		$nodes{$node}{mode} = $os_op_mode;
		$nodes{$node}{mode_timestamp} = $now;
		$str .= "Forced op_mode to '$os_op_mode'.\n";
	    }
	    notify($str);
	}
677 678
	checkGenISUP($node);
    }
679

680 681 682 683 684
    # Check if this state has any triggers
    my @nodetrigs = GetNodeTriggerList($node,$mode,$newstate);
    if (defined($triggers{"$mode:$newstate"}) ||
        (@nodetrigs > 0) ) {
	# check for global triggers
685
	my @trigs = split(/\s*,\s*/,$triggers{"$mode:$newstate"});
686 687 688 689
	# Run all the triggers
	debug("Running triggers. Global=".join("/",@trigs).
	      "   node=".join("/",@nodetrigs)."\n");
	foreach ( @trigs , @nodetrigs) {
690 691
	    my $trig = $_;
	    /^$TBRESET$/ && do {
692 693 694
		# We successfully booted, so clear some flags
		$nodes{$node}{noretry}   = 0;
		$nodes{$node}{timedout}  = 0;
695 696 697 698 699 700 701 702 703 704 705 706 707
		# Check if we really need to do a reset
		my $r = DBQueryWarn("select osid,def_boot_osid from nodes ".
				    "where node_id='$node'");
		my ($osid,$defosid) = $r->fetchrow();
		if ($osid ne $defosid) {
		    handleCtrlEvent($node,$trig);
		}
		next;
	    };
	    /^$TBRELOADDONE$/ && do {
		handleCtrlEvent($node,$trig);
		next;
	    };
708 709 710 711
	    /^$TBFREENODE$/ && do {
		handleCtrlEvent($node,$trig);
		next;
	    };
712 713 714 715 716 717 718 719
	    /^$TBISUP$/ && do {
		info("$node: Triggered $TBISUP\n");
		EventSendWarn(host      => $BOSSNODE ,
			      objtype   => TBDB_TBEVENT_NODESTATE ,
			      eventtype => TBDB_NODESTATE_ISUP ,
			      objname   => $node);
		next;
	    };
720
	    notify("Unknown trigger '$trig' for $node in $mode/$newstate!\n");
721
	}
722 723 724
	# Clear any of the node triggers that we ran
	debug("Clearing node triggers: ".join("/",@nodetrigs)."\n");
	ClearNodeTrigger($node,$mode,$newstate,@nodetrigs);
725
    }
726

727 728 729 730 731 732 733 734
    # 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
735 736 737
	} else {
	    debug("No next mode.\n");
	}
738 739
    }
}
740

741
sub opModeTransition($$;$) {
Mac Newbold's avatar
Mac Newbold committed
742

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

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
    info("$node: Mode change to $newmode requested\n");
    # Check for invalid transitions
    my ($oldstate, $mode, $nextstate);
    if ($nodes{$node}) {
	$oldstate = $nodes{$node}{state};
	$mode = $nodes{$node}{mode};
    } else {
	# Try reloading the cache once before we give up on this node
	reload();
	if ($nodes{$node}) {
	    $oldstate = $nodes{$node}{state};
	    $mode = $nodes{$node}{mode};
	} else {
	    notify("Got an event for a node ($node) I don't know about\n");
	}
    }
762
    if (defined($modeTrans{"$mode:$oldstate"}) || $force) {
763
	if (!$force) {
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
	    debug("Mode Transition check:\n");
	    my $translist = join(",",@{$modeTrans{"$mode:$oldstate"}});
	    #debug("translist=$translist\n");
	    #debug("splitlist=".join(", ",split(/[:,]/,$translist))."\n");
	    my %trans = split(/[:,]/,$translist);
	    debug("Valid transitions from $mode/$oldstate are:\n");
	    foreach my $k (sort keys %trans) {
		debug("$k => $trans{$k}\n");
	    }
	    if (defined($trans{$newmode})) {
		$nextstate=$trans{$newmode};
	    } else {
		notify("Invalid mode transition for $node from ".
		       "$mode/$oldstate to $newmode!\n");
	    }
779 780
	}
    } else {
781
	notify("Invalid mode transition for $node from $mode/$oldstate: ".
782 783
	       "Not a valid mode transition state!\n");
    }
Mac Newbold's avatar
Mac Newbold committed
784 785 786
    if (!$nextstate) {
	$nextstate=$oldstate;
    }
Mac Newbold's avatar
Mac Newbold committed
787

788 789 790 791 792 793
    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
794

795 796 797 798 799
    info("$node: $mode/$oldstate => $newmode/$nextstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$nextstate', ".
		 "next_op_mode='', op_mode='$newmode', ".
		 "state_timestamp='$now', ".
		 "op_mode_timestamp='$now' WHERE node_id='$node'");
Mac Newbold's avatar
Mac Newbold committed
800 801 802 803

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

804 805 806 807
}

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

809
    info("CtrlEvent: $node, $event\n");
810

811 812
    foreach ($event) {
	/^$TBRESET$/ && do {
Mac Newbold's avatar
Mac Newbold committed
813 814 815
	    my $result = DBQueryFatal("SELECT pxe_boot_path, def_boot_osid ".
				      "FROM nodes where node_id='$node'");
	    my ($pxepath,$osid) = $result->fetchrow();
816

817 818 819 820
	    # Important note on ordering here:
	    # Because setting a normal osid resets pxe path to PXEBOOT,
	    # We need to read it out first, then set the osid, then set
	    # the pxepath back to its original value at the end.
821

822 823
	    $cmd = "$osselect $osid $node";
	    system($cmd) and
Mac Newbold's avatar
Mac Newbold committed
824 825
	      notify("$node/$event: Couldn't clear next_boot_*\n".
		     "\tcmd=$cmd\n\t*** $!\n");
826

827
	    $pxepath = "-p ".$pxepath;
Mac Newbold's avatar
Mac Newbold committed
828 829 830 831
	    if ($pxepath eq "-p ") {
		$pxepath="PXEBOOT";
	    }
	    ;
Mac Newbold's avatar
Mac Newbold committed
832
	    my $cmd = "$osselect -m $pxepath $node";
833
	    system($cmd) and
Mac Newbold's avatar
Mac Newbold committed
834 835
	      notify("$node/$event: Couldn't clear next_pxe_boot_path\n".
		     "\tcmd=$cmd\n\t*** $!\n");
836

Mac Newbold's avatar
Mac Newbold committed
837
	    info("Performed RESET for $node to $osid/$pxepath\n");
838 839 840 841 842 843 844 845 846 847
	    next;
	};
	/^$TBRELOADDONE$/ && do {
	    info("Clearing reload info for $node\n");
	    DBQueryFatal("delete from current_reloads where node_id='$node'");
	    my ($pid,$eid);
	    NodeidToExp($node,\$pid,\$eid);
	    if (($pid eq NODERELOADING_PID) && ($eid eq NODERELOADING_EID)) {
		DBQueryFatal("delete from scheduled_reloads ".
			     "where node_id='$node'");
848 849 850 851
		AddNodeTrigger($node, $TBANYMODE, TBDB_NODESTATE_ISUP,
			       $TBFREENODE)
		  && notify("$node: Couldn't add trigger $TBFREENODE!\n");
		info("Set up freeing of $node from $pid/$eid\n");
852 853 854
	    }
	    next;
	};
855 856 857 858 859 860 861 862
	/^$TBFREENODE$/ && do {
	    # Don't need pid/eid, but we should put it in the log
	    my ($pid,$eid);
	    NodeidToExp($node,\$pid,\$eid);
	    DBQueryFatal("delete from reserved where node_id='$node'");
	    info("Released $node from $pid/$eid\n");
	    next;
	};
863
	/^$TBTIMEOUT$/ && do {
864 865 866 867
	    my ($mode,$state) = split(":",$timeout_tag{$node});
	    delete($timeout_tag{$node});
	    my $curstate = $nodes{$node}{state};
	    my $curmode = $nodes{$node}{mode};
868
	    my ($timeout,$action);
869 870 871 872 873
	    if (!defined($nodes{$node}{notified})) {
		$nodes{$node}{notified}=0;
	    }
	    $nodes{$node}{notified}++;
	    my $notified = $nodes{$node}{notified};
874 875
	    $nodes{$node}{timedout}++;
	    my $timedout = $nodes{$node}{timedout};
876 877 878 879
	    if ($mode && $state && $timeouts{$mode} &&
		$timeouts{$mode}{$state}) {
		($timeout, $action) = @{$timeouts{$mode}{$state}};
	    }
880 881
	    if ($mode eq $TBCOMMAND) {
		# It is a command, not a true state
882
		if ($action eq $TBTIMEOUTCMDRETRY) {
883
		    # Retry the command
884
		    notify("$node: Command $state, retry #$timedout\n");
885
		    # notify in case we get in a retry loop...
886
		    handleCommand($node,$state,$timedout,1);
887 888 889 890 891 892
		} else {
		    notify("$node: Unknown timeout action for ".
			   "$mode/$state: '$action'\n");
		}
		next;
	    }
893 894 895 896 897 898
	    info("Node $node has timed out in state $mode/$state".
		 ($action ne "" ? "\n\tRequested action $action." : "").
		 "\n");

	    foreach ($action) {
		/^$TBTIMEOUTREBOOT/ && do {
899 900 901 902 903
		    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;
904
		    } else {
905 906 907 908 909 910
			# 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);
911 912 913 914 915 916 917
		    }
		    last; };
		/^$TBTIMEOUTNOTIFY/ && do {
		    notify("Node $node has timed out in state $mode/$state\n");
		    last; };
		notify("$node: Unknown Timeout Action: $action\n");
	    }
918 919
	    next;
	};
920
	notify("$node: Unknown CtrlEvent: $event\n");
921 922
    }
}
Robert Ricci's avatar
Robert Ricci committed
923

924 925
sub handleCommand($$;$$) {
    my ($params,$command,$retry,$force) = @_;
926
    if (!defined($retry)) { $retry=0; }
927
    if (!defined($force)) { $force=0; }
928 929 930 931 932 933 934 935

    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.

936
    if ($command eq $TBREBOOT && $retry >=4) {
937 938
	announce("Node $params has tried rebooting $retry times and has \n".
		 "still not been successful. Please look into it soon.\n".
939 940 941
	"" );#	 "In the meantime, $params will be powered off.\n");
	# Just return...
	return 0;
942
	# change my command to poweroff.
943
	#$command = $TBPOWEROFF;
944 945 946 947 948 949
    }

    foreach ($command) {
	/^$TBREBOOT$/ && do {
	    # For reboot, the params is a comma-separated list of nodes
	    my @nodes = split(",",$params);
950 951 952 953 954 955 956 957

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

963 964 965 966 967 968 969 970 971 972
			info("$node: Trying to reboot too soon! Skipping.\n");
			# Cut it out of the list
			debug("Nodelist before ==> ".join(" ",@nodes)."\n");
			splice(@nodes,$n,1);
			debug("Nodelist after  ==> ".join(" ",@nodes)."\n");
		    }
		}
		if (@nodes == 0) { next; }
	    }

973 974 975 976 977
	    my $nodelist=join(" ",@nodes);
	    info("Rebooting nodes: $nodelist\n");
	    # Permissions were checked in order to send the message,
	    # so we don't need to do any fancy stuff here.

978 979 980 981 982
	    my $cmd = "$nodereboot -r $nodelist";
	    my $redir = " 2>&1 >> /usr/testbed/log/nodereboot.log &";
	    debug("$cmd $redir\n");
	    system("date $redir");
	    system($cmd.$redir) and
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
	      notify("$params/$command: ".
		     "Command '$cmd' failed, error $?: $!\n");

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

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

	    my $cmd = "$power $func $nodelist &";
1010 1011
	    debug("$cmd\n") and
	    system($cmd) and
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
	      notify("$params/$command: ".
		     "Command '$cmd' failed, error $?: $!\n");

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

1022 1023 1024 1025
#
# Check if we need to generate an ISUP
#
sub checkGenISUP($) {
Mac Newbold's avatar
Mac Newbold committed
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    my ($node) = @_;
    debug("$node: Checking ISUP Generation\n");
    my $r = DBQueryWarn("select osfeatures from nodes as n ".
			"left join os_info as o on o.osid=n.osid ".
			"where node_id='$node' and osfeatures is not null");
    my $osfeatures="";
    # If we don't get anything back, assume it has no features.
    if ($r->num_rows() > 0) {
	($osfeatures) = $r->fetchrow();
    }
Mac Newbold's avatar
Mac Newbold committed
1036

Mac Newbold's avatar
Mac Newbold committed
1037 1038 1039 1040 1041 1042
    my @features = split(",",$osfeatures);
    # Make sure features I care about are defined
    my %can=("ping"=>0, "isup"=>0);
    foreach my $f (@features) {
	$can{"\L$f"}=1;	# make sure it's all lowercase
    }
Mac Newbold's avatar
Mac Newbold committed
1043

Mac Newbold's avatar
Mac Newbold committed
1044 1045 1046 1047 1048
    # If os will send ISUP on its own, do nothing here.
    if ($can{"isup"}) {
	debug("$node: Will send own ISUP\n"); 
	return 0;
    }
Mac Newbold's avatar
Mac Newbold committed
1049

Mac Newbold's avatar
Mac Newbold committed
1050 1051 1052 1053 1054 1055
    # If os doesn't support isup but can ping, fork and ping it every
    # few seconds and send isup when it pings, or timeout after too long.
    if ($can{"ping"}) {
	debug("$node: Needs to be pinged - calling eventping\n");
	system("$TB/sbin/eventping $node &");
	return 0;
1056
    }
Mac Newbold's avatar
Mac Newbold committed
1057

Mac Newbold's avatar
Mac Newbold committed
1058 1059 1060 1061 1062 1063 1064 1065
    # If os doesn't support ping or isup, stated sends ISUP just after 
    # the node gets to BOOTING (a bit early, but the best we can do)

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

1068 1069 1070 1071
# Figure out if this node belongs to us (ie. if it's using our database.)
# Returns 1 if it does, 0 if not
sub checkDBRedirect($) {

Mac Newbold's avatar
Mac Newbold committed
1072
    my ($node) = @_;
1073

Mac Newbold's avatar
Mac Newbold committed
1074 1075 1076 1077 1078 1079 1080 1081
    # XXX: I don't want to do this every time, for performance reaons,
    # but we need to make sure that we don't get into an inconsistent 
    # state
    my $result=DBQueryFatal("SELECT testdb FROM nodes as n " .
			    "LEFT JOIN reserved as r ON n.node_id=r.node_id ".
			    "LEFT JOIN experiments as e ON r.pid = e.pid " .
			    "AND r.eid = e.eid " .
			    "WHERE n.node_id = '$node'");
1082

Mac Newbold's avatar
Mac Newbold committed
1083 1084 1085 1086
    if (!$result->num_rows()) {
	notify("Got an event for a node ($node) I don't know about\n");
	return 0;
    }
1087

Mac Newbold's avatar
Mac Newbold committed
1088
    my ($testdb) = $result->fetchrow();
1089

Mac Newbold's avatar
Mac Newbold committed
1090 1091 1092
    # XXX: It's hokey to hardcode tbdb here, but....

    #debug("checkDBRedirect: $node => $testdb (I'm $TBDBNAME)\n");
1093
    if ((!$testdb && ($TBDBNAME eq $REALTBDBNAME)) ||
Mac Newbold's avatar
Mac Newbold committed
1094 1095 1096 1097 1098
	($testdb && ($testdb eq $TBDBNAME))) {
	return 1;
    } else {
	return 0;
    }
1099 1100
}

1101 1102 1103 1104
# Check if this state has a timeout, and if so, put it in the queue
sub setTimeout( $$$$ ) {
    my ($mode,$state,$node,$now) = @_;
    if (0) { print "Original: ($mode,$state,$node,$now)\n"; qshow(); }
1105
    if (defined(qfind($node))) { qdelete($node); delete($timeout_tag{$node}); }
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    if (0) { print "Deleted:\n"; qshow(); }
    if (defined($mode) && defined($state) &&
	defined($timeouts{$mode}) &&
	defined($timeouts{$mode}{$state})) {
	my $deadline = ${$timeouts{$mode}{$state}}[0];
        if (defined($deadline) &&
	    $deadline != $TBNOTIMEOUT) {
	    my $TO = $deadline + $now;
	    debug("Setting timeout for ($node,$mode,$state) at ".
		  "$deadline + $now ($TO)\n");
	    qinsert($TO,$node);
1117
	    $timeout_tag{$node} = "$mode:$state";
1118 1119 1120 1121 1122 1123
	    if (0) { qshow(); }
	}
    }
    if (0) { print "Done:\n"; qshow(); }
}

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
# Remove a timeout.
sub remTimeout ($)
{
    my ($node) = @_;

    if (defined(qfind($node))) {
	qdelete($node);
	delete($timeout_tag{$node});
    }
}

Robert Ricci's avatar
Robert Ricci committed
1135 1136
# Reload state from the database
sub reload() {
Mac Newbold's avatar
Mac Newbold committed
1137 1138 1139 1140 1141 1142
    debug("Reloading state from database\n");
    $last_reload = time();
    %timeouts  = getTimeouts();
    %valid     = getValid();
    %modeTrans = getModeTrans();
    %triggers  = getTriggers();
1143
    %nodes     = readStates(%nodes);
Robert Ricci's avatar
Robert Ricci committed
1144 1145
}

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
#
# Some functions for node triggers
#

# $rv   = AddNodeTrigger($node, $mode, $state, @triglist);
sub AddNodeTrigger( $$$@ ) {
    my ($node, $mode, $state, @trigs) = @_;
    if (@trigs == 0) { return 1; }
    if (defined($triggers{"$node:$mode:$state"})) {
	my %t = ();
	foreach $k (@{$triggers{"$node:$mode:$state"}}) { $t{$k} = 1; }
	my @newtrigs = ();
	foreach $k (@trigs) { if (!defined($t{$k})) { push(@newtrigs,$k); } }
	push(@{$triggers{"$node:$mode:$state"}},@newtrigs);
    } else {
	$triggers{"$node:$mode:$state"} = \@trigs;
    }
    my $triglist = join(",",@{$triggers{"$node:$mode:$state"}});
    DBQueryFatal("replace into state_triggers ".
		 "(node_id,op_mode,state,trigger) values ".
		 "('$node','$mode','$state','$triglist')");
    return 0;
}

# @list = GetNodeTriggerList($node, $mode, $state);
sub GetNodeTriggerList( $$$ ) {
    my ($node, $mode, $state) = @_;
    my @l = ();
    if (defined($triggers{"$node:$mode:$state"})) {
	push(@l,@{$triggers{"$node:$mode:$state"}});
    }
    if (defined($triggers{"$node:$TBANYMODE:$state"})) {
	push(@l,@{$triggers{"$node:$TBANYMODE:$state"}});
    }
    return @l;
}

# $rv   = ClearNodeTrigger($node, $mode, $state, @triglist);
# Note: When not clearing all triggers, ordering is not preserved!
sub ClearNodeTrigger( $$$ ; @ ) {
    my ($node, $mode, $state, @trigs) = @_;
    # We have to keep any triggers that aren't on the list, but the
    # most common case will be that the list they give us is the whole
    # list anyway. So treat that case special.
    my @reallist = GetNodeTriggerList($node,$mode,$state);
    # empty list means clear all...
    if ((@trigs==0) || join(",",sort @reallist) eq join(",",sort @trigs)) {
	# Same list... just nuke the entry
	debug("Clearing all triggers for $node...\n");
	delete($triggers{"$node:$mode:$state"});
	delete($triggers{"$node:$TBANYMODE:$state"});
	DBQueryFatal("delete from state_triggers ".
		     "where node_id='$node' and state='$state' and ".
		     "(op_mode='$mode' or op_mode='$TBANYMODE')");
    } else {
	# Subtract @trigs from @reallist
	my %temptrigs = ();
	foreach $k (@reallist) { $temptrigs{$k} = 1; }
	debug("Reallist = ".join("/",@reallist).", trigs=".
	      join("/",@trigs).".\n");
	foreach $t (@trigs) {
	    if (defined($temptrigs{$t})) {
		delete($temptrigs{$t});
		debug("Clearing $t\n");
	    }
	}
	# Note: This doesn't quite do the right thing with triggers
	# for a fixed mode vs TBANYMODE. So if you start using this
	# code, make sure and debug it first!
	my @newtrigs = keys %temptrigs;
	debug("Newlist = ".join("/",@newtrigs).".\n");
	delete($triggers{"$node:$mode:$state"});
	if (@newtrigs > 0) {
	    AddNodeTrigger($node,$mode,$state,@newtrigs);
	} 
    }

    return 0;
}

1226 1227
sub os_opmode() {
    my $osid = shift || "";
Mac Newbold's avatar
Mac Newbold committed
1228 1229 1230
    if ($osid eq $TB_OSID_MBKERNEL) {
	return "MINIMAL";
    }
1231 1232
    my $cmd = "select op_mode from os_info where osid='$osid';";
    my $q = DBQueryFatal($cmd);
Mac Newbold's avatar
Mac Newbold committed
1233 1234 1235
    if ($q->numrows() < 1) {
	return "";
    }
1236 1237 1238
    my @r = $q->fetchrow_array();
    my $opmode=$r[0];
    debug("OpMode for '$osid' is '$opmode'\n");
Mac Newbold's avatar
Mac Newbold committed
1239 1240 1241
    if (defined($opmode) && $opmode ne "") {
	return $opmode;
    }
1242 1243
    return "";
}
Mac Newbold's avatar
Mac Newbold committed
1244

1245 1246 1247 1248
#
# Functions for controlling output/logging, and signal handling
#

Robert Ricci's avatar
Robert Ricci committed
1249
sub debug(@) {
Mac Newbold's avatar
Mac Newbold committed
1250 1251 1252
    if ($debug) {
	print @_;
    }
Mac Newbold's avatar
Mac Newbold committed
1253 1254 1255
}

sub fatal($) {
Mac Newbold's avatar
Mac Newbold committed
1256 1257 1258
    my $msg = shift;
    notify($msg);
    die($msg);
Robert Ricci's avatar
Robert Ricci committed
1259 1260
}

Mac Newbold's avatar
Mac Newbold committed
1261
sub showqueue() {
Mac Newbold's avatar
Mac Newbold committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
    if ($debug < 2) {
	return;
    }
    if ((keys %msgs) > 0) {
	debug("\nMAILQUEUE:\n");
    }
    foreach $k (sort keys %msgs) {
	my @l = @{$msgs{$k}};
	debug("MSGS:\n$k==> (".(@l+0).",'".join("','",@l)."')\n");
    }
Mac Newbold's avatar
Mac Newbold committed
1272 1273 1274
}

sub notify($;$) {
Mac Newbold's avatar
Mac Newbold committed
1275 1276 1277 1278
    my $message = shift;
    my $checkonly = shift || 0;
    # Use a timestamp, now that we're throttling mail
    my $tstamp=strftime("%b %e %H:%M:%S",localtime);