expire_daemon.in 38.9 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
70
my $TRIGGERUPDATE = "$TB/sbin/protogeni/triggerimageupdate";
my $POSTIMAGEDATA = "$TB/sbin/protogeni/postimagedata";
71
my $DELETEIMAGEDATA = "$TB/sbin/protogeni/deleteimagedata";
72
my $IMPORTER      = "$TB/sbin/image_import";
73
my $CLEANUPSLICE  = "$TB/sbin/cleanupslice";
74
my $CLEANUPTICKET = "$TB/sbin/cleanupticket";
75
my $SLEEP_INTERVAL= 60;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

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

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

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

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

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

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

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

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

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

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

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

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

	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
360
361
362
363
364
365
366

	#
	# 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. 
	#
367
	if (time() - $created < $minwarn) {
Leigh B Stoller's avatar
Leigh B Stoller committed
368
	    print STDERR "Skipping email for just created sliver $aggregate\n";
369
370
371
372
	    $expires{$idx} = $stamp;
	    $slice->UnLock();
	    goto skip;
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
373
374
	
	if ($impotent) {
375
	    print STDERR
Leigh B Stoller's avatar
Leigh B Stoller committed
376
		"Would send mail to $geniuser: $idx,$hrn,$diff $unit\n";
377
378
379
380
	}
	else {
	    print STDERR
		"Sending mail to $geniuser about expiring sliver $aggregate\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
381
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) {
	    SENDMAIL($emailaddr, "Sliver expiring at $OURDOMAIN",
402
403
		     "Sliver $sliver_urn\n".
		     "from slice $urn,\n".
Leigh B Stoller's avatar
Leigh B Stoller committed
404
405
406
		     "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",
407
		     "Geni Operations <$TBOPS>");
408
409
410
411
412
413
414
415
	}
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

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

    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)) {
444
	    print STDERR "Could not get experiment for $slice. Expiring ...\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
445
	    $slice->UnLock();
446
	    goto cleanup;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
447
448
449
450
451
452
	}
	if ($experiment->Refresh() != 0) {
	    print STDERR "Could not flush $experiment\n";
	    $slice->UnLock();
	    goto skip;
	}
453
454
455
456
457
	if ($experiment->state() eq EXPTSTATE_PANICED()) {
	    print STDERR "Refusing to terminate a paniced experiment\n";
	    goto skip;
	}
	
Leigh B. Stoller's avatar
Leigh B. Stoller committed
458
459
460
461
	#
	# See if we have any local nodes. No point in using the idle
	# check if there are no nodes. 
	#
462
	if (0 && $idlecheck && !$slice->isplaceholder()) {
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
	    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
480
	    }
Leigh B Stoller's avatar
Leigh B Stoller committed
481
482
483
	    print STDERR "$slice ($experiment) is idle; releasing.\n";
	}
	else {
Leigh B Stoller's avatar
Leigh B Stoller committed
484
	    if ($slice->isplaceholder()) {
485
486
487
488
		print STDERR "Releasing placeholder $slice";
		print STDERR " - $experiment"
		    if (defined($experiment));
		print STDERR "\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
489
490
	    }
	    else {
491
492
493
494
		print STDERR "Expiring $slice";
		print STDERR " - $experiment"
		    if (defined($experiment));
		print STDERR "\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
495
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
496
	}
497
      cleanup:
498
	my $slice_uuid  = $slice->uuid();
499
500
	my $output = emutil::ExecQuiet("$CLEANUPSLICE -f -m $slice_uuid");
	my $status = $?;
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
	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";
516
	}
517
	if ($status) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
518
	    print STDERR "Could not release $slice\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
519
520
	    SENDMAIL($TBOPS, "Could not release slice $slice",
		     "Could not release slice $slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
521
522
523
	    # Leave it locked. 
	    goto skip;
	}
524
525
	delete($warned{"$idx"});
	delete($expires{"$idx"});
Leigh B. Stoller's avatar
Leigh B. Stoller committed
526
527
528
529
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
530
531
	$experiment->Flush()
	    if (defined($experiment));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
532
533
534
    }
}

535
536
537
538
539
540
541
#
# Look for slices that need to be shutdown
#
sub ShutdownSlices()
{
    my $query_result =
	GeniDB::DBQueryWarn("select idx from geni_slices ".
542
			    "where shutdown is not null and isshutdown=0");
543
544
545
546
547
548
549
550
551
552
553
554
555
556

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

	#
557
	# The isshutdown flag avoids churning the system.
558
559
560
561
562
563
	#
	if (GeniCM::CleanupDeadSlice($slice, 0) != 0) {
	    print STDERR "Could not shutdown $slice\n";
	    SENDMAIL($TBOPS, "Could not shutdown slice",
		     "Could not shutdown slice $slice");
	}
564
	$slice->SetShutdownFlag(1);
565
566
567
568
569
570
571
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
}

572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
#
# 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.
592
	    $aggregate->Flush();
593
594
595
596
597
	    next;
	}
	# Run the register script. Ignore errors; we will retry again later.
	print STDERR "Registering $slice ($aggregate)\n";
	system("$REGISTER " . $slice->idx());
598
599
	$slice->Flush();
	$aggregate->Flush();
600
601
602
    }
}

603
604
605
606
607
sub ReportLockedSlices()
{
    my $msg = "";
    
    my $query_result =
608
	GeniDB::DBQueryWarn("select idx,locked,expires,hosed,now() > expires ".
Leigh B Stoller's avatar
Leigh B Stoller committed
609
			    "  from geni_slices ".
610
611
612
			    "where locked is not null and ".
			    "      DATE_SUB(NOW(),INTERVAL 1 DAY) >= locked");
    if (!$query_result) {
613
614
	print STDERR "ReportLockedSlices: Error getting info from the DB.\n";
	return;
615
616
617
618
    }
    return
	if (!$query_result->numrows);

619
    while (my ($idx, $locked, $expires,$hosed, $expired) =
Leigh B Stoller's avatar
Leigh B Stoller committed
620
	   $query_result->fetchrow_array()) {
621
622
623
624
625
626
627
628
	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
629
630
631
632
633
634
635
	# 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);
636

Leigh B Stoller's avatar
Leigh B Stoller committed
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
	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:
666
	$msg .= ($hosed ? "Hosed - " : "") . "$urn : $locked, $expires\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
667
	print STDERR
668
	    ($hosed ? "Hosed - " : "") . "$urn : locked since $locked, expires at $expires\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
669
	$slice->Flush();
670
671
672
673
674
675
676
677
    }
    return
	if ($msg eq "");

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
678
	     "ProtoGENI CM daemon: Locked Slices",
679
680
681
682
683
	     "The following CM slices have been locked for a long time\n\n".
	     $msg,
	     $TBOPS);
}

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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
#
# 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
727
728
729
730
731
732
733
	if (!$impotent) {
	    GeniDB::DBQueryWarn("delete from geni_certificates ".
				"where uuid='$uuid'");
	}
	else {
	    $msg .= "$uuid : $urn\n";
	}
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
	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);
}

749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
#
# 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 ".
771
772
773
			    "where type='Aggregate' and ".
			    "      (idx>$lastidx or ".
			    "       (idx<=$lastidx and reported is null)) ".
774
			    "limit 100");
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
    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;
}

953
954
955
956
957
#
# Look for idle slivers. 
#
sub CheckIdle()
{
958
959
960
    my $mailinterval        = 1;
    my $idlecheck_threshold = 1;
    my $idlecheck_norenew   = 0;
961
    my $debug = 1;
962

963
    if (! (GetSiteVar("idle/mailinterval", \$mailinterval) &&
964
965
	   GetSiteVar("protogeni/idlecheck_threshold", \$idlecheck_threshold) &&
	   GetSiteVar("protogeni/idlecheck_norenew",\$idlecheck_norenew))) {
966
967
968
	print STDERR "Could not get idle parameters.\n";
	return;
    }
969
    # Threshold in hours, convert to minutes.
970
    $idlecheck_threshold = $idlecheck_threshold * 60;
971
972
973
974
    
    my $query_result =
	GeniDB::DBQueryWarn("select idx,UNIX_TIMESTAMP(created) ".
			    "  from geni_slices ".
Leigh B Stoller's avatar
Leigh B Stoller committed
975
			    "where shutdown is null and ".
976
			    "      hosed=0 and lockdown=0 and isplaceholder=0");
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993

    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)) {
994
995
	    print STDERR "No aggregate created yet for $slice\n"
		if ($debug);
996
997
998
999
1000
1001
1002
	    $slice->UnLock();
	    goto skip;
	}
	my $experiment = $slice->GetExperiment();
	if (!defined($experiment)) {
	    print STDERR "Could not get experiment for $slice. Expiring ...\n";
	    $slice->UnLock();
1003
	    goto skip;
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
	}
	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, ".
1027
			"  count(r.node_id) as nodes ".
1028
1029
			"from node_activity as na ".
			"left join reserved as r on na.node_id=r.node_id ".
1030
1031
		        "left join nodes as n on na.node_id=n.node_id ".
		        "left join node_types as nt on nt.type=n.type ".
1032
			"left join experiments as e on r.exptidx=e.idx ".
1033
			"where r.exptidx=$exptidx and nt.isvirtnode=0 ".
1034
1035
1036
1037
1038
1039
1040
1041
1042
			"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'};
1043
	# idleswap_timeout in minutes
1044
1045
1046
	my $timeout    = $row->{'idleswap_timeout'};
	my $ignore     = $row->{'idle_ignore'};
	my $swapreqs   = $row->{'swap_requests'};
1047
	# lastreq in hours
1048
1049
	my $lastreq    = $row->{'lastreq'};
	my $nodes      = $row->{'nodes'};
1050
	my $urn        = $slice->urn();
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
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
	# 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
1092
1093
1094
1095
1096
1097
1098
1099
	# 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.
	#
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
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
	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;
	    }
1142

1143
1144
1145
1146
1147
1148
1149
1150
1151
	    #
	    # Finally, look at the idle time.
	    #
	    if ($idletime > $idlecheck_threshold) {
		$idlenodes++;
		$noderow->{'idle'} = 1;
		next;
	    }
	}
1152
	#
1153
	# If no idle data, nothing do do.
1154
	#
1155
1156
	if (! $reporting) {
	    print STDERR "-> No idle data for $slice. Skipping ...\n"
1157
1158
1159
1160
		if ($debug);
	    $slice->UnLock();
	    goto skip;
	}
1161
1162
1163
1164
1165
	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);
1166
1167
1168
1169
1170
1171
	
	#
	# 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.
	#
1172
1173
1174
1175
	my $geniuser  = GeniUser->Lookup($slice->creator_uuid(), 1);
	my $emailaddr = $geniuser->email();
	my $sliver_urn= $aggregate->urn();
	
1176
	if ($idleswap && ($idlenodes / ($reporting * 1.0) >= 0.50)) {
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
	    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);
		}
	    }
	    
1188
1189
1190
	    #
	    # Send email if none sent or if the minimum time since
	    # since the last message has passed. In general, we will not
1191
1192
	    # send more then one message in a 24 hour period to avoid
	    # annoying people to much.
1193
	    #
1194
	    if ($idlecheck_norenew &&
1195
		$swapreqs && ($lastreq * 60) > (2 * $idlecheck_threshold)) {
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
		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",
1215
			     "Geni Operations <$TBOPS>", "CC: $TBAUTOMAIL");
1216
		
1217
			$slice->SetRenewLimit(0);
1218
1219
		    }
		}
1220
1221
1222
1223
1224
1225
	    }
	    elsif ($swapreqs == 0 || $lastreq > 24 || $debug > 1) {
		my $norenew   =
		    (defined($slice->renew_limit()) &&
		     $slice->renew_limit_stamp() == 0 ? 1 : 0);

1226
1227
1228
1229
1230
1231
1232
		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";
1233

1234
		    SENDMAIL($emailaddr, "Sliver $sliver_urn is mostly idle",
1235
1236
			"Sliver $sliver_urn\n".
			"from slice $urn,\n".
1237
1238
1239
1240
			"has been mostly idle for an unusual length of time,\n".
			"and is using $nodes physical nodes.\n\n".
			"$stats\n".
			($idlecheck_norenew ?
1241
1242
1243
1244
			 ($norenew ?
			  "You may no longer renew this sliver, and it might ".
			  "be terminated " :
			  "You will not be allowed to renew this sliver ") :
1245
1246
			 "This sliver might be terminated ") .
			"if it stays idle.\n",
1247
			"Geni Operations <$TBOPS>", "CC: $TBAUTOMAIL");
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257

		    emdb::DBQueryWarn("update experiments set ".
				      "   swap_requests=swap_requests+1, ".
				      "   last_swap_req=now() ".
				      "where idx='$exptidx'");
		}
	    }
	}
	else {
	    # Reset warnings.
1258
1259
1260
	    print STDERR "Resetting swap_requests for $slice\n"
		if ($debug);
	   
1261
1262
1263
1264
1265
1266
1267
1268
1269
	    emdb::DBQueryWarn("update experiments set swap_requests=0 ".
			      "where idx='$exptidx'")
		if (!$impotent);
	}
	$slice->UnLock();
      skip:
	$slice->Flush()
	    if (defined($slice));
    }
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
}

#
# Deal with image tracker stuff. 
#
sub HandleImageTracking()
{
    if (!GetSiteVar("protogeni/use_imagetracker")) {
	return;
    }
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

    #
    # Look for images deletions.
    #
    my $query_result =
	DBQueryWarn("select * from image_deletions");
    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'");
    }
1309
1310
1311
1312
1313
1314
    
    #
    # 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.
    #
1315
    $query_result =
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
	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 $output;
	    SENDMAIL($TBOPS,
		     "Could not trigger an image update for $imageid",
		     $output,
		     $TBOPS);
	}
    }

    #
    # 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 $output;
	    SENDMAIL($TBOPS,
		     "Could not import image update for $imageid",
		     $output,
		     $TBOPS);
	}
    }
    my $opt = ($impotent ? "-n" : "");

    # Trigger a posting to the IMS for any new images.
    my $output = emutil::ExecQuiet("$POSTIMAGEDATA -v $opt all");
    print $output;
    if ($?) {
	SENDMAIL($TBOPS,
		 "Could not post image data to the IMS",
		 $output,
		 $TBOPS);
    }
}
1394

1395
if ($oneshot) {
1396
    HandleImageTracking();
1397
1398
1399
    exit(0);
}

1400
# Do this once at startup
1401
1402
1403
1404
1405
1406
if (! NoLogins()) {
    sleep(5);
    ReportLockedSlices();
    ReportOrphanedCerts();
    CheckIdle();
}
1407

1408
1409
my $reportcounter = 0;
my $idlecounter   = 0;
1410

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1411
while (1) {
1412
1413
1414
1415
    if (NoLogins()) {
	sleep(5);
	next;
    }
1416
1417
1418
1419
    my $doidlechecks;

    # Site var normally controls idle checks, but it can be turned
    # via the command line as well.
1420
    if (! GetSiteVar('protogeni/idlecheck', \$doidlechecks)) {
1421
1422
1423
1424
1425
1426
	# Cannot get the value, default it to off.
	$doidlechecks = 0;
    }
    
    $reportcounter += $SLEEP_INTERVAL;
    $idlecounter   += $SLEEP_INTERVAL;
1427
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1428
1429
    print "Running at ".
	POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime()) . "\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
1430

1431
    if (0) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1432
1433
1434
	WarnSlices();
	goto loop;
    }
1435
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1436
    ExpireTickets();
1437
1438
    WarnSlices();
    ExpireSlices();
1439
1440
1441
1442

    #
    # Run the idle check periodically. 
    # 
1443
    if ($idlecounter >= (10 * 60)) {
1444
1445
1446
1447
	CheckIdle()
	    if ($idlecheck || $doidlechecks);
	$idlecounter = 0;
    }
1448
    ShutdownSlices();
1449
    RegisterSlices();
1450
    PushStats();
1451

1452
    if ($reportcounter >= (24 * 60 * 60)) {
1453
	ReportLockedSlices();
1454
	ReportOrphanedCerts();
1455
	$reportcounter = 0;
1456
    }
1457
    HandleImageTracking();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1458

1459
1460
1461
    # Be certain stale info is gone.
    Experiment->FlushAll();
    Node->FlushAll();
1462
    GeniUtil::FlushCaches();
1463

Leigh B Stoller's avatar
Leigh B Stoller committed
1464
  loop:
Leigh B Stoller's avatar
Leigh B Stoller committed
1465
    print "Sleeping for $SLEEP_INTERVAL seconds ...\n";
1466
    sleep($SLEEP_INTERVAL);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1467
1468
1469
1470
1471
1472
1473
}
exit(0);

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

1474
1475
1476
1477
1478
1479
1480
    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
	     "ProtoGENI expire daemon died",
	     $msg,
	     $TBOPS);
1481
    MarkDaemonStopped("expire_daemon");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1482
1483
1484
    die("*** $0:\n".
	"    $msg\n");
}