repos_daemon.in 15.5 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT

#
4
# Copyright (c) 2005-2009 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#

use English;
use Getopt::Std;

#
# This should run as root to make sure that it has permission to reboot nodes
# (since only root is allowed to power cycle nodes at any time - it's time-
# limited for anyone else)
#
if ($UID != 0) {
    die("*** $0:\n".
	"    Only root can run this script!\n");
}

#
# Look for nodes to reposition.
#
#	usage: repos_daemon [-d]
#
# TODO: Use "logger" instead of writing a log file.
#
sub usage()
{
    print STDOUT "Usage: repos_daemon [-dc]\n" .
	"Use the -d option to prevent daemonization\n";
    exit(-1);
}
my  $optlist = "dc";

#
# Configure variables
#
my $TB       = "@prefix@";
my $DBNAME   = "@TBDBNAME@";
my $TBOPS    = "@TBOPSEMAIL@";
60
my $MAINSITE = @TBMAINSITE@;
61 62 63 64 65 66 67 68 69

# XXX
my $BUILDING = "MEB-ROBOTS";
my $FLOOR = 4;

# Testbed Support library
use lib "@prefix@/lib";
use libdb;
use libtestbed;
70 71
use User;
use Project;
72 73 74 75 76 77 78 79 80 81 82 83 84 85

#
# These come from the library.
# 
my $REPOSPID	= NODEREPOSITIONING_PID;
my $REPOSEID	= NODEREPOSITIONING_EID;
my $PENDINGEID	= NODEREPOSPENDING_EID;
my $RLPENDINGEID= NODERELOADPENDING_EID;
my $NODEDEAD_PID= NODEDEAD_PID;
my $NODEDEAD_EID= NODEDEAD_EID;

sub fatal($);
sub notify($);
sub daemonize();
86 87 88
sub movetoreloading($);
sub evsysctrl($);
sub freefromrepositioning($);
89 90 91 92 93 94 95

my $reboot	= "$TB/bin/node_reboot";
my $evsys	= "$TB/bin/eventsys_control";
my $locpiper	= "$TB/sbin/locpiper";
my $logfile	= "$TB/log/repositionlog";
my $debug	= 0;
my $cleanup	= 1;
96
my $retry_time  = 10;              # in minutes
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
my $max_attempts= 4;
my %retried     = ();
my %warned	= ();
my %failed	= ();

#
# Turn off line buffering on output (dots ...).
#
$| = 1;

#
# Untaint the path
# 
$ENV{'PATH'} = "/bin:/usr/bin:";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV != 0) {
    usage();
}
if (defined($options{"d"})) {
    $debug = $options{"d"};
}
if (defined($options{"c"})) {
    $cleanup = $options{"c"};
}

131 132 133 134
# Do not bother outside of Utah.
exit(0)
    if (! $MAINSITE);

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
if ($cleanup) {
    # For testing purposes mostly, cleanup any leftovers...
    DBQueryFatal("delete from reserved ".
		 "where pid='$REPOSPID' and eid='$REPOSEID'");
    DBQueryFatal("delete from virt_node_startloc ".
		 "where pid='$REPOSPID' and eid='$REPOSEID'");
    DBQueryFatal("delete from virt_agents ".
		 "where pid='$REPOSPID' and eid='$REPOSEID'");
}

# Go to ground.
if (! $debug) {
    daemonize();
}

print "Repositioning Daemon starting... pid $$, at ".`date`;

152 153 154 155 156 157 158
# Need the unix uid for the emulab-ops user.
my $user = User->Lookup('elabman');
fatal("Could not get object for emulab-ops user")
    if (!defined($user));
my $ev_uid   = $user->unix_uid();

# and need the unix gid for the group.
159 160
my $project = Project->Lookup($REPOSPID);
fatal("Could not get object for $REPOSPID project")
161 162
    if (!defined($project));
my $unix_gid = $project->unix_gid();
163 164 165 166

print "Experiment head: $ev_uid\n"
    if ($debug);

167 168 169 170 171
my $exptidx;
if (!TBExptIDX($REPOSPID, $REPOSEID, \$exptidx)) {
    fatal("No such experiment $REPOSPID/$REPOSEID!");
}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
#
# Loop, looking for nodes to reposition.
# 
my $idle=0;
MAINLOOP: while (1) {
    my($count, $which, @row, %hrow, $node, $retry, $attempts, $stamp);
    my($pid, $eid);

    # Partial delay between loops in case of an error.
    if ($idle) { sleep(10); } # Wait longer if we're not doing anything
    else { sleep(1); }

    $idle=1; # Assume we're going to be idle this iteration
    #
    # We use this to figure out when to delete nodes from the retried and
    # warned hashes
    #
    my $time = time();

    #
    # First, look for nodes that have been in the repositioning experiment for
    # longer than $retry_time, and try reloading them
    #
    $query_result =
	DBQueryWarn("select r.node_id,rs.attempts from reserved as r " .
197
		    "left join nodes as n on n.node_id=r.node_id ".
198 199
		    "left join reposition_status as rs on rs.node_id=r.node_id ".
		    "where pid='$REPOSPID' and eid='$REPOSEID' and " .
200 201
		    "(n.destination_x is not NULL or ".
		    "n.destination_y is not NULL) and ".
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
		    "(CURRENT_TIMESTAMP - INTERVAL $retry_time MINUTE)".
		    "  > rsrv_time");

    if (! $query_result) {
	print "DB Error. Waiting a bit.\n";
	next;
    }

    while (($node,$attempts) = $query_result->fetchrow) {
	$idle=0;
	if (!$retried{$node}) {
	    print "\nReposition appears wedged at ".`date`."\n";
	    
	    if ($attempts >= $max_attempts) {
		# The node has passed through reloading/repositioning too many
		# times, move to hwdown.
		DBQueryFatal("delete from reposition_status ".
			     "where node_id='$node'");
		notify("$node is wedged... literally.\n".
		       "Moved to $NODEDEAD_PID/$NODEDEAD_EID\n");

		MarkPhysNodeDown($node);
		TBSetNodeLogEntry($node, "daemon",
				  TB_DEFAULT_NODELOGTYPE(),
				  "'Moved to hwdown; reposition failed'");
	    }
	    else {
		# Try reloading the node and restarting pilot.
		movetoreloading($node);
	    }
	}
	$retried{$node} = $time;
    }

    #
    # We can pull out all nodes that were not 'touched' (matched by the
    # select above) during this pass
    #
    foreach $node (keys %retried) {
	if ($retried{$node} != $time) {
	    delete $retried{$node};
	}
    }

    # Now we check the status of the rest of the nodes in repositioning.
    $query_result =
	DBQueryWarn("select n.node_id,li.loc_x,li.loc_y,".
		    "n.destination_x,n.destination_y from nodes as n ".
		    "left join reserved as r on r.node_id=n.node_id ".
		    "left join location_info as li on li.node_id=n.node_id ".
		    "and li.building='$BUILDING' ".
		    "where r.pid='$REPOSPID' and r.eid='$REPOSEID' and ".
		    "(n.destination_x is not NULL or ".
		    "n.destination_y is not NULL) order by node_id");

    if (! $query_result) {
	print "DB Error. Waiting a bit.\n";
	next;
    }

    if ($query_result->numrows) {
	print "Robots are still in motion\n";
	$idle = 1;
	while (%hrow = $query_result->fetchhash()) {
	    $node = $hrow{'node_id'};
	    my $xdist = $hrow{'loc_x'} - $hrow{'destination_x'};
	    my $ydist = $hrow{'loc_y'} - $hrow{'destination_y'};
269
	    my $dist = sqrt(($xdist * $xdist) + ($ydist * $ydist));
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 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 323 324 325 326 327 328 329 330 331 332 333 334 335 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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	    if (!DBQueryWarn("UPDATE reposition_status set ".
			     "distance_remaining=$dist ".
			     "where node_id='$node'")) {
		print "DB Error. Waiting a bit.\n";
		next MAINLOOP;
	    }
	}
	next;
    }
    else {
	$query_result =
	    DBQueryWarn("select node_id from reserved where ".
			"pid='$REPOSPID' and eid='$REPOSEID' ".
			"order by node_id");
	
	if (! $query_result) {
	    print "DB Error. Waiting a bit.\n";
	    next;
	}

	if ($query_result->numrows) {
	    # Robots are back in their pens...
	    if (evsysctrl("stop")) {
		print "Failed to stop the event system...\n"; # XXX fatal?
	    }
	    while (my ($node) = $query_result->fetchrow_array()) {
		freefromrepositioning($node);
	    }
	}
	else {
	    # No robots, make sure the event-system and locpiper are really
	    # dead.  The daemons can be left over if the nodes are all moved
	    # over to reloading.
	    $query_result =
		DBQueryWarn("select locpiper_pid from experiments where ".
			    "pid='$REPOSPID' and eid='$REPOSEID' and ".
			    "locpiper_pid!=0");

	    if ($query_result->numrows) {
		if (evsysctrl("stop")) {
		    print "Failed to stop the event system...\n"; # XXX fatal?
		}
	    }
	}
    }

    # Grab any pending nodes that are up or have failed and need to be reloaded
    # first.  Only take nodes that are up or have definitely failed.
    # XXX We should check for nodes that have been in TBSETUP too long...
    $query_result =
	DBQueryWarn("select r.node_id,n.eventstate from reserved as r ".
		    "left join nodes as n on n.node_id=r.node_id ".
		    "where r.pid='$REPOSPID' and r.eid='$PENDINGEID' ".
		    "and (n.eventstate='". TBDB_NODESTATE_ISUP ."' or ".
		    "n.eventstate='" . TBDB_NODESTATE_TBFAILED ."') ".
		    "order by node_id");

    if (! $query_result) {
	print "DB Error. Waiting a bit.\n";
	next;
    }
    $count = $query_result->numrows;

    if (!$count) {
	print "Nothing to do, sleeping for a bit...\n"
	    if ($debug);
	next;
    } else {
	$idle=0;
    }

    # Grab all the nodes that match
    my @pending_list = ();
    while (%hrow = $query_result->fetchhash()) {
	$node = $hrow{'node_id'};

	my $subresult =
	    DBQueryWarn("SELECT * FROM reposition_status ".
			"WHERE node_id='$node'");
	if ($subresult->numrows == 0) {
	    if (!DBQueryWarn("REPLACE INTO reposition_status SET ".
			     "node_id='$node'")) {
		print "DB Error. Waiting a bit.\n";
		next MAINLOOP;
	    }
	}

	if ($hrow{'eventstate'} eq TBDB_NODESTATE_TBFAILED) {
	    movetoreloading($node);
	}
	else {
	    push(@pending_list, $node);
	}
    }
    my $nodes = join(" ", @pending_list);
    if (!$nodes) {
	$idle=1;
	next;
    }

    print "Trying to reposition $nodes at ".`date`;

    #
    # What we do depends on whether its a free node or a node reserved
    # into the repositioning pending experiment.
    #
    if (@pending_list > 0) {
	my $cond = "node_id in (" .
	    join(",", map("'$_'", @pending_list)) . ")";

	$query_result =
	    DBQueryWarn("SELECT node_id,loc_x,loc_y,orientation ".
			"FROM node_startloc ".
			"WHERE $cond and building='$BUILDING'");

	if (! $query_result) {
	    print "DB Error. Waiting a bit.\n";
	    next;
	}

	while (my ($node,$loc_x,$loc_y,$o) = $query_result->fetchrow_array()) {
	    # Setup some tables for the event scheduler.
	    if (!DBQueryWarn("UPDATE reposition_status set ".
			     "attempts=attempts+1 where node_id='$node'")) {
		print "DB Error. Waiting a bit.\n";
		next MAINLOOP;
	    }
	    if (!DBQueryWarn("REPLACE virt_node_startloc set ".
398
			     "exptidx='$exptidx',".
399 400 401 402 403 404 405 406 407 408 409 410 411 412
			     "pid='$REPOSPID',eid='$REPOSEID',".
			     "vname='$node',building='$BUILDING',".
			     "floor=$FLOOR,loc_x=$loc_x,loc_y=$loc_y,".
			     "orientation=$o")) {
		print "DB Error. Waiting a bit.\n";
		next MAINLOOP;
	    }
	    if (!DBQueryWarn("UPDATE nodes set ".
			     "destination_x=$loc_x,destination_y=$loc_y,".
			     "destination_orientation=$o ".
			     "where node_id='$node'")) {
		print "DB Error. Waiting a bit.\n";
		next MAINLOOP;
	    }
413
	    if (!DBQueryWarn("REPLACE virt_agents set exptidx='$exptidx', ".
414 415 416 417 418 419 420 421 422
			     "pid='$REPOSPID',eid='$REPOSEID',".
			     "vname='$node',vnode='$node',objecttype=10")) {
		print "DB Error. Waiting a bit.\n";
		next MAINLOOP;
	    }
	}

	# Add a topography object so the locpiper will get updates for dynamic
	# obstacles.
423
	if (!DBQueryWarn("REPLACE virt_agents set exptidx='$exptidx', ".
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 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
			 "pid='$REPOSPID',eid='$REPOSEID',".
			 "vname='topo',vnode='*',objecttype=14")) {
	    print "DB Error. Waiting a bit.\n";
	    next MAINLOOP;
	}
	
	# Commit here.
	if (!DBQueryWarn("update reserved set ".
			 "rsrv_time=now(),eid='$REPOSEID' ".
			  "where $cond")) {
	    print "Could not update EID for " . join(" ", @pending_list) .
		". Waiting a bit.\n";
	    next;
	} else {
	    print "Pending nodes moved to $REPOSEID at ".`date`;

	    foreach my $n (@pending_list) {
		TBSetNodeHistory($n, TB_NODEHISTORY_OP_MOVE, $UID,
				 $REPOSPID, $REPOSEID);
	    }
	}

	# The node might need the full vnames to exist in DNS...
	if (system("$TB/sbin/named_setup")) {
	    print "*** WARNING: Failed to reset named map.\n";
	}
	if (evsysctrl("start")) {
	    foreach $node (@pending_list) {
		MarkPhysNodeDown($node);
		TBSetNodeLogEntry($node, "daemon",
				  TB_DEFAULT_NODELOGTYPE(),
				  "'Moved to hwdown; event system failed'");
	    }
	}
    }
    
    $stamp = DBDateTime();
	
    print "Reposition of $nodes has started at $stamp.\n";

    next;
}


#
# free up the node and clear any assocaited repositioning DB state.
# (code stolen from stated).
#
sub freefromrepositioning($) {
    my $node = shift;

    DBQueryFatal("delete from reposition_status where node_id='$node'");

    my $result =
	DBQueryFatal("select node_id from scheduled_reloads ".
		     "where node_id='$node'");

    if ($result->numrows) {
	# Need to reload before releasing into the free pool.
	movetoreloading($node);
    }
    else {
	my ($pid,$eid);
	NodeidToExp($node,\$pid,\$eid);
	if ($pid eq $REPOSPID && ($eid eq $REPOSEID || $eid eq $PENDINGEID)) {
	    print "Freeing $node\n";
	    DBQueryFatal("delete from reserved where node_id='$node'");
	    DBQueryFatal("delete from virt_node_startloc ".
			 "where pid='$REPOSPID' and eid='$REPOSEID' ".
			 "and vname='$node'");
	    DBQueryFatal("delete from virt_agents where pid='$REPOSPID' ".
			 "and eid='$REPOSEID' and vname='$node'");
	    TBSetNodeHistory($node, TB_NODEHISTORY_OP_FREE,
			     $UID, $pid, $eid);
	}
    }
}

sub movetoreloading($) {
    my $node = shift;

    print "Reloading $node\n";
    DBQueryWarn("update nodes set destination_x=NULL,destination_y=NULL, ".
		"destination_orientation=NULL where node_id='$node'");
    DBQueryFatal("delete from virt_node_startloc where pid='$REPOSPID' ".
		 "and eid='$REPOSEID' and vname='$node'");
    DBQueryFatal("delete from virt_agents where pid='$REPOSPID' ".
		 "and eid='$REPOSEID' and vname='$node'");
    if (!DBQueryWarn("update reserved set ".
		     "rsrv_time=now(),eid='$RLPENDINGEID' ".
		     "where node_id='$node'")) {
	print "Could not update EID for $node. Waiting a bit.\n";
    } else {
	print "Reload pending nodes moved to $RLPENDINGEID at ".
	    `date`;
	
	TBSetNodeHistory($node, TB_NODEHISTORY_OP_MOVE, $UID,
			 $REPOSPID, $RLPENDINGEID);
    }
}

sub fatal($)
{
    local($msg) = $_[0];

    SENDMAIL($TBOPS, "Repositioning Daemon Died", $msg, $TBOPS);
    die($msg);
}

sub notify($)
{
    my($mesg) = $_[0];

    print "$mesg\n";
    SENDMAIL($TBOPS, "Repositioning Daemon Message", $mesg, $TBOPS);
}

sub evsysctrl($)
{
    my ($action) = shift;

    print "Event system: $action\n";
    my $childpid = fork();
    if ($childpid == 0) {
	my $lpflag = "";
	my $retval = 1;

	$GID = $unix_gid;
	$EGID = "$unix_gid";
	$EUID = $UID = $ev_uid;
	if ($action eq "stop") {
	    $lpflag = "-k";
	}
	if (system("$locpiper $lpflag $REPOSPID $REPOSEID")) {
	    notify("Failed to $action locpiper\n");
	}
560
	elsif (system("$evsys $action $REPOSPID,$REPOSEID")) {
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
	    notify("Failed to $action event system\n");
	}
	else {
	    $retval = 0;
	}

	exit($retval);
    }
    waitpid($childpid, 0);

    return $?;
}

#
# Become a daemon.
# 
sub daemonize()
{
    my $mypid = fork();
    if ($mypid) {
	exit(0);
    }

    #
    # We have to disconnect from the caller by redirecting both STDIN and
    # STDOUT away from the pipe. Otherwise the caller will continue to wait
    # even though the parent has exited. 
    #
    open(STDIN, "< /dev/null") or
	die("opening /dev/null for STDIN: $!");

    #
    # Open the batch log and start writing to it. 
    #
    open(STDERR, ">> $logfile") or die("opening $logfile for STDERR: $!");
    open(STDOUT, ">> $logfile") or die("opening $logfile for STDOUT: $!");

    return 0;
}