stated.in 24.7 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@";
Robert Ricci's avatar
Robert Ricci committed
23
my $BOSSNODE = "@BOSSNODE@";
24
my $TBOPS = '@TBSTATEDEMAIL@';
25
my $TBDBNAME = "@TBDBNAME@";
26
my $osselect = "$TB/bin/os_select";
Robert Ricci's avatar
Robert Ricci committed
27 28 29 30 31 32 33

$| = 1;

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

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

# Process command-line arguments

sub usage {
	print << "END";
53 54 55
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
56 57
-s server       Use specified server, instead of this site's bossnode
-p port	        Use specified port
58
Send SIGHUP to reload database state, or SIGUSR1 to restart completely.
Robert Ricci's avatar
Robert Ricci committed
59 60 61
END
}

62
my @args = @ARGV; # save a copy for restart before we mess with them.
Robert Ricci's avatar
Robert Ricci committed
63
my %opt = ();
64
getopts("ds:p:h",\%opt);
Robert Ricci's avatar
Robert Ricci committed
65 66 67 68

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

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

74 75 76 77 78 79 80 81 82
# 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;

Mac Newbold's avatar
Mac Newbold committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
my $pidfile;
$pidfile = "$TB/locks/stated.pid";
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");
}
Robert Ricci's avatar
Robert Ricci committed
99
# Background
100 101 102
if (!$debug) {
  # We use syslog, so redirect the output to nothing
  if (TBBackGround("/dev/null")) { exit(0); }
Robert Ricci's avatar
Robert Ricci committed
103
}
Mac Newbold's avatar
Mac Newbold committed
104 105
# set up syslog
openlog("stated","pid","user");
Mac Newbold's avatar
Mac Newbold committed
106 107 108 109 110 111
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
112

113 114 115
# Change my $0 so that it is easier to see in a ps/top
$0 = "$0";

Robert Ricci's avatar
Robert Ricci committed
116 117 118 119 120
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);
Mac Newbold's avatar
Mac Newbold committed
121
if (!$handle) { fatal("Unable to register with event system\n"); }
Robert Ricci's avatar
Robert Ricci committed
122 123

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

126 127
%$tuple = ( objtype => join(",",$TBNODESTATE,$TBNODEOPMODE,$TBCONTROL) );

Robert Ricci's avatar
Robert Ricci committed
128
if (!event_subscribe($handle,\&handleEvent,$tuple)) {
Mac Newbold's avatar
Mac Newbold committed
129
	fatal("Could not subscribe to events\n");
Robert Ricci's avatar
Robert Ricci committed
130 131 132 133
}

# Read in the pre-existing node states, and timeout and valid transition
# information from the database
134 135 136 137 138
my %nodes     = readStates();
my %timeouts  = getTimeouts();
my %valid     = getValid();
my %modeTrans = getModeTrans();
my %triggers  = getTriggers();
Robert Ricci's avatar
Robert Ricci committed
139 140 141 142

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

Mac Newbold's avatar
Mac Newbold committed
143 144 145 146 147 148
# Set when I've got a child pinging a node for me.
my $have_children = 0;

# Keep track of which pid was pinging which node.
my %children= (); # $children($child} = "pcXXX";

Robert Ricci's avatar
Robert Ricci committed
149 150 151
# 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.
152 153
$SIG{HUP}  = sub { info("SIGHUP - Reloading DB state\n"); $do_reload = 1; };

Mac Newbold's avatar
Mac Newbold committed
154
# Set up other signals.
155 156 157
$SIG{USR1} = \&restart;
$SIG{USR2} = \&cleanup;
$SIG{INT}  = \&cleanup;
158 159 160 161
$SIG{QUIT} = \&cleanup;
$SIG{ABRT} = \&cleanup;
$SIG{TERM} = \&cleanup;
$SIG{KILL} = \&cleanup;
Robert Ricci's avatar
Robert Ricci committed
162

Mac Newbold's avatar
Mac Newbold committed
163
# Set up some notification throttling
164
my $mailgap = 15; # in seconds
165
my $lastmail = time - $mailgap + 2; # Send a digest of startup msgs after 2s.
Mac Newbold's avatar
Mac Newbold committed
166 167
my %msgs = ();

168
info("stated starting up\n");
Robert Ricci's avatar
Robert Ricci committed
169

170
# Now, we just poll for events, and watch for timeouts
Robert Ricci's avatar
Robert Ricci committed
171 172 173 174 175 176 177 178
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) {
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
	    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
194 195 196 197 198 199 200 201
	}

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

Mac Newbold's avatar
Mac Newbold committed
202 203 204 205 206 207 208 209
	if ($have_children) {
	  # Check for kids that have finished
	  handleChild();
	}

	# Send any messages in the queue if it is time
	notify("",1);

Robert Ricci's avatar
Robert Ricci committed
210 211 212 213
	$iterations++;
	sleep(1);
}

Mac Newbold's avatar
Mac Newbold committed
214 215
exit(0);

Robert Ricci's avatar
Robert Ricci committed
216
# Read the current states of nodes from the database
217 218 219
sub readStates(;@) {
    	my %oldnodes = @_;

220 221 222 223 224 225 226
	#
	# Guard against undefined variable warnings
	#
	if (! defined(%oldnodes)) {
		%oldnodes = ();
	}

227
	#debug("readStates called\n");
Robert Ricci's avatar
Robert Ricci committed
228
	my $result = DBQueryFatal("SELECT node_id, eventstate, " .
229 230
				  "state_timestamp, op_mode, " .
				  "op_mode_timestamp FROM nodes");
Robert Ricci's avatar
Robert Ricci committed
231 232

	my %nodes;
233 234
	while (my ($node_id, $state, $timestamp, $mode, $mode_timestamp)
			= $result->fetchrow()) {
235 236 237 238 239 240
	    	#
		# 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.)
		#
241 242
		if ($oldnodes{$node_id} && $state && $timestamp &&
		   ($oldnodes{$node_id}{state} eq $state) &&
243
		   ($oldnodes{$node_id}{mode} eq $mode) &&
244
		   ($oldnodes{$node_id}{timestamp} == $timestamp)) {
245 246
		       $nodes{$node_id} = $oldnodes{$node_id};
		} else { 
247 248 249 250
		    $nodes{$node_id}{state}          = $state;
		    $nodes{$node_id}{timestamp}      = $timestamp;
		    $nodes{$node_id}{mode}           = $mode;
		    $nodes{$node_id}{mode_timestamp} = $mode_timestamp;
251
		}
Robert Ricci's avatar
Robert Ricci committed
252 253 254 255 256 257 258 259
	}
	return %nodes;
}

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

	my %timeouts;
265 266
	while (my ($op_mode, $state, $timeout, $action) = $result->fetchrow()) {
		$timeouts{$op_mode}{$state} = [ $timeout, $action ];
Robert Ricci's avatar
Robert Ricci committed
267 268 269 270 271 272 273 274
	}
	return %timeouts;
}

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

	my %valid;
280 281
	while (my ($mode,$state1, $state2) = $result->fetchrow()) {
		$valid{$mode}{$state1}{$state2} = 1;
Robert Ricci's avatar
Robert Ricci committed
282 283 284 285
	}
	return %valid;
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
#
# 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
323 324 325 326 327
#
# Gets called for every event that we recieve
#
sub handleEvent($$$) {
	my ($handle,$notification,$data) = @_;
328
	my $objtype = event_notification_get_objtype($handle,$notification);
Robert Ricci's avatar
Robert Ricci committed
329 330 331
	my $objname = event_notification_get_objname($handle,$notification);
	my $eventtype = event_notification_get_eventtype($handle,$notification);

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

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

342 343
	SWITCH: for ($objtype) {

344
	    (/$TBNODESTATE/) && do {
345 346 347
		stateTransition($objname,$eventtype);
		last;
	    };
348
	    (/$TBNODEOPMODE/) && do {
349
		opModeTransition($objname,$eventtype);
350 351 352 353
		notify("Use of deprecated event TBNODEOPMODE:\n".
		       "$objname->$eventtype\n");
		last;
	    };
354
	    (/$TBCONTROL/) && do {
355
		handleCtrlEvent($objname,$eventtype);
356 357 358 359 360 361 362 363 364
		last;
	    };

	}

}

sub stateTransition($$) {

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

367 368 369 370 371 372 373 374
    # 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();
375
	if ($nodes{$node}) {
376 377
	    $oldstate = $nodes{$node}{state};
	    $mode = $nodes{$node}{mode};
Robert Ricci's avatar
Robert Ricci committed
378
	} else {
379
	    notify("Got an event for a node ($node) I don't know about\n");
Robert Ricci's avatar
Robert Ricci committed
380
	}
381 382 383 384
    }
    if ($oldstate && $mode && $valid{$mode} && $valid{$mode}{$oldstate} &&
	!$valid{$mode}{$oldstate}{$newstate}) {
	notify("Invalid transition for node $node from $mode/$oldstate " .
Mac Newbold's avatar
Mac Newbold committed
385
	       "to $newstate\n".`/usr/testbed/sbin/inuse | grep $node\\  `);
386
    }
Robert Ricci's avatar
Robert Ricci committed
387

388 389 390 391
    my $now = time();
    $nodes{$node}{state}     = $newstate;
    $nodes{$node}{timestamp} = $now;
    $nodes{$node}{notified}  = 0;
392

393 394 395
    info("$node: $mode/$oldstate => $mode/$newstate\n");
    DBQueryFatal("UPDATE nodes SET eventstate='$newstate', " .
		 "state_timestamp='$now' WHERE node_id='$node'");
396

397 398 399 400 401
    # 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'");
402

403 404
	checkGenISUP($node);
    }
405

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    # 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");
	}
    }
428

429 430 431 432 433 434 435 436 437 438 439
    # 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"); }
    }
}
440

441
sub opModeTransition($$) {
Mac Newbold's avatar
Mac Newbold committed
442

443
    my ($node,$newmode) = @_;
Mac Newbold's avatar
Mac Newbold committed
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
    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;
Mac Newbold's avatar
Mac Newbold committed
487

488 489 490 491 492 493 494 495 496 497 498 499 500 501
    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 {
Mac Newbold's avatar
Mac Newbold committed
502 503 504 505
	    my $result = DBQueryFatal("SELECT pxe_boot_path, def_boot_osid ".
				      "FROM nodes where node_id='$node'");
	    my ($pxepath,$osid) = $result->fetchrow();

506 507 508 509 510 511 512 513 514 515
	    # 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.

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

516 517
	    $pxepath = "-p ".$pxepath;
	    if ($pxepath eq "-p ") { $pxepath="PXEBOOT"; };
Mac Newbold's avatar
Mac Newbold committed
518
	    my $cmd = "$osselect -m $pxepath $node";
519 520 521
	    system($cmd) and
		notify("$node/$event: Couldn't clear next_pxe_boot_path\n".
		       "\tcmd=$cmd\n\t*** $!\n");
522

Mac Newbold's avatar
Mac Newbold committed
523
	    info("Performed RESET for $node to $osid/$pxepath\n");
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
	    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." : "").
549
		   "\n".`/home/newbold/z/bin/statetime | grep '$node\t'`);
550 551
	    next;
	};
552
	notify("$node: Unknown CtrlEvent: $event\n");
553 554
    }
}
Robert Ricci's avatar
Robert Ricci committed
555

556 557 558 559
#
# Check if we need to generate an ISUP
#
sub checkGenISUP($) {
Mac Newbold's avatar
Mac Newbold committed
560 561 562 563 564 565 566 567 568 569
  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();
  }
Robert Ricci's avatar
Robert Ricci committed
570

Mac Newbold's avatar
Mac Newbold committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
  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
  }

  # If os will send ISUP on its own, do nothing here.
  if ($can{"isup"}) {
    debug("$node: Will send own ISUP\n"); return 0;
  }

  # 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\n");
    my $pid = fork();
    if ($pid) {
      $children{$pid}= $node;
      $have_children = 1;
      # don't wait, return and go on with life
      return 0;
    } else {
      info("Forked process $$ to ping $node\n");
595
      $lockfile = ""; # Don't clean up my pidfile, since I'm a child
Mac Newbold's avatar
Mac Newbold committed
596 597 598 599 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 631 632 633 634 635 636 637 638

      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(4);
      };

      alarm $maxtime;

      my $n=0;
      while ( $n <= ($maxtime/$wait)) {
	my $status=system("/sbin/ping -c 1 -t 1 $node > /dev/null");
	my $rv = $status >> 8;
	my $sig = $status & 127;
	debug("checkGenISUP: ping returned $status ($rv / $sig)\n");
	if ($rv==0) {
	  # we got a response
	  info("$node: ping response received... sending ISUP\n");
	  # We want to send an ISUP event for the node. But we
	  # can't just call stateTransition, because that will
	  # only make the change happen in our state, not the real
	  # stated that we forked from. We do this by exit(0)
	  # and the handleChild function will pick it up and
	  # send the ISUP for us.
	  exit(0);
	} elsif ($rv==2) {
	  # no response
	  debug("$node: 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(2);
	} else {
	  notify("$node: checkGenISUP ping returned $rv!\n");
	  exit(3);
639
	}
Mac Newbold's avatar
Mac Newbold committed
640 641 642 643 644 645
	sleep $wait;
	$n+=1;
      }
      notify("$node: Sent $n pings in ".($n*$wait)." seconds ".
	     "with no response.\n");
      exit(1);
646
    }
Mac Newbold's avatar
Mac Newbold committed
647 648 649 650 651 652
  }
  # 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
653 654
}

655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
# 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....
	#
682 683

	#debug("checkDBRedirect: $node => $testdb (I'm $TBDBNAME)\n");
684 685 686 687 688 689 690 691
	if ((!$testdb && ($TBDBNAME eq "tbdb")) ||
	    ($testdb && ($testdb eq $TBDBNAME))) {
		return 1;
	} else {
		return 0;
	}
}

Robert Ricci's avatar
Robert Ricci committed
692 693
# Reload state from the database
sub reload() {
Mac Newbold's avatar
Mac Newbold committed
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
  info("Reloading state from database\n");
  %nodes     = readStates(%nodes);
  %timeouts  = getTimeouts();
  %valid     = getValid();
  %modeTrans = getModeTrans();
  %triggers  = getTriggers();
}

# This gets called to check for forked pids that have finished.  Right
# now we only fork in checkGenISUP to ping nodes.
sub handleChild() {
  my $child = wait;
  if ($child==-1) { return 0; }
  my $node = $children{$child};
  if (!defined($node)) { $node=""; }
  my $stat = $?;
  my $rv = $stat >> 8;
  my $sig = $stat & 127;
  debug("Child = $child, I am $$, children are: (".
	join(",",sort keys %children).")\n");
  if (($node ne "") && ($child!=-1) && ($child!=$$)) {
    info("handleChild: pid $child (node $node), exited $rv (sig $sig)\n");
    delete $children{$child};
    if (($sig == 0) && ($rv == 0)) {
      # Node is pingable, send isup
      info("handleChild: Sending ISUP for $node)\n");
      stateTransition($node, TBDB_NODESTATE_ISUP);
    } else {
      notify("handleChild: Caught a child that failed!\n".
	     "pid $child (node $node), exited $rv (sig $sig)\n");
    }
  }
  if (0+%children == 0) {
    debug("No more children now.\n");
    $have_children=0;
  }
  return 0;
Robert Ricci's avatar
Robert Ricci committed
731 732
}

Mac Newbold's avatar
Mac Newbold committed
733

Robert Ricci's avatar
Robert Ricci committed
734
sub debug(@) {
Mac Newbold's avatar
Mac Newbold committed
735 736 737 738 739 740 741
  if ($debug) { print @_; }
}

sub fatal($) {
  my $msg = shift;
  notify($msg);
  die($msg);
Robert Ricci's avatar
Robert Ricci committed
742 743
}

Mac Newbold's avatar
Mac Newbold committed
744 745 746 747 748 749 750 751 752 753 754
sub showqueue() {
  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");
  }
}

sub notify($;$) {
Mac Newbold's avatar
Mac Newbold committed
755
  my $message = shift;
Mac Newbold's avatar
Mac Newbold committed
756 757 758 759 760 761 762 763 764 765 766 767 768 769
  my $checkonly = shift || 0;
  # Use a timestamp, now that we're throttling mail
  my $tstamp=strftime("%b %e %H:%M:%S",localtime);
  showqueue();
  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);
    } else {
      $msgs{$message} = [$tstamp];
    }
    showqueue();
Mac Newbold's avatar
Mac Newbold committed
770
  }
Mac Newbold's avatar
Mac Newbold committed
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
  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.">",
		 "Node State Daemon 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
806 807
}

808
sub info($;$) {
809
    my $message = shift;
810
    my $notice = shift || 0;
Mac Newbold's avatar
Mac Newbold committed
811 812 813 814
    # Use syslog
    my $prio="info";
    if ($notice) { $prio = "notice"; }
    if ($debug) {
815 816 817
      # 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";
Mac Newbold's avatar
Mac Newbold committed
818
      $message = "DEBUG: ".$message;
819
    }
Mac Newbold's avatar
Mac Newbold committed
820
    syslog($prio,$message) || notify("syslog failed: $? $!\n");
821 822 823 824
}

# This gets called if we catch a signal USR1
sub restart {
Mac Newbold's avatar
Mac Newbold committed
825 826
  info("SIGUSER1 received: Performing final event poll before restarting\n");
  event_poll($handle);
827 828 829 830
  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"; }
Mac Newbold's avatar
Mac Newbold committed
831
  info("Restarting from '$prog".($params ne "" ? " $params" : "")."'\n");
832 833 834
  if ($handle && event_unregister($handle) == 0) {
    warn "Unable to unregister with event system\n";
  }
Mac Newbold's avatar
Mac Newbold committed
835
  if (defined($lockfile) && $lockfile ne "") { unlink $lockfile; }
836 837 838 839
  if (!defined(sigprocmask(SIG_UNBLOCK, POSIX::SigSet->new(SIGUSR1,SIGHUP)))) {
    notify("sigprocmask: sig unblock failed! $?, $!\n");
    die("\n");
  }
840
  notify("Stated restarted\n");
841 842 843 844 845 846 847
  exec("$prog $params") or 
    do {
      my $msg = "Couldn't restart stated! cmd='$prog $params'\n".
	"Error: ($?) $!\n";
      notify($msg);
      die($msg);
    };
Robert Ricci's avatar
Robert Ricci committed
848 849
}

850 851
# This gets called if we catch a signal (TERM, etc.)
sub cleanup {
852
  notify("Signal received, exiting\n");
853 854
  # now do the normal exit stuff in END {}
  exit(0);
855 856
}

Robert Ricci's avatar
Robert Ricci committed
857 858
# This gets called if we die of 'natural causes' (exit, die, etc.)
END {
859
  notify("Stated exiting, cleaning up\n");
Mac Newbold's avatar
Mac Newbold committed
860
  if (defined($lockfile) && $lockfile ne "") { unlink $lockfile; }
Mac Newbold's avatar
Mac Newbold committed
861 862
  # clean up Syslog
  closelog();
863 864 865
  if ($handle) {
    if (event_unregister($handle) == 0) {
      die "Unable to unregister with event system\n";
866
    }
867
  }
Robert Ricci's avatar
Robert Ricci committed
868
}
869