expire_daemon.in 47.6 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2018 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.
# 
# }}}
Leigh Stoller's avatar
Leigh Stoller committed
29 30 31 32
#
use strict;
use English;
use Getopt::Std;
33 34 35
use Data::Dumper;
use Date::Parse;
use POSIX qw(strftime);
Leigh Stoller's avatar
Leigh Stoller committed
36 37 38 39

#
# Look for things that need to be expired and resources released. This is
# incredibly primitive at the moment.
40 41 42
#
# Also TODO. On the clearinghouse we also want to expire things in the
# the geni-ch DB.
Leigh Stoller's avatar
Leigh Stoller committed
43 44 45
# 
sub usage()
{
46
    print "Usage: expire_daemon [-d] [-i]\n";
Leigh Stoller's avatar
Leigh Stoller committed
47 48
    exit(1);
}
49
my $optlist   = "dnis";
50 51
my $debug     = 0;
my $idlecheck = 0;
52
my $impotent  = 0;
53
my $oneshot   = 0;
Leigh Stoller's avatar
Leigh Stoller committed
54 55 56 57 58 59 60

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
61
my $TBAUTOMAIL    = "@TBAUTOMAILEMAIL@";
Leigh Stoller's avatar
Leigh Stoller committed
62
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
63
my $OURDOMAIN     = "@OURDOMAIN@";
Leigh Stoller's avatar
Leigh Stoller committed
64
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
65
my $CLUSTER_PORTAL= "@CLUSTER_PORTAL@";
66
my $LOGFILE       = "$TB/log/expire_daemon.log";
Leigh Stoller's avatar
Leigh Stoller committed
67
my $IDLETIMES	  = "$TB/sbin/idletimes";
68
my $EMULAB_PEMFILE = "$TB/etc/genicm.pem";
69
my $REGISTER      = "$TB/sbin/protogeni/register_sliver";
70 71
my $TRIGGERUPDATE = "$TB/sbin/protogeni/triggerimageupdate";
my $POSTIMAGEDATA = "$TB/sbin/protogeni/postimagedata";
72
my $DELETEIMAGEDATA = "$TB/sbin/protogeni/deleteimagedata";
73
my $IMPORTER      = "$TB/sbin/image_import";
74
my $CLEANUPSLICE  = "$TB/sbin/cleanupslice";
75
my $CLEANUPTICKET = "$TB/sbin/cleanupticket";
76
my $SLEEP_INTERVAL= 60;
Leigh Stoller's avatar
Leigh Stoller committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

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

94 95 96 97 98 99 100
#
# Exit if not a protogeni site.
#
if (! $PGENISUPPORT) {
    exit(0);
}

Leigh Stoller's avatar
Leigh Stoller committed
101 102 103 104 105 106 107 108
#
# Check args early so we get the right DB.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
109
    $debug++;
Leigh Stoller's avatar
Leigh Stoller committed
110
}
111 112 113
if (defined($options{"i"})) {
    $idlecheck = 1;
}
114 115 116 117 118 119
if (defined($options{"s"})) {
    $oneshot = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}
Leigh Stoller's avatar
Leigh Stoller committed
120 121 122

# Do this early so that we talk to the right DB.
use vars qw($GENI_DBNAME);
123
$GENI_DBNAME = "geni-cm";
Leigh Stoller's avatar
Leigh Stoller committed
124 125 126

# Load the Testbed support stuff.
use lib "@prefix@/lib";
127
use emdb;
Leigh Stoller's avatar
Leigh Stoller committed
128 129 130 131 132
require GeniDB;
require GeniUtil;
require GeniTicket;
require GeniSlice;
require GeniCM;
133
require GeniCertificate;
134
require GeniCredential;
135
require GeniAggregate;
136 137
require Genixmlrpc;
use GeniResponse;
138
use Experiment;
139
use EmulabConstants;
140
use Node;
Leigh Stoller's avatar
Leigh Stoller committed
141
use libtestbed;
142
use emutil;
143
use libEmulab;
144
use Logfile;
145
use Project;
146
use OSImage;
Leigh Stoller's avatar
Leigh Stoller committed
147

148 149 150 151 152 153 154
#
# 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");
}
155 156
Genixmlrpc->SetContext(Genixmlrpc->Context($certificate));
Genixmlrpc->SetTimeout(10);
157 158 159
$ENV{'MYUUID'} = $certificate->uuid();
$ENV{'MYURN'} = "urn:publicid:IDN+@OURDOMAIN@+authority+cm";

160
if (!$oneshot) {
161
    if (!$impotent && CheckDaemonRunning("expire_daemon")) {
162 163 164 165 166 167 168 169
	fatal("Not starting another expire daemon!");
    }
    # Go to ground.
    if (! $debug) {
	if (TBBackGround($LOGFILE)) {
	    exit(0);
	}
    }
170
    if (!$impotent && MarkDaemonRunning("expire_daemon")) {
171
	fatal("Could not mark daemon as running!");
Leigh Stoller's avatar
Leigh Stoller committed
172
    }
173 174 175 176 177 178 179 180 181 182 183 184 185
}
#
# Setup a signal handler for newsyslog.
#
sub handler()
{
    my $SAVEEUID = $EUID;
    
    $EUID = 0;
    ReOpenLog($LOGFILE);
    $EUID = $SAVEEUID;
}
$SIG{HUP} = \&handler
186
    if (! ($debug || $oneshot));
187

188
GeniUtil::FlipToGeniUser();
Leigh Stoller's avatar
Leigh Stoller committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

#
# 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;
	}
207 208
	if ($ticket->Lock() != 0) {
	    print STDERR "Could not lock ticket $ticket\n";
Leigh Stoller's avatar
Leigh Stoller committed
209 210
	    goto skip;
	}
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
	my $slice = $ticket->slice();
	#
	# Lock the slice from further access.
	#
	if ($slice->Lock() != 0) {
	    $ticket->UnLock();
	    print STDERR "Could not lock ticket slice $slice\n";
	    goto skip;
	}
	my $experiment = $slice->GetExperiment();
	if (!defined($experiment)) {
	    $ticket->UnLock();
	    $slice->UnLock();
	    print STDERR "Could not get experiment for $ticket\n";
	    goto skip;
	}
	my $ticket_idx = $ticket->idx();
	    
Leigh Stoller's avatar
Leigh Stoller committed
229
	print "Expiring ticket $ticket\n";
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	my $output = emutil::ExecQuiet("$CLEANUPTICKET -f $ticket_idx");
	my $status = $?;
	my $logfile = Logfile->CreateFromString($experiment->gid_idx(),
						$output);
	if (defined($logfile)) {
	    $logfile->SetMetadata([["ticket_idx",  $ticket->idx()],
				   ["slice_idx",   $slice->idx()],
				   ["slice_urn",   $slice->urn()],
				   ["slice_uuid",  $slice->uuid()],
				   # For web interface listing
 				   ["Method",     "CleanupTicket"],
				  ], 1);
	    $logfile->Store();
	}
	if ($status) {
Leigh Stoller's avatar
Leigh Stoller committed
245 246
	    print STDERR "Could not delete $ticket\n";
	    SENDMAIL($TBOPS, "Could not delete ticket $idx",
247
		     "Could not delete ticket $ticket\nfor $slice");
248
	    # We leave it locked.
Leigh Stoller's avatar
Leigh Stoller committed
249 250 251
	}
	else {
	    print STDERR "$ticket has been deleted\n";
252
	    $slice->UnLock();
Leigh Stoller's avatar
Leigh Stoller committed
253 254
	}
      skip:
255 256 257 258 259 260
	$ticket->Flush()
	    if (defined($ticket));
	$slice->Flush()
	    if (defined($slice));
	$experiment->Flush()
	    if (defined($experiment));
Leigh Stoller's avatar
Leigh Stoller committed
261 262 263
    }
}

264 265 266 267 268 269 270 271
#
# 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;
272 273
# Always warn within an hour of expiration, even short lived slices.
my $minwarn = 3600;
274 275 276 277 278 279 280 281 282 283

#
# 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 ".
284
			    "where shutdown is null and ".
285
			    "      hosed=0 and lockdown=0 and isplaceholder=0");
286 287 288 289

    while (my ($idx,$expires,$stamp,$created) =
	   $query_result->fetchrow_array()) {
	if (exists($expires{$idx})) {
290 291 292 293 294 295
	    #
	    # We use expires to mark first warning, and to indicate that
	    # the user changed the expiration time since the that first
	    # warning.
	    #
	    if ($expires{$idx} != $stamp) {
296 297 298 299
		# 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});
300
		next;
301
	    }
302 303 304 305 306 307 308 309 310
	    # Already warned. We skip after first warning, until within
	    # an hour of expiration, and then skip again after the second
	    # warning. The warned array marks the second warning.
	    next if
		(exists($warned{$idx}));

	    # Waiting to send out second warning. 
	    next 
		if ($stamp - time() > $minwarn);
311 312 313 314
	}
	#
	# If expiration is greater then 24 hours out, skip. 
	#
315
	#print STDERR "$stamp, $created, $grace, ". time() . "\n";
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

	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";
	}
361 362 363 364 365 366 367

	#
	# If nothing is in the expires array, then this is first warning. 
	#
	# If this was created in the last hour, skip the actual
	# email. Wait until the second warning. 
	#
368
	if (time() - $created < $minwarn) {
369
	    print STDERR "Skipping email for just created sliver $aggregate\n";
370 371 372 373
	    $expires{$idx} = $stamp;
	    $slice->UnLock();
	    goto skip;
	}
374 375
	
	if ($impotent) {
376
	    print STDERR
377
		"Would send mail to $geniuser: $idx,$hrn,$diff $unit\n";
378 379 380 381
	}
	else {
	    print STDERR
		"Sending mail to $geniuser about expiring sliver $aggregate\n";
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
	}
	if (!exists($expires{$idx})) {
	    print STDERR "--> This is first warning\n";
	    $expires{$idx} = $stamp;

	    #
	    # Watch for startup condition; we do not want to send two
	    # emails right away cause we started up close to expiraton
	    # time of a sliver.
	    #
	    if ($stamp - time() <= $minwarn) {
		print STDERR "--> And second warning\n";
		$warned{$idx} = time();
	    }
	}
	else {
	    print STDERR "--> This is second warning\n";
	    $warned{$idx} = time();
	}
	if (! $impotent) {
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
	    my $subject;
	    my $message;
	    if (!defined($slice->portal_tag())) {
		$subject = "Sliver expiring at $OURDOMAIN";
		$message = "Sliver $sliver_urn\n".
		    "from slice $urn,\n".
		    "is going to expire in approximately $diff $unit.\n\n".
		    "Please renew it".
		    " or let it expire if you are not using it anymore.\n";
	    }
	    else {
		my $tag = ucfirst($slice->portal_tag());
		my $url = $slice->portal_url();
		my $eid = $slice->portal_eid();
		$subject = "$tag portal experiment is expiring";
		$message = "Your $tag portal experiment $eid at $OURDOMAIN".
		    (defined($url) ?
		     ":\n\n" . "   $url" . "\n\n" : "\n") .
		    "is going to expire in approximately $diff $unit.\n\n".
		    "Please extend it".
		    " or let it expire if you are not using it anymore.\n";
	    }
	    SENDMAIL($emailaddr, $subject, $message, "$TBOPS");
425 426 427 428 429 430 431 432
	}
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

Leigh Stoller's avatar
Leigh Stoller committed
433
#
434 435
# Look for slices that need to be expired. Do not expire shutdown slices;
# Handled below, and we want to keep the record around.
Leigh Stoller's avatar
Leigh Stoller committed
436 437 438 439
#
sub ExpireSlices()
{
    my $query_result =
440 441 442 443 444 445
	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)) ".
446
			    " and shutdown is null and lockdown=0");
Leigh Stoller's avatar
Leigh Stoller committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460

    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)) {
461
	    print STDERR "Could not get experiment for $slice. Expiring ...\n";
Leigh Stoller's avatar
Leigh Stoller committed
462
	    $slice->UnLock();
463
	    goto cleanup;
Leigh Stoller's avatar
Leigh Stoller committed
464 465 466 467 468 469
	}
	if ($experiment->Refresh() != 0) {
	    print STDERR "Could not flush $experiment\n";
	    $slice->UnLock();
	    goto skip;
	}
470 471 472 473 474
	if ($experiment->state() eq EXPTSTATE_PANICED()) {
	    print STDERR "Refusing to terminate a paniced experiment\n";
	    goto skip;
	}
	
Leigh Stoller's avatar
Leigh Stoller committed
475 476 477 478
	#
	# See if we have any local nodes. No point in using the idle
	# check if there are no nodes. 
	#
479
	if (0 && $idlecheck && !$slice->isplaceholder()) {
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	    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 Stoller's avatar
Leigh Stoller committed
497
	    }
Leigh Stoller's avatar
Leigh Stoller committed
498 499 500
	    print STDERR "$slice ($experiment) is idle; releasing.\n";
	}
	else {
501
	    if ($slice->isplaceholder()) {
502 503 504 505
		print STDERR "Releasing placeholder $slice";
		print STDERR " - $experiment"
		    if (defined($experiment));
		print STDERR "\n";
506 507
	    }
	    else {
508 509 510 511
		print STDERR "Expiring $slice";
		print STDERR " - $experiment"
		    if (defined($experiment));
		print STDERR "\n";
512
	    }
Leigh Stoller's avatar
Leigh Stoller committed
513
	}
514
      cleanup:
515
	my $slice_uuid  = $slice->uuid();
516 517
	my $output = emutil::ExecQuiet("$CLEANUPSLICE -f -m $slice_uuid");
	my $status = $?;
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
	if (defined($experiment)) {
	    my $gid_idx = $experiment->gid_idx();
	    my $logfile = Logfile->CreateFromString($gid_idx, $output);
	    if (defined($logfile)) {
		$logfile->SetMetadata([["slice_idx",  $slice->idx()],
				       ["slice_urn",  $slice->urn()],
				       ["slice_uuid", $slice->uuid()],
				       # For web interface listing
				       ["Method",     "Cleanup"],
				      ], 1);
		$logfile->Store();
	    }
	}
	else {
	    print STDERR "$output\n";
533
	}
534
	if ($status) {
Leigh Stoller's avatar
Leigh Stoller committed
535
	    print STDERR "Could not release $slice\n";
Leigh Stoller's avatar
Leigh Stoller committed
536 537
	    SENDMAIL($TBOPS, "Could not release slice $slice",
		     "Could not release slice $slice");
Leigh Stoller's avatar
Leigh Stoller committed
538 539 540
	    # Leave it locked. 
	    goto skip;
	}
541 542
	delete($warned{"$idx"});
	delete($expires{"$idx"});
Leigh Stoller's avatar
Leigh Stoller committed
543 544 545 546
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
547 548
	$experiment->Flush()
	    if (defined($experiment));
Leigh Stoller's avatar
Leigh Stoller committed
549 550 551
    }
}

552 553 554 555 556 557 558
#
# Look for slices that need to be shutdown
#
sub ShutdownSlices()
{
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_slices ".
559
			    "where shutdown is not null and isshutdown=0");
560 561 562 563 564 565 566 567 568 569 570 571 572 573

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

	#
574
	# The isshutdown flag avoids churning the system.
575 576 577 578 579 580
	#
	if (GeniCM::CleanupDeadSlice($slice, 0) != 0) {
	    print STDERR "Could not shutdown $slice\n";
	    SENDMAIL($TBOPS, "Could not shutdown slice",
		     "Could not shutdown slice $slice");
	}
581
	$slice->SetShutdownFlag(1);
582 583 584 585 586 587 588
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
#
# 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.
609
	    $aggregate->Flush();
610 611 612 613 614
	    next;
	}
	# Run the register script. Ignore errors; we will retry again later.
	print STDERR "Registering $slice ($aggregate)\n";
	system("$REGISTER " . $slice->idx());
615 616
	$slice->Flush();
	$aggregate->Flush();
617 618 619
    }
}

620 621 622 623 624
sub ReportLockedSlices()
{
    my $msg = "";
    
    my $query_result =
625
	GeniDB::DBQueryWarn("select idx,locked,expires,hosed,now() > expires ".
626
			    "  from geni_slices ".
627 628 629
			    "where locked is not null and ".
			    "      DATE_SUB(NOW(),INTERVAL 1 DAY) >= locked");
    if (!$query_result) {
630 631
	print STDERR "ReportLockedSlices: Error getting info from the DB.\n";
	return;
632 633 634 635
    }
    return
	if (!$query_result->numrows);

636
    while (my ($idx, $locked, $expires,$hosed, $expired) =
637
	   $query_result->fetchrow_array()) {
638 639 640 641 642 643 644 645
	my $slice = GeniSlice->Lookup($idx);

	if (!defined($slice)) {
	    # Slice is gone, lets not worry.
	    next;
	}
	my $urn = $slice->urn();
	
646 647 648 649 650 651 652
	# If hosed, we have already tried to clean it up, but failed.
	# Just add to the report, again.
	goto hosed
	    if ($hosed);

	goto hosed
	    if ($impotent);
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 682
	if ($expired) {
	    my $logfile;
	    my $experiment  = $slice->GetExperiment();
	    my $slice_uuid  = $slice->uuid();
	    my $output = emutil::ExecQuiet("$CLEANUPSLICE -f -m $slice_uuid");
	    my $status = $?;
	    if (defined($experiment)) {
		my $gid_idx = $experiment->gid_idx();
		my $logfile = Logfile->CreateFromString($gid_idx, $output);
		if (defined($logfile)) {
		    $logfile->SetMetadata([["slice_idx",  $slice->idx()],
					   ["slice_urn",  $slice->urn()],
					   ["slice_uuid", $slice->uuid()],
					   # For web interface listing
					   ["Method",     "Cleanup"],
					  ], 1);
		    $logfile->Store();
		}
	    }
	    else {
		print STDERR "$output\n";
	    }
	    if ($status) {
		$hosed = 1;
		$slice->SetHosedFlag(1);
	    }
	}
	
      hosed:
683
	$msg .= ($hosed ? "Hosed - " : "") . "$urn : $locked, $expires\n";
684
	print STDERR
685
	    ($hosed ? "Hosed - " : "") . "$urn : locked since $locked, expires at $expires\n";
686
	$slice->Flush();
687 688 689 690 691 692 693 694
    }
    return
	if ($msg eq "");

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
695
	     "ProtoGENI CM daemon: Locked Slices",
696 697 698 699 700
	     "The following CM slices have been locked for a long time\n\n".
	     $msg,
	     $TBOPS);
}

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 731 732 733 734 735 736 737 738 739 740 741 742 743
#
# 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()) {
744 745 746 747 748 749 750
	if (!$impotent) {
	    GeniDB::DBQueryWarn("delete from geni_certificates ".
				"where uuid='$uuid'");
	}
	else {
	    $msg .= "$uuid : $urn\n";
	}
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
	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);
}

766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
#
# Push stats up to the clearing house.
#
sub PushStats()
{
    my $lastidx = VersionInfo("aggregates_pushed");
    if (!defined($lastidx)) {
	$lastidx = 0;
	UpdateVersionInfo("aggregates_pushed", 0) == 0
	    or return -1;
    }

    #
    # Look for any records we have not reported. Note that we do not mark
    # a record as reported until it actually has a destroyed date. We still
    # send in the record though, we just might report it again when it is
    # destroyed. The CH will notice that.
    #
    # Limit to small number of records at a time to avoid pounding the CH.
    #
    my $query_result =
	GeniDB::DBQueryWarn("select * from aggregate_history ".
788 789 790
			    "where type='Aggregate' and ".
			    "      (idx>$lastidx or ".
			    "       (idx<=$lastidx and reported is null)) ".
791
			    "limit 100");
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
    return -1
	if (!$query_result);
    return 0
	if (!$query_result->numrows);
    
    my $clearinghouse = GeniRegistry::ClearingHouse->Create();
    if (!defined($clearinghouse)) {
	print STDERR "Could not create a clearinghouse client\n";
	return -1;
    }
    
    while (my $row = $query_result->fetchrow_hashref()) {
	my $aggregate_uuid = $row->{'uuid'};
	my $aggregate_idx  = $row->{'idx'};

	# Older records do not have this, but easy to generate.
	if (!defined($row->{'urn'}) || $row->{'urn'} eq "") {
	    $row->{'urn'} =
		GeniHRN::Generate($OURDOMAIN, "sliver", $aggregate_idx);
	}
	my $aggregate_urn = $row->{'urn'};

	#
	# If not destroyed, check for active aggregate. Maybe something
	# went wrong. There is a bit of race here; the aggregate might
	# have been destroyed in the meantime. Try to deal with that, but
	# in the end it is not that important, we can just fix up the
	# record.
	#
	if (!defined($row->{'destroyed'})) {
	    my $aggregate = GeniAggregate->Lookup($aggregate_idx);
	    if (!defined($aggregate)) {
		sleep(2);
		my $history_result =
		    GeniDB::DBQueryWarn("select destroyed from aggregate_history ".
					"where idx='$aggregate_idx'");

		return -1
		    if (!defined($history_result));

		if ($history_result->numrows == 0) {
		    #
		    # No idea what happened and not much to do.
		    #
		    print STDERR "aggregate_history record for ".
			"$aggregate_uuid ($aggregate_idx) is gone!\n";
		    next;
		}
		my ($destroyed) = $history_result->fetchrow_array();
		if (!defined($destroyed)) {
		    #
		    # Fix up the record.
		    #
		    print STDERR "aggregate_history says $aggregate_idx not ".
			"destroyed, but no aggregate exists. Fixing record\n";
		    GeniDB::DBQueryWarn("update aggregate_history set ".
					"  destroyed=now() ".
					"where idx='$aggregate_idx'")
			or return -1;
		    # We can catch it next loop.
		    next;
		}
		# Update and continue.
		$row->{'destroyed'} = $destroyed;
	    }
	}
	
	#
	# Find the manifests that have not been reported. We do not
	# record updates in a formal manner, except that there will
	# be a manifest record for each update.
	#
	my $manifest_results =
	    GeniDB::DBQueryWarn("select idx,created,manifest ".
				"  from manifest_history ".
				"where aggregate_uuid='$aggregate_uuid' and ".
				"      reported is null");
	return -1
	    if (!$manifest_results);

	#
	# If there are no manifests, and the index is less then then
	# the cutoff, this is one that is waiting to terminate. There
	# is no reason to send a new record. 
	#
	my $count = $manifest_results->numrows;

	if (!$count && $aggregate_idx <= $lastidx &&
	    !defined($row->{'destroyed'})) {
	    print STDERR "Skipping running aggregate $aggregate_idx\n";
	    next;
	}

	#
	# No manifests is okay, probably means we are reporting the demise
	# of an aggregate we reported earlier.
	#
	do {
	    $count--;
	    my ($manifest_idx, $manifest_created, $manifest) =
		$manifest_results->fetchrow_array();

	    if (defined($manifest_idx)) {
		$row->{'manifest'} = $manifest;
		# convert to gmt
		$row->{'created'} =
		    POSIX::strftime("20%y-%m-%dT%H:%M:%SZ",
				    gmtime(str2time($manifest_created)));
	    }
	    else {
		# convert to gmt
		$row->{'created'} =
		    POSIX::strftime("20%y-%m-%dT%H:%M:%SZ",
				    gmtime(str2time($row->{'created'})));
	    }
	    if (defined($row->{'destroyed'})) {
		# convert to gmt
		$row->{'destroyed'} =
		    POSIX::strftime("20%y-%m-%dT%H:%M:%SZ",
				    gmtime(str2time($row->{'destroyed'})));
	    }
	    else {
		# Do not send undefined value.
		delete($row->{'destroyed'});
	    }
	    # Do not send this. 
	    delete($row->{'reported'});
	    
	    if ($impotent) {
		print STDERR "Would post:\n";
		print STDERR Dumper($row);
		next;
	    } else {
		print STDERR "Posting aggregate record: $aggregate_urn\n";
		print STDERR "Posting with manifest: $manifest_idx\n"
		    if (defined($manifest_idx));
	    }
	    my $response = $clearinghouse->PostHistoryRecord($row);
	    if (!defined($response)) {
		print STDERR "Could not talk to clearinghouse\n";
		return -1;
	    }
	    if ($response->code() != GENIRESPONSE_SUCCESS) {
		print STDERR "Error posting history record: ".
		    $response->output() . "\n";
		return -1;
	    }
	    #
	    # Mark manifest reported.
	    #
	    if (defined($manifest_idx)) {
		GeniDB::DBQueryWarn("update manifest_history set reported=now() ".
				    "where idx='$manifest_idx'")
		    or return -1;
	    }
	    sleep(1);
	} while ($count > 0);

	next
	    if ($impotent);

	#
	# Mark aggregate record reported if destroyed.
	#
	if (defined($row->{'destroyed'})) {
	    GeniDB::DBQueryWarn("update aggregate_history set reported=now() ".
				"where idx='$aggregate_idx'")
		or return -1;
	}
	#
	# Update the last idx we reported on, for the next time.
	#
	UpdateVersionInfo("aggregates_pushed", $aggregate_idx) == 0
	    or return -1;
    }
    return 0;
}

970 971 972 973 974
#
# Look for idle slivers. 
#
sub CheckIdle()
{
975 976 977
    my $mailinterval        = 1;
    my $idlecheck_threshold = 1;
    my $idlecheck_norenew   = 0;
978
    my $debug = 1;
979

980
    if (! (GetSiteVar("idle/mailinterval", \$mailinterval) &&
981 982
	   GetSiteVar("protogeni/idlecheck_threshold", \$idlecheck_threshold) &&
	   GetSiteVar("protogeni/idlecheck_norenew",\$idlecheck_norenew))) {
983 984 985
	print STDERR "Could not get idle parameters.\n";
	return;
    }
986
    # Threshold in hours, convert to minutes.
987
    $idlecheck_threshold = $idlecheck_threshold * 60;
988 989 990 991
    
    my $query_result =
	GeniDB::DBQueryWarn("select idx,UNIX_TIMESTAMP(created) ".
			    "  from geni_slices ".
992
			    "where shutdown is null and ".
993
			    "      hosed=0 and lockdown=0 and isplaceholder=0");
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

    while (my ($idx,$created) = $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;
	}

	# We want the aggregate for the sliver urn, but it might
	# not actually exist yet.
	my $aggregate = GeniAggregate->SliceAggregate($slice);
	if (!defined($aggregate)) {
1011 1012
	    print STDERR "No aggregate created yet for $slice\n"
		if ($debug);
1013 1014 1015 1016 1017 1018 1019
	    $slice->UnLock();
	    goto skip;
	}
	my $experiment = $slice->GetExperiment();
	if (!defined($experiment)) {
	    print STDERR "Could not get experiment for $slice. Expiring ...\n";
	    $slice->UnLock();
1020
	    goto skip;
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
	}
	if ($experiment->Refresh() != 0) {
	    print STDERR "Could not flush $experiment\n";
	    $slice->UnLock();
	    goto skip;
	}
	my $exptidx = $experiment->idx();

	if ($debug) {
	    print STDERR "Checking idle for $slice\n";
	}

	#
	# This query comes out of db/idlemail.in ... I'm not willing
	# to mess with that code.
	#
	my $idle_result =
	    emdb::DBQueryWarn(
		        "select r.pid, e.gid, r.eid, idleswap_timeout, ".
			"  swap_requests, idle_ignore, idleswap, ".
			"  round((unix_timestamp(now()) - ".
			"         unix_timestamp(last_swap_req))/3600,2) ".
			"    as lastreq, ".
1044
			"  count(r.node_id) as nodes ".
1045 1046
			"from node_activity as na ".
			"left join reserved as r on na.node_id=r.node_id ".
1047 1048
		        "left join nodes as n on na.node_id=n.node_id ".
		        "left join node_types as nt on nt.type=n.type ".
1049
			"left join experiments as e on r.exptidx=e.idx ".
1050
			"where r.exptidx=$exptidx and nt.isvirtnode=0 ".
1051 1052 1053 1054 1055 1056 1057 1058 1059
			"group by pid,eid having nodes > 0 ");
	if (!defined($idle_result)) {
	    print STDERR "Could not get idle data for $experiment\n";
	    $slice->UnLock();
	    goto skip;
	}
	my $row = $idle_result->fetchrow_hashref();

	my $idleswap   = $row->{'idleswap'};
1060
	# idleswap_timeout in minutes
1061 1062 1063
	my $timeout    = $row->{'idleswap_timeout'};
	my $ignore     = $row->{'idle_ignore'};
	my $swapreqs   = $row->{'swap_requests'};
1064
	# lastreq in hours
1065 1066
	my $lastreq    = $row->{'lastreq'};
	my $nodes      = $row->{'nodes'};
1067
	my $urn        = $slice->urn();
1068 1069

	#
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
	# Now pull in per-node data. We want to compute a percentage
	# of idle nodes so that we can be a little smarter.
	#
	my $node_result =
	    emdb::DBQueryWarn("select r.node_id, ".
			"  greatest(last_tty_act,last_net_act,last_cpu_act,".
			"           last_ext_act) as lastact,".
			"  round((unix_timestamp(now()) - ".
			"         unix_timestamp(greatest(last_tty_act, ".
			"           last_net_act, last_cpu_act, ".
			"           last_ext_act)))/60,1) as idle_time, ".
			"  (unix_timestamp(now()) - ".
			"   unix_timestamp(last_report)) as staleness ".
			"from reserved as r ".
			"left join node_activity as na on ".
			"     na.node_id=r.node_id ".
		        "left join nodes as n on n.node_id=r.node_id ".
		        "left join node_types as nt on nt.type=n.type ".
			"left join experiments as e on r.exptidx=e.idx ".
			"where r.exptidx=$exptidx and nt.isvirtnode=0");

	if (!defined($node_result)) {
	    print STDERR "** Could not get node idle data for $experiment\n";
	    $slice->UnLock();
	    goto skip;
	}
	# Skip if no physical nodes; eventually come back to this.
	if (!$node_result->numrows) {
	    print STDERR "-> No physical nodes; skipping\n";
	    $slice->UnLock();
	    goto skip;
	}
	my %node_idledata = ();
	my $stalenodes    = 0;
	my $idlenodes     = 0;
	my $reporting     = 0;

	#
	# staleness. If undef, the node has not reported any idle data
1109 1110 1111 1112 1113 1114 1115 1116
	# since inception, lets skip since we do not know anything. Note
	# that idletime will also be null. If the staleness is really big,
	# all of the nodes have stopped reporting, and that means they are
	# all offline or otherwise munged to stop reporting. I am going to
	# treat those as idle. The user can argue with us about it.  If the
	# staleness is small, we trust the data idle data to be accurate.
	# If the staleness is medium, then wait longer.
	#
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
	while (my $noderow = $node_result->fetchrow_hashref()) {
	    my $node_id   = $noderow->{'node_id'};
	    my $lastact   = $noderow->{'lastact'};
	    # idletime in in minutes
	    my $idletime  = $noderow->{'idle_time'};
	    # staleness in in seconds
	    my $staleness = $noderow->{'staleness'};
	    $node_idledata{$node_id} = $noderow;

	    #
	    # staleness; if null, the node is not reporting any idle
	    # data since inception; lets skip it since we do not know
	    # anything. We view these nodes at not idle for now. Needs
	    # more thought.
	    #
	    next
		if (!defined($staleness));

	    $reporting++;

	    #
	    # If the staleness is big the node has stopped reporting,
	    # and that means it is offline or otherwise munged to stop
	    # reporting. I am going to treat those as idle. The user can
	    # argue with us about it.
	    #
	    if ($staleness > ($idlecheck_threshold * 60)) {
		$idlenodes++;
		$noderow->{'idle'} = 1;
		next;
	    }

	    #
	    # Otherwise, if the staleness is small, we trust the 
	    # idle data to be accurate. If the staleness is medium, then
	    # wait longer before using this node.
	    #
	    if ($staleness > (15 * 60)) {
		$stalenodes++;
		$noderow->{'stale'} = 1;
		next;
	    }
1159

1160 1161 1162 1163 1164 1165 1166 1167 1168
	    #
	    # Finally, look at the idle time.
	    #
	    if ($idletime > $idlecheck_threshold) {
		$idlenodes++;
		$noderow->{'idle'} = 1;
		next;
	    }
	}
1169
	#
1170
	# If no idle data, nothing do do.
1171
	#
1172 1173
	if (! $reporting) {
	    print STDERR "-> No idle data for $slice. Skipping ...\n"
1174 1175 1176 1177
		if ($debug);
	    $slice->UnLock();
	    goto skip;
	}
1178 1179 1180 1181 1182
	print STDERR "-> $urn is using $nodes physical nodes:\n";
	print STDERR "   reporting:$reporting, idle:$idlenodes, ".
	    "stale:$stalenodes\n";
	print STDERR "   But idle ignore is set.\n"
	    if ($ignore);
1183 1184 1185 1186 1187 1188
	
	#
	# We want to report as much idle data as possible, but
	# if the slice has not passed its idletime setting, or
	# if idleswap is off, we skip.
	#
1189 1190 1191 1192
	my $geniuser  = GeniUser->Lookup($slice->creator_uuid(), 1);
	my $emailaddr = $geniuser->email();
	my $sliver_urn= $aggregate->urn();
	
1193
	if ($idleswap && ($idlenodes / ($reporting * 1.0) >= 0.50)) {
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
	    my $stats     = "";

	    foreach my $node (keys(%node_idledata)) {
		if (exists($node_idledata{$node}->{'idle'})) {
		    $stats .=
			sprintf("%40s - %.2f hours idle\n",
				"${node}.${OURDOMAIN}",
				$node_idledata{$node}->{'idle_time'}/60.0);
		}
	    }
	    
1205 1206 1207
	    #
	    # Send email if none sent or if the minimum time since
	    # since the last message has passed. In general, we will not
1208 1209
	    # send more then one message in a 24 hour period to avoid
	    # annoying people to much.
1210
	    #
1211
	    if ($idlecheck_norenew &&
1212
		$swapreqs && ($lastreq * 60) > (2 * $idlecheck_threshold)) {
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
		if (!defined($slice->renew_limit()) ||
		    $slice->renew_limit_stamp()) {
		    #
		    # Current policy is no second warnings; the 
		    # slice may not be renewed, even if it goes non idle
		    # again. Setting the renew limit to zero tells the CM
		    # to not allow any renew.
		    #
		    print STDERR "** Slice can no longer be renewed!\n";

		    if (!$impotent) {
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
			my $subject;
			my $message;
			if (defined($slice->portal_tag())) {
			    my $tag = ucfirst($slice->portal_tag());
			    my $url = $slice->portal_url();
			    my $eid = $slice->portal_eid();
			    $subject = "$tag portal experiment ".
				"may not be extended";
			    $message = "Your $tag portal experiment $eid at ".
				"$OURDOMAIN".
				(defined($url) ?
				 ":\n\n" . "   $url" . "\n\n" : "\n");
			}
			else {
			    $subject = "Sliver $sliver_urn may not be renewed";
			    $message = "Sliver $sliver_urn\n".
				"from slice $urn,\n";
			}
			$message .= 
			    "has been mostly idle for too long,\n".
			    "and is using $nodes physical nodes.\n\n".
			    "$stats\n".
			    "You will not be allowed to extend it!\n";
1247
		
1248 1249
			SENDMAIL($emailaddr, $subject, $message,
				 $TBOPS, "CC: $TBAUTOMAIL");
1250
			$slice->SetRenewLimit(0);
1251 1252
		    }
		}
1253 1254 1255 1256 1257 1258
	    }
	    elsif ($swapreqs == 0 || $lastreq > 24 || $debug > 1) {
		my $norenew   =
		    (defined($slice->renew_limit()) &&
		     $slice->renew_limit_stamp() == 0 ? 1 : 0);

1259 1260 1261 1262 1263 1264 1265
		if ($impotent) {
		    print STDERR "   Would send email to $geniuser\n";
		    print STDERR $stats if ($stats ne "");
		}
		else {
		    print STDERR "   Sending mail to $geniuser about ".
			"idle sliver $aggregate\n";
1266

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
		    my $subject;
		    my $message;
		    if (defined($slice->portal_tag())) {
			my $tag = ucfirst($slice->portal_tag());
			my $url = $slice->portal_url();
			my $eid = $slice->portal_eid();
			$subject = "$tag portal experiment ".
			    "is mostly idle";
			$message = "Your $tag portal experiment $eid at ".
			    "$OURDOMAIN".
			    (defined($url) ?
			     ":\n\n" . "   $url" . "\n\n" : "\n") .
			    "has been mostly idle for an unusual length ".
			    "of time,\n".
			    "and is using $nodes physical nodes.\n\n".
			    "$stats\n".
			    ($idlecheck_norenew ?
			     ($norenew ?
			      "You may no longer extend this experiment, and ".
			      "it might be terminated " :
			      "You will not be allowed to extend this ".
			      "experiment ") :
			     "This experiment might be terminated ") .
			    "if it stays idle.\n",
		    }
		    else {
			$subject = "Sliver $sliver_urn is mostly idle";
			$message = "Sliver $sliver_urn\n".
			    "from slice $urn,\n".
			    "has been mostly idle for an unusual length ".
			    "of time,\n".
			    "and is using $nodes physical nodes.\n\n".
			    "$stats\n".
			    ($idlecheck_norenew ?
			     ($norenew ?
			      "You may no longer renew this sliver, and it ".
			      "might be terminated " :
			      "You will not be allowed to renew this sliver ") :
			     "This sliver might be terminated ") .
			    "if it stays idle.\n",
		    }
		    SENDMAIL($emailaddr, $subject, $message,
			     $TBOPS, "CC: $TBAUTOMAIL");
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

		    emdb::DBQueryWarn("update experiments set ".
				      "   swap_requests=swap_requests+1, ".
				      "   last_swap_req=now() ".
				      "where idx='$exptidx'");
		}
	    }
	}
	else {
	    # Reset warnings.
1320 1321 1322
	    print STDERR "Resetting swap_requests for $slice\n"
		if ($debug);
	   
1323 1324 1325 1326 1327 1328 1329 1330 1331
	    emdb::DBQueryWarn("update experiments set swap_requests=0 ".
			      "where idx='$exptidx'")
		if (!$impotent);
	}
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
1332 1333
}

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
#
# Check Aggregate states/status. 
#
sub CheckAggregates()
{
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_aggregates ".
			    "where type='Aggregate' and status!='ready'");

    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.
	    $aggregate->Flush();
	    next;
	}
	if ($slice->Lock() != 0) {
	    goto skip;
	}
	my $state  = $aggregate->state();
	my $status = $aggregate->status();
	my $stamp  = $aggregate->status_state_timestamp();
	
	#
	# If an aggregate have been trying to update users for more then
	# 30 minutes, kill that and return the aggregate to normal status.
	#
	if ($state eq "updating_users" && time() - $stamp > 1 * 60) {
	    if ($impotent) {
		print STDERR "Would cancel update accounts for $aggregate\n";
	    }
	    else {
		print STDERR "Canceling update accounts for $aggregate\n";
		$aggregate->CancelUpdateAccounts();
	    }
	}
	$slice->UnLock();
      skip:
	$slice->Flush();
	$aggregate->Flush();
    }
}

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
#
# Notify the "portal" of the status of all slivers. Might be the local
# portal or the Cloudlab portal. Or both since a cluster might be part
# of Cloudlab, but allowing use of the local portal UI.
#
my %notify_timestamps = ();

sub NotifyPortal()
{
    my %slices     = ();
    my %aggregates = ();
    my $count      = 0;
    my $max        = 15;  # 15 at a time.
    my $interval   = 600; # 10 minutes;
    
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_aggregates ".
			    "where type='Aggregate'");
    
    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.
	    $aggregate->Flush();
	    next;
	}
	$slices{$slice->uuid()} = $slice;
	$aggregates{$slice->uuid()} = $aggregate;
    }
    foreach my $slice (values(%slices)) {
	my $aggregate = $aggregates{$slice->uuid()};
	
	if ($slice->Lock() != 0) {
	    print STDERR "NotifyPortal: Could not lock slice $slice.\n";
	    goto skip;
	}
	#
	# Send events every 10 minutes for a slice, but do not want to
	# do all of them at exactly the same time, so lets spread things
	# out a bit.
	#
	if (!exists($notify_timestamps{$slice->uuid()})) {
	    $notify_timestamps{$slice->uuid()} = time();
	}
	my $last = $notify_timestamps{$slice->uuid()};
	if (time() - $last < $interval) {
	    if ($debug) {
		print STDERR "NotifyPortal: Skipping $slice this time\n";
	    }
	    $slice->UnLock();
	    goto skip;
	}
	
	#
	# If this causes anything to change, events will get sent.
	#
	if ($debug) {
	    print STDERR "NotifyPortal: $slice\n";
	}
	$aggregate->SendAllStatusEvents();
	$slice->UnLock();
	$count++;
	$notify_timestamps{$slice->uuid()} = time();
	# Lets not flood too fast.
	sleep(1);
      skip:
	$slice->Flush();
	$aggregate->Flush();
	# Only this many per minute.
	last
	    if ($count >= $max);
    }
    my %tmp = ();
    # Watch for slices that are gone so that this array does not get big.
    foreach my $uuid (keys(%notify_timestamps)) {
	$tmp{$uuid} = $notify_timestamps{$uuid} if (exists($slices{$uuid}));
    }
    %notify_timestamps = %tmp;
}

1469 1470 1471
#
# Deal with image tracker stuff. 
#
1472 1473 1474 1475
# Lets not send repeat email for these failures, one is enough.
#
my %image_notifications = ();

1476 1477 1478 1479 1480
sub HandleImageTracking()
{
    if (!GetSiteVar("protogeni/use_imagetracker")) {
	return;
    }
1481 1482

    #
1483
    # Look for images deletions. Process in order deleted.
1484 1485
    #
    my $query_result =
1486
	DBQueryWarn("select * from image_deletions order by deleted asc");
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
    return
	if (!$query_result);
    while (my $row = $query_result->fetchrow_hashref()) {
	my $urn  = $row->{'urn'};
	my $uuid = $row->{'image_uuid'};

	if ($impotent) {
	    print "Would trigger image delete for $urn\n";
	    next;
	}

	my $output = emutil::ExecQuiet("$DELETEIMAGEDATA '$urn' $uuid");
	if ($?) {
	    print $output;
	    SENDMAIL($TBOPS,
		     "Could not delete image data at the IMS for $urn/$uuid",
		     $output,
		     $TBOPS);
	    next;
	}
	DBQueryWarn("delete from image_deletions ".
		    "where urn='$urn' and image_uuid='$uuid'");
    }
1510 1511 1512 1513 1514 1515
    
    #
    # Look for images notifications; these are new local snapshots that need
    # to be copied back to their origin, so we have to tell the origin of that
    # image.
    #
1516
    $query_result =
1517 1518 1519 1520 1521
	DBQueryWarn("select * from image_notifications");
    return
	if (!$query_result);
    while (my $row = $query_result->fetchrow_hashref()) {
	my $imageid = $row->{'imageid'};
1522
	my $image   = OSImage->Lookup($imageid);
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
	if (!defined($image)) {
	    print STDERR "$imageid no longer exists. Skipping notification.\n";
	    next;
	}
	if ($impotent) {
	    print "Would trigger update for $image\n";
	    next;
	}
	
	#
	# Lets avoid needless errors cause the image is locked, take the
	# lock here and call it with the nolock option.
	#
	if ($image->Lock()) {
	    print STDERR "$image is locked, skipping\n";
	    next;
	}
	my $output = emutil::ExecQuiet("$TRIGGERUPDATE -l $imageid");
	my $status = $?;
	$image->Unlock();
	if ($?) {
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
	    print STDERR "Could not trigger an image update for $imageid:\n";
	    print STDERR $output;
	    if (!exists($image_notifications{$image->versid()})) {
		SENDMAIL($TBOPS,
			 "Could not trigger an image update for $imageid",
			 $output, $TBOPS);

		$image_notifications{$image->versid()} = 1;
	    }
	    next;
1554
	}
1555
	delete($image_notifications{$image->versid()});
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
    }

    #
    # Look for images that need to be copied back (cause we were notified
    # in the loop above). These are images that need to be imported from
    # the cluster where the snapshot was made.
    #
    $query_result =
	DBQueryWarn("select * from image_updates");
    return
	if (!$query_result);
    
    while (my $row = $query_result->fetchrow_hashref()) {
	my $imageid = $row->{'imageid'};
1570
	my $image   = OSImage->Lookup($imageid);
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
	
	if (!defined($image)) {
	    print STDERR "$imageid no longer exists. Skipping update ...\n";
	    next;
	}
	if ($impotent) {
	    print "Would import new version of $image\n";
	    next;
	}
	my $output = emutil::ExecQuiet("$IMPORTER -d -g -r -c $imageid");
	if ($?) {
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
	    print STDERR "Could not import image update for $imageid\n";
	    print STDERR $output;
	    if (!exists($image_notifications{$image->versid()})) {
		SENDMAIL($TBOPS,
			 "Could not import image update for $imageid",
			 $output,
			 $TBOPS);
		$image_notifications{$image->versid()} = 1;
	    }
	    next;
1592
	}
1593
	delete($image_notifications{$image->versid()});
1594 1595 1596 1597 1598
    }
    my $opt = ($impotent ? "-n" : "");

    # Trigger a posting to the IMS for any new images.
    my $output = emutil::ExecQuiet("$POSTIMAGEDATA -v $opt all");
1599 1600 1601 1602
    if ($?) {
	print STDERR "Could not post image data to the IMS:\n";
	print STDERR $output;
    }
1603
    print $output;
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
}

#
# Watch for stuff that has been failing for more then a few minutes,
# and send email periodically.
#
sub HandleImageFailures()
{
    if (!GetSiteVar("protogeni/use_imagetracker")) {
	return;
    }

    #
    # Look for images deletions that have not been accepted.
    #
    my $query_result =
	DBQueryWarn("select * from image_deletions ".
		    "where ".
		    "order by deleted asc");
    return
	if (!$query_result);
    while (my $row = $query_result->fetchrow_hashref()) {
	my $urn  = $row->{'urn'};
	my $uuid = $row->{'image_uuid'};

	if ($impotent) {
	    print "Would trigger image delete for $urn\n";
	    next;
	}

	my $output = emutil::ExecQuiet("$DELETEIMAGEDATA '$urn' $uuid");
	if ($?) {
	    print STDERR
		"Could not delete image data at the IMS for $urn/$uuid:\n";
	    print STDERR $output;
	    next;
	}
	DBQueryWarn("delete from image_deletions ".
		    "where urn='$urn' and image_uuid='$uuid'");
    }
    
    #
    # Look for images notifications; these are new local snapshots that need
    # to be copied back to their origin, so we have to tell the origin of that
    # image.
    #
    $query_result =
	DBQueryWarn("select * from image_notifications");
    return
	if (!$query_result);
    while (my $row = $query_result->fetchrow_hashref()) {
	my $imageid = $row->{'imageid'};
	my $image   = Image->Lookup($imageid);
	if (!defined($image)) {
	    print STDERR "$imageid no longer exists. Skipping notification.\n";
	    next;
	}
	if ($impotent) {
	    print "Would trigger update for $image\n";
	    next;
	}
	
	#
	# Lets avoid needless errors cause the image is locked, take the
	# lock here and call it with the nolock option.
	#
	if ($image->Lock()) {
	    print STDERR "$image is locked, skipping\n";
	    next;
	}
	my $output = emutil::ExecQuiet("$TRIGGERUPDATE -l $imageid");
	my $status = $?;
	$image->Unlock();
	if ($?) {
	    print STDERR "Could not trigger an image update for $imageid:\n";
	    print STDERR $output;
	}
    }

    #
    # Look for images that need to be copied back (cause we were notified
    # in the loop above). These are images that need to be imported from
    # the cluster where the snapshot was made.
    #
    $query_result =
	DBQueryWarn("select * from image_updates");
    return
	if (!$query_result);
    
    while (my $row = $query_result->fetchrow_hashref()) {
	my $imageid = $row->{'imageid'};
	my $image   = Image->Lookup($imageid);
	
	if (!defined($image)) {
	    print STDERR "$imageid no longer exists. Skipping update ...\n";
	    next;
	}
	if ($impotent) {
	    print "Would import new version of $image\n";
	    next;
	}
	my $output = emutil::ExecQuiet("$IMPORTER -d -g -r -c $imageid");
	if ($?) {
	    print STDERR "Could not import image update for $imageid\n";
	    print STDERR $output;
	}
1710
    }
1711

1712
}
1713

1714
if ($oneshot) {
1715
    WarnSlices();
1716 1717 1718
    exit(0);
}

1719
# Do this once at startup
1720 1721 1722 1723 1724 1725
if (! NoLogins()) {
    sleep(5);
    ReportLockedSlices();
    ReportOrphanedCerts();
    CheckIdle();
}
1726

1727 1728
my $reportcounter = 0;
my $idlecounter   = 0;
1729

Leigh Stoller's avatar
Leigh Stoller committed
1730
while (1) {
1731 1732 1733 1734
    if (NoLogins()) {
	sleep(5);
	next;
    }
1735 1736 1737 1738
    my $doidlechecks;

    # Site var normally controls idle checks, but it can be turned
    # via the command line as well.
1739
    if (! GetSiteVar('protogeni/idlecheck', \$doidlechecks)) {
1740 1741 1742 1743 1744 1745
	# Cannot get the value, default it to off.
	$doidlechecks = 0;
    }
    
    $reportcounter += $SLEEP_INTERVAL;
    $idlecounter   += $SLEEP_INTERVAL;
1746
    
Leigh Stoller's avatar
Leigh Stoller committed
1747 1748
    print "Running at ".
	POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime()) . "\n";
1749

1750
    if (0) {
1751 1752 1753
	WarnSlices();
	goto loop;
    }
1754
    
Leigh Stoller's avatar
Leigh Stoller committed
1755
    ExpireTickets();
1756 1757
    WarnSlices();
    ExpireSlices();
1758 1759 1760 1761

    #
    # Run the idle check periodically. 
    # 
1762
    if ($idlecounter >= (10 * 60)) {
1763 1764 1765 1766
	CheckIdle()
	    if ($idlecheck || $doidlechecks);
	$idlecounter = 0;
    }
1767
    ShutdownSlices();
1768
    RegisterSlices();
1769
    PushStats();
1770

1771
    if ($reportcounter >= (24 * 60 * 60)) {
1772
	ReportLockedSlices();
1773
	ReportOrphanedCerts();
1774
	$reportcounter = 0;
1775
    }
1776
    NotifyPortal();
1777
    HandleImageTracking();
1778
    CheckAggregates();
Leigh Stoller's avatar
Leigh Stoller committed
1779

1780 1781 1782
    # Be certain stale info is gone.
    Experiment->FlushAll();
    Node->FlushAll();
1783
    GeniUtil::FlushCaches();
1784

1785
  loop:
Leigh Stoller's avatar
Leigh Stoller committed
1786
    print "Sleeping for $SLEEP_INTERVAL seconds ...\n";
1787
    sleep($SLEEP_INTERVAL);
Leigh Stoller's avatar
Leigh Stoller committed
1788 1789 1790 1791 1792 1793 1794
}
exit(0);

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

1795 1796 1797 1798 1799 1800 1801
    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
	     "ProtoGENI expire daemon died",
	     $msg,
	     $TBOPS);
1802
    MarkDaemonStopped("expire_daemon");
Leigh Stoller's avatar
Leigh Stoller committed
1803 1804 1805
    die("*** $0:\n".
	"    $msg\n");
}