stated.in 25.5 KB
Newer Older
Robert Ricci's avatar
Robert Ricci committed
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2 3 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
#
# 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";
Robert Ricci's avatar
Robert Ricci committed
30 31 32 33 34 35 36

$| = 1;

use event;
use libdb;
use libtestbed;
use Getopt::Std;
37
#use strict;
Robert Ricci's avatar
Robert Ricci committed
38
use English;
Mac Newbold's avatar
Mac Newbold committed
39 40
use POSIX;			# for strftime, and sigprocmask and friends
use Fcntl;			# file constants for pidfile
Mac Newbold's avatar
Mac Newbold committed
41 42 43 44 45
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
46

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

Robert Ricci's avatar
Robert Ricci committed
50 51 52
# 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.
53 54
my $reload_time = 600;
my $last_reload = 0;
Robert Ricci's avatar
Robert Ricci committed
55 56 57 58

# Process command-line arguments

sub usage {
Mac Newbold's avatar
Mac Newbold committed
59
    print << "END";
60 61 62
Usage: $0 [-h] [-d] [-s server] [-p port]
-h              This message
-d              Turn on debugging output, and don't go into the background
Robert Ricci's avatar
Robert Ricci committed
63 64
-s server       Use specified server, instead of this site's bossnode
-p port	        Use specified port
65
Send SIGHUP to reload database state, or SIGUSR1 to restart completely.
Robert Ricci's avatar
Robert Ricci committed
66 67 68
END
}

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

75
my @args = @ARGV;    # save a copy for restart before we mess with them.
Robert Ricci's avatar
Robert Ricci committed
76
my %opt = ();
77
getopts("ds:p:h",\%opt);
Robert Ricci's avatar
Robert Ricci committed
78

Mac Newbold's avatar
Mac Newbold committed
79 80 81 82 83 84
if ($opt{h}) {
    exit &usage;
}
if (@ARGV) {
    exit &usage;
}
Robert Ricci's avatar
Robert Ricci committed
85

86
my ($server,$port,$debug);
Mac Newbold's avatar
Mac Newbold committed
87 88 89 90 91 92 93 94 95 96 97 98 99
if ($opt{s}) {
    $server = $opt{s};
} else {
    $server = $BOSSNODE;
}
if ($opt{p}) {
    $port = $opt{p};
}
if ($opt{d}) {
    $debug = 1;
} else {
    $debug = 0;
}
Robert Ricci's avatar
Robert Ricci committed
100

101 102 103 104 105 106 107 108
# 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;
109
my $TB_OSID_MBKERNEL = TB_OSID_MBKERNEL;
110

111
# Set up some notification throttling
Mac Newbold's avatar
Mac Newbold committed
112
my $mailgap = 15;		# in seconds
113 114 115
my $lastmail = time() - $mailgap + 2; # Send a digest of startup msgs after 2s.
my %msgs = ();

Mac Newbold's avatar
Mac Newbold committed
116
my $pidfile;
117
if ( $TB eq $REALTB ) {
Mac Newbold's avatar
Mac Newbold committed
118 119
    $pidfile = "/var/run/stated.pid";
} else {
120
    $pidfile = "$TB/locks/stated.pid";
Mac Newbold's avatar
Mac Newbold committed
121
}
Mac Newbold's avatar
Mac Newbold committed
122 123
debug("Using pidfile $pidfile\n");
if (-e $pidfile) {
Mac Newbold's avatar
Mac Newbold committed
124 125 126 127 128 129 130 131 132 133 134
    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");
Mac Newbold's avatar
Mac Newbold committed
135
}
Robert Ricci's avatar
Robert Ricci committed
136
# Background
137
if (!$debug) {
Mac Newbold's avatar
Mac Newbold committed
138 139 140 141
    # We use syslog, so redirect the output to nothing
    if (TBBackGround("/dev/null")) {
	exit(0);
    }
Robert Ricci's avatar
Robert Ricci committed
142
}
Mac Newbold's avatar
Mac Newbold committed
143 144
# set up syslog
openlog("stated","pid","user");
Mac Newbold's avatar
Mac Newbold committed
145 146 147 148 149 150
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
my $lockfile=$pidfile;
Robert Ricci's avatar
Robert Ricci committed
151

152 153 154
# Change my $0 so that it is easier to see in a ps/top
$0 = "$0";

Robert Ricci's avatar
Robert Ricci committed
155
my $URL = "elvin://$server";
Mac Newbold's avatar
Mac Newbold committed
156 157 158
if ($port) {
    $URL .= ":$port";
}
Robert Ricci's avatar
Robert Ricci committed
159 160 161

# 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
162 163 164
if (!$handle) {
    fatal("Unable to register with event system\n");
}
Robert Ricci's avatar
Robert Ricci committed
165 166

my $tuple = address_tuple_alloc();
Mac Newbold's avatar
Mac Newbold committed
167 168 169
if (!$tuple) {
    fatal("Could not allocate an address tuple\n");
}
Robert Ricci's avatar
Robert Ricci committed
170

171 172
%$tuple = ( objtype => join(",",$TBNODESTATE,$TBNODEOPMODE,$TBCONTROL) );

Robert Ricci's avatar
Robert Ricci committed
173
if (!event_subscribe($handle,\&handleEvent,$tuple)) {
Mac Newbold's avatar
Mac Newbold committed
174
    fatal("Could not subscribe to events\n");
Robert Ricci's avatar
Robert Ricci committed
175 176 177 178
}

# Read in the pre-existing node states, and timeout and valid transition
# information from the database
179 180 181 182 183
my %nodes     = readStates();
my %timeouts  = getTimeouts();
my %valid     = getValid();
my %modeTrans = getModeTrans();
my %triggers  = getTriggers();
Robert Ricci's avatar
Robert Ricci committed
184 185 186 187 188 189 190

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

Mac Newbold's avatar
Mac Newbold committed
193
# Set up other signals.
194 195 196
$SIG{USR1} = \&restart;
$SIG{USR2} = \&cleanup;
$SIG{INT}  = \&cleanup;
197 198 199 200
$SIG{QUIT} = \&cleanup;
$SIG{ABRT} = \&cleanup;
$SIG{TERM} = \&cleanup;
$SIG{KILL} = \&cleanup;
Robert Ricci's avatar
Robert Ricci committed
201

202 203 204 205 206 207 208 209 210 211 212 213 214
# Track if I handled an event or not
my $event_count = 0;

notify("Stated starting up\n");

sub process_event_queue() {
    $event_count=0;
    my $lastcount=-1;
    while ($event_count != $lastcount) {
	$lastcount = $event_count;
	event_poll($handle);
    }
    if ($event_count > 0) {
Mac Newbold's avatar
Mac Newbold committed
215
	debug("Handled $event_count event(s).\n");
216 217
    }
}
Robert Ricci's avatar
Robert Ricci committed
218

219
# Now, we just poll for events, and watch for timeouts
Robert Ricci's avatar
Robert Ricci committed
220
while (1) {
Mac Newbold's avatar
Mac Newbold committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234
    process_event_queue;
    my $now = time();
    #
    # Look for nodes that have passed their timeout
    #
    while (my ($node, $value) = each %nodes) {
	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}};
Robert Ricci's avatar
Robert Ricci committed
235
	}
Mac Newbold's avatar
Mac Newbold committed
236 237 238 239 240
	if ((!$notified) && $time && $timeout && 
	    $timeout!= $TBNOTIMEOUT && (($time + $timeout) < $now)) {
	    handleCtrlEvent($node,$TBTIMEOUT);
	    $value->{notified} = 1;
		
Robert Ricci's avatar
Robert Ricci committed
241
	}
Mac Newbold's avatar
Mac Newbold committed
242
    }
Robert Ricci's avatar
Robert Ricci committed
243

Mac Newbold's avatar
Mac Newbold committed
244 245 246 247
    if ($do_reload || ($now - $last_reload > $reload_time)) {
	reload();
	$do_reload = 0;
    }
Mac Newbold's avatar
Mac Newbold committed
248

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

Mac Newbold's avatar
Mac Newbold committed
252
    sleep(1);
Robert Ricci's avatar
Robert Ricci committed
253 254
}

Mac Newbold's avatar
Mac Newbold committed
255 256
exit(0);

Robert Ricci's avatar
Robert Ricci committed
257
# Read the current states of nodes from the database
258
sub readStates(;@) {
Mac Newbold's avatar
Mac Newbold committed
259 260 261 262 263 264 265 266
    my %oldnodes = @_;

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

Mac Newbold's avatar
Mac Newbold committed
268 269 270 271 272 273 274 275
    #debug("readStates called\n");
    my $result = DBQueryFatal("SELECT node_id, eventstate, " .
			      "state_timestamp, op_mode, " .
			      "op_mode_timestamp FROM nodes");

    my %nodes;
    while (my ($node_id, $state, $timestamp, $mode, $mode_timestamp)
	   = $result->fetchrow()) {
276
	#
Mac Newbold's avatar
Mac Newbold committed
277 278 279 280
	# 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.)
281
	#
Mac Newbold's avatar
Mac Newbold committed
282 283 284 285 286 287 288 289 290 291
	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};
	} else { 
	    $nodes{$node_id}{state}          = $state;
	    $nodes{$node_id}{timestamp}      = $timestamp;
	    $nodes{$node_id}{mode}           = $mode;
	    $nodes{$node_id}{mode_timestamp} = $mode_timestamp;
292
	}
Mac Newbold's avatar
Mac Newbold committed
293 294
    }
    return %nodes;
Robert Ricci's avatar
Robert Ricci committed
295 296 297 298 299 300
}

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

Mac Newbold's avatar
Mac Newbold committed
305 306 307 308 309
    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
310 311 312 313 314 315
}

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

Mac Newbold's avatar
Mac Newbold committed
320 321 322 323 324
    my %valid;
    while (my ($mode,$state1, $state2) = $result->fetchrow()) {
	$valid{$mode}{$state1}{$state2} = 1;
    }
    return %valid;
Robert Ricci's avatar
Robert Ricci committed
325 326
}

327 328 329 330
#
# Read the list of valid mode transitions from the database
#
sub getModeTrans() {
Mac Newbold's avatar
Mac Newbold committed
331 332 333 334 335 336 337 338 339 340 341 342 343
    #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;
344
	}
Mac Newbold's avatar
Mac Newbold committed
345 346
    }
    return %modeTrans;
347 348 349 350 351 352
}

#
# Read the list of states which trigger an action
#
sub getTriggers() {
Mac Newbold's avatar
Mac Newbold committed
353 354 355 356 357 358 359 360 361
    #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;
362 363
}

Robert Ricci's avatar
Robert Ricci committed
364 365 366 367
#
# Gets called for every event that we recieve
#
sub handleEvent($$$) {
Mac Newbold's avatar
Mac Newbold committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    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++;
    debug("Got an event: ($objtype,$objname,$eventtype)\n");

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

Mac Newbold's avatar
Mac Newbold committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  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;
	};
400

Mac Newbold's avatar
Mac Newbold committed
401
    }
402 403 404 405 406

}

sub stateTransition($$) {

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

409 410 411 412 413 414 415 416
    # 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();
417
	if ($nodes{$node}) {
418 419
	    $oldstate = $nodes{$node}{state};
	    $mode = $nodes{$node}{mode};
Robert Ricci's avatar
Robert Ricci committed
420
	} else {
421
	    notify("Got an event for a node ($node) I don't know about\n");
Robert Ricci's avatar
Robert Ricci committed
422
	}
423 424 425 426
    }
    if ($oldstate && $mode && $valid{$mode} && $valid{$mode}{$oldstate} &&
	!$valid{$mode}{$oldstate}{$newstate}) {
	notify("Invalid transition for node $node from $mode/$oldstate " .
427
	       "to $newstate\n");
428
    }
Robert Ricci's avatar
Robert Ricci committed
429

430 431 432 433
    my $now = time();
    $nodes{$node}{state}     = $newstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{notified}  = 0;
434

435 436 437
    info("$node: $mode/$oldstate => $mode/$newstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$newstate', " .
		 "state_timestamp='$now' WHERE node_id='$node'");
438

439 440
    # Check if this is TBDB_NODESTATE_BOOTING , which has actions
    if ($newstate eq TBDB_NODESTATE_BOOTING) {
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	# 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
459
	my $osid = TBBootWhat($node,$debug);
460 461
	my $os_op_mode = os_opmode($osid);
	info("$node: Current OS is '$osid', OS mode is '$os_op_mode'\n");
462
	DBQueryFatal("UPDATE nodes SET osid='$osid' WHERE node_id='$node'");
463
	if ($os_op_mode ne $mode) {
464 465
	    my $str = "Node $node is running OS '$osid' but in mode '$mode' ".
	      "instead of mode '$os_op_mode'!\n";
466 467 468
	    # 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") {
469 470 471 472 473 474 475 476 477
		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);
	}
478 479
	checkGenISUP($node);
    }
480

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    # 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;
	    };
500
	    notify("Unknown trigger '$trig' for $node in $mode/$newstate!\n");
501 502
	}
    }
503

504 505 506 507 508 509 510 511
    # 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
512 513 514
	} else {
	    debug("No next mode.\n");
	}
515 516
    }
}
517

518
sub opModeTransition($$;$) {
Mac Newbold's avatar
Mac Newbold committed
519

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

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    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");
	}
    }
539 540
    if (defined($modeTrans{"$mode:$oldstate"}) || $force) {
	if ($force) {
541 542
	    $nextstate=$trans{$newmode};
	} else {
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
	    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");
	    }
558 559
	}
    } else {
560
	notify("Invalid mode transition for $node from $mode/$oldstate: ".
561 562
	       "Not a valid mode transition state!\n");
    }
Mac Newbold's avatar
Mac Newbold committed
563 564 565 566
    if (!$nextstate) {
	$nextstate=$oldstate;
    }
    
567 568 569 570 571 572
    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
573
    
574 575 576 577 578 579 580 581 582
    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) = @_;
Mac Newbold's avatar
Mac Newbold committed
583
    
584
    info("CtrlEvent: $node, $event\n");
Mac Newbold's avatar
Mac Newbold committed
585
    
586 587
    foreach ($event) {
	/^$TBRESET$/ && do {
Mac Newbold's avatar
Mac Newbold committed
588 589 590
	    my $result = DBQueryFatal("SELECT pxe_boot_path, def_boot_osid ".
				      "FROM nodes where node_id='$node'");
	    my ($pxepath,$osid) = $result->fetchrow();
Mac Newbold's avatar
Mac Newbold committed
591
	    
592 593 594 595
	    # 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.
Mac Newbold's avatar
Mac Newbold committed
596
	    
597 598
	    $cmd = "$osselect $osid $node";
	    system($cmd) and
Mac Newbold's avatar
Mac Newbold committed
599 600 601
	      notify("$node/$event: Couldn't clear next_boot_*\n".
		     "\tcmd=$cmd\n\t*** $!\n");
	    
602
	    $pxepath = "-p ".$pxepath;
Mac Newbold's avatar
Mac Newbold committed
603 604 605 606
	    if ($pxepath eq "-p ") {
		$pxepath="PXEBOOT";
	    }
	    ;
Mac Newbold's avatar
Mac Newbold committed
607
	    my $cmd = "$osselect -m $pxepath $node";
608
	    system($cmd) and
Mac Newbold's avatar
Mac Newbold committed
609 610 611
	      notify("$node/$event: Couldn't clear next_pxe_boot_path\n".
		     "\tcmd=$cmd\n\t*** $!\n");
	    
Mac Newbold's avatar
Mac Newbold committed
612
	    info("Performed RESET for $node to $osid/$pxepath\n");
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
	    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." : "").
638
		   "\n");
639 640
	    next;
	};
641
	notify("$node: Unknown CtrlEvent: $event\n");
642 643
    }
}
Robert Ricci's avatar
Robert Ricci committed
644

645 646 647 648
#
# Check if we need to generate an ISUP
#
sub checkGenISUP($) {
Mac Newbold's avatar
Mac Newbold committed
649 650 651 652 653 654 655 656 657 658
    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
659

Mac Newbold's avatar
Mac Newbold committed
660 661 662 663 664 665
    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
666

Mac Newbold's avatar
Mac Newbold committed
667 668 669 670 671
    # 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
672

Mac Newbold's avatar
Mac Newbold committed
673 674 675 676 677 678
    # 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;
679
    }
Mac Newbold's avatar
Mac Newbold committed
680

Mac Newbold's avatar
Mac Newbold committed
681 682 683 684 685 686 687 688
    # 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
689 690
}

691 692 693 694
# 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
695
    my ($node) = @_;
696

Mac Newbold's avatar
Mac Newbold committed
697 698 699 700 701 702 703 704
    # 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'");
705

Mac Newbold's avatar
Mac Newbold committed
706 707 708 709
    if (!$result->num_rows()) {
	notify("Got an event for a node ($node) I don't know about\n");
	return 0;
    }
710

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

Mac Newbold's avatar
Mac Newbold committed
713 714 715
    # XXX: It's hokey to hardcode tbdb here, but....

    #debug("checkDBRedirect: $node => $testdb (I'm $TBDBNAME)\n");
716
    if ((!$testdb && ($TBDBNAME eq $REALTBDBNAME)) ||
Mac Newbold's avatar
Mac Newbold committed
717 718 719 720 721
	($testdb && ($testdb eq $TBDBNAME))) {
	return 1;
    } else {
	return 0;
    }
722 723
}

Robert Ricci's avatar
Robert Ricci committed
724 725
# Reload state from the database
sub reload() {
Mac Newbold's avatar
Mac Newbold committed
726 727 728 729 730 731 732
    debug("Reloading state from database\n");
    $last_reload = time();
    %nodes     = readStates(%nodes);
    %timeouts  = getTimeouts();
    %valid     = getValid();
    %modeTrans = getModeTrans();
    %triggers  = getTriggers();
Robert Ricci's avatar
Robert Ricci committed
733 734
}

735 736
sub os_opmode() {
    my $osid = shift || "";
Mac Newbold's avatar
Mac Newbold committed
737 738 739
    if ($osid eq $TB_OSID_MBKERNEL) {
	return "MINIMAL";
    }
740 741
    my $cmd = "select op_mode from os_info where osid='$osid';";
    my $q = DBQueryFatal($cmd);
Mac Newbold's avatar
Mac Newbold committed
742 743 744
    if ($q->numrows() < 1) {
	return "";
    }
745 746 747
    my @r = $q->fetchrow_array();
    my $opmode=$r[0];
    debug("OpMode for '$osid' is '$opmode'\n");
Mac Newbold's avatar
Mac Newbold committed
748 749 750
    if (defined($opmode) && $opmode ne "") {
	return $opmode;
    }
751 752
    return "";
}
Mac Newbold's avatar
Mac Newbold committed
753

Robert Ricci's avatar
Robert Ricci committed
754
sub debug(@) {
Mac Newbold's avatar
Mac Newbold committed
755 756 757
    if ($debug) {
	print @_;
    }
Mac Newbold's avatar
Mac Newbold committed
758 759 760
}

sub fatal($) {
Mac Newbold's avatar
Mac Newbold committed
761 762 763
    my $msg = shift;
    notify($msg);
    die($msg);
Robert Ricci's avatar
Robert Ricci committed
764 765
}

Mac Newbold's avatar
Mac Newbold committed
766
sub showqueue() {
Mac Newbold's avatar
Mac Newbold committed
767 768 769 770 771 772 773 774 775 776
    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
777 778 779
}

sub notify($;$) {
Mac Newbold's avatar
Mac Newbold committed
780 781 782 783
    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);
Mac Newbold's avatar
Mac Newbold committed
784
    showqueue();
Mac Newbold's avatar
Mac Newbold committed
785 786 787 788 789 790
    if (!$checkonly) {
	info($message);
	# Queue up the message
	# (The queue is a hash of lists of timestamps, keyed by message
	if (defined($msgs{$message})) {
	    push(@{$msgs{$message}},$tstamp);
Mac Newbold's avatar
Mac Newbold committed
791
	} else {
Mac Newbold's avatar
Mac Newbold committed
792
	    $msgs{$message} = [$tstamp];
Mac Newbold's avatar
Mac Newbold committed
793
	}
Mac Newbold's avatar
Mac Newbold committed
794
	showqueue();
Mac Newbold's avatar
Mac Newbold committed
795
    }
Mac Newbold's avatar
Mac Newbold committed
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    my $now = time;
    if ($now - $lastmail >= $mailgap) {
	if ((keys %msgs)>0) {
	    debug("SENDING MAILQUEUE\n"."(now $now, lastmail $lastmail, ".
		  ($now-$lastmail).">=$mailgap)\n");
	    my $mailbody="";
	    my $sep = '-'x5;
	    # We're okay to send. Make a digest of all the queued messages.
	    foreach my $msg (sort keys %msgs) {
		my @tlist = @{$msgs{$msg}};
		my $count = 0+@tlist;
		$mailbody .= "\n$msg\n";
		if ($count > 1) {
		    my $first = shift @tlist;
		    my $last = pop @tlist;
		    $mailbody .= "($count copies from $first to $last)\n";
		} else {
		    $mailbody .= "($count copy at $tlist[0])\n";
		}
		$mailbody .= "$sep\n";
	    }
	    # Now reset the mail queue
	    %msgs = ();
	    showqueue();
	    $lastmail = time;
	    if (!$debug) {
		SENDMAIL("Stated List <".$TBOPS.">",
			 "Stated Messsage",$mailbody,
			 "Stated Daemon <".$TBOPS.">");
	    } else {
		debug("notify: Not sending mail in debug mode\n");
		debug("MAIL CONTAINS:\n".$mailbody."\n");
	    }
	}
    } # else do nothing, not time yet
831 832
}

833
sub announce($) {
Mac Newbold's avatar
Mac Newbold committed
834 835 836 837 838 839 840 841 842 843 844 845
    my $message = shift;
    my $tstamp=strftime("%b %e %H:%M:%S",localtime);
    notify("ANNOUCEMENT: ".$message."\n\n(Sent to $REALTBOPS)\n");
    $mailbody = "\n$message\n\n$tstamp\n";
    if (!$debug) {
	SENDMAIL($REALTBOPS,
		 "Stated Messsage",$mailbody,
		 "Stated Daemon <".$TBOPS.">");
    } else {
	debug("announce: Not sending mail in debug mode\n");
	debug("MAIL CONTAINS:\n".$mailbody."\n");
    }
846 847
}

848
sub info($;$) {
849
    my $message = shift;
850
    my $notice = shift || 0;
Mac Newbold's avatar
Mac Newbold committed
851 852
    # Use syslog
    my $prio="info";
Mac Newbold's avatar
Mac Newbold committed
853 854 855
    if ($notice) {
	$prio = "notice";
    }
Mac Newbold's avatar
Mac Newbold committed
856
    if ($debug) {
Mac Newbold's avatar
Mac Newbold committed
857 858 859 860
	# Print out log entries like this:
	# Sep 20 09:36:00 stated[238]: Reloading state from database
	print strftime("%b %e %H:%M:%S",localtime)." stated[$$]: $message";
	$message = "DEBUG: ".$message;
861
    }
Mac Newbold's avatar
Mac Newbold committed
862
    syslog($prio,$message) || notify("syslog failed: $? $!\n");
863 864 865 866
}

# This gets called if we catch a signal USR1
sub restart {
Mac Newbold's avatar
Mac Newbold committed
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
    info("SIGUSER1 received: Performing final event poll before restarting\n");
    process_event_queue;
    my $params = join(" ",@args);
    my $prog = "";
    # If we're started from an abosolute path, use that.
    if ($0 =~ /^\//) {
	$prog = $0;
    } else {
	$prog = "$TB/sbin/stated";
    }
    info("Restarting from '$prog".($params ne "" ? " $params" : "")."'\n");
    if ($handle && event_unregister($handle) == 0) {
	warn "Unable to unregister with event system\n";
    }
    if (defined($lockfile) && $lockfile ne "") {
	unlink $lockfile;
    }
    if (!defined(sigprocmask(SIG_UNBLOCK, POSIX::SigSet->new(SIGUSR1,SIGHUP)))) {
	notify("sigprocmask: sig unblock failed! $?, $!\n");
	die("\n");
    }
    announce("Stated restarted\n");
    exec("$prog $params") or 
      do {
	  my $msg = "Couldn't restart stated! cmd='$prog $params'\n".
	    "Error: ($?) $!\n";
	  announce($msg);
	  die($msg);
      };
Robert Ricci's avatar
Robert Ricci committed
896 897
}

898 899
# This gets called if we catch a signal (TERM, etc.)
sub cleanup {
Mac Newbold's avatar
Mac Newbold committed
900 901 902
    notify("Signal received, exiting\n");
    # now do the normal exit stuff in END {}
    exit(0);
903 904
}

Robert Ricci's avatar
Robert Ricci committed
905 906
# This gets called if we die of 'natural causes' (exit, die, etc.)
END {
Mac Newbold's avatar
Mac Newbold committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
    my $stat = $?;
    if (defined($lockfile) && $lockfile ne "") {
	unlink $lockfile;
	announce("Stated exiting, cleaning up\n");
    } else {
	# Must be a child
	info("Stated child exiting\n");
    }
    # clean up Syslog
    closelog();
    if ($handle) {
	if (event_unregister($handle) == 0) {
	    die "Unable to unregister with event system\n";
	}
    }
    # Restore $? in case one of the things I called changed it
    $? = $stat;
Robert Ricci's avatar
Robert Ricci committed
924
}
925