expire_daemon.in 14.2 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1 2
#!/usr/bin/perl -w
#
3
# GENIPUBLIC-COPYRIGHT
Leigh B Stoller's avatar
Leigh B Stoller committed
4
# Copyright (c) 2008-2011 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5 6 7 8 9 10 11 12 13
# All rights reserved.
#
use strict;
use English;
use Getopt::Std;

#
# Look for things that need to be expired and resources released. This is
# incredibly primitive at the moment.
14 15 16
#
# Also TODO. On the clearinghouse we also want to expire things in the
# the geni-ch DB.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
17 18 19
# 
sub usage()
{
20
    print "Usage: expire_daemon [-d] [-i]\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
21 22
    exit(1);
}
23 24 25
my $optlist   = "di";
my $debug     = 0;
my $idlecheck = 0;
26
my $impotent  = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
27 28 29 30 31 32 33 34 35

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
36
my $LOGFILE       = "$TB/log/expire_daemon.log";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
37
my $IDLETIMES	  = "$TB/sbin/idletimes";
38
my $EMULAB_PEMFILE = "$TB/etc/genicm.pem";
39
my $REGISTER      = "$TB/sbin/protogeni/register_sliver";
40
my $SLEEP_INTERVAL= 60;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/usr/site/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

# Protos
sub fatal($);
	  
#
# Turn off line buffering on output
#
$| = 1; 

if ($UID != 0) {
    fatal("Must be root to run this script\n");
}

58 59 60 61 62 63 64
#
# Exit if not a protogeni site.
#
if (! $PGENISUPPORT) {
    exit(0);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
65 66 67 68 69 70 71 72 73 74
#
# Check args early so we get the right DB.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
75 76 77
if (defined($options{"i"})) {
    $idlecheck = 1;
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
78 79 80

# Do this early so that we talk to the right DB.
use vars qw($GENI_DBNAME);
81
$GENI_DBNAME = "geni-cm";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
82 83 84 85 86 87 88 89

# Load the Testbed support stuff.
use lib "@prefix@/lib";
require GeniDB;
require GeniUtil;
require GeniTicket;
require GeniSlice;
require GeniCM;
90
require GeniCertificate;
Leigh B Stoller's avatar
Leigh B Stoller committed
91
require GeniCredential;
92
require GeniAggregate;
93 94
use Experiment;
use Node;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
95
use libtestbed;
96
use emutil;
97
use libEmulab;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
98
use POSIX qw(strftime);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
99

100 101 102 103 104 105 106
#
# So we know who/what we are acting as.
#
my $certificate = GeniCertificate->LoadFromFile($EMULAB_PEMFILE);
if (!defined($certificate)) {
    fatal("Could not get uuid/urn from $EMULAB_PEMFILE\n");
}
107 108
Genixmlrpc->SetContext(Genixmlrpc->Context($certificate));
Genixmlrpc->SetTimeout(10);
109 110 111
$ENV{'MYUUID'} = $certificate->uuid();
$ENV{'MYURN'} = "urn:publicid:IDN+@OURDOMAIN@+authority+cm";

112 113 114
if (CheckDaemonRunning("expire_daemon")) {
    fatal("Not starting another expire daemon!");
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
115 116 117 118 119 120
# Go to ground.
if (! $debug) {
    if (TBBackGround($LOGFILE)) {
	exit(0);
    }
}
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
if (MarkDaemonRunning("expire_daemon")) {
    fatal("Could not mark daemon as running!");
}
#
# Setup a signal handler for newsyslog.
#
sub handler()
{
    my $SAVEEUID = $EUID;
    
    $EUID = 0;
    ReOpenLog($LOGFILE);
    $EUID = $SAVEEUID;
}
$SIG{HUP} = \&handler
    if (!$debug);

138
GeniUtil::FlipToGeniUser();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

#
# Look for tickets.
#
sub ExpireTickets()
{
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_tickets ".
			    "where UNIX_TIMESTAMP(now()) > ".
			    "      UNIX_TIMESTAMP(redeem_before)");

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $ticket = GeniTicket->Lookup($idx);

	if (!defined($ticket)) {
	    # Ticket is gone, lets not worry.
	   next;
	}
157 158
	if ($ticket->Lock() != 0) {
	    print STDERR "Could not lock ticket $ticket\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
159 160 161 162
	    goto skip;
	}
	print "Expiring ticket $ticket\n";

163
	if ($ticket->Release(GeniTicket::TICKET_EXPIRED()) != 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
164 165 166
	    print STDERR "Could not delete $ticket\n";
	    SENDMAIL($TBOPS, "Could not delete ticket $idx",
		     "Could not delete ticket $ticket");
167
	    # We leave it locked.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
168 169 170 171 172 173 174 175 176
	}
	else {
	    print STDERR "$ticket has been deleted\n";
	}
      skip:
	$ticket->Flush();
    }
}

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
#
# Keep track of who has been warned. Do not expire until 24 hours after
# warning.
#
my %warned  = ();
my %expires = ();
my $hours   = 24;
my $grace   = $hours * 3600;

#
# Send out warnings about 24 hours ahead of time.
#
sub WarnSlices()
{
    my $query_result =
	GeniDB::DBQueryWarn("select idx,expires,UNIX_TIMESTAMP(expires), ".
			    "   UNIX_TIMESTAMP(created) ".
			    "  from geni_slices ".
			    "where shutdown is null and isplaceholder=0");

    while (my ($idx,$expires,$stamp,$created) =
	   $query_result->fetchrow_array()) {
	if (exists($expires{$idx})) {
	    if ($expires{$idx} == $stamp) {
		# Already warned, skip.
	    }
	    else {
		# Expiration changed, delete and catch in the next loop
		print STDERR "Expiration changed for slice $idx to $expires\n";
		delete($expires{$idx});
		delete($warned{$idx});
	    }
	    next;
	}
	#
	# If expiration is greater then 24 hours out, skip. 
	#
214
	#print STDERR "$stamp, $created, $grace, ". time() . "\n";
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

	if ($stamp > time() + $grace) {
	    delete($expires{$idx});
	    delete($warned{$idx});
	    next;
	}
	my $slice = GeniSlice->Lookup($idx);

	if (!defined($slice)) {
	    # Slice is gone, lets not worry.
	    delete($expires{$idx});
	    delete($warned{$idx});
	    next;
	}
	if ($slice->Lock() != 0) {
	    print STDERR "Could not lock slice $slice.\n";
	    goto skip;
	}

	# We want the aggregate for the sliver urn, but it might
	# not actually exist yet.
	my $aggregate = GeniAggregate->SliceAggregate($slice);
	if (!defined($aggregate)) {
	    print STDERR "No aggregate created yet for $slice\n";
	    $slice->UnLock();
	    goto skip;
	}
	my $geniuser  = GeniUser->Lookup($slice->creator_uuid(), 1);
	my $emailaddr = $geniuser->email();
	my $urn       = $slice->urn();
	my $hrn       = $slice->hrn();
	my $sliver_urn= $aggregate->urn();
	my $diff      = $stamp - time();
	my $unit;
	if ($diff < 0) {
	    $diff = 0;
	    $unit = "minutes";
	}
	elsif ($diff < 60) {
	    $diff = POSIX::ceil($diff / 60);
	    $unit = "minutes";
	}
	else {
	    $diff = POSIX::ceil($diff / 3600);
	    $unit = "hours";
	}
	
	if ($impotent) {
	    if ($stamp - $created < $grace) {
		print STDERR
		    "Short lived sliver is going to expire: ".
		    "$geniuser,$idx,$hrn,$diff $unit\n";
	    }
	    else {
		print STDERR
		    "Would send mail to $geniuser: $idx,$hrn,$diff $unit\n";
	    }
	    $warned{$idx}  = time();
	    $expires{$idx} = $stamp;
	    $slice->UnLock();
	    goto skip;
	}
	#
	# If this is a short lived slice then do not bother to send
	# email. Assume negative reenforcement will teach users what
	# to do.
	#
	if ($stamp - $created < $grace) {
	    print STDERR
		"Short lived sliver is going to expire: ".
		"$geniuser,$idx,$hrn,$diff $unit\n";
	}
	else {
	    print STDERR
		"Sending mail to $geniuser about expiring sliver $aggregate\n";
	    SENDMAIL($emailaddr, "Sliver $sliver_urn expiring",
		     "Sliver $sliver_urn\n".
		     "from slice $urn,\n".
		     "is going to expire in approximately $diff $unit.\n".
		     "Please renew it or let it expire if you not using it.\n",
		     undef, "CC: $TBOPS");
	}
	$warned{$idx}  = time();
	$expires{$idx} = $stamp;
	$slice->UnLock();
	
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
307
#
308 309
# Look for slices that need to be expired. Do not expire shutdown slices;
# Handled below, and we want to keep the record around.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
310 311 312 313
#
sub ExpireSlices()
{
    my $query_result =
Leigh B Stoller's avatar
Leigh B Stoller committed
314 315 316 317 318 319 320
	GeniDB::DBQueryWarn("select idx from geni_slices where ".
			    " (UNIX_TIMESTAMP(now()) > ".
			    "     UNIX_TIMESTAMP(expires) or ".
			    "  (isplaceholder=1 and ".
			    "     (UNIX_TIMESTAMP(now()) - ".
			    "      UNIX_TIMESTAMP(created)) > 3600)) ".
			    " and shutdown is null");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($idx);

	if (!defined($slice)) {
	    # Slice is gone, lets not worry.
	    next;
	}
	if ($slice->Lock() != 0) {
	    print STDERR "Could not lock slice $slice.\n";
	    goto skip;
	}
	my $experiment = $slice->GetExperiment();
	if (!defined($experiment)) {
335
	    print STDERR "Could not get experiment for $slice. Expiring ...\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
336
	    $slice->UnLock();
337
	    goto cleanup;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
338 339 340 341 342 343 344 345 346 347
	}
	if ($experiment->Refresh() != 0) {
	    print STDERR "Could not flush $experiment\n";
	    $slice->UnLock();
	    goto skip;
	}
	#
	# See if we have any local nodes. No point in using the idle
	# check if there are no nodes. 
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
348
	if ($idlecheck && !$slice->isplaceholder()) {
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
	    my @localnodes = ();
	    $experiment->LocalNodeListNames(\@localnodes);
	    if (@localnodes) {
		my $pid = $experiment->pid();
		my $eid = $experiment->eid();
		
		#
		# Use the idletimes program in summary mode to see if the
		# the nodes are idle. If they are then it gets swapped.
		# This is going to have to get more sophisticated.
		#
		print STDERR "Checking to see if $slice ($eid) is idle\n";
		system("$IDLETIMES -s $pid,$eid");
		if (! $?) {
		    $slice->UnLock();
		    goto skip;
		}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
366
	    }
Leigh B Stoller's avatar
Leigh B Stoller committed
367 368 369
	    print STDERR "$slice ($experiment) is idle; releasing.\n";
	}
	else {
Leigh B Stoller's avatar
Leigh B Stoller committed
370 371 372 373 374 375
	    if ($slice->isplaceholder()) {
		print STDERR "Releasing placeholder $slice $experiment.\n";
	    }
	    else {
		print STDERR "Expiring $slice $experiment.\n";
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
376
	}
377
      cleanup:
Leigh B. Stoller's avatar
Leigh B. Stoller committed
378 379
	if (GeniCM::CleanupDeadSlice($slice) != 0) {
	    print STDERR "Could not release $slice\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
380 381
	    SENDMAIL($TBOPS, "Could not release slice $slice",
		     "Could not release slice $slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
382 383 384
	    # Leave it locked. 
	    goto skip;
	}
385 386
	delete($warned{"$idx"});
	delete($expires{"$idx"});
Leigh B. Stoller's avatar
Leigh B. Stoller committed
387 388 389 390 391 392 393
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

394 395 396 397 398 399 400
#
# Look for slices that need to be shutdown
#
sub ShutdownSlices()
{
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_slices ".
401
			    "where shutdown is not null and isshutdown=0");
402 403 404 405 406 407 408 409 410 411 412 413 414 415

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($idx);

	if (!defined($slice)) {
	    # Slice is gone, lets not worry.
	    next;
	}
	if ($slice->Lock() != 0) {
	    print STDERR "Could not lock slice $slice.\n";
	    goto skip;
	}

	#
416
	# The isshutdown flag avoids churning the system.
417 418 419 420 421 422
	#
	if (GeniCM::CleanupDeadSlice($slice, 0) != 0) {
	    print STDERR "Could not shutdown $slice\n";
	    SENDMAIL($TBOPS, "Could not shutdown slice",
		     "Could not shutdown slice $slice");
	}
423
	$slice->SetShutdownFlag(1);
424 425 426 427 428 429 430
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

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
#
# Look for slices that need to be registered.
#
sub RegisterSlices()
{
    # Only toplevel aggregates. 
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_aggregates ".
			    "where type='Aggregate' and registered is null");

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $aggregate = GeniAggregate->Lookup($idx);

	if (!defined($aggregate)) {
	    # aggregate is gone, lets not worry.
	    next;
	}
	my $slice = $aggregate->GetSlice();
	if (!defined($slice)) {
	    # slice is gone, lets not worry.
	    next;
	}
	# Run the register script. Ignore errors; we will retry again later.
	print STDERR "Registering $slice ($aggregate)\n";
	system("$REGISTER " . $slice->idx());
    }
}

459 460 461 462 463 464 465 466 467
sub ReportLockedSlices()
{
    my $msg = "";
    
    my $query_result =
	GeniDB::DBQueryWarn("select idx,locked from geni_slices ".
			    "where locked is not null and ".
			    "      DATE_SUB(NOW(),INTERVAL 1 DAY) >= locked");
    if (!$query_result) {
468 469
	print STDERR "ReportLockedSlices: Error getting info from the DB.\n";
	return;
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    }
    return
	if (!$query_result->numrows);

    while (my ($idx, $locked) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($idx);

	if (!defined($slice)) {
	    # Slice is gone, lets not worry.
	    next;
	}
	my $urn = $slice->urn();
	
	$msg .= "$urn : $locked\n";

	print STDERR "$urn : locked since $locked\n";
    }
    return
	if ($msg eq "");

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
494
	     "ProtoGENI CM daemon: Locked Slices",
495 496 497 498 499
	     "The following CM slices have been locked for a long time\n\n".
	     $msg,
	     $TBOPS);
}

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 560 561 562 563 564
#
# Look for orphaned certificates.
#
sub ReportOrphanedCerts()
{
    my $msg = "";

    GeniDB::DBQueryWarn("lock tables geni_certificates as c write, ".
			"  geni_users as u write, ".
			"  geni_slices as s write, ".
			"  geni_slivers as sl write, ".
			"  geni_aggregates as a write, ".
			"  geni_authorities as auth write, ".
			"  geni_components as cm write, ".
			"  geni_credentials as cr write")
	or return;
    
    my $query_result =
	GeniDB::DBQueryWarn("select c.uuid,c.urn from geni_certificates as c ".
		   "  left join geni_users as u on u.uuid=c.uuid ".
		   "  left join geni_slices as s on s.uuid=c.uuid ".
		   "  left join geni_slivers as sl on sl.uuid=c.uuid ".
		   "  left join geni_aggregates as a on a.uuid=c.uuid ".
		   "  left join geni_authorities as auth on auth.uuid=c.uuid ".
		   "  left join geni_components as cm on cm.uuid=c.uuid ".
	           "  left join geni_credentials as cr on cr.uuid=c.uuid ".
	     	   "  where u.uuid is null and ".
		   "        s.uuid is null and ".
		   "        sl.uuid is null and ".
		   "        a.uuid is null and ".
		   "        auth.uuid is null and ".
		   "        cm.uuid is null and ".
		   "        cr.uuid is null ");

    GeniDB::DBQueryWarn("unlock tables");
    if (!$query_result) {
	print STDERR "ReportOrphanedCerts: Error getting info from the DB.\n";
	return;
    }
    return
	if (!$query_result->numrows);

    while (my ($uuid, $urn) = $query_result->fetchrow_array()) {
	$msg .= "$uuid : $urn\n";

	print STDERR "$uuid,$urn : orphaned certificates\n";
    }
    return
	if ($msg eq "");

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
	     "ProtoGENI CM daemon: Orphaned Certificates",
	     "The following CM certificates are orphans\n\n".
	     $msg,
	     $TBOPS);
}

# Do this once at startup
sleep(5);
ReportLockedSlices();
ReportOrphanedCerts();

565 566
my $counter = 0;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
567
while (1) {
568 569 570 571
    if (NoLogins()) {
	sleep(5);
	next;
    }
572
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
573 574 575
    print "Running at ".
	POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime()) . "\n";
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
576
    ExpireTickets();
577
    WarnSlices();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
578
    ExpireSlices();
579
    ShutdownSlices();
580
    RegisterSlices();
581 582 583 584

    $counter += $SLEEP_INTERVAL;
    if ($counter >= (24 * 60 * 60)) {
	ReportLockedSlices();
585
	ReportOrphanedCerts();
586 587
	$counter = 0;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
588

589 590 591
    # Be certain stale info is gone.
    Experiment->FlushAll();
    Node->FlushAll();
592
    GeniUtil::FlushCaches();
593

594
    sleep($SLEEP_INTERVAL);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
595 596 597 598 599 600 601
}
exit(0);

sub fatal($)
{
    my ($msg) = @_;

602 603 604 605 606 607 608
    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
	     "ProtoGENI expire daemon died",
	     $msg,
	     $TBOPS);
609
    MarkDaemonStopped("expire_daemon");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
610 611 612
    die("*** $0:\n".
	"    $msg\n");
}