stated.in 18.2 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 4 5 6 7
#
# EMULAB-COPYRIGHT
# Copyright (c) 2000-2002 University of Utah and the Flux Group.
# All rights reserved.
#

Robert Ricci's avatar
Robert Ricci committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#
# stated - A daemon to monitor the states of nodes in the testbed. Recives
# state change notification through the event system, and writes the new
# state into the database.
#
# In the future, will watch for invalid state transitions, and watch for nodes
# that time out.
#
# Send it a HUP signal to get it to reload the timeout and transition
# information. Periodically reloads this information regardless, though.
#

#
# Configure variables
#
use lib '@prefix@/lib';
my $BOSSNODE = "@BOSSNODE@";
25
my $TBOPS = '@TBSTATEDEMAIL@';
26
my $TBDBNAME = "@TBDBNAME@";
27
my $osselect = "@prefix@/bin/os_select";
Robert Ricci's avatar
Robert Ricci committed
28 29 30 31 32 33 34

$| = 1;

use event;
use libdb;
use libtestbed;
use Getopt::Std;
35
#use strict;
Robert Ricci's avatar
Robert Ricci committed
36
use English;
37
use POSIX qw(strftime);
Robert Ricci's avatar
Robert Ricci committed
38 39 40 41 42 43

#
# 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.
#
44
my $reload_time = 3600;
Robert Ricci's avatar
Robert Ricci committed
45 46 47 48 49 50 51

#
# Process command-line arguments
#

sub usage {
	print << "END";
52
Usage: $0 [-d] [-s server] [-p port] [-f] [-h]
Robert Ricci's avatar
Robert Ricci committed
53 54 55
-s server       Use specified server, instead of this site's bossnode
-p port	        Use specified port
-d              Turn on debugging output, and don't go into the background
56
-f              Stay in the foreground, rather than forking
Robert Ricci's avatar
Robert Ricci committed
57 58 59 60 61
-h              This message
END
}

my %opt = ();
62
getopts("ds:p:hf",\%opt);
Robert Ricci's avatar
Robert Ricci committed
63 64 65 66

if ($opt{h}) { exit &usage; }
if (@ARGV) { exit &usage; }

67
my ($server,$port,$debug,$nofork);
Robert Ricci's avatar
Robert Ricci committed
68 69 70
if ($opt{s}) { $server = $opt{s}; } else { $server = $BOSSNODE; }
if ($opt{p}) { $port = $opt{p}; }
if ($opt{d}) { $debug = 1; } else { $debug = 0; }
71
if ($opt{f}) { $nofork = 1; } else { $nofork = 0; }
Robert Ricci's avatar
Robert Ricci committed
72

73 74 75 76 77 78 79 80 81 82 83
#
# Grab some constants into variables
#
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;
my $TBCONTROL    = TBDB_TBEVENT_TBCONTROL;

Robert Ricci's avatar
Robert Ricci committed
84 85 86
#
# Background
#
87 88 89
my $logname = "@prefix@/log/stated.log";
if (!$debug && !$nofork) {
	if (TBBackGround($logname)) {
Robert Ricci's avatar
Robert Ricci committed
90 91
		exit(0);
	}
92 93 94 95 96 97 98 99
} else {
    if ($nofork) {
	#
	# Open our log file manually
	#
	open(STDERR, ">> $logname") or die("opening $logname for STDERR: $!");
	open(STDOUT, ">> $logname") or die("opening $logname for STDOUT: $!");
    }
Robert Ricci's avatar
Robert Ricci committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113
}

my $URL = "elvin://$server";
if ($port) { $URL .= ":$port"; }

#
# Connect to the event system, and subscribe the the events we want 
#
my $handle = event_register($URL,0);
if (!$handle) { die "Unable to register with event system\n"; }

my $tuple = address_tuple_alloc();
if (!$tuple) { die "Could not allocate an address tuple\n"; }

114 115
%$tuple = ( objtype => join(",",$TBNODESTATE,$TBNODEOPMODE,$TBCONTROL) );

Robert Ricci's avatar
Robert Ricci committed
116
if (!event_subscribe($handle,\&handleEvent,$tuple)) {
117
	die "Could not subscribe to events\n";
Robert Ricci's avatar
Robert Ricci committed
118 119 120 121 122 123
}

#
# Read in the pre-existing node states, and timeout and valid transition
# information from the database
#
124 125 126 127 128
my %nodes     = readStates();
my %timeouts  = getTimeouts();
my %valid     = getValid();
my %modeTrans = getModeTrans();
my %triggers  = getTriggers();
Robert Ricci's avatar
Robert Ricci committed
129 130 131 132 133 134 135 136 137 138 139

#
# Gets set if a reload of state from the database should happen.
#
my $do_reload = 0;

#
# 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.
#
140
$SIG{HUP} = sub { info("Recieved a SIGHUP\n"); $do_reload = 1; };
141 142 143 144 145
$SIG{INT} = \&cleanup;
$SIG{QUIT} = \&cleanup;
$SIG{ABRT} = \&cleanup;
$SIG{TERM} = \&cleanup;
$SIG{KILL} = \&cleanup;
Robert Ricci's avatar
Robert Ricci committed
146

147
info("stated starting up\n");
Robert Ricci's avatar
Robert Ricci committed
148 149 150 151 152 153 154 155 156 157 158 159

#
# Now, we just poll for events, and watch for 
#
my $iterations = 0;
while (1) {
	event_poll($handle);
	my $now = time();
	#
	# Look for nodes that have passed their timeout
	#
	while (my ($node, $value) = each %nodes) {
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
	    my $state    = $value->{state};
	    my $mode     = $value->{mode};
	    my $time     = $value->{timestamp};
	    my $notified = $value->{notified};
	    my ($timeout,$action);
	    if ($mode && $state && $timeouts{$mode} &&
		$timeouts{$mode}{$state}) {
		($timeout, $action) = @{$timeouts{$mode}{$state}};
	    }
	    if ((!$notified) && $time && $timeout && 
		$timeout!= $TBNOTIMEOUT && (($time + $timeout) < $now)) {
		handleCtrlEvent($node,$TBTIMEOUT);
		$value->{notified} = 1;
		
	    }
Robert Ricci's avatar
Robert Ricci committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	}

	if ($do_reload || ($iterations > $reload_time)) {
		reload();
		$do_reload = 0;
		$iterations = 0;
	}

	$iterations++;
	sleep(1);
}

#
# Read the current states of nodes from the database
#
190 191 192
sub readStates(;@) {
    	my %oldnodes = @_;

193 194 195 196 197 198 199
	#
	# Guard against undefined variable warnings
	#
	if (! defined(%oldnodes)) {
		%oldnodes = ();
	}

200
	#debug("readStates called\n");
Robert Ricci's avatar
Robert Ricci committed
201
	my $result = DBQueryFatal("SELECT node_id, eventstate, " .
202 203
				  "state_timestamp, op_mode, " .
				  "op_mode_timestamp FROM nodes");
Robert Ricci's avatar
Robert Ricci committed
204 205

	my %nodes;
206 207
	while (my ($node_id, $state, $timestamp, $mode, $mode_timestamp)
			= $result->fetchrow()) {
208 209 210 211 212 213
	    	#
		# 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.)
		#
214 215
		if ($oldnodes{$node_id} && $state && $timestamp &&
		   ($oldnodes{$node_id}{state} eq $state) &&
216
		   ($oldnodes{$node_id}{mode} eq $mode) &&
217
		   ($oldnodes{$node_id}{timestamp} == $timestamp)) {
218 219
		       $nodes{$node_id} = $oldnodes{$node_id};
		} else { 
220 221 222 223
		    $nodes{$node_id}{state}          = $state;
		    $nodes{$node_id}{timestamp}      = $timestamp;
		    $nodes{$node_id}{mode}           = $mode;
		    $nodes{$node_id}{mode_timestamp} = $mode_timestamp;
224
		}
Robert Ricci's avatar
Robert Ricci committed
225 226 227 228 229 230 231 232
	}
	return %nodes;
}

#
# Read timeouts for various states from the database
#
sub getTimeouts() {
233
	#debug("getTimeouts called\n");
234
	my $result = DBQueryFatal("SELECT op_mode, state, timeout, action " .
Robert Ricci's avatar
Robert Ricci committed
235 236 237
				  "FROM state_timeouts");

	my %timeouts;
238 239
	while (my ($op_mode, $state, $timeout, $action) = $result->fetchrow()) {
		$timeouts{$op_mode}{$state} = [ $timeout, $action ];
Robert Ricci's avatar
Robert Ricci committed
240 241 242 243 244 245 246 247
	}
	return %timeouts;
}

#
# Read the list of valid state transitions from the database
#
sub getValid() {
248
	#debug("getValid called\n");
249
	my $result = DBQueryFatal("SELECT op_mode, state1, state2 " .
Robert Ricci's avatar
Robert Ricci committed
250 251 252
				  "FROM state_transitions");

	my %valid;
253 254
	while (my ($mode,$state1, $state2) = $result->fetchrow()) {
		$valid{$mode}{$state1}{$state2} = 1;
Robert Ricci's avatar
Robert Ricci committed
255 256 257 258
	}
	return %valid;
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
#
# Read the list of valid mode transitions from the database
#
sub getModeTrans() {
	#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;
	    }
	}
	return %modeTrans;
}

#
# Read the list of states which trigger an action
#
sub getTriggers() {
	#debug("getTriggers called\n");
	my $result = 
	    DBQueryFatal("SELECT op_mode, state, trigger " .
			 "FROM state_triggers order by op_mode,state");
	my %t;
	while (my ($mode,$state, $trig) = $result->fetchrow()) {
	    $t{"$mode:$state"} = $trig;
	}
	return %t;
}

Robert Ricci's avatar
Robert Ricci committed
296 297 298 299 300
#
# Gets called for every event that we recieve
#
sub handleEvent($$$) {
	my ($handle,$notification,$data) = @_;
301
	my $objtype = event_notification_get_objtype($handle,$notification);
Robert Ricci's avatar
Robert Ricci committed
302 303 304
	my $objname = event_notification_get_objname($handle,$notification);
	my $eventtype = event_notification_get_eventtype($handle,$notification);

305
	info("Got an event: ($objtype,$objname,$eventtype)\n");
306

307 308 309 310
	#
	# Check to see if another instance is supposed to be handling this node
	#
	if (!checkDBRedirect($objname)) {
311
	    info("Got an event for node $objname, which isn't mine\n");
312 313 314
	    return;
	}

315 316
	SWITCH: for ($objtype) {

317
	    (/$TBNODESTATE/) && do {
318 319 320
		stateTransition($objname,$eventtype);
		last;
	    };
321
	    (/$TBNODEOPMODE/) && do {
322
		opModeTransition($objname,$eventtype);
323 324 325 326
		notify("Use of deprecated event TBNODEOPMODE:\n".
		       "$objname->$eventtype\n");
		last;
	    };
327
	    (/$TBCONTROL/) && do {
328
		handleCtrlEvent($objname,$eventtype);
329 330 331 332 333 334 335 336 337
		last;
	    };

	}

}

sub stateTransition($$) {

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

340 341 342 343 344 345 346 347
    # 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();
348
	if ($nodes{$node}) {
349 350
	    $oldstate = $nodes{$node}{state};
	    $mode = $nodes{$node}{mode};
Robert Ricci's avatar
Robert Ricci committed
351
	} else {
352
	    notify("Got an event for a node ($node) I don't know about\n");
Robert Ricci's avatar
Robert Ricci committed
353
	}
354 355 356 357 358 359
    }
    if ($oldstate && $mode && $valid{$mode} && $valid{$mode}{$oldstate} &&
	!$valid{$mode}{$oldstate}{$newstate}) {
	notify("Invalid transition for node $node from $mode/$oldstate " .
	       "to $newstate\n");
    }
Robert Ricci's avatar
Robert Ricci committed
360

361 362 363 364
    my $now = time();
    $nodes{$node}{state}     = $newstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{notified}  = 0;
365

366 367 368
    info("$node: $mode/$oldstate => $mode/$newstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$newstate', " .
		 "state_timestamp='$now' WHERE node_id='$node'");
369

370 371 372 373 374
    # Check if this is TBDB_NODESTATE_BOOTING , which has actions
    if ($newstate eq TBDB_NODESTATE_BOOTING) {
	my $osid = TBBootWhat($node,$debug);
	info("$node: Current OS is '$osid'\n");
	DBQueryFatal("UPDATE nodes SET osid='$osid' WHERE node_id='$node'");
375

376 377
	checkGenISUP($node);
    }
378

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    # Check if this state is the "successful boot" state
    if (defined($triggers{"$mode:$newstate"})) {
	my @trigs = split(/\s*,\s*/,$triggers{"$mode:$newstate"});
	foreach ( @trigs ) {
	    my $trig = $_;
	    /^$TBRESET$/ && do {
		# 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;
	    };
	    notify("Unknown trigger '$trig' in $mode/$newstate!\n");
	}
    }
401

402 403 404 405 406 407 408 409 410 411 412 413
    # 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);
	} else { debug("No next mode.\n"); }
    }
    
}
414

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
sub opModeTransition($$) {
    
    my ($node,$newmode) = @_;
    
    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");
	}
    }
    if (defined($modeTrans{"$mode:$oldstate"})) {
	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 from ".
		   "$mode/$oldstate to $newmode!\n");
	}
    } else {
	notify("Invalid mode transition from $mode/$oldstate: ".
	       "Not a valid mode transition state!\n");
    }
    if (!$nextstate) { $nextstate=$oldstate; }

    my $now = time();
    $nodes{$node}{state}     = $nextstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{mode}           = $newmode;
    $nodes{$node}{mode_timestamp} = $now;
    $nodes{$node}{notified}       = 0;
    
    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'");
    
}

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

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

    foreach ($event) {
	/^$TBRESET$/ && do {
	    system("$osselect -m PXEBOOT $node") and
		notify("$node/$event: Couldn't clear next_pxe_boot_path\n");

	    my $result = DBQueryFatal("SELECT def_boot_osid FROM nodes ".
				      "where node_id='$node'");
	    my ($osid) = $result->fetchrow();

	    system("$osselect $osid $node") and
		notify("$node/$event: Couldn't clear next_boot_*\n");

	    info("Performed RESET for $node to $osid\n");
	    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'");
		DBQueryFatal("delete from reserved where node_id='$node'");
		info("Released $node from $pid/$eid\n");
	    }
	    next;
	};
	/^$TBTIMEOUT$/ && do {
	    my $state = $nodes{$node}{state};
	    my $mode = $nodes{$node}{mode};
	    my ($timeout,$action);
	    if ($mode && $state && $timeouts{$mode} &&
		$timeouts{$mode}{$state}) {
		($timeout, $action) = @{$timeouts{$mode}{$state}};
	    }
	    notify("Node $node has timed out in state $mode/$state".
		   ($action ne "" ? "\n\tRequested action $action." : "").
		   "\n");
	    next;
	};
	notify("Unknown CtrlEvent: $event\n");
    }
}
Robert Ricci's avatar
Robert Ricci committed
519

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
#
# Check if we need to generate an ISUP
#
sub checkGenISUP($) {
    my ($node) = @_;
    info("$node: Checking ISUP Generation\n");
    my $r = DBQueryWarn("select osfeatures from os_info as o ".
			"left join nodes as n 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(); }
   
    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
    }
Robert Ricci's avatar
Robert Ricci committed
539

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
    # If os will send ISUP on its own, do nothing here.
    if ($can{"isup"}) { return 0; }

    # If os doesn't support isup but can ping, fork and ping it every
    # 5 seconds and send isup when it pings, or timeout after too long.
    if ($can{"ping"}) {
	my $pid = fork();
	if ($pid) { return 0; } # don't wait, return and go on with life
	else {
	    debug("Forked process to ping $node\n");

	    my $wait=5; # 5 seconds between ping attempts
	    my $maxtime=600; # Set the timer for 10 minutes
	    
	    # XXX : If our maxtime is very different from os_setup's
	    #idea of how long a node should take to reboot, then we've
	    #got a problem, since it might reboot the nodes.

	    # Set an alarm in case it never comes up...
	    local $SIG{ALRM} = sub { 
		notify("$node: checkGenISUP timed out waiting ".
		       "for ping responses after $maxtime seconds.\n");
		exit(); 
	    };
	    
	    alarm $maxtime;

	    my $n=0;
	    while ( $n <= ($maxtime/$wait)) {
		my $rv=system("/sbin/ping -c 1 -t 1 $node > /dev/null") >> 8;
		if ($rv==0) {
		    # we got a response
		    debug("$node: ping response received... sending ISUP\n");
		    stateTransition($node, TBDB_NODESTATE_ISUP);
		    exit();
		} elsif ($rv==2) {
		    # no response
		    debug("No ping response, waiting $wait seconds...\n");
		} elsif ($rv==68) {
		    # ping: cannot resolve $node: Unknown host
		    notify("$node: ping couldn't resolve $node!\n");
		    exit();
		} else {
		    notify("$node: checkGenISUP ping returned $rv!\n");
		    exit();
		}
		sleep $wait;
		$n+=1;
	    }
	    notify("$node: Sent $n pings in ".($n*$wait)." seconds ".
		   "with no response.\n");
	    exit();
	}
    }
    # If os doesn't support ping or isup, stated sets it to ISUP at the
    # same time.
    
    debug("$node: OS doesn't ping - sending ISUP\n");
    stateTransition($node, TBDB_NODESTATE_ISUP);
    
Robert Ricci's avatar
Robert Ricci committed
600 601
}

602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
#
# 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($) {

	my ($node) = @_;

	#
	# 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'");

	if (!$result->num_rows()) {
		notify("Got an event for a node ($node) I don't know about\n");
		return 0;
	}

	my ($testdb) = $result->fetchrow();

	#
	# XXX: It's hokey to hardcode tbdb here, but....
	#
631 632

	#debug("checkDBRedirect: $node => $testdb (I'm $TBDBNAME)\n");
633 634 635 636 637 638 639 640
	if ((!$testdb && ($TBDBNAME eq "tbdb")) ||
	    ($testdb && ($testdb eq $TBDBNAME))) {
		return 1;
	} else {
		return 0;
	}
}

Robert Ricci's avatar
Robert Ricci committed
641 642 643 644
#
# Reload state from the database
#
sub reload() {
645
    	info("Reloading state from database\n");
646 647
	%nodes     = readStates(%nodes);
	%timeouts  = getTimeouts();
Robert Ricci's avatar
Robert Ricci committed
648
	%valid     = getValid();
649 650
	%modeTrans = getModeTrans();
	%triggers  = getTriggers();
Robert Ricci's avatar
Robert Ricci committed
651 652 653 654 655 656 657 658 659
}

sub debug(@) {
	if ($debug) { print @_; }
}

sub notify($) {
    	my $message = shift;
	if (!$debug) {
660
	    SENDMAIL($TBOPS,"Node State Daemon Messsage",$message,$TBOPS);
661 662
	} else {
	    print "notify: Not sending mail in debug mode\n";
Robert Ricci's avatar
Robert Ricci committed
663
	}
664 665 666 667 668 669 670
	info($message);
}

sub info($) {
    my $message = shift;
    # Print out log entries like this:
    # Sep 20 09:36:00 stated[238]: Reloading state from database
Mac Newbold's avatar
Mac Newbold committed
671
    print strftime("%b %e %H:%M:%S",localtime)." stated[$$]: $message";
Robert Ricci's avatar
Robert Ricci committed
672 673
}

674 675 676 677 678 679 680 681
#
# This gets called if we catch a signal (TERM, etc.)
#
sub cleanup {
    info("Signal received, exiting\n");
    exit(0);
}

Robert Ricci's avatar
Robert Ricci committed
682 683 684 685
#
# This gets called if we die of 'natural causes' (exit, die, etc.)
#
END {
686 687 688 689
    if ($handle) {
	info("Exiting, cleaning up\n");
	if (event_unregister($handle) == 0) {
	    die "Unable to unregister with event system\n";
Robert Ricci's avatar
Robert Ricci committed
690
	}
691
    }
Robert Ricci's avatar
Robert Ricci committed
692
}
693