expire_daemon.in 35.4 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
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.
# 
# }}}
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
43 44 45
# 
sub usage()
{
46
    print "Usage: expire_daemon [-d] [-i]\n";
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
62
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
63
my $OURDOMAIN     = "@OURDOMAIN@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
64
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
65
my $LOGFILE       = "$TB/log/expire_daemon.log";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
66
my $IDLETIMES	  = "$TB/sbin/idletimes";
67
my $EMULAB_PEMFILE = "$TB/etc/genicm.pem";
68
my $REGISTER      = "$TB/sbin/protogeni/register_sliver";
69
my $CLEANUPSLICE  = "$TB/sbin/cleanupslice";
70
my $CLEANUPTICKET = "$TB/sbin/cleanupticket";
71
my $SLEEP_INTERVAL= 60;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

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

89 90 91 92 93 94 95
#
# Exit if not a protogeni site.
#
if (! $PGENISUPPORT) {
    exit(0);
}

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

# Do this early so that we talk to the right DB.
use vars qw($GENI_DBNAME);
118
$GENI_DBNAME = "geni-cm";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
119 120 121

# Load the Testbed support stuff.
use lib "@prefix@/lib";
122
use emdb;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
123 124 125 126 127
require GeniDB;
require GeniUtil;
require GeniTicket;
require GeniSlice;
require GeniCM;
128
require GeniCertificate;
Leigh B Stoller's avatar
Leigh B Stoller committed
129
require GeniCredential;
130
require GeniAggregate;
131 132
require Genixmlrpc;
use GeniResponse;
133 134
use Experiment;
use Node;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
135
use libtestbed;
136
use emutil;
137
use libEmulab;
138
use Logfile;
139
use Project;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
140

141 142 143 144 145 146 147
#
# 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");
}
148 149
Genixmlrpc->SetContext(Genixmlrpc->Context($certificate));
Genixmlrpc->SetTimeout(10);
150 151 152
$ENV{'MYUUID'} = $certificate->uuid();
$ENV{'MYURN'} = "urn:publicid:IDN+@OURDOMAIN@+authority+cm";

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

181
GeniUtil::FlipToGeniUser();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

#
# 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;
	}
200 201
	if ($ticket->Lock() != 0) {
	    print STDERR "Could not lock ticket $ticket\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
202 203
	    goto skip;
	}
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
	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 B. Stoller's avatar
Leigh B. Stoller committed
222
	print "Expiring ticket $ticket\n";
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
	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 B. Stoller's avatar
Leigh B. Stoller committed
238 239
	    print STDERR "Could not delete $ticket\n";
	    SENDMAIL($TBOPS, "Could not delete ticket $idx",
240
		     "Could not delete ticket $ticket\nfor $slice");
241
	    # We leave it locked.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
242 243 244
	}
	else {
	    print STDERR "$ticket has been deleted\n";
245
	    $slice->UnLock();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
246 247
	}
      skip:
248 249 250 251 252 253
	$ticket->Flush()
	    if (defined($ticket));
	$slice->Flush()
	    if (defined($slice));
	$experiment->Flush()
	    if (defined($experiment));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
254 255 256
    }
}

257 258 259 260 261 262 263 264
#
# 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;
Leigh B Stoller's avatar
Leigh B Stoller committed
265 266
# Always warn within an hour of expiration, even short lived slices.
my $minwarn = 3600;
267 268 269 270 271 272 273 274 275 276

#
# 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 ".
Leigh B Stoller's avatar
Leigh B Stoller committed
277
			    "where shutdown is null and ".
278
			    "      hosed=0 and lockdown=0 and isplaceholder=0");
279 280 281 282

    while (my ($idx,$expires,$stamp,$created) =
	   $query_result->fetchrow_array()) {
	if (exists($expires{$idx})) {
Leigh B Stoller's avatar
Leigh B Stoller committed
283 284 285 286 287 288
	    #
	    # 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) {
289 290 291 292
		# 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});
Leigh B Stoller's avatar
Leigh B Stoller committed
293
		next;
294
	    }
Leigh B Stoller's avatar
Leigh B Stoller committed
295 296 297 298 299 300 301 302 303
	    # 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);
304 305 306 307
	}
	#
	# If expiration is greater then 24 hours out, skip. 
	#
308
	#print STDERR "$stamp, $created, $grace, ". time() . "\n";
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

	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";
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
354 355 356 357 358 359 360

	#
	# 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. 
	#
361
	if (time() - $created < $minwarn) {
Leigh B Stoller's avatar
Leigh B Stoller committed
362
	    print STDERR "Skipping email for just created sliver $aggregate\n";
363 364 365 366
	    $expires{$idx} = $stamp;
	    $slice->UnLock();
	    goto skip;
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
367 368
	
	if ($impotent) {
369
	    print STDERR
Leigh B Stoller's avatar
Leigh B Stoller committed
370
		"Would send mail to $geniuser: $idx,$hrn,$diff $unit\n";
371 372 373 374
	}
	else {
	    print STDERR
		"Sending mail to $geniuser about expiring sliver $aggregate\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	}
	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) {
	    SENDMAIL($emailaddr, "Sliver expiring at $OURDOMAIN",
396 397
		     "Sliver $sliver_urn\n".
		     "from slice $urn,\n".
Leigh B Stoller's avatar
Leigh B Stoller committed
398 399 400
		     "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",
401
		     "Geni Operations <$TBOPS>");
402 403 404 405 406 407 408 409
	}
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
410
#
411 412
# 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
413 414 415 416
#
sub ExpireSlices()
{
    my $query_result =
Leigh B Stoller's avatar
Leigh B Stoller committed
417 418 419 420 421 422
	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)) ".
423
			    " and shutdown is null and lockdown=0");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
424 425 426 427 428 429 430 431 432 433 434 435 436 437

    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)) {
438
	    print STDERR "Could not get experiment for $slice. Expiring ...\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
439
	    $slice->UnLock();
440
	    goto cleanup;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
441 442 443 444 445 446 447 448 449 450
	}
	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. 
	#
451
	if (0 && $idlecheck && !$slice->isplaceholder()) {
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
	    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
469
	    }
Leigh B Stoller's avatar
Leigh B Stoller committed
470 471 472
	    print STDERR "$slice ($experiment) is idle; releasing.\n";
	}
	else {
Leigh B Stoller's avatar
Leigh B Stoller committed
473
	    if ($slice->isplaceholder()) {
474 475 476 477
		print STDERR "Releasing placeholder $slice";
		print STDERR " - $experiment"
		    if (defined($experiment));
		print STDERR "\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
478 479
	    }
	    else {
480 481 482 483
		print STDERR "Expiring $slice";
		print STDERR " - $experiment"
		    if (defined($experiment));
		print STDERR "\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
484
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
485
	}
486
      cleanup:
487
	my $slice_uuid  = $slice->uuid();
488 489
	my $output = emutil::ExecQuiet("$CLEANUPSLICE -f -m $slice_uuid");
	my $status = $?;
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
	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";
505
	}
506
	if ($status) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
507
	    print STDERR "Could not release $slice\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
508 509
	    SENDMAIL($TBOPS, "Could not release slice $slice",
		     "Could not release slice $slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
510 511 512
	    # Leave it locked. 
	    goto skip;
	}
513 514
	delete($warned{"$idx"});
	delete($expires{"$idx"});
Leigh B. Stoller's avatar
Leigh B. Stoller committed
515 516 517 518
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
519 520
	$experiment->Flush()
	    if (defined($experiment));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
521 522 523
    }
}

524 525 526 527 528 529 530
#
# Look for slices that need to be shutdown
#
sub ShutdownSlices()
{
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_slices ".
531
			    "where shutdown is not null and isshutdown=0");
532 533 534 535 536 537 538 539 540 541 542 543 544 545

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

	#
546
	# The isshutdown flag avoids churning the system.
547 548 549 550 551 552
	#
	if (GeniCM::CleanupDeadSlice($slice, 0) != 0) {
	    print STDERR "Could not shutdown $slice\n";
	    SENDMAIL($TBOPS, "Could not shutdown slice",
		     "Could not shutdown slice $slice");
	}
553
	$slice->SetShutdownFlag(1);
554 555 556 557 558 559 560
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
#
# 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());
    }
}

589 590 591 592 593
sub ReportLockedSlices()
{
    my $msg = "";
    
    my $query_result =
594
	GeniDB::DBQueryWarn("select idx,locked,expires,hosed,now() > expires ".
Leigh B Stoller's avatar
Leigh B Stoller committed
595
			    "  from geni_slices ".
596 597 598
			    "where locked is not null and ".
			    "      DATE_SUB(NOW(),INTERVAL 1 DAY) >= locked");
    if (!$query_result) {
599 600
	print STDERR "ReportLockedSlices: Error getting info from the DB.\n";
	return;
601 602 603 604
    }
    return
	if (!$query_result->numrows);

605
    while (my ($idx, $locked, $expires,$hosed, $expired) =
Leigh B Stoller's avatar
Leigh B Stoller committed
606
	   $query_result->fetchrow_array()) {
607 608 609 610 611 612 613 614
	my $slice = GeniSlice->Lookup($idx);

	if (!defined($slice)) {
	    # Slice is gone, lets not worry.
	    next;
	}
	my $urn = $slice->urn();
	
Leigh B Stoller's avatar
Leigh B Stoller committed
615 616 617 618 619 620 621
	# 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);
622

Leigh B Stoller's avatar
Leigh B Stoller committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
	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:
652
	$msg .= ($hosed ? "Hosed - " : "") . "$urn : $locked, $expires\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
653
	print STDERR
654
	    ($hosed ? "Hosed - " : "") . "$urn : locked since $locked, expires at $expires\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
655
	$slice->Flush();
656 657 658 659 660 661 662 663
    }
    return
	if ($msg eq "");

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
664
	     "ProtoGENI CM daemon: Locked Slices",
665 666 667 668 669
	     "The following CM slices have been locked for a long time\n\n".
	     $msg,
	     $TBOPS);
}

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
#
# 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()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
713 714 715 716 717 718 719
	if (!$impotent) {
	    GeniDB::DBQueryWarn("delete from geni_certificates ".
				"where uuid='$uuid'");
	}
	else {
	    $msg .= "$uuid : $urn\n";
	}
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
	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);
}

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
#
# 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 ".
757 758 759
			    "where type='Aggregate' and ".
			    "      (idx>$lastidx or ".
			    "       (idx<=$lastidx and reported is null)) ".
760
			    "limit 100");
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 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
    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;
}

939 940 941 942 943
#
# Look for idle slivers. 
#
sub CheckIdle()
{
944 945 946
    my $mailinterval        = 1;
    my $idlecheck_threshold = 1;
    my $idlecheck_norenew   = 0;
947
    my $debug = 1;
948

949
    if (! (GetSiteVar("idle/mailinterval", \$mailinterval) &&
950 951
	   GetSiteVar("protogeni/idlecheck_threshold", \$idlecheck_threshold) &&
	   GetSiteVar("protogeni/idlecheck_norenew",\$idlecheck_norenew))) {
952 953 954
	print STDERR "Could not get idle parameters.\n";
	return;
    }
955
    # Threshold in hours, convert to minutes.
956
    $idlecheck_threshold = $idlecheck_threshold * 60;
957 958 959 960
    
    my $query_result =
	GeniDB::DBQueryWarn("select idx,UNIX_TIMESTAMP(created) ".
			    "  from geni_slices ".
Leigh B Stoller's avatar
Leigh B Stoller committed
961
			    "where shutdown is null and ".
962
			    "      hosed=0 and lockdown=0 and isplaceholder=0");
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979

    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)) {
980 981
	    print STDERR "No aggregate created yet for $slice\n"
		if ($debug);
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
	    $slice->UnLock();
	    goto skip;
	}
	my $experiment = $slice->GetExperiment();
	if (!defined($experiment)) {
	    print STDERR "Could not get experiment for $slice. Expiring ...\n";
	    $slice->UnLock();
	    goto cleanup;
	}
	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, ".
1013
			"  count(r.node_id) as nodes ".
1014 1015
			"from node_activity as na ".
			"left join reserved as r on na.node_id=r.node_id ".
1016 1017
		        "left join nodes as n on na.node_id=n.node_id ".
		        "left join node_types as nt on nt.type=n.type ".
1018
			"left join experiments as e on r.exptidx=e.idx ".
1019
			"where r.exptidx=$exptidx and nt.isvirtnode=0 ".
1020 1021 1022 1023 1024 1025 1026 1027 1028
			"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'};
1029
	# idleswap_timeout in minutes
1030 1031 1032
	my $timeout    = $row->{'idleswap_timeout'};
	my $ignore     = $row->{'idle_ignore'};
	my $swapreqs   = $row->{'swap_requests'};
1033
	# lastreq in hours
1034 1035
	my $lastreq    = $row->{'lastreq'};
	my $nodes      = $row->{'nodes'};
1036
	my $urn        = $slice->urn();
1037 1038

	#
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
	# 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
1078 1079 1080 1081 1082 1083 1084 1085
	# 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.
	#
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
	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;
	    }
1128

1129 1130 1131 1132 1133 1134 1135 1136 1137
	    #
	    # Finally, look at the idle time.
	    #
	    if ($idletime > $idlecheck_threshold) {
		$idlenodes++;
		$noderow->{'idle'} = 1;
		next;
	    }
	}
1138
	#
1139
	# If no idle data, nothing do do.
1140
	#
1141 1142
	if (! $reporting) {
	    print STDERR "-> No idle data for $slice. Skipping ...\n"
1143 1144 1145 1146
		if ($debug);
	    $slice->UnLock();
	    goto skip;
	}
1147 1148 1149 1150 1151
	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);
1152 1153 1154 1155 1156 1157
	
	#
	# 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.
	#
1158 1159 1160 1161
	my $geniuser  = GeniUser->Lookup($slice->creator_uuid(), 1);
	my $emailaddr = $geniuser->email();
	my $sliver_urn= $aggregate->urn();
	
1162
	if ($idleswap && ($idlenodes / ($reporting * 1.0) >= 0.50)) {
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
	    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);
		}
	    }
	    
1174 1175 1176
	    #
	    # Send email if none sent or if the minimum time since
	    # since the last message has passed. In general, we will not
1177 1178
	    # send more then one message in a 24 hour period to avoid
	    # annoying people to much.
1179
	    #
1180
	    if ($idlecheck_norenew &&
1181
		$swapreqs && ($lastreq * 60) > (2 * $idlecheck_threshold)) {
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
		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) {
			SENDMAIL($emailaddr,
			     "Sliver $sliver_urn may not be renewed",
			     "Sliver $sliver_urn\n".
			     "from slice $urn,\n".
			     "has been mostly idle for too long,\n".
			     "and is using $nodes physical nodes.\n\n".
			     "$stats\n".
			     "You will not be allowed to renew this sliver!\n",
1201
			     "Geni Operations <$TBOPS>", "CC: $TBAUTOMAIL");
1202
		
1203
			$slice->SetRenewLimit(0);
1204 1205
		    }
		}
1206 1207 1208 1209 1210 1211
	    }
	    elsif ($swapreqs == 0 || $lastreq > 24 || $debug > 1) {
		my $norenew   =
		    (defined($slice->renew_limit()) &&
		     $slice->renew_limit_stamp() == 0 ? 1 : 0);

1212 1213 1214 1215 1216 1217 1218
		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";
1219

1220
		    SENDMAIL($emailaddr, "Sliver $sliver_urn is mostly idle",
1221 1222
			"Sliver $sliver_urn\n".
			"from slice $urn,\n".
1223 1224 1225 1226
			"has been mostly idle for an unusual length of time,\n".
			"and is using $nodes physical nodes.\n\n".
			"$stats\n".
			($idlecheck_norenew ?
1227 1228 1229 1230
			 ($norenew ?
			  "You may no longer renew this sliver, and it might ".
			  "be terminated " :
			  "You will not be allowed to renew this sliver ") :
1231 1232
			 "This sliver might be terminated ") .
			"if it stays idle.\n",
1233
			"Geni Operations <$TBOPS>", "CC: $TBAUTOMAIL");
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

		    emdb::DBQueryWarn("update experiments set ".
				      "   swap_requests=swap_requests+1, ".
				      "   last_swap_req=now() ".
				      "where idx='$exptidx'");
		}
	    }
	}
	else {
	    # Reset warnings.
1244 1245 1246
	    print STDERR "Resetting swap_requests for $slice\n"
		if ($debug);
	   
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
	    emdb::DBQueryWarn("update experiments set swap_requests=0 ".
			      "where idx='$exptidx'")
		if (!$impotent);
	}
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}    

1258
if ($oneshot) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1259
    WarnSlices();
1260 1261 1262
    exit(0);
}

1263
# Do this once at startup
1264 1265 1266 1267 1268 1269
if (! NoLogins()) {
    sleep(5);
    ReportLockedSlices();
    ReportOrphanedCerts();
    CheckIdle();
}
1270

1271 1272
my $reportcounter = 0;
my $idlecounter   = 0;
1273

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1274
while (1) {
1275 1276 1277 1278
    if (NoLogins()) {
	sleep(5);
	next;
    }
1279 1280 1281 1282
    my $doidlechecks;

    # Site var normally controls idle checks, but it can be turned
    # via the command line as well.
1283
    if (! GetSiteVar('protogeni/idlecheck', \$doidlechecks)) {
1284 1285 1286 1287 1288 1289
	# Cannot get the value, default it to off.
	$doidlechecks = 0;
    }
    
    $reportcounter += $SLEEP_INTERVAL;
    $idlecounter   += $SLEEP_INTERVAL;
1290
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1291 1292
    print "Running at ".
	POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime()) . "\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
1293

1294
    if (0) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1295 1296 1297
	WarnSlices();
	goto loop;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1298
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1299
    ExpireTickets();
1300
    WarnSlices();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1301
    ExpireSlices();
1302 1303 1304 1305

    #
    # Run the idle check periodically. 
    # 
1306
    if ($idlecounter >= (10 * 60)) {
1307 1308 1309 1310
	CheckIdle()
	    if ($idlecheck || $doidlechecks);
	$idlecounter = 0;
    }
1311
    ShutdownSlices();
1312
    RegisterSlices();
1313
    PushStats();
Leigh B Stoller's avatar