manage_reservations.in 32.3 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2017 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 33 34 35 36 37 38
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;
use CGI;
use POSIX ":sys_wait_h";
use Date::Parse;

#
# Back-end script to manage APT profiles.
#
sub usage()
{
    print("Usage: manage_reservations [-a <urn>] list [-u uid | -p pid]\n");
39 40
    print("Usage: manage_reservations [-a <urn>] delete pid uuid\n");
    print("Usage: manage_reservations [-a <urn>] approve -p portal uuid\n");
41
    print("Usage: manage_reservations [-a <urn>] systeminfo\n");
42
    print("Usage: manage_reservations [-a <urn>] prediction\n");
43 44 45 46 47 48 49
    exit(-1);
}
my $optlist     = "dt:a:";
my $debug       = 0;
my $webtask_id;
my $webtask;
my $authority;
50
my $aggregate;
51 52 53 54 55 56 57

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $OURDOMAIN	= "@OURDOMAIN@";
58
my $ANNOUNCE    = "$TB/sbin/announce";
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
my $MYURN	= "urn:publicid:IDN+${OURDOMAIN}+authority+cm";

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use EmulabConstants;
use emdb;
use emutil;
79
use Brand;
80 81 82 83 84 85 86 87
use User;
use Project;
use Reservation;
use EmulabConstants;
use libEmulab;
use libtestbed;
use WebTask;
use APT_Geni;
88
use APT_Aggregate;
89
use APT_Instance;
90 91 92 93 94 95 96 97
use GeniResponse;
use GeniUser;

# Protos
sub fatal($);
sub DoReserve();
sub DoList();
sub DoDelete();
98 99
sub DoApprove();
sub DoSystemInfo();
100
sub DoPrediction();
101
sub DoCancel();
102
sub readfile($);
103
sub AddAnnouncement($$$$$$$);
104
sub DeleteAnnouncement($);
105 106
sub RetireAnnouncement($);
sub RestoreAnnouncement($);
107 108 109 110 111 112
sub RecordReservationRequest($$$$;$);
sub UpdateReservationRequest($$$);
my $RESERVATION_RECORD_APPROVE  = 1;
my $RESERVATION_RECORD_DELETE   = 2;
my $RESERVATION_RECORD_CANCEL   = 3;
my $RESERVATION_RECORD_UNCANCEL = 4;
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

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
    $webtask = WebTask->Lookup($webtask_id);
    if (!defined($webtask)) {
	fatal("Could not lookup webtask $webtask_id");
    }
    # Convenient.
    $webtask->AutoStore(1);
}
if (defined($options{"d"})) {
    $debug++;
}
if (@ARGV < 1) {
    usage();
}
my $action = shift(@ARGV);

#
# Default to local cluster
#
if (defined($options{"a"})) {
143 144 145 146 147 148
    if (GeniHRN::IsValid($options{"a"})) {
	$aggregate = APT_Aggregate->Lookup($options{"a"});
    }
    else {
	$aggregate = APT_Aggregate->LookupByNickname($options{"a"});
    }
149 150
}
else {
151
    $aggregate = APT_Aggregate->Lookup($MYURN);
152
}
153 154 155
if (!defined($aggregate)) {
    fatal("Could not lookup aggregate");
}
156 157 158 159
$authority = APT_Geni::GetAuthority($aggregate->urn());
if (!defined($authority)) {
    fatal("Could not look up authority");
}
160

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
# For credentials.
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    fatal("You ($UID) do not exist!");
}
my $geniuser = GeniUser->CreateFromLocal($this_user);

if ($action eq "reserve") {
    DoReserve();
}
elsif ($action eq "list") {
    DoList();
}
elsif ($action eq "delete") {
    DoDelete();
}
177 178 179 180 181 182
elsif ($action eq "approve") {
    DoApprove();
}
elsif ($action eq "systeminfo") {
    DoSystemInfo();
}
183 184 185
elsif ($action eq "prediction") {
    DoPrediction();
}
186 187 188
elsif ($action eq "cancel") {
    DoCancel();
}
189 190 191 192 193 194 195 196 197 198 199 200 201
else {
    usage();
}
exit(0);

#
# Create a reservation.
#
sub DoReserve()
{
    #
    # We allow for a user or project argument.
    #
202
    my $optlist = "t:s:e:nN:u:p:";
203 204
    my ($start, $end, $type, $reason, $update);
    my $checkonly = 0;
205 206
    my $portal;
    my $brand;
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
    my %rpcargs = ();
    my $context;
    my ($credential,$speaksfor);
    
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    usage()
	if (@ARGV < 2);
    my $project = Project->Lookup($ARGV[0]);
    my $count   = $ARGV[1];

    if (defined($options{"s"})) {
	$start = $options{"s"};
    }
    if (defined($options{"e"})) {
	$end = $options{"e"};
    }
    if (defined($options{"t"})) {
	$type = $options{"t"};
    }
    if (defined($options{"u"})) {
	$update = $options{"u"};
    }
232 233 234
    if (defined($options{"p"})) {
	$portal = $options{"p"};
    }
235 236 237 238 239 240 241
    if (defined($options{"N"})) {
	$reason = readfile($options{"N"});
    }
    if (defined($options{"n"})) {
	$checkonly = 1;
    }
    usage()
242
	if (!defined($project));
243 244 245 246 247
    # Need brand for email. No portal argument means emulab brand.
    $brand = Brand->Create($portal);
    if (!defined($brand)) {
	fatal("Bad branding");
    }
248 249 250
    if (defined($update)) {
	usage()
	    if (! (defined($count) || defined($start) || defined($end)));
251
    }
252 253
    else {
	usage()
254
	    if (! (defined($count) && defined($type) && defined($end)));
255 256 257 258 259 260 261
	
	if ($type !~ /^[-\w]+$/) {
	    fatal("Type is not a string");
	}
    }
    if (defined($count) && $count !~ /^\d+$/) {
	fatal("Count is not an integer");
262
    }
263 264 265
    if (defined($start) &&
	!($start =~ /^\d+$/ || str2time($start))) {
	fatal("Start is not a unix timestamp or datetime");
266
    }
267 268 269
    if (defined($end) &&
	!($end =~ /^\d+$/ || str2time($end))) {
	fatal("End is not a unix timestamp or datetime");
270
    }
271 272 273 274
    $rpcargs{"start"} = TBDateStringGMT($start) if (defined($start));
    $rpcargs{"end"}   = TBDateStringGMT($end) if (defined($end));
    $rpcargs{"count"} = $count if (defined($count));
    $rpcargs{"type"}  = $type if (!defined($update));
275 276 277 278 279 280 281
    $rpcargs{"check"} = $checkonly;
    $rpcargs{"reason"}= $reason if (defined($reason));
    $rpcargs{"update"}= $update if (defined($update));
    
    if ($this_user->IsAdmin()) {
	#
	# We do not have a very good notion of cross site admin.
282 283
	# So first we make sure that the user exists at the cluster
	# and then we make an "admin" call as the root authority.
284
	#
285 286 287
	if (APT_Geni::CreatePortalUser($authority, $geniuser)) {
	    fatal("Could not create admin user at remote cluster");
	}
288
	$rpcargs{"project_urn"} = $project->urn()->asString();
289
	$rpcargs{"user_urn"} = $geniuser->urn()->asString();
290 291 292 293 294 295 296
    }
    else {
	if (!$project->AccessCheck($this_user, TB_PROJECT_CREATEEXPT())) {
	    fatal("No permission to access reservation list for $project")
	}
	($credential,$speaksfor) =
	    APT_Geni::GenProjectCredential($project, $geniuser);
297 298 299 300 301 302 303 304 305

	fatal("Could not generate credentials")
	    if (!defined($credential));
	my $credentials = [$credential->asString()];
	if (defined($speaksfor)) {
	    $credentials = [@$credentials, $speaksfor->asString()];
	}
	$rpcargs{"credentials"} = $credentials;
	$context = APT_Geni::GeniContext();
306 307 308 309 310
    }
    my $response =
	APT_Geni::PortalRPC($authority, $context, "Reserve", \%rpcargs);
    if (GeniResponse::IsError($response)) {
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
311
	# Watch for a refused error, we want to tell the user that.
312
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
313
	if ($response->code() == GENIRESPONSE_REFUSED) {
314 315
	    RecordReservationRequest($this_user,
				     $project, $aggregate, \%rpcargs);
Leigh B Stoller's avatar
Leigh B Stoller committed
316 317
	    UserError($response->output());
	}
318 319 320
	fatal($response->output());
    }
    print Dumper($response);
321 322 323 324 325 326 327
    #
    # Exit with different status if the reservation is feasible but
    # needs to be approved. The value is a boolean indicating
    # approved.  Note that this applies even in "check" mode; the
    # approval code indicates if the request is feasible and will be
    # immediately approved.
    #
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    my $approved;
    my $uuid;
    my $idx;

    if (ref($response->value()) eq "HASH") {
	my $blob  = $response->value();
	$approved = $blob->{'approved'};
	$uuid     = $blob->{'uuid'} if (exists($blob->{'uuid'}));
	$idx      = $blob->{'idx'} if (exists($blob->{'idx'}));
	if (defined($idx) && $idx !~ /^\d*$/) {
	    fatal("Bad format for index from cluster");
	}
	if (defined($uuid) && !ValidUUID($uuid)) {
	    fatal("Bad format for uuid from cluster");
	}
343 344
	RecordReservationRequest($this_user,
				 $project, $aggregate, \%rpcargs, $blob);
345 346 347 348 349 350 351
    }
    else {
	# Backwards compat.
	$approved = $response->value();
    }
    if ($checkonly) {
	exit($approved ? 0 : 2);
352 353 354 355 356 357 358 359
    }
    #
    # Needs to be approved, exit with special status.
    #
    # If this was not $checkonly, then we want to send email locally
    # since the email was generated to the tbops but not the portal
    # email lists.
    #
360
    if (!$approved) {
361 362 363 364 365 366 367 368 369 370
	my $this_uid   = $this_user->uid();
	my $this_email = $this_user->email();
	my $url        = $brand->wwwBase() . "/list-reservations.php";
    
	$brand->SendEmail($brand->ExtensionsEmailAddress(),
	  "Pending reservation request needs approval",
	  "A reservation request was made by $this_uid, but it needs approval.".
	  "\n\n".
	  "See: $url", $this_email);
    }
371 372 373 374
    elsif (defined($uuid)) {
	#
	# Schedule an announcement for the user.
	#
375
	AddAnnouncement($portal, $brand, $uuid, $this_user, $count, $type, $start);
376 377 378 379 380 381 382
    }
    if (defined($webtask)) {
	$webtask->approved($approved);
	$webtask->idx($idx) if (defined($idx));
	$webtask->uuid($uuid) if (defined($uuid));
    }
    exit($approved ? 0 : 2);
383 384 385 386 387 388 389 390 391 392 393 394
}

#
# Ask for a list of reservations.
#
sub DoList()
{
    #
    # We allow for a user or project argument.
    #
    my $optlist = "u:p:Ai:";
    my $anon    = 0;
395
    my $uuid;
396
    my $project;
397
    my $user;
398 399 400 401 402 403 404 405 406 407 408
    my %rpcargs = ();
    my $context;
    
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"A"})) {
	$anon = 1;
    }
    if (defined($options{"i"})) {
409
	$uuid = $options{"i"};
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    }
    if (defined($options{"u"})) {
	$user = User->Lookup($options{"u"});
	if (!defined($user)) {
	    fatal("No such user");
	}
	if (!$this_user->IsAdmin() && !$this_user->SameUser($user)) {
	    fatal("No permission to access reservation list for $user")
	}
	$geniuser = $this_user->CreateFromLocal($user);
    }
    if (defined($options{"p"})) {
	$project = Project->Lookup($options{"p"});

	if (!defined($project)) {
	    fatal("No such project");
	}
	if (!$this_user->IsAdmin() &&
428
	    !$project->AccessCheck($this_user, TB_PROJECT_CREATEEXPT())) {
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	    fatal("No permission to access reservation list for $project")
	}
    }
    if ($this_user->IsAdmin() || $anon) {
	#
	# We do not have a very good notion of cross site admin. Get
	# the entire list, we will filter here.
	#
    }
    else {
	my ($credential,$speaksfor);
	
	if (defined($project)) {
	    ($credential,$speaksfor) =
		APT_Geni::GenProjectCredential($project, $geniuser);
	}
	else {
	    ($credential,$speaksfor) =
		APT_Geni::GenUserCredential($geniuser);
	}
	fatal("Could not generate credentials")
	    if (!defined($credential));
	
	my $credentials = [$credential->asString()];
	if (defined($speaksfor)) {
	    $credentials = [@$credentials, $speaksfor->asString()];
	}
	$rpcargs{"credentials"} = $credentials;
	$context = APT_Geni::GeniContext();
    }
459 460
    if (defined($uuid)) {
	$rpcargs{"uuid"} = $uuid;
461 462 463 464 465
    }
    my $response =
	APT_Geni::PortalRPC($authority, $context, "Reservations", (\%rpcargs));
    if (GeniResponse::IsError($response)) {
	#
466 467
	# Do not throw a fatal error if we get a search failure, no need
	# to send any email.
468
	#
469 470 471 472 473 474
	if (defined($uuid) && $response->code() == GENIRESPONSE_SEARCHFAILED) {
	    UserError($response->output());
	}
	else {
	    fatal($response->output());
	}
475 476
    }
    my $list = $response->value()->{'reservations'};
477 478 479
    my $history = $response->value()->{'history'}
        if (exists($response->value()->{'history'}));
    
480 481 482 483 484
    #
    # Map remote URNs to local projects and users. Not all of them can
    # be mapped of course, we leave those as is. 
    #
    foreach my $details (values(%$list)) {
485
	my $userhrn  = GeniHRN->new($details->{'user'});
486
	my $geniuser = GeniUser->Lookup($details->{'user'}, 1);
487
	if (defined($geniuser) && $geniuser->IsLocal()) {
488
	    #print Dumper($geniuser);
489
	    $details->{'uid'}     = $geniuser->uid();
490
	    $details->{'uid_idx'} = $geniuser->idx();
491
	}
492 493 494
	else {
	    $details->{'uid'}     = $userhrn->id();
	}
495 496 497 498 499 500 501 502
	my $projhrn = GeniHRN->new($details->{'project'});
	if ($projhrn->domain() eq $OURDOMAIN && defined($projhrn->project())) {
	    my $project = Project->Lookup($projhrn->project());
	    if (defined(($project))) {
		$details->{'pid'}     = $project->pid();
		$details->{'pid_idx'} = $project->pid_idx();
	    }
	}
503 504 505
	else {
	    $details->{'pid'} = $projhrn->id();
	}
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

	#
	# If we have the history, then go through and map the
	# experiments to local experiments so we can link to them in
	# the web interface.
	#
	if (exists($history->{$projhrn})) {
	    foreach my $ref (@{ $history->{$projhrn} }) {
		#print Dumper($ref);
		    
		# Local experiment on the remote cluster.
		next
		    if (!(exists($ref->{'urn'}) && exists($ref->{'slice_uuid'})));
		# Already processed.
		next
		    if (exists($ref->{'instance_uuid'}));

		my $hrn = GeniHRN->new($ref->{'urn'});
		if (defined($hrn) &&
		    $hrn->domain() eq $OURDOMAIN && defined($hrn->project())) {
		    my $instance = APT_Instance->LookupBySlice($hrn);
		    if (defined($instance) &&
			$instance->slice_uuid() eq $ref->{'slice_uuid'}) {
			$ref->{'instance_uuid'} = $instance->uuid();
		    }
		}
	    }
	}
534 535 536 537 538
    }
    #
    # Strip out unwanted results if we asked as an admin for a specific
    # user or project.
    #
539 540 541 542 543
    if ($this_user->IsAdmin() && (defined($project) || defined($user))) {
	my $tmp = {};
	
	foreach my $key (keys(%$list)) {
	    my $details = $list->{$key};
544
	    my $projhrn = $details->{'project'};
545

546
	    if (defined($project)) {
547 548 549 550 551 552 553
		if (!defined($details->{'pid_idx'}) ||
		    $details->{'pid_idx'} != $project->pid_idx()) {
		    # Kill the history entry when skipping.
		    delete($history->{$projhrn})
			if (defined($history) && exists($history->{$projhrn}));
		    next
		}
554 555
	    }
	    else {
556 557 558 559 560 561 562
		if (!defined($details->{'uid_idx'}) ||
		    $details->{'uid_idx'} != $user->uid_idx()) {
		    # Kill the history entry when skipping.
		    delete($history->{$projhrn}) 
			if (defined($history) && exists($history->{$projhrn}));
		    next
		}
563 564 565
	    }
	    $tmp->{$key} = $details;
	}
566
	$response->value()->{'reservations'} = $tmp;
567 568
    }
    if (defined($webtask)) {
569
	$webtask->value($response->value());
570 571 572
	$webtask->Exited(0);
    }
    else {
573
	print Dumper($response->value());
574 575 576 577 578 579 580
    }
    exit(0);
}

#
# Delete a reservation.
#
581 582
# This is not doing proper permission checks or credentials. Need to fix.
#
583 584
sub DoDelete()
{
585 586 587 588 589 590 591 592 593 594 595 596 597 598
    #
    # We allow for admins to pass a reason (deny with cause).
    #
    my $optlist = "N:";
    my $reason;
    
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"N"})) {
	$reason = readfile($options{"N"});
	chomp($reason);
    }
599 600
    usage()
	if (@ARGV != 2);
601 602
    my $pid  = shift(@ARGV);
    my $uuid = shift(@ARGV);
603 604
    
    # Check this since Reservation->Lookup() does not validate.
605 606
    fatal("Invalid uuid")
	if (!ValidUUID($uuid));
607 608 609 610 611 612 613 614 615

    my $project = Project->Lookup($pid);
    fatal("No such project")
	if (!defined($project));
    
    if (!$this_user->IsAdmin() &&
	!$project->AccessCheck($this_user, TB_PROJECT_CREATEEXPT())) {
	fatal("No permission to access reservation list for $project")
    }
616
    my $blob = { "uuid" => $uuid,
617 618 619 620 621
		 "project" => $project->urn()->asString()
    };
    if ($this_user->IsAdmin() && defined($reason) && $reason ne "") {
	$blob->{'reason'} = $reason;
    }
622
    my $response =
623
	APT_Geni::PortalRPC($authority, undef, "DeleteReservation", $blob);
624 625 626 627 628 629
    if (GeniResponse::IsError($response)) {
	#
	# All errors are fatal.
	#
	fatal($response->output());
    }
630
    UpdateReservationRequest($aggregate, $uuid, $RESERVATION_RECORD_DELETE);
631
    DeleteAnnouncement($uuid);
632 633 634 635 636 637 638 639 640
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    else {
	print Dumper($response);
    }
    exit(0);
}

641 642 643 644 645
#
# Approve a reservation.
#
sub DoApprove()
{
646 647 648 649 650 651 652 653 654 655
    my $optlist = "p:";
    my $portal;

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"p"})) {
	$portal = $options{"p"}
    }
656
    usage()
657 658
	if (@ARGV != 1 || !defined($portal));
    my $uuid = shift(@ARGV);
659 660
    
    # Check this since Reservation->Lookup() does not validate.
661 662 663 664 665 666 667
    fatal("Invalid uuid")
	if (!ValidUUID($uuid));

    my $brand = Brand->Create($portal);
    if (!defined($brand)) {
	fatal("Bad branding");
    }
668 669 670 671 672 673 674 675

    if (!$this_user->IsAdmin()) {
	fatal("No permission to approve reservations")
    }
    # PortalRPC will use the root context in this case, which is
    # essentially saying the caller is an admin.
    my $response =
	APT_Geni::PortalRPC($authority, undef, "ApproveReservation",
676
			    {"uuid" => $uuid});
677 678 679 680 681 682
    if (GeniResponse::IsError($response)) {
	#
	# All errors are fatal.
	#
	fatal($response->output());
    }
683 684
    UpdateReservationRequest($aggregate, $uuid, $RESERVATION_RECORD_APPROVE);
    
685 686 687 688
    #
    # Schedule an announcement for the user.
    #
    my $blob = $response->value();
689 690 691 692 693 694 695
    if (exists($blob->{'user'})) {
	my $geniuser = GeniUser->Lookup($blob->{'user'}, 1);
	if (defined($geniuser) && $geniuser->IsLocal()) {
	    AddAnnouncement($portal, $brand, $uuid, $geniuser->emulab_user(),
			    $blob->{'nodes'}, $blob->{'type'}, $blob->{'start'});
	}
    }
696 697 698 699 700 701 702 703 704
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    else {
	print Dumper($response);
    }
    exit(0);
}

705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
#
# Schedule (or clear) reservation cancellation
#
sub DoCancel()
{
    my $optlist = "p:ce:N:";
    my $clear   = 0;
    my $when;
    my $portal;
    my $reason;

    if (!$this_user->IsAdmin()) {
	fatal("No permission to schedule reservation cancellation")
    }    

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"N"})) {
	$reason = readfile($options{"N"});
	chomp($reason);
    }
    if (defined($options{"p"})) {
	$portal = $options{"p"}
    }
    if (defined($options{"c"})) {
	$clear = 1;
    }
    elsif (defined($options{"e"})) {
	$when = $options{"e"};
	if ($when !~ /^\d+$/) {
	    $when = str2time($when);
	    if (!defined($when)) {
		fatal("Could not parse -e option.");
	    }
	}
    }
    else {
	usage();
    }
    usage()
	if (@ARGV != 1 || !defined($portal));
    my $uuid = shift(@ARGV);
    
    # Check this since Reservation->Lookup() does not validate.
    fatal("Invalid uuid")
	if (!ValidUUID($uuid));

    my $brand = Brand->Create($portal);
    if (!defined($brand)) {
	fatal("Bad branding");
    }
    my $args = {"uuid" => $uuid};
    if ($clear) {
	$args->{"clear"} = 1;
    }
    else {
	$args->{"when"} = $when;
    }
    $args->{'reason'} = $reason if (defined($reason));

    # PortalRPC will use the root context in this case, which is
    # essentially saying the caller is an admin.
    my $response =
	APT_Geni::PortalRPC($authority, undef, "CancelReservation", $args);
    if (GeniResponse::IsError($response)) {
	#
	# All errors are fatal.
	#
	fatal($response->output());
    }
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    else {
	print Dumper($response);
    }
    if ($clear) {
784 785
	UpdateReservationRequest($aggregate, $uuid,
				 $RESERVATION_RECORD_UNCANCEL);
786 787 788 789
	RestoreAnnouncement($uuid);
    }
    else {
	RetireAnnouncement($uuid);
790 791
	UpdateReservationRequest($aggregate, $uuid,
				 $RESERVATION_RECORD_CANCEL);
792 793 794 795
    }
    exit(0);
}

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
#
# Get the reservation system info.
#
sub DoSystemInfo()
{
    my $optlist = "p:";
    my $portal;
    my $errmsg;
    my @aggregates = ($authority);
    my @webtasks   = ();

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"p"})) {
	$portal = $options{"p"}
    }
    usage()
	if (@ARGV);

    #
    # Portal argument says to ignore aggregate argument, and contact
    # all aggregates listed for the portal. 
    #
    if (defined($portal)) {
	@aggregates = ();
	
	my @list = APT_Aggregate->LookupForPortal($portal);
825 826
	foreach my $agg (@list) {
	    my $authority = APT_Geni::GetAuthority($agg->urn());
827
	    if (!defined($authority)) {
828
		$errmsg = "Cannot lookup authority for $agg";
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
		goto bad;
	    }
	    push(@aggregates, $authority);
	}
    }

    my $coderef = sub {
	my ($blob) = @_;
	my $authority = $blob->{"authority"};
	my $webtask   = $blob->{"webtask"};
	
	# PortalRPC will use the root context in this case, which is
	# essentially saying the caller is an admin. But thats okay
	# for this call, it is just informational.
	my $response =
	    APT_Geni::PortalRPC($authority, undef, "ReservationSystemInfo");
	
	if (GeniResponse::IsError($response)) {
	    #
	    # All errors are fatal.
	    #
	    if (defined($webtask)) {
		$webtask->output($response->output());
		$webtask->Exited(-1);
	    }
	    else {
Leigh B Stoller's avatar
Leigh B Stoller committed
855
		print STDERR "$authority: " . $response->output() . "\n";
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
	    }
	    return -1;
	}
	if (defined($webtask)) {
	    $webtask->value($response->value());
	    $webtask->Exited(0);
	}
	return 0;
    };
    #
    # Multiple aggregates, we use parrun. We need a webtask for each
    # authority to communicate the results back to the parent, who
    # then combines them all.
    #
    my @return_codes = ();
    my @agglist = ();

    foreach my $auth (@aggregates) {
	my $temptask = WebTask->CreateAnonymous();
	# For delete below.
	push(@webtasks, $temptask);
	push(@agglist, {"authority" => $auth,
			"webtask"   => $temptask});
    }
    if (ParRun({"maxwaittime" => 60,
		"maxchildren" => scalar(@agglist)},
	    \@return_codes, $coderef, @agglist)) {
	#
	# The parent caught a signal. Leave things intact so that we can
	# kill things cleanly later.
	#
	$errmsg = "Internal error get reservation info";
	goto bad;
    }
    #
    # Check the exit codes, create return structure for the web interface.
    #
    my $blob = {};
    
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
    foreach my $agg (@agglist) {
	my $code  = shift(@return_codes);
	my $auth  = $agg->{'authority'};
	my $wtask = $agg->{'webtask'};

	$wtask->Refresh();

	if ($code) {
	    $errmsg  = "$auth: " . $wtask->output();
	    goto bad;
	}
	$blob->{$auth->urn()} = $wtask->value();
    }
    if (defined($webtask)) {
	$webtask->value($blob);
	$webtask->Exited(0);
    }
    else {
	print Dumper($blob);
    }
    foreach my $temptask (@webtasks) {
	$temptask->Delete();
    }
    exit(0);

  bad:
    foreach my $temptask (@webtasks) {
	$temptask->Delete();
    }
    fatal($errmsg);
}

#
# Get the prediction data.
#
sub DoPrediction()
{
    my $optlist = "p:";
    my $portal;
    my $errmsg;
    my @aggregates = ($authority);
    my @webtasks   = ();
    my @projlist   = ();

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"p"})) {
	$portal = $options{"p"}
    }
    # Argument is a list of projects, else we generate one for user.
    if (@ARGV) {
	foreach my $pid (@ARGV) {
	    my $project = Project->Lookup($pid);
	    if (!defined($project)) {
		fatal("No such project: $pid");
	    }
	    push(@projlist, $project->urn());
	}
    }
956
    elsif (!$this_user->IsAdmin()) {
957 958 959 960
	my @plist;
	if ($this_user->ProjectMembershipList(\@plist)) {
	    fatal("Could not get project membership list");
	}
961 962 963
	# Do not need CREATE experiment permission, just membership.
	# This solves the problem of users having "user" privs in the
	# project, but local_root in a subgroup.
964
	foreach my $project (@plist) {
965
	    push(@projlist, $project->urn());
966 967 968 969 970 971 972 973 974 975 976 977 978 979
	}
	if (!@projlist) {
	    fatal("No projects to create experiments in");
	}
    }

    #
    # Portal argument says to ignore aggregate argument, and contact
    # all aggregates listed for the portal. 
    #
    if (defined($portal)) {
	@aggregates = ();
	
	my @list = APT_Aggregate->LookupForPortal($portal);
980 981
	foreach my $agg (@list) {
	    my $authority = APT_Geni::GetAuthority($agg->urn());
982
	    if (!defined($authority)) {
983
		$errmsg = "Cannot lookup authority for $agg";
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 1013 1014 1015 1016 1017 1018
		goto bad;
	    }
	    push(@aggregates, $authority);
	}
    }

    my $coderef = sub {
	my ($blob) = @_;
	my $authority = $blob->{"authority"};
	my $webtask   = $blob->{"webtask"};
	
	# PortalRPC will use the root context in this case, which is
	# essentially saying the caller is an admin. But thats okay
	# for this call, it is just informational.
	my $response =
	    APT_Geni::PortalRPC($authority, undef,
				"ReservationPrediction",
				{"projlist" => \@projlist});
	
	if (GeniResponse::IsError($response)) {
	    #
	    # All errors are fatal.
	    #
	    if (defined($webtask)) {
		$webtask->output($response->output());
		$webtask->Exited(-1);
	    }
	    else {
		print STDERR "$authority: " . $response->output() . "\n";
	    }
	    return -1;
	}
	if (defined($webtask)) {
	    $webtask->value($response->value());
	    $webtask->Exited(0);
1019
	    $webtask->Store();
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
	}
	return 0;
    };
    #
    # Multiple aggregates, we use parrun. We need a webtask for each
    # authority to communicate the results back to the parent, who
    # then combines them all.
    #
    my @return_codes = ();
    my @agglist = ();

    foreach my $auth (@aggregates) {
	my $temptask = WebTask->CreateAnonymous();
	# For delete below.
	push(@webtasks, $temptask);
	push(@agglist, {"authority" => $auth,
			"webtask"   => $temptask});
    }
1038
    if (ParRun({"maxwaittime" => 30,
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
		"maxchildren" => scalar(@agglist)},
	    \@return_codes, $coderef, @agglist)) {
	#
	# The parent caught a signal. Leave things intact so that we can
	# kill things cleanly later.
	#
	$errmsg = "Internal error get reservation prediction info";
	goto bad;
    }
    #
    # Check the exit codes, create return structure for the web interface.
    #
    my $blob = {};
    
1053 1054 1055 1056 1057 1058 1059 1060
    foreach my $agg (@agglist) {
	my $code  = shift(@return_codes);
	my $auth  = $agg->{'authority'};
	my $wtask = $agg->{'webtask'};

	$wtask->Refresh();

	if ($code) {
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	    #
	    # If this timed out, lets not return a fatal error since
	    # this info is informational and does not prevent the web
	    # server from operating normally.
	    #
	    if ($code == 15) {
		$blob->{$auth->urn()} = "Timed out getting reservation ".
		    "system information";
		next;
	    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1071
	    $errmsg  = "$auth: " . $wtask->output();
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
	    goto bad;
	}
	$blob->{$auth->urn()} = $wtask->value();
    }
    if (defined($webtask)) {
	$webtask->value($blob);
	$webtask->Exited(0);
    }
    else {
	print Dumper($blob);
    }
    foreach my $temptask (@webtasks) {
	$temptask->Delete();
    }
    exit(0);

  bad:
    foreach my $temptask (@webtasks) {
	$temptask->Delete();
    }
    fatal($errmsg);
}

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 1128 1129 1130
sub fatal($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->code(-1);
    }
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

sub UserError($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->code(1);
    }
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(1);
}

sub readfile($) {
    local $/ = undef;
    my ($filename) = @_;
    open(FILE, $filename) or fatal("Could not open $filename: $!");
    my $contents = <FILE>;
    close(FILE);
    return $contents;
}

1131 1132 1133
#
# Add or Edit a reservation announcement.
#
1134
sub AddAnnouncement($$$$$$$)
1135
{
1136 1137
    my ($portal, $brand, $uuid, $user, $nodes, $type, $start) = @_;
    my $this_uid = $user->uid();
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    my $nickname = $aggregate->nickname();
    my $name     = $aggregate->name();
    my $url      = $brand->wwwBase() .
	"/reserve.php?edit=1&uuid=${uuid}&cluster=${nickname}";
    my $text = "You have a reservation at $name for $nodes $type ".
	"node(s) starting soon.";
    my $command;
    my $dateopt = "";

    #
    # If the reservation is more then 24 hours out, schedule an announcement
    # for 24 hours ahead. 
    #
    if (defined($start)) {
	if ($start !~ /^\d+$/) {
	    $start = str2time($start);
	}
	if ($start - time() > (3600 * 24)) {
	    $dateopt = "-S " . ($start - (3600 * 23));
	}
    }

    # This is awkward, the announcement stuff should be a library some day.
    my $query_result =
	emdb::DBQueryWarn("select idx from apt_announcements where uuid='$uuid'");
    return
	if (!$query_result);
    # Update mode.
    if ($query_result->numrows) {
	$command = "$ANNOUNCE -A $uuid -b 'View Reservation' ".
	    "-u '$url' $dateopt '$text'";
    }
    else {
1171
	$command = "$ANNOUNCE -a -p $portal -U $this_uid -I 4 ".
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
	    "-b 'View Reservation' -u '$url' -t $uuid $dateopt '$text'";
    }
    system($command);
}
sub DeleteAnnouncement($)
{
    my ($uuid) = @_;

    system("$ANNOUNCE -R $uuid");    
}
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
sub RetireAnnouncement($)
{
    my ($uuid) = @_;

    system("$ANNOUNCE -r $uuid");    
}
sub RestoreAnnouncement($)
{
    my ($uuid) = @_;

    system("$ANNOUNCE -w $uuid");    
}
1194

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
#
# Reservation history support.
#
sub RecordReservationRequest($$$$;$)
{
    my ($user, $project, $aggregate, $details, $response) = @_;
    my $uid        = $user->uid();
    my $uid_idx    = $user->uid_idx();
    my $pid        = $project->pid();
    my $pid_idx    = $project->pid_idx();
    my $urn        = $aggregate->urn();
    my $nodes      = $details->{'count'};
    my $type       = $details->{'type'};
    my $start      = $details->{'start'};
    my $end        = $details->{'end'};
    my $reason     = $details->{'reason'};
    my $checkonly  = $details->{'check'};
    my $update     = $details->{'update'}; # reservation_uuid
    my $stamp      = time();
    my @action_sets = ();
    my @detail_sets = ();

    push(@detail_sets, "uid='$uid'");
    push(@detail_sets, "uid_idx='$uid_idx'");
    push(@detail_sets, "pid='$pid'");
    push(@detail_sets, "pid_idx='$pid_idx'");
    push(@detail_sets, "nodes='$nodes'");
    push(@detail_sets, "type='$type'");
    push(@detail_sets, "end=FROM_UNIXTIME(" . str2time($end) . ")");    
    push(@detail_sets, "start=FROM_UNIXTIME(" . str2time($start) . ")")
	if (defined($start));
    push(@detail_sets, "reason=" . DBQuoteSpecial($reason))
	if (defined($reason));
    
    push(@action_sets, "aggregate_urn='$urn'");
    push(@action_sets, "stamp=now()");
    if (defined($response)) {
	push(@action_sets, "reservation_uuid=" .
	     DBQuoteSpecial($response->{'uuid'}));
	push(@detail_sets, "approved='1'") if ($response->{'approved'});
    }
    elsif (defined($update)) {
	push(@action_sets, "reservation_uuid=" . DBQuoteSpecial($update));
	push(@detail_sets, "refused='1'");
    }
    else {
	push(@detail_sets, "refused='1'");
    }
    @detail_sets = (@action_sets, @detail_sets);

    if ($checkonly) {
	push(@action_sets, "action='validate'");
    }
    else {
	push(@action_sets, "action='submit'");
    }

    DBQueryWarn("lock tables apt_reservation_history_actions write, ".
		"            apt_reservation_history_details write")
	or return -1;

    #
    # Insert the action record, the idx becomes the idx for the details
    #
    my $query = "insert into apt_reservation_history_actions set ".
	join(",", @action_sets);
    my $query_result = DBQueryWarn($query);
    if (!defined($query_result)) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    my ($idx) = $query_result->insertid();
    push(@detail_sets, "idx='$idx'");

    $query = "insert into apt_reservation_history_details set ".
	join(",", @detail_sets);
    if (!DBQueryWarn($query)) {
	DBQueryWarn("delete from apt_reservation_history_actions ".
		    "where idx='$idx'");
	DBQueryWarn("unlock tables");
	return -1;
    }
    DBQueryWarn("unlock tables");
    return 0;
}

#
# Update a reservation request for approval,deletion,etc.
#
sub UpdateReservationRequest($$$)
{
    my ($aggregate, $uuid, $flags) = @_;
    my $urn = $aggregate->urn();
    if ($flags == $RESERVATION_RECORD_APPROVE) {
	$action = "approve";
    }
    elsif ($flags == $RESERVATION_RECORD_DELETE) {
	$action = "delete";
    }
    elsif ($flags == $RESERVATION_RECORD_CANCEL) {
	$action = "cancel";
    }
    elsif ($flags == $RESERVATION_RECORD_UNCANCEL) {
	$action = "restore";
    }
    else {
	return -1;
    }
    DBQueryWarn("lock tables apt_reservation_history_actions write, ".
		"            apt_reservation_history_details write")
	or return -1;
1306

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    #
    # Insert an action record.
    #
    if (!DBQueryWarn("insert into apt_reservation_history_actions set ".
		     " aggregate_urn='$urn', reservation_uuid='$uuid', ".
		     " stamp=now(), action='$action'")) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    DBQueryWarn("unlock tables")
	or return -1;
    return 0;
}