stated.in 9.82 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 25
#
# 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@";
my $TBOPS = "@TBOPSEMAIL@";
26
my $TBDBNAME = "@TBDBNAME@";
Robert Ricci's avatar
Robert Ricci committed
27 28 29 30 31 32 33 34 35

$| = 1;

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

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

#
# Process command-line arguments
#

sub usage {
	print << "END";
51
Usage: $0 [-d] [-s server] [-p port] [-f] [-h]
Robert Ricci's avatar
Robert Ricci committed
52 53 54
-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
55
-f              Stay in the foreground, rather than forking
Robert Ricci's avatar
Robert Ricci committed
56 57 58 59 60
-h              This message
END
}

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

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

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

#
# Background
#
75 76 77
my $logname = "@prefix@/log/stated.log";
if (!$debug && !$nofork) {
	if (TBBackGround($logname)) {
Robert Ricci's avatar
Robert Ricci committed
78 79
		exit(0);
	}
80 81 82 83 84 85 86 87
} 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
88 89 90 91 92 93 94 95 96 97 98 99 100 101
}

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"; }

102 103 104 105 106 107
#
# Unfortunately, we can't subscribe to multiple objtypes - so, we subscribe
# to all events to $BOSSNODE, and throw away notificattions whose objtypes
# do not match the ones we care about.
#
%$tuple = ( host => $BOSSNODE );
Robert Ricci's avatar
Robert Ricci committed
108 109

if (!event_subscribe($handle,\&handleEvent,$tuple)) {
110
	die "Could not subscribe to events\n";
Robert Ricci's avatar
Robert Ricci committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
}

#
# Read in the pre-existing node states, and timeout and valid transition
# information from the database
#
my %nodes    = readStates();
my %timeouts = getTimeouts();
my %valid    = getValid();

#
# 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.
#
131
$SIG{HUP} = sub { info("Recieved a SIGHUP\n"); $do_reload = 1; };
Robert Ricci's avatar
Robert Ricci committed
132

133
info("stated starting up\n");
Robert Ricci's avatar
Robert Ricci committed
134 135 136 137 138 139 140 141 142 143 144 145 146

#
# 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) {
		my $state    = $value->{state};
147 148
		my $mode     = $value->{mode};
		my $time     = $value->{timestamp};
Robert Ricci's avatar
Robert Ricci committed
149 150
		my $notified = $value->{notified};
		my ($timeout,$action);
151 152 153
		if ($mode && $state && $timeouts{$mode} &&
				$timeouts{$mode}{$state}) {
			($timeout, $action) = @{$timeouts{$mode}{$state}};
Robert Ricci's avatar
Robert Ricci committed
154 155 156 157 158 159
		}
		if ((!$notified) && $time && $timeout &&
				(($time + $timeout) < $now)) {
			   #
			   # TODO: Need to actually do something!
			   #
160 161
			   notify("Node $node has timed out in state $state" .
			   	  ", mode $mode\n");
Robert Ricci's avatar
Robert Ricci committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
			   $value->{notified} = 1;
		}
	}

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

	$iterations++;
	sleep(1);
}

#
# Read the current states of nodes from the database
#
179 180 181
sub readStates(;@) {
    	my %oldnodes = @_;

182 183 184 185 186 187 188
	#
	# Guard against undefined variable warnings
	#
	if (! defined(%oldnodes)) {
		%oldnodes = ();
	}

Robert Ricci's avatar
Robert Ricci committed
189 190
	debug("readStates called\n");
	my $result = DBQueryFatal("SELECT node_id, eventstate, " .
191 192
				  "state_timestamp, op_mode, " .
				  "op_mode_timestamp FROM nodes");
Robert Ricci's avatar
Robert Ricci committed
193 194

	my %nodes;
195 196
	while (my ($node_id, $state, $timestamp, $mode, $mode_timestamp)
			= $result->fetchrow()) {
197 198 199 200 201 202
	    	#
		# 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.)
		#
203 204 205
		if ($oldnodes{$node_id} && $state && $timestamp &&
		   ($oldnodes{$node_id}{state} eq $state) &&
		   ($oldnodes{$node_id}{timestamp} == $timestamp)) {
206 207
		       $nodes{$node_id} = $oldnodes{$node_id};
		} else { 
208 209 210 211
		    $nodes{$node_id}{state}          = $state;
		    $nodes{$node_id}{timestamp}      = $timestamp;
		    $nodes{$node_id}{mode}           = $mode;
		    $nodes{$node_id}{mode_timestamp} = $mode_timestamp;
212
		}
Robert Ricci's avatar
Robert Ricci committed
213 214 215 216 217 218 219 220 221
	}
	return %nodes;
}

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

	my %timeouts;
226 227
	while (my ($op_mode, $state, $timeout, $action) = $result->fetchrow()) {
		$timeouts{$op_mode}{$state} = [ $timeout, $action ];
Robert Ricci's avatar
Robert Ricci committed
228 229 230 231 232 233 234 235 236
	}
	return %timeouts;
}

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

	my %valid;
241 242
	while (my ($mode,$state1, $state2) = $result->fetchrow()) {
		$valid{$mode}{$state1}{$state2} = 1;
Robert Ricci's avatar
Robert Ricci committed
243 244 245 246 247 248 249 250 251
	}
	return %valid;
}

#
# Gets called for every event that we recieve
#
sub handleEvent($$$) {
	my ($handle,$notification,$data) = @_;
252
	my $objtype = event_notification_get_objtype($handle,$notification);
Robert Ricci's avatar
Robert Ricci committed
253 254 255
	my $objname = event_notification_get_objname($handle,$notification);
	my $eventtype = event_notification_get_eventtype($handle,$notification);

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

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

266 267
	SWITCH: for ($objtype) {

268 269 270 271 272
	    #
	    # Handle both the new TBNODEOPMODE and the old TBCONTROL events, 
	    # for backward compatibility.
	    #
	    (/TBNODESTATE/ || /TBCONTROL/) && do {
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
		stateTransition($objname,$eventtype);
		last;
	    };
	    (/TBNODEOPMODE/) && do {
		opModeTransition($objname,$eventtype);
		last;
	    };

	}

}

sub stateTransition($$) {

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

	# Check for invalid transitions
290 291 292 293
	my ($oldstate, $mode);
	if ($nodes{$node}) {
		$oldstate = $nodes{$node}{state};
		$mode = $nodes{$node}{mode};
Robert Ricci's avatar
Robert Ricci committed
294
	} else {
295 296 297 298 299 300 301 302 303 304 305
		#
		# 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");
		}
Robert Ricci's avatar
Robert Ricci committed
306
	}
307
	if ($oldstate && $mode && $valid{$mode} && $valid{$mode}{$oldstate} &&
308 309 310
			!$valid{$mode}{$oldstate}{$newstate}) {
		notify("Invalid transition for node $node from $oldstate " .
		       " to $newstate\n");
Robert Ricci's avatar
Robert Ricci committed
311 312 313
	}

	my $now = time();
314 315 316 317 318 319 320 321 322 323 324 325 326
	$nodes{$node}{state}     = $newstate;
	$nodes{$node}{timestamp} = $now;
	$nodes{$node}{notified}  = 0;

	DBQueryFatal("UPDATE nodes SET eventstate='$newstate', " .
		     "state_timestamp='$now' WHERE node_id='$node'");

}

sub opModeTransition($$) {

	my ($node,$newmode) = @_;

327
	info("opModeTransition: $node, $newmode\n");
328 329 330 331 332

	my $now = time();
	$nodes{$node}{mode}           = $newmode;
	$nodes{$node}{mode_timestamp} = $now;
	$nodes{$node}{notified}       = 0;
Robert Ricci's avatar
Robert Ricci committed
333

334 335
	DBQueryFatal("UPDATE nodes SET op_mode='$newmode', " .
		     "op_mode_timestamp='$now' WHERE node_id='$node'");
Robert Ricci's avatar
Robert Ricci committed
336 337 338

}

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
#
# 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....
	#
	if ((!$testdb && ($TBDBNAME eq "tbdb")) ||
	    ($testdb && ($testdb eq $TBDBNAME))) {
		return 1;
	} else {
		return 0;
	}
}

Robert Ricci's avatar
Robert Ricci committed
376 377 378 379
#
# Reload state from the database
#
sub reload() {
380
    	info("Reloading state from database\n");
381
	%nodes    = readStates(%nodes);
Robert Ricci's avatar
Robert Ricci committed
382 383 384 385 386 387 388 389 390 391 392
	%timeouts = getTimeouts();
	%valid     = getValid();
}

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

sub notify($) {
    	my $message = shift;
	if (!$debug) {
393
	    	SENDMAIL($TBOPS,"Node State Daemon Messsage",$message,$TBOPS);
Robert Ricci's avatar
Robert Ricci committed
394
	}
395 396 397 398 399 400 401
	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
402
    print strftime("%b %e %H:%M:%S",localtime)." stated[$$]: $message";
Robert Ricci's avatar
Robert Ricci committed
403 404 405 406 407 408 409
}

#
# This gets called if we die of 'natural causes' (exit, die, etc.)
#
END {
    	if ($handle) {
410
		info("Exiting, cleaning up\n");
Robert Ricci's avatar
Robert Ricci committed
411 412 413 414 415 416
		if (event_unregister($handle) == 0) {
			die "Unable to unregister with event system\n";
		}
	}

}