apt_daemon.in 17.3 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2018 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
# 
# {{{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.
# 
# }}}
#
use strict;
use English;
use Getopt::Std;
33 34 35
use Data::Dumper;
use JSON;
use File::Basename;
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

#
# Look for APT things that need to be dealt with.
#
sub usage()
{
    print "Usage: apt_daemon [-d] [-s] [-n]\n";
    exit(1);
}
my $optlist   = "dns";
my $debug     = 0;
my $impotent  = 0;
my $oneshot   = 0;


#
# Configure variables
#
my $TB		     = "@prefix@";
my $TBOPS            = "@TBOPSEMAIL@";
my $TBLOGS           = "@TBLOGSEMAIL@";
my $MAINSITE         = @TBMAINSITE@;
my $LOGFILE          = "$TB/log/apt_daemon.log";
my $MANAGEINSTANCE   = "$TB/bin/manage_instance";
60
my $MANAGEDATASET    = "$TB/bin/manage_dataset";
Leigh B Stoller's avatar
Leigh B Stoller committed
61 62
my $PROTOUSER	     = "elabman";
my $SUDO	     = "/usr/local/bin/sudo";
63 64
my $WGET             = "/usr/local/bin/wget";
my $SLEEP_INTERVAL   = 300;
65
my $DAILY_INTERVAL   = 24 * 3600;
66
my $OPENSTACK_INTERVAL = 600;
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

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

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

# Load the Testbed support stuff.
use lib "@prefix@/lib";
use emdb;
use Experiment;
use Node;
use libtestbed;
use emutil;
use libEmulab;
109
use GeniResponse;
110
use APT_Instance;
111
use APT_Dataset;
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
use POSIX qw(strftime ceil);

if (!$oneshot) {
    if (CheckDaemonRunning("apt_daemon")) {
	fatal("Not starting another apt daemon!");
    }
    # Go to ground.
    if (! $debug) {
	if (TBBackGround($LOGFILE)) {
	    exit(0);
	}
    }
    if (MarkDaemonRunning("apt_daemon")) {
	fatal("Could not mark daemon as running!");
    }
}

#
# Setup a signal handler for newsyslog.
#
sub handler()
{
    my $SAVEEUID = $EUID;
    
    $EUID = 0;
    ReOpenLog($LOGFILE);
    $EUID = $SAVEEUID;
}
$SIG{HUP} = \&handler
    if (! ($debug || $oneshot));

Leigh B Stoller's avatar
Leigh B Stoller committed
143
#
144
# Kill instances that need to be killed. 
Leigh B Stoller's avatar
Leigh B Stoller committed
145
#
146
sub KillInstances()
147
{
148 149 150
    #
    # Do not bother to try and terminate a locked slice. It will just fail.
    #
151
    my $query_result =
152 153 154 155 156 157 158 159
	DBQueryWarn("select a.uuid,a.status from apt_instances as a ".
		    "left join geni.geni_slices as s on s.uuid=a.slice_uuid ".
		    "where (a.canceled!=0 or ".
		    "       (a.status='failed' and ".
		    "        (UNIX_TIMESTAMP(now()) - ".
		    "         UNIX_TIMESTAMP(a.created) > 7200))) and ".
		    # Not locked or corresponding slice does not exist.
		    "      (s.locked is null or s.idx is null)");
160 161 162 163 164 165 166 167 168
    return
	if (!$query_result);

    while (my ($uuid,$status) = $query_result->fetchrow_array()) {
	my $instance = APT_Instance->Lookup($uuid);
	if (!defined($instance)) {
	    print STDERR "No such instance $uuid\n";
	    next;
	}
169 170 171
	print "$instance is in the $status state\n";
	print "$instance has its canceled flag set\n"
	    if ($instance->canceled());
172 173 174 175 176 177

	#
	# Try to terminate the instance. We cannot take the lock since
	# we are going to call manage_instance to do the termination.
	# So, manage_instance might collide with the sa_daemon which
	# locks the underlying slice, but if that happens we will just
178
	# try again after a short wait. 
179 180 181 182 183
	#
	if ($impotent) {
	    print STDERR "Would try to terminate $instance\n";
	    next;
	}
184
	# Use debug option to keep it from going into the background.
Leigh B Stoller's avatar
Leigh B Stoller committed
185
	my $output = emutil::ExecQuiet("$SUDO -u $PROTOUSER ".
186
				       "$MANAGEINSTANCE -d terminate $uuid");
Leigh B Stoller's avatar
Leigh B Stoller committed
187 188 189 190 191 192 193 194 195 196 197
	my $status = $?;
	print STDERR "$output\n"
	    if ($output ne "");
	if ($status) {
	    #
	    # Need to send email at some point. 
	    #
	}
    }
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
#
# Look for failed imaging operations. 
#
sub FixFailedImaging()
{
    my $query_result =
	DBQueryWarn("select uuid,status from apt_instances ".
		    "where (status='imaging' or status='imaging-failed') and ".
		    "      status_timestamp is not null and ".
		    "      (UNIX_TIMESTAMP(now()) - ".
		    "       UNIX_TIMESTAMP(status_timestamp) > 3600)");
    return
	if (!$query_result);

    while (my ($uuid,$status) = $query_result->fetchrow_array()) {
	my $instance = APT_Instance->Lookup($uuid);
	if (!defined($instance)) {
	    print STDERR "No such instance $uuid\n";
	    next;
	}
	print STDERR "$instance is in the $status state\n";

	#
	# We want to move it back to the ready state if its been there
	# a long time. But must lock so as not to collide with with
	# sa_daemon or the user.
	#
	my $genislice = $instance->GetGeniSlice();
	goto skip
	    if (!defined($genislice));
	goto skip
	    if ($genislice->Lock() != 0);
	if ($impotent) {
	    print STDERR
		"Would change $instance status from $status to ready\n";
	}
	else {
	    print STDERR
		"Changing $instance status from $status to ready\n";
	    $instance->SetStatus("ready");
	}
	$genislice->UnLock();
      skip:
241 242
	$genislice->Flush()
	    if (defined($genislice));
243 244 245 246
	next;
    }
}

Leigh B Stoller's avatar
Leigh B Stoller committed
247 248 249 250 251 252
#
# Expire instances.
#
sub ExpireInstances()
{
    my $query_result =
Leigh B Stoller's avatar
Leigh B Stoller committed
253
	DBQueryWarn("select a.uuid,s.expires from apt_instances as a ".
Leigh B Stoller's avatar
Leigh B Stoller committed
254 255
		    "left join geni.geni_slices as s on s.uuid=a.slice_uuid ".
		    "where (a.status='ready') and ".
256
		    "      a.admin_lockdown=0 and s.lockdown=0 and ".
257
		    "      a.paniced=0 and ".
Leigh B Stoller's avatar
Leigh B Stoller committed
258 259
		    "      (UNIX_TIMESTAMP(now()) > ".
		    "       UNIX_TIMESTAMP(s.expires))");
Leigh B Stoller's avatar
Leigh B Stoller committed
260 261 262
    return
	if (!$query_result);

Leigh B Stoller's avatar
Leigh B Stoller committed
263
    while (my ($uuid,$expires) = $query_result->fetchrow_array()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
264 265 266 267 268
	my $instance = APT_Instance->Lookup($uuid);
	if (!defined($instance)) {
	    print STDERR "No such instance $uuid\n";
	    next;
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
269
	print STDERR "$uuid expired at $expires\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
270 271 272 273 274 275 276 277 278 279 280 281 282

	#
	# Try to terminate the instance. We cannot take the lock since
	# we are going to call manage_instance to do the termination.
	# So, manage_instance might collide with the sa_daemon which
	# locks the underlying slice, but if that happens we will just
	# try again after a short wait. If it still fails, then
	# something is wrong and we will notify.
	#
	if ($impotent) {
	    print STDERR "Would try to terminate $instance\n";
	    next;
	}
283
	# Use debug option to keep it from going into the background.
Leigh B Stoller's avatar
Leigh B Stoller committed
284
	my $output = emutil::ExecQuiet("$SUDO -u $PROTOUSER ".
285
				       "$MANAGEINSTANCE -d terminate $uuid -e");
286
	my $status = $?;
Leigh B Stoller's avatar
Leigh B Stoller committed
287 288
	print STDERR "$output\n"
	    if ($output ne "");
289 290 291 292 293 294 295 296
	if ($status) {
	    #
	    # Need to send email at some point. 
	    #
	}
    }
}

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
#
# Warn about locked down instances that have expired. 
#
sub ReportLockdownExpired()
{
    my @instances;
    
    my $query_result =
	DBQueryWarn("select a.uuid,s.expires from apt_instances as a ".
		    "left join geni.geni_slices as s on s.uuid=a.slice_uuid ".
		    "where (a.admin_lockdown=1 or s.lockdown=1) and ".
		    "      (UNIX_TIMESTAMP(now()) > ".
		    "       UNIX_TIMESTAMP(s.expires))");
    return
	if (!$query_result);

    while (my ($uuid,$expires) = $query_result->fetchrow_array()) {
	my $instance = APT_Instance->Lookup($uuid);
	if (!defined($instance)) {
	    print STDERR "No such instance $uuid\n";
	    next;
	}
	print STDERR "$uuid is locked down but expired at $expires\n";
	push(@instances, $instance);
    }
    return
	if (!@instances);

    my $text = "";
    foreach my $instance (@instances) {
	my $profile = $instance->Profile();
	my $creator = $instance->creator();
	my $wwwlink = $instance->webURL();

	$text .= $profile->name() . ",$creator: $wwwlink\n";
    }
333
    SENDMAIL("portal-extensions\@aptlab.net",
334 335 336 337 338 339 340
	     "APT daemon: Locked down instances",
	     "The following instances are locked down but expired:\n\n".
	     $text . "\n",
	     $TBOPS);
    
}

341
#
342
# Update the json files that are used to build the fancy cluster graphs.
343 344 345 346 347 348
#
sub UpdateAggregateGraphs()
{
    my $freeblob = {};

    my $query_result =
349
	DBQueryWarn("select urn from apt_aggregates where noupdate=0");
350 351 352 353

    return 0
	if (!$query_result->numrows);

354 355 356 357
    while (my ($urn) = $query_result->fetchrow_array()) {
	my $aggregate = APT_Aggregate->Lookup($urn);
	if (!defined($aggregate)) {
	    print STDERR "Could not lookup aggregate: $urn\n";
358 359
	    next;
	}
360
	my $name = $aggregate->nickname();
361

362 363 364 365 366 367 368 369 370 371 372 373 374
	#
	# Load the nodetype info that the portal_monitor gathers.
	#
	my $types_result =
	    DBQueryWarn("select type,count,free from apt_aggregate_nodetypes ".
			"where urn='$urn'");
	next
	    if (!$types_result || !$types_result->numrows());

	$freeblob->{$name} = {};
	while (my ($type,$count,$free) = $types_result->fetchrow_array()) {
	    $freeblob->{$name}->{$type} =
	        {"count" => $count, "free" => $free};
375 376
	}
    }
377 378 379
    if ($debug && $oneshot) {
	print Dumper($freeblob);
    }
380 381 382 383 384 385 386 387 388 389 390 391

    #
    # We are currently operating from two master json files. We make a
    # a copy of those, and then update them with new info, and write them
    # back. This will need to be generalized at some point. 
    #
    my $NOFED   = "$TB/etc/cloudlab-nofed.json";
    my $FEDONLY = "$TB/etc/cloudlab-fedonly.json";

    foreach my $file ($NOFED, $FEDONLY) {
	if (-e $file) {
	    my $data = `/bin/cat $file`;
392 393 394 395 396
	    my $obj  = eval { decode_json($data); };
	    if ($@ || !defined($obj)) {
		if ($@) {
		    print STDERR $@;
		}
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
		print STDERR "Could not decide json in $file\n";
		next;
	    }
	    foreach my $cluster (@{ $obj->{'children'} }) {
		my $name = $cluster->{'name'};
		next
		    if (!exists($freeblob->{$name}));

		my $total_size  = 0;
		my $total_inuse = 0;

		foreach my $child (@{ $cluster->{'children'} }) {
		    my $type = $child->{'name'};
		    
		    if (!exists($freeblob->{$name}->{$type})) {
			print STDERR "$name: Did not get a count for $type\n";
			next;
		    }
415 416
		    my $size  = $freeblob->{$name}->{$type}->{'count'};
		    my $inuse = $size - $freeblob->{$name}->{$type}->{'free'};
417 418 419 420 421 422

		    $child->{'howfull'} = int($inuse);
		    $child->{'size'}    = int($size);
		    $total_inuse += $inuse;
		    $total_size  += $size;
		}
423 424
		# Rob says the toplevel numbers both have to be total_size.
		$cluster->{'howfull'} = int($total_size);
425 426
		$cluster->{'size'}    = int($total_size);
	    }
427 428 429 430 431 432
	    if ($debug || $oneshot) {
		print Dumper($obj);
	    }
	    next
		if ($impotent);
	    
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
	    #
	    # Write out new file for web ui.
	    #
	    my $tfile = "/tmp/$$.json";
	    if (open(JS, ">$tfile")) {
		my $json_text = to_json($obj, { pretty => 1 });
		print JS $json_text . "\n";
		close(JS);
	    }
	    else {
		print STDERR "Could not open temp json file for new data\n";
		next;
	    }
	    system("/bin/mv -f $tfile $TB/www/apt/" . basename($file));
	    if ($?) {
		print STDERR "Could not copy new json file to ".
		    "$TB/www/apt/" . basename($file) . "\n";
	    }
	    unlink($tfile);
	}
    }
    return 0;
}

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
#
# Push out updates.
#
sub PushUpdates()
{
    my $query_result =
	DBQueryWarn("select uuid from apt_instances ".
		    "where status='ready' and needupdate!=0");
    return
	if (!$query_result);

    while (my ($uuid) = $query_result->fetchrow_array()) {
	my $instance = APT_Instance->Lookup($uuid);
	if (!defined($instance)) {
	    print STDERR "No such instance $uuid\n";
	    next;
	}
	print STDERR "$instance needs update.\n";
	next
	    if ($impotent);

	#
	# If its locked, then do not bother trying; wait till next time
	# through the loop. 
	#
	my $genislice = $instance->GetGeniSlice();
	next
	    if (!defined($genislice));
	goto skip
	    if ($genislice->Lock() != 0);

	#
	# Clear the needupdate flag now. If a user comes along and
	# adds a new key during this update, the next time through the
	# loop we will get it. If it results in doing the same thing
	# twice, no big deal. 
	#
	$instance->Update({"needupdate" => 0}) == 0
	    or goto skip;

	#
	# Unlock before we call out to do the update; if someone else
	# locks it, the update will fail and we will reset the needupdate
	# flag for next time through the loop. No one else clears it
	# so this is safe for now. 
	#	
	$genislice->UnLock();
504
	system("$SUDO -u $PROTOUSER $MANAGEINSTANCE updatekeys $uuid");
505
	if ($?) {
506 507 508
	    if ($? >> 8 != GENIRESPONSE_REFUSED) {
		$instance->Update({"needupdate" => 1});
	    }
509 510 511 512 513 514
	}
      skip:
	$genislice->Flush();
    }
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
#
# Gather the Openstack utilization file.
#
my %openstackfailures = ();

sub GatherOpenstackUtilization()
{
    my $query_result =
	DBQueryWarn("select uuid from apt_instances ".
		    "where status='ready' and isopenstack!=0");
    return
	if (!$query_result);

    while (my ($uuid) = $query_result->fetchrow_array()) {
	my $instance = APT_Instance->Lookup($uuid);
	if (!defined($instance)) {
	    print STDERR "No such instance $uuid\n";
	    next;
	}
	print STDERR "$instance is running openstack\n"
	    if ($debug);
	next
	    if ($impotent);

	system("$SUDO -u $PROTOUSER $MANAGEINSTANCE openstackstats $uuid");
	if ($?) {
	    my $stat = $? >> 8;
	    print STDERR "Request for openstackstats returned $stat\n"
		if ($debug);
		
	    #
	    # We want to look for openstack instances that are not running
	    # the stats gathering code, there will not be a file. But it is
	    # not going to show up for a while, so we let it fail for a
	    # while before clearing the openstack flag in the DB.
	    #
	    if ($stat == GENIRESPONSE_SEARCHFAILED) {
		$openstackfailures{"$uuid"} = 0
		    if (!exists($openstackfailures{"$uuid"}));

		if ($openstackfailures{"$uuid"} > 10) {
		    print STDERR
			"Failed to get openstack stats too many times. " .
			"Clearing the flag.\n";
		    
		    $instance->Update({"isopenstack" => 0});
		}
		else {
		    $openstackfailures{"$uuid"}++;
		}
	    }
	}
	$instance->Flush();
    }
}

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
#
# Kill off stale datasets (that were deleted at the cluster). They are
# gone, no point in keeping them around.
#
sub KillStaleDatasets()
{
    my $query_result =
	DBQueryWarn("select uuid,expires from apt_datasets as d ".
		    "where (type='stdataset' or type='ltdataset') and ".
		    "      (UNIX_TIMESTAMP(now()) > ".
		    "       UNIX_TIMESTAMP(expires))");
    return
	if (!$query_result);

    while (my ($uuid,$expires) = $query_result->fetchrow_array()) {
	my $dataset = APT_Dataset->Lookup($uuid);
	if (!defined($dataset)) {
	    print STDERR "No such dataset $uuid\n";
	    next;
	}
	my $pid = $dataset->pid();
	my $id  = $dataset->dataset_id();
	my $agg = $dataset->aggregate_urn();
	print STDERR "Dataset $pid/$id at $agg expired at $expires. ".
	    "Asking for new info ...\n";

	#
	# Try to refresh the dataset. We might get back a new expiration,
	# or we might get back a search failure. If we do get back a search
	# failure, kill the local record for it.
	#
	my $output = emutil::ExecQuiet("$SUDO -u $PROTOUSER ".
				       "$MANAGEDATASET -d refresh $uuid");
	#
	# No error means it is still there. Did the expiration change?
	#
	if (!$?) {
	    $dataset->Refresh();
	    if ($dataset->IsExpired()) {
		# Still expired, not sure what to do here. 
		print STDERR "Dataset is still expired after refresh?\n";
	    }
	    else {
		print STDERR "Dataset is no longer expired after refresh.\n";
	    }
	    next;
	}
	if ($?) {
	    print STDERR $output;
	}
	# Do nothing here, probably an RPC error.
	next
	    if ($? >> 8 != GENIRESPONSE_SEARCHFAILED);
	    
	if ($impotent) {
	    print STDERR "Would try to delete $dataset\n";
	    next;
	}
	print STDERR "Trying to delete $dataset\n";
	$output = emutil::ExecQuiet("$SUDO -u $PROTOUSER ".
				    "$MANAGEDATASET -d delete $uuid");
	if ($?) {
	    print STDERR $output;
	}
    }
}

638
if ($oneshot) {
639 640
    KillInstances();
    KillStaleDatasets();
641 642 643
    exit(0);
}

644 645
my $reportcounter    = 0;
my $openstackcounter = 0;
646 647 648 649 650 651

# Do this once at startup
if (! NoLogins()) {
    ReportLockdownExpired();
}

652 653 654 655 656
while (1) {
    if (NoLogins()) {
	sleep(5);
	next;
    }
657
    $reportcounter += $SLEEP_INTERVAL;
658
    $openstackcounter += $SLEEP_INTERVAL;
659 660 661 662

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

663
    KillInstances();
664
    KillStaleDatasets();
665
    FixFailedImaging();
Leigh B Stoller's avatar
Leigh B Stoller committed
666
    ExpireInstances();
667 668 669
    if ($MAINSITE) {
	UpdateAggregateGraphs();
    }
670
    PushUpdates();
671

672
    if ($reportcounter >= $DAILY_INTERVAL) {
673 674 675
	ReportLockdownExpired();
	$reportcounter = 0;
    }
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
    exit(0)
	if ($oneshot);
    
    sleep($SLEEP_INTERVAL);
}
exit(0);

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

    if (! ($oneshot || $debug)) {
	#
	# Send a message to the testbed list. 
	#
	SENDMAIL($TBOPS,
		 "APT daemon died",
		 $msg,
		 $TBOPS);
    }
    MarkDaemonStopped("apt_daemon")
	if (!$oneshot);

    die("*** $0:\n".
	"    $msg\n");
}