manage_reservations.in 36.3 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-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
# 
# {{{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";
31
use POSIX qw(:signal_h ceil);
32 33 34 35 36 37 38 39
use Date::Parse;

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

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $OURDOMAIN	= "@OURDOMAIN@";
60
my $ANNOUNCE    = "$TB/sbin/announce";
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
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;
81
use Brand;
82 83 84 85 86 87 88 89
use User;
use Project;
use Reservation;
use EmulabConstants;
use libEmulab;
use libtestbed;
use WebTask;
use APT_Geni;
90
use APT_Aggregate;
91
use APT_Instance;
92
use APT_Utility;
93 94 95 96 97
use GeniResponse;
use GeniUser;

# Protos
sub fatal($);
98 99
sub UserError($);
sub ExitWithError($);
100 101 102
sub DoReserve();
sub DoList();
sub DoDelete();
103
sub DoApprove();
104
sub DoPrediction();
105
sub DoCancel();
106
sub DoHistory();
107
sub readfile($);
108
sub AddAnnouncement($$$$$$$);
109
sub DeleteAnnouncement($);
110 111
sub RetireAnnouncement($);
sub RestoreAnnouncement($);
112 113 114 115 116 117
sub RecordReservationRequest($$$$;$);
sub UpdateReservationRequest($$$);
my $RESERVATION_RECORD_APPROVE  = 1;
my $RESERVATION_RECORD_DELETE   = 2;
my $RESERVATION_RECORD_CANCEL   = 3;
my $RESERVATION_RECORD_UNCANCEL = 4;
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 143 144 145 146 147

#
# 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"})) {
148 149 150 151 152 153
    if (GeniHRN::IsValid($options{"a"})) {
	$aggregate = APT_Aggregate->Lookup($options{"a"});
    }
    else {
	$aggregate = APT_Aggregate->LookupByNickname($options{"a"});
    }
154 155
}
else {
156
    $aggregate = APT_Aggregate->Lookup($MYURN);
157
}
158 159 160
if (!defined($aggregate)) {
    fatal("Could not lookup aggregate");
}
161 162 163 164
$authority = APT_Geni::GetAuthority($aggregate->urn());
if (!defined($authority)) {
    fatal("Could not look up authority");
}
165 166 167
# In general, these calls should not take a lot of time, so reduce the
# RPC timeout value. We will adjust them below if needed.
Genixmlrpc->SetTimeout(30);
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
# 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();
}
185 186 187
elsif ($action eq "approve") {
    DoApprove();
}
188 189 190
elsif ($action eq "prediction") {
    DoPrediction();
}
191 192 193
elsif ($action eq "history") {
    DoHistory();
}
194 195 196
elsif ($action eq "cancel") {
    DoCancel();
}
197 198 199 200 201 202 203 204 205 206 207 208 209
else {
    usage();
}
exit(0);

#
# Create a reservation.
#
sub DoReserve()
{
    #
    # We allow for a user or project argument.
    #
210
    my $optlist = "t:s:e:nN:u:p:";
211 212
    my ($start, $end, $type, $reason, $update);
    my $checkonly = 0;
213 214
    my $portal;
    my $brand;
215 216 217
    my %rpcargs = ();
    my $context;
    my ($credential,$speaksfor);
218
    my $errmsg;
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    
    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"};
    }
241 242 243
    if (defined($options{"p"})) {
	$portal = $options{"p"};
    }
244 245 246 247 248 249 250
    if (defined($options{"N"})) {
	$reason = readfile($options{"N"});
    }
    if (defined($options{"n"})) {
	$checkonly = 1;
    }
    usage()
251
	if (!defined($project));
252 253 254 255 256
    # Need brand for email. No portal argument means emulab brand.
    $brand = Brand->Create($portal);
    if (!defined($brand)) {
	fatal("Bad branding");
    }
257 258 259
    if (defined($update)) {
	usage()
	    if (! (defined($count) || defined($start) || defined($end)));
260
    }
261 262
    else {
	usage()
263
	    if (! (defined($count) && defined($type) && defined($end)));
264 265 266 267 268 269 270
	
	if ($type !~ /^[-\w]+$/) {
	    fatal("Type is not a string");
	}
    }
    if (defined($count) && $count !~ /^\d+$/) {
	fatal("Count is not an integer");
271
    }
272 273 274
    if (defined($start) &&
	!($start =~ /^\d+$/ || str2time($start))) {
	fatal("Start is not a unix timestamp or datetime");
275
    }
276 277 278
    if (defined($end) &&
	!($end =~ /^\d+$/ || str2time($end))) {
	fatal("End is not a unix timestamp or datetime");
279
    }
280 281 282 283
    $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));
284 285 286 287
    $rpcargs{"check"} = $checkonly;
    $rpcargs{"reason"}= $reason if (defined($reason));
    $rpcargs{"update"}= $update if (defined($update));
    
288 289 290 291
    # We can check for disabled aggregate now, nothing below matters.
    if ($aggregate->CheckStatus(\$errmsg, 1)) {
	UserError($errmsg);
    }
292 293 294
    if ($this_user->IsAdmin()) {
	#
	# We do not have a very good notion of cross site admin.
295 296
	# So first we make sure that the user exists at the cluster
	# and then we make an "admin" call as the root authority.
297
	#
298 299 300
	if (APT_Geni::CreatePortalUser($authority, $geniuser)) {
	    fatal("Could not create admin user at remote cluster");
	}
301
	$rpcargs{"project_urn"} = $project->urn()->asString();
302
	$rpcargs{"user_urn"} = $geniuser->urn()->asString();
303 304 305 306 307 308 309
    }
    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);
310 311 312 313 314 315 316 317 318

	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();
319 320 321 322
    }
    my $response =
	APT_Geni::PortalRPC($authority, $context, "Reserve", \%rpcargs);
    if (GeniResponse::IsError($response)) {
323
	# Watch for a refused error, we want to record these.
Leigh B Stoller's avatar
Leigh B Stoller committed
324
	if ($response->code() == GENIRESPONSE_REFUSED) {
325 326
	    RecordReservationRequest($this_user,
				     $project, $aggregate, \%rpcargs);
Leigh B Stoller's avatar
Leigh B Stoller committed
327
	}
328
	ExitWithError($response);
329 330
    }
    print Dumper($response);
331 332 333 334 335 336 337
    #
    # 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.
    #
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    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");
	}
353 354
	RecordReservationRequest($this_user,
				 $project, $aggregate, \%rpcargs, $blob);
355 356 357 358 359 360 361
    }
    else {
	# Backwards compat.
	$approved = $response->value();
    }
    if ($checkonly) {
	exit($approved ? 0 : 2);
362 363 364 365 366 367 368 369
    }
    #
    # 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.
    #
370
    if (!$approved) {
371 372 373 374 375 376 377 378 379 380
	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);
    }
381 382 383 384
    elsif (defined($uuid)) {
	#
	# Schedule an announcement for the user.
	#
385
	AddAnnouncement($portal, $brand, $uuid, $this_user, $count, $type, $start);
386 387 388 389 390 391 392
    }
    if (defined($webtask)) {
	$webtask->approved($approved);
	$webtask->idx($idx) if (defined($idx));
	$webtask->uuid($uuid) if (defined($uuid));
    }
    exit($approved ? 0 : 2);
393 394 395 396 397 398 399 400 401 402 403 404
}

#
# Ask for a list of reservations.
#
sub DoList()
{
    #
    # We allow for a user or project argument.
    #
    my $optlist = "u:p:Ai:";
    my $anon    = 0;
405
    my $uuid;
406
    my $project;
407
    my $user;
408 409
    my %rpcargs = ();
    my $context;
410
    my $errmsg;
411 412 413 414 415 416 417 418 419
    
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"A"})) {
	$anon = 1;
    }
    if (defined($options{"i"})) {
420
	$uuid = $options{"i"};
421 422 423 424 425 426 427 428 429
    }
    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")
	}
430
	$geniuser = GeniUser->CreateFromLocal($user);
431 432 433 434 435 436 437 438
    }
    if (defined($options{"p"})) {
	$project = Project->Lookup($options{"p"});

	if (!defined($project)) {
	    fatal("No such project");
	}
	if (!$this_user->IsAdmin() &&
439
	    !$project->AccessCheck($this_user, TB_PROJECT_CREATEEXPT())) {
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
	    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();
    }
470 471
    if (defined($uuid)) {
	$rpcargs{"uuid"} = $uuid;
472
    }
473 474 475 476
    # We can check for disabled aggregate now, nothing below matters.
    if ($aggregate->CheckStatus(\$errmsg, 1)) {
	UserError($errmsg);
    }
477 478 479
    my $response =
	APT_Geni::PortalRPC($authority, $context, "Reservations", (\%rpcargs));
    if (GeniResponse::IsError($response)) {
480
	ExitWithError($response);
481 482
    }
    my $list = $response->value()->{'reservations'};
483 484 485
    my $history = $response->value()->{'history'}
        if (exists($response->value()->{'history'}));
    
486 487 488 489 490
    #
    # 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)) {
491
	my $userhrn  = GeniHRN->new($details->{'user'});
492 493 494 495 496
	my $geniuser = MapUserURN($userhrn);
	if (defined($geniuser)) {
	    $details->{'remote_uid'} = $details->{'uid'};
	    $details->{'uid'}        = $geniuser->uid();
	    $details->{'uid_idx'}    = $geniuser->idx();
497
	}
498
	else {
499
	    $details->{'remote_uid'} = $details->{'uid'};
500
	}
501
	my $projhrn = GeniHRN->new($details->{'project'});
502 503 504 505 506
	my $project = APT_Utility::MapProjectURN($projhrn);
	if (defined($project)) {
	    $details->{'remote_pid'} = $details->{'pid'};
	    $details->{'pid'}        = $project->pid();
	    $details->{'pid_idx'}    = $project->pid_idx();
507
	}
508
	else {
509
	    $details->{'remote_pid'} = $details->{'pid'};
510
	}
511

512 513 514 515 516 517 518
	#
	# Add these for the web interface since we are already messing
	# with the results.
	#
	$details->{'cluster_id'}  = $aggregate->nickname();
	$details->{'cluster_urn'} = $aggregate->urn();

519 520 521 522
	# We need numbers.
	$details->{'nodes'} = int($details->{'nodes'});
	$details->{'using'} = int($details->{'using'});

523 524 525 526 527 528 529 530
	# Backwards compat
	if (!exists($details->{'nodes'})) {
	    $details->{'nodes'} = $details->{'count'};
	}

	#
	# Hmm, undef/null is a pain with XMLRPC.
	#
531 532 533 534 535
	foreach my $key ("approved", "cancel", "deleted") {
	    if (!exists($details->{$key}) || $details->{$key} eq "") {
		$details->{$key} = undef;

	    }
536 537
	}

538 539 540 541 542 543
	#
	# Lets calculate a utilization numbers, this will update the
	# res hash. Flag says not an active reservation.
	#
	APT_Utility::ReservationUtilization($details, 1);

544 545 546 547 548 549 550 551 552 553 554
	#
	# 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
555 556 557 558
		    if (!(exists($ref->{'urn'}) &&
			  exists($ref->{'slice_uuid'}) &&
			  $ref->{'slice_uuid'} ne "" && $ref->{'urn'} ne ""));
			  
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
		# 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();
		    }
		}
	    }
	}
574 575 576 577 578
    }
    #
    # Strip out unwanted results if we asked as an admin for a specific
    # user or project.
    #
579 580 581 582 583
    if ($this_user->IsAdmin() && (defined($project) || defined($user))) {
	my $tmp = {};
	
	foreach my $key (keys(%$list)) {
	    my $details = $list->{$key};
584
	    my $projhrn = $details->{'project'};
585

586
	    if (defined($project)) {
587 588 589 590 591 592 593
		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
		}
594 595
	    }
	    else {
596 597 598 599 600 601 602
		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
		}
603 604 605
	    }
	    $tmp->{$key} = $details;
	}
606
	$response->value()->{'reservations'} = $tmp;
607 608
    }
    if (defined($webtask)) {
609
	$webtask->value($response->value());
610 611 612
	$webtask->Exited(0);
    }
    else {
613
	print Dumper($response->value());
614 615 616 617 618 619 620
    }
    exit(0);
}

#
# Delete a reservation.
#
621 622
# This is not doing proper permission checks or credentials. Need to fix.
#
623 624
sub DoDelete()
{
625 626 627 628 629
    #
    # We allow for admins to pass a reason (deny with cause).
    #
    my $optlist = "N:";
    my $reason;
630
    my $errmsg;
631 632 633 634 635 636 637 638 639
    
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"N"})) {
	$reason = readfile($options{"N"});
	chomp($reason);
    }
640 641
    usage()
	if (@ARGV != 2);
642 643
    my $pid  = shift(@ARGV);
    my $uuid = shift(@ARGV);
644 645
    
    # Check this since Reservation->Lookup() does not validate.
646 647
    fatal("Invalid uuid")
	if (!ValidUUID($uuid));
648 649 650 651 652 653 654 655 656

    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")
    }
657
    my $blob = { "uuid" => $uuid,
658 659 660 661 662
		 "project" => $project->urn()->asString()
    };
    if ($this_user->IsAdmin() && defined($reason) && $reason ne "") {
	$blob->{'reason'} = $reason;
    }
663 664 665 666
    # We can check for disabled aggregate now, nothing below matters.
    if ($aggregate->CheckStatus(\$errmsg, 1)) {
	UserError($errmsg);
    }
667
    my $response =
668
	APT_Geni::PortalRPC($authority, undef, "DeleteReservation", $blob);
669
    if (GeniResponse::IsError($response)) {
670
	ExitWithError($response);
671
    }
672
    UpdateReservationRequest($aggregate, $uuid, $RESERVATION_RECORD_DELETE);
673
    DeleteAnnouncement($uuid);
674 675 676 677 678 679 680 681 682
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    else {
	print Dumper($response);
    }
    exit(0);
}

683 684 685 686 687
#
# Approve a reservation.
#
sub DoApprove()
{
688
    my $optlist = "p:F:";
689
    my $portal;
690
    my $errmsg;
691
    my $message;
692 693 694 695 696 697 698 699

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"p"})) {
	$portal = $options{"p"}
    }
700 701 702 703
    if (defined($options{"F"})) {
	$message = readfile($options{"F"});
	chomp($message);
    }
704
    usage()
705 706
	if (@ARGV != 1 || !defined($portal));
    my $uuid = shift(@ARGV);
707 708
    
    # Check this since Reservation->Lookup() does not validate.
709 710 711 712 713 714 715
    fatal("Invalid uuid")
	if (!ValidUUID($uuid));

    my $brand = Brand->Create($portal);
    if (!defined($brand)) {
	fatal("Bad branding");
    }
716 717 718
    if (!$this_user->IsAdmin()) {
	fatal("No permission to approve reservations")
    }
719 720 721 722
    # We can check for disabled aggregate now, nothing below matters.
    if ($aggregate->CheckStatus(\$errmsg, 1)) {
	UserError($errmsg);
    }
723 724 725 726
    my $blob = {"uuid" => $uuid};
    if (defined($message) && $message ne "") {
	$blob->{'message'} = $message;
    }
727 728 729
    # PortalRPC will use the root context in this case, which is
    # essentially saying the caller is an admin.
    my $response =
730
	APT_Geni::PortalRPC($authority, undef, "ApproveReservation", $blob);
731
    if (GeniResponse::IsError($response)) {
732
	ExitWithError($response);
733
    }
734 735
    UpdateReservationRequest($aggregate, $uuid, $RESERVATION_RECORD_APPROVE);
    
736 737 738
    #
    # Schedule an announcement for the user.
    #
739
    $blob = $response->value();
740 741 742 743 744 745 746
    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'});
	}
    }
747 748 749 750 751 752 753 754 755
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    else {
	print Dumper($response);
    }
    exit(0);
}

756 757 758 759 760 761 762 763 764 765
#
# Schedule (or clear) reservation cancellation
#
sub DoCancel()
{
    my $optlist = "p:ce:N:";
    my $clear   = 0;
    my $when;
    my $portal;
    my $reason;
766
    my $errmsg;
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818

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

819 820 821 822
    # We can check for disabled aggregate now, nothing below matters.
    if ($aggregate->CheckStatus(\$errmsg, 1)) {
	UserError($errmsg);
    }
823 824 825 826 827
    # 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)) {
828
	ExitWithError($response);
829 830 831 832 833 834 835 836
    }
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    else {
	print Dumper($response);
    }
    if ($clear) {
837 838
	UpdateReservationRequest($aggregate, $uuid,
				 $RESERVATION_RECORD_UNCANCEL);
839 840 841 842
	RestoreAnnouncement($uuid);
    }
    else {
	RetireAnnouncement($uuid);
843 844
	UpdateReservationRequest($aggregate, $uuid,
				 $RESERVATION_RECORD_CANCEL);
845 846 847 848
    }
    exit(0);
}

849 850 851 852 853 854 855 856
#
# Get the prediction data.
#
sub DoPrediction()
{
    my $optlist = "p:";
    my $portal;
    my $errmsg;
857 858
    my @aggregates  = ($aggregate);
    my @authorities = ($authority);
859 860
    my @webtasks   = ();
    my @projlist   = ();
861
    my $blob       = {};
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

    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());
	}
    }
880
    elsif (!$this_user->IsAdmin()) {
881 882 883 884
	my @plist;
	if ($this_user->ProjectMembershipList(\@plist)) {
	    fatal("Could not get project membership list");
	}
885 886 887
	# 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.
888
	foreach my $project (@plist) {
889
	    push(@projlist, $project->urn());
890
	}
891
	# Okay not to be in any projects ... 
892 893 894 895 896 897 898
    }

    #
    # Portal argument says to ignore aggregate argument, and contact
    # all aggregates listed for the portal. 
    #
    if (defined($portal)) {
899 900
	@authorities = ();
	@aggregates  = ();
901 902
	
	my @list = APT_Aggregate->LookupForPortal($portal);
903
	foreach my $agg (@list) {
904 905 906 907 908
	    if ($agg->disabled()) {
		print STDERR "The " . $aggregate->name() . " cluster ".
		    "is currently offline, please try again later.";
		next;
	    }
909
	    my $authority = APT_Geni::GetAuthority($agg->urn());
910
	    if (!defined($authority)) {
911
		$errmsg = "Cannot lookup authority for $agg";
912 913
		goto bad;
	    }
914 915
	    push(@aggregates, $agg);
	    push(@authorities, $authority);
916
	}
917 918 919 920
	if (!@aggregates) {
	    UserError("No clusters are online, please try again later.");
	}
    }
921 922 923 924

    my $coderef = sub {
	my ($blob) = @_;
	my $authority = $blob->{"authority"};
925
	my $aggregate = $blob->{"aggregate"};
926
	my $webtask   = $blob->{"webtask"};
927
	my $errmsg;
928
	
929 930 931 932 933 934 935 936 937
	if ($aggregate->CheckStatus(\$errmsg, 1)) {
	    # Need unblessed ref to store into webtask.
	    my $response =
		GeniResponse->Create(GENIRESPONSE_SERVER_UNAVAILABLE,
				     undef, $errmsg);
	    $webtask->response($response);
	    print "$aggregate offline\n";
	    return 1;
	}
938 939 940 941 942 943 944
	# 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});
945 946 947 948
	# Need unblessed ref to store into webtask.
	$response = GeniResponse->Create($response->code(),
					 $response->value(),
					 $response->output);
949 950
	$webtask->response($response);

951 952
	if (GeniResponse::IsError($response)) {
	    # All errors are fatal.
953
	    return -1;
954 955 956
	}
	return 0;
    };
957 958 959 960 961

    #
    # Do not bother with ParRun if only one aggregate.
    #
    if (@aggregates == 1) {
962 963
	my $authority = $authorities[0];
	my $aggregate = $aggregates[0];
964
	my $temptask  = WebTask->CreateAnonymous();
965 966
	my $retval    = &$coderef({"aggregate" => $aggregate,
				   "authority" => $authority,
967
				   "webtask"   => $temptask});
968 969 970 971
	my $response = $temptask->response();
	# No longer a blessed object (see above).
	$response = GeniResponse->Bless($response);

972 973 974 975 976 977 978 979 980
	$temptask->Delete();

	if ($retval == 0) {
	    $blob->{$authority->urn()} = $response->value();
	    goto done;
	}
	ExitWithError($response);
    }
    
981 982 983 984 985 986 987 988
    #
    # 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 = ();

989 990 991 992
    while (@aggregates) {
	my $aggregate = shift(@aggregates);
	my $authority = shift(@authorities);

993
	my $temptask = WebTask->CreateAnonymous();
994
	$temptask->AutoStore(1);
995 996
	# For delete below.
	push(@webtasks, $temptask);
997 998 999
	
	push(@agglist, {"aggregate" => $aggregate,
			"authority" => $authority,
1000 1001
			"webtask"   => $temptask});
    }
1002
    if (ParRun({"maxwaittime" => 30,
1003
		"maxchildren" => scalar(@agglist)},
1004 1005 1006 1007
	       \@return_codes, $coderef, @agglist)) {
	       
	map { $_->Delete(); } @webtasks;
	fatal("Internal error getting reservation prediction info");
1008
    }
1009
    
1010 1011 1012
    #
    # Check the exit codes, create return structure for the web interface.
    #
1013
    foreach my $ref (@agglist) {
1014
	my $code  = shift(@return_codes);
1015 1016 1017
	my $auth  = $ref->{'authority'};
	my $agg   = $ref->{'aggregate'};
	my $wtask = $ref->{'webtask'};
1018
	my $response;
1019

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
	if ($code == SIGTERM) {
	    # Need to think about proper handling of this.
	    $response = GeniResponse->Create(GENIRESPONSE_NETWORK_ERROR,
					     GENIRESPONSE_NETWORK_ERROR_TIMEDOUT,
					     "Timed out talking to server");
	}
	else {
	    $wtask->Refresh();
	    $response = $wtask->response();
	}
1030 1031
	# No longer a blessed object (see above).
	$response = GeniResponse->Bless($response);
1032
	    
1033
	if ($code) {
1034
	    #
1035
	    # If this failed, lets not return a fatal error since
1036 1037 1038
	    # this info is informational and does not prevent the web
	    # server from operating normally.
	    #
1039
	    my $msg = "Could not get reservation data: ".
1040
		$response->error();
1041 1042 1043
	    
	    $blob->{$auth->urn()} = $msg;
	    print STDERR $msg . "\n";
1044
	}
1045
	$blob->{$auth->urn()} = $response->value();
1046
    }
1047
  done:
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    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);
}

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 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
#
# Get the history for a specific user.
#
sub DoHistory()
{
    my $optlist = "";
    my $portal;
    my $errmsg;
    my $blob       = {};
    my ($user, $geniuser);

    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    usage()
	if (@ARGV > 1);

    # Argument is a target user.
    if (@ARGV) {
	$user = User->Lookup($ARGV[0]);
	if (!defined($user)) {
	    fatal("No such user");
	}
	if (!$this_user->IsAdmin() && !$this_user->SameUser($user)) {
	    fatal("No permission to access reservation history for $user")
	}
	$geniuser = GeniUser->CreateFromLocal($user);
    }
    else {
	$geniuser = GeniUser->CreateFromLocal($this_user);	
    }
    
    if ($aggregate->CheckStatus(\$errmsg, 1)) {
	UserError($errmsg);
    }

    # 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,
			    "ReservationHistory",
			    {"user_urn" => $geniuser->urn()->asString()});
    
    if (GeniResponse::IsError($response)) {
	ExitWithError($response);
    }
    
    #
    # Munge the return value like we do above, converting user/proj
    # URNs to local names. One minor difference is that we know the
    # results are only for local users and projects, but lets be
    # consistent. 
    #
    my @reslist = @{ $response->value()->{'history'} };

    foreach my $res (@reslist) {
	my $userhrn  = GeniHRN->new($res->{'user'});
	if ($userhrn->domain() eq $OURDOMAIN &&
	    $userhrn->id eq $geniuser->uid()) {
1128 1129 1130
	    $res->{'remote_uid'} = $res->{'uid'};
	    $res->{'uid'}        = $geniuser->uid();
	    $res->{'uid_idx'}    = $geniuser->idx();
1131 1132 1133
	}
	my $project = APT_Utility::MapProjectURN($res->{'project'});
	if (defined($project)) {
1134 1135 1136
	    $res->{'remote_pid'} = $res->{'pid'};
	    $res->{'pid'}        = $project->pid();
	    $res->{'pid_idx'}    = $project->pid_idx();
1137 1138
	}
	else {
1139
	    $res->{'remote_pid'} = $res->{'pid'};
1140 1141 1142 1143 1144 1145 1146 1147 1148
	}

	#
	# Add these for the web interface since we are already messing
	# with the results.
	#
	$res->{'cluster_id'}  = $aggregate->nickname();
	$res->{'cluster_urn'} = $aggregate->urn();

1149 1150 1151 1152
	# We need numbers.
	$res->{'nodes'} = int($res->{'nodes'});
	$res->{'using'} = int($res->{'using'});

1153 1154 1155 1156 1157 1158 1159
	# Backwards compat
	if (!exists($res->{'nodes'})) {
	    $res->{'nodes'} = $res->{'count'};
	}
	#
	# Hmm, undef/null is a pain with XMLRPC.
	#
1160 1161 1162 1163 1164
	foreach my $key ("approved", "cancel", "deleted") {
	    if (!exists($res->{$key}) || $res->{$key} eq "") {
		$res->{$key} = undef;

	    }
1165
	}
1166 1167 1168 1169 1170
	#
	# Lets calculate a utilization numbers, this will update the
	# res hash. Flag says not an active reservation.
	#
	APT_Utility::ReservationUtilization($res, 0);
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    }
  done:
    if (defined($webtask)) {
	$webtask->value({"reservations" => \@reslist});
	$webtask->Exited(0);
    }
    else {
	print Dumper(@reslist);
    }
    exit(0);
  bad:
    fatal($errmsg);
}

1185 1186 1187 1188 1189 1190
sub fatal($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
1191
	$webtask->Exited(-1);
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    }
    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);
1205
	$webtask->Exited(1);
1206 1207 1208 1209 1210 1211
    }
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(1);
}

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
#
# These are errors which the user might need to see. Some errors are
# exceptions though, and those we want to treat as internal errors.
#
sub ExitWithError($)
{
    my ($response) = @_;
    my $mesg = $response->error();
    my $code = $response->code();

    #
    # In general, these errors are to be expected by the caller.
    #
    if ($code == GENIRESPONSE_REFUSED ||
	$code == GENIRESPONSE_SEARCHFAILED ||
	$code == GENIRESPONSE_SERVER_UNAVAILABLE ||
	$code == GENIRESPONSE_NETWORK_ERROR ||
	$code == GENIRESPONSE_BUSY) {

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

1242 1243 1244 1245 1246 1247 1248 1249 1250
sub readfile($) {
    local $/ = undef;
    my ($filename) = @_;
    open(FILE, $filename) or fatal("Could not open $filename: $!");
    my $contents = <FILE>;
    close(FILE);
    return $contents;
}

1251 1252 1253
#
# Add or Edit a reservation announcement.
#
1254
sub AddAnnouncement($$$$$$$)
1255
{
1256 1257
    my ($portal, $brand, $uuid, $user, $nodes, $type, $start) = @_;
    my $this_uid = $user->uid();
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
    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 {
1291
	$command = "$ANNOUNCE -a -p $portal -U $this_uid -I 4 ".
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
	    "-b 'View Reservation' -u '$url' -t $uuid $dateopt '$text'";
    }
    system($command);
}
sub DeleteAnnouncement($)
{
    my ($uuid) = @_;

    system("$ANNOUNCE -R $uuid");    
}
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
sub RetireAnnouncement($)
{
    my ($uuid) = @_;

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

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

1315 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 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
#
# 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;
1426

1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    #
    # 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;
}