sa_daemon.in 14.4 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2015 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#
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.
#
sub usage()
{
    print "Usage: sa_daemon [-d] [-n]\n";
    exit(1);
}
my $optlist   = "dn";
my $debug     = 0;
my $impotent  = 0;

47

48 49 50 51 52 53 54 55
#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
56
my $MAINSITE      = @TBMAINSITE@;
57 58 59
my $LOGFILE       = "$TB/log/sa_daemon.log";
my $EMULAB_PEMFILE = "$TB/etc/genisa.pem";
my $CLEANUPSLICE  = "$TB/sbin/cleanupslice";
60 61 62 63
my $REREGISTER    = "$TB/sbin/protogeni/reregister";
my $REGRESOURCES  = "$TB/sbin/protogeni/register_resources";
my $SLEEP_INTERVAL  = 60;
my $UPDATE_INTERVAL = (60 * 60 * 24);
64

65 66 67 68 69
#
# Update interval countdown. Set to zero so it runs right away.
#
my $update_countdown = 0;
	  
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
# 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");
}

#
# Exit if not a protogeni site.
#
if (! $PGENISUPPORT) {
    exit(0);
}

#
# Check args early so we get the right DB.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}

# Do this early so that we talk to the right DB.
use vars qw($GENI_DBNAME);
$GENI_DBNAME = "geni";

# Load the Testbed support stuff.
use lib "@prefix@/lib";
require GeniDB;
require GeniUtil;
require GeniSlice;
require GeniCertificate;
117
require GeniCredential;
118
require GeniUser;
119
require libGeni;
120 121 122
use Experiment;
use Node;
use libtestbed;
123
use emutil;
124
use libEmulab;
125
use POSIX qw(strftime ceil);
126

Leigh B Stoller's avatar
Leigh B Stoller committed
127 128 129 130 131
# Experimental
if ($MAINSITE) {
    require APT_Instance;
}

132 133 134 135 136 137 138 139 140 141 142 143
#
# 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");
}
Genixmlrpc->SetContext(Genixmlrpc->Context($certificate));
Genixmlrpc->SetTimeout(10);
$ENV{'MYUUID'} = $certificate->uuid();
$ENV{'MYURN'} = "urn:publicid:IDN+@OURDOMAIN@+authority+sa";

144 145 146
if (CheckDaemonRunning("sa_daemon")) {
    fatal("Not starting another sa daemon!");
}
147 148 149 150 151 152
# Go to ground.
if (! $debug) {
    if (TBBackGround($LOGFILE)) {
	exit(0);
    }
}
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
if (MarkDaemonRunning("sa_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);

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
GeniUtil::FlipToGeniUser();

#
# 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. Do not delete until
# at least 24 hours goes by, even if expired.
#
sub WarnSlices()
{
187 188 189 190 191 192 193 194 195 196
    #
    # Override the short slice warning.
    #
    my $warn_short_slices;
    if (!libEmulab::GetSiteVar('protogeni/warn_short_slices', 
			       \$warn_short_slices)) {
	# Cannot get the value, default it to off.
	$warn_short_slices = 0;
    }

197 198 199 200 201
    #
    # This query purposely skips slices that are attached to cooked
    # mode experiments; those that have a non-null exptidx of a local
    # experiment.
    #
202
    my $query_result =
203 204
	GeniDB::DBQueryWarn("select idx,expires,UNIX_TIMESTAMP(expires), ".
			    "   UNIX_TIMESTAMP(created) ".
205
			    "  from geni_slices ".
206 207
			    "where shutdown is null and lockdown=0 and ".
			    "      exptidx is null");
208

209 210
    while (my ($idx,$expires,$stamp,$created) =
	   $query_result->fetchrow_array()) {
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
	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. 
	#
	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.
	    next;
	}
237 238
	my $slice_uuid = $slice->uuid();
	
239 240 241 242
	if ($slice->Lock() != 0) {
	    print STDERR "Could not lock slice $slice.\n";
	    goto skip;
	}
243

244
	my $geniuser  = GeniUser->Lookup($slice->creator_uuid(), 1);
245
	my $emailaddr = (defined($geniuser) ? $geniuser->email() : undef);
246 247 248 249 250 251 252 253 254 255
	if (!defined($geniuser)) {
	    #
	    # No user to warn
	    #
	    print STDERR "Creator no longer exists for $slice. Skipping ...\n";
	    $warned{$idx}  = time();
	    $expires{$idx} = $stamp;
	    $slice->UnLock();
	    goto skip;
	}
256 257
	my $urn       = $slice->urn();
	my $hrn       = $slice->hrn();
258 259 260 261 262 263 264 265 266 267 268 269 270 271
	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";
	}
272 273
	
	if ($impotent) {
274 275 276 277 278 279 280 281 282
	    if ($stamp - $created < $grace) {
		print STDERR
		    "Short lived slice is going to expire: ".
		    "$geniuser,$idx,$hrn,$diff $unit\n";
	    }
	    else {
		print STDERR
		    "Would send mail to $geniuser: $idx,$hrn,$diff $unit\n";
	    }
283 284 285 286 287
	    $warned{$idx}  = time();
	    $expires{$idx} = $stamp;
	    $slice->UnLock();
	    goto skip;
	}
288 289 290 291 292
	#
	# If this is a short lived slice then do not bother to send
	# email. Assume negative reenforcement will teach users what
	# to do.
	#
293
	if ($stamp - $created < $grace && !$warn_short_slices) {
294 295 296 297 298 299 300
	    print STDERR
		"Short lived slice is going to expire: ".
		"$geniuser,$idx,$hrn,$diff $unit\n";
	}
	else {
	    print STDERR
		"Sending mail to $geniuser about expiring slice $idx,$hrn\n";
301

Leigh B Stoller's avatar
Leigh B Stoller committed
302 303 304
	    # Experimental
	    if ($MAINSITE) {
		# Do not expose slices to APT/Cloud users.
Leigh B Stoller's avatar
Leigh B Stoller committed
305
		my $instance = APT_Instance->LookupBySlice($slice->uuid());
Leigh B Stoller's avatar
Leigh B Stoller committed
306 307 308 309
		if (defined($instance)) {
		    $instance->WarnExpiring("$diff $unit");
		    goto noemail;
		}
310
	    }
Leigh B Stoller's avatar
Leigh B Stoller committed
311
	    SENDMAIL($emailaddr, "Slice $urn expiring",
312 313 314
		     "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",
315
		     "Geni Operations <$TBOPS>");
316
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
317
  noemail:
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
	$warned{$idx}  = time();
	$expires{$idx} = $stamp;
	$slice->UnLock();
	
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

#
# Look for slices that have expired.
#
sub ExpireSlices()
{
333 334 335 336 337
    #
    # This query purposely skips slices that are attached to cooked
    # mode experiments; those that have a non-null exptidx of a local
    # experiment.
    #
338 339 340 341
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_slices ".
			    "where UNIX_TIMESTAMP(now()) > ".
			    "      UNIX_TIMESTAMP(expires) and ".
342 343
			    "      shutdown is null and lockdown=0 and ".
			    "      exptidx is null");
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

    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;
	}
	if (! $slice->IsExpired()) {
	    $slice->UnLock();
	    delete($warned{"$idx"});
	    delete($expires{"$idx"});
	    goto skip;
	}
	if ($impotent) {
	    print STDERR "Would expire $slice\n";
	    $slice->UnLock();
	    goto skip;
	}
367 368
	# Experimental
	if ($MAINSITE) {
369
	    my $instance = APT_Instance->LookupBySlice($slice->uuid());
370 371 372 373 374 375 376 377 378 379 380
	    if (defined($instance)) {
		#
		# If this is for an APT instance, skip it and let the
		# apt_daemon deal with it.
		#
		print STDERR "Skipping slice for $instance\n";
		$slice->UnLock();
		goto skip;
	    }
	}
	
381
	my $geniuser  = GeniUser->Lookup($slice->creator_uuid(), 1);
382
	my $emailaddr = (defined($geniuser) ? $geniuser->email() : undef);
383 384
	my $urn       = $slice->urn();
	my $hrn       = $slice->hrn();
385
	my $slice_uuid= $slice->uuid();
386 387
	
	print STDERR "Expiring $slice\n";
388 389

	# Needs to move.
390
	GeniSlice::ClientSliver->SliceDelete($slice);
391 392 393 394

	# Remove any stored credentials for this slice.
	GeniCredential->DeleteForTarget($slice);
	
395 396 397 398 399
	system("$CLEANUPSLICE -f -s $idx");
	if (! $?) {
	    $slice->UnLock();
	    goto skip;
	}
400 401 402 403
	if (defined($emailaddr)) {
	    SENDMAIL($emailaddr, "Slice $urn has expired",
		     "Slice $urn\n".
		     "has been expired. Sorry :-(\n",
404
		     "Geni Operations <$TBOPS>");
405
	}
406 407 408 409 410 411 412 413
	delete($warned{"$idx"});
	delete($expires{"$idx"});
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

414 415 416 417 418 419 420 421 422 423 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
#
# Look for slices that need to be registered at the CH.
#
sub RegisterSlices()
{
    #
    # This query purposely skips slices that are attached to cooked
    # mode experiments; those that have a non-null exptidx of a local
    # experiment.
    #
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_slices ".
			    "where registered=0 and exptidx is null");

    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 $creator = GeniUser->Lookup($slice->creator_uuid(), 1);
	if (!defined($creator)) {
	    print STDERR "Could not find creator for $slice\n";
	    $slice->UnLock();
	    goto skip;
	}
	if ($impotent) {
	    print STDERR "Would register $creator at the clearinghouse\n";
	    print STDERR "Would register $slice at the clearinghouse\n";
	    $slice->UnLock();
	    goto skip;
	}
	print "Registering $creator at the clearinghouse\n";
	if ($creator->Register() != 0) {
	    print STDERR "Could not register $creator at the clearinghouse\n";
	    $slice->UnLock();
	    goto skip;
	}
	print "Registering $slice at the clearinghouse\n";
	if ($slice->Register() != 0) {
	    print STDERR "Could not register $slice at the clearinghouse\n";
	    $slice->UnLock();
	    goto skip;
	}
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
	$creator->Flush()
	    if (defined($creator));
    }
}

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
#
# Renew slices and slivers for local cooked mode experiments.
#
sub RenewSlices()
{
    my $query_result =
	GeniDB::DBQueryWarn("select idx,UNIX_TIMESTAMP(expires), ".
			    "  from geni_slices ".
			    "where shutdown is null and exptidx is not null");

    while (my ($idx,$stamp) = $query_result->fetchrow_array()) {
	#
	# Wait until within $hours of expiration.
	#
	if ($stamp > time() + $grace) {
	    next;
	}
	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;
	}
	#
	# There should be an experiment.
	#
	my $experiment = $slice->GetExperiment();
	if (!defined($experiment)) {
	    print STDERR "No experiment for $slice.\n";
	    $slice->UnLock();
	    goto skip;
	}
	#
	# And we want to take the lock to prevent it from changing.
	#
	if ($experiment->LockTables()) {
	    print STDERR "Could not lock tables for $experiment\n";
	    $slice->UnLock();
	    goto skip;
	}
	if ($experiment->Lock(undef, 1)) {
	    print STDERR "Could not lock $experiment\n";
	    $slice->UnLock();
	    goto skip;
	}
	if ($impotent) {
	    print STDERR "Would renew $slice\n";
	    $experiment->Unlock();
	    $slice->UnLock();
	    goto skip;
	}
	
	if (libGeni::RenewSlivers($experiment)) {
	    print STDERR "Could not renew $slice/$experiment\n";

	    SENDMAIL($TBOPS,
		     "SA daemon renew failure",
		     "Could not renew $slice/$experiment\n",
		     $TBOPS);
	}
	$experiment->Unlock();
	$slice->UnLock();
	
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

545
while (1) {
546 547 548 549
    if (NoLogins()) {
	sleep(5);
	next;
    }
550

551 552 553 554 555
    print "Running at ".
	POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime()) . "\n";

    WarnSlices();
    ExpireSlices();
556
    RegisterSlices();
557
#    RenewSlices();
558

559 560 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
    #
    # Look for update orders
    #
    $update_countdown -= $SLEEP_INTERVAL;
    if ($update_countdown <= 0) {
	$update_countdown = $UPDATE_INTERVAL;
    
	my $register = emutil::VersionInfo("protogeni_reregister");
	if (!defined($register) || $register) {
	    #
	    # ReRegister our certs at the CH.
	    #
	    print "Registering certificates at Clearinghouse.\n";
	    if (system("$REREGISTER")) {
		SENDMAIL($TBOPS,
			 "SA daemon reregister failure",
			 "Could not reregister certificates at the Clearing House\n",
			 $TBOPS);
	    }
	    #
	    # ReRegister our resources at the CH.
	    #
	    print "Registering resources at Clearinghouse. \n";
	    if (system("$REGRESOURCES -r")) {
		SENDMAIL($TBOPS,
			 "SA daemon reregister failure",
			 "Could not reregister resources at the Clearing House\n",
			 $TBOPS);
	    }
588
	    emutil::UpdateVersionInfo("protogeni_reregister", "0");
589 590 591
	}
    }

592 593 594
    # Be certain stale info is gone.
    GeniUtil::FlushCaches();

595
    sleep($SLEEP_INTERVAL);
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
}
exit(0);

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

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
	     "ProtoGENI SA daemon died",
	     $msg,
	     $TBOPS);

611
    MarkDaemonStopped("sa_daemon");
612 613 614
    die("*** $0:\n".
	"    $msg\n");
}