Reservation.pm.in 55 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2016-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 33
# 
# {{{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/>.
# 
# }}}
#
package Reservation;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

use English;
34
use Date::Parse;
35 36
use emdb;
use libtestbed;
37
use emutil;
38
use EmulabConstants;
39 40
use Project;
use User;
41
use Experiment;
42
use NodeType;
43
use POSIX qw(strftime);
44 45 46 47
use overload ('""' => 'Stringify');

# Configure variables
my $TB		= "@prefix@";
48
my $PGENISUPPORT= @PROTOGENI_SUPPORT@;
49 50

my %cache = ();
51 52 53 54 55 56 57 58
BEGIN { use emutil; emutil::AddCache(\%cache); }

sub FlushAll($)
{
    my ($class) = @_;

    %cache = ();
}
59 60 61 62

sub CreateCommon($$$$$$$$)
{
    my ($class, $pid, $eid, $uid, $start, $end, $type, $nodes) = @_;
63
    my $uid_idx;
64 65 66 67 68
    my $project;
    
    if( defined( $pid ) ) {
	$project = Project->Lookup( $pid );
	if( !defined( $project ) ) {
69
	    print STDERR "Res->CreateCommon: no DB record for project: $pid\n";
70 71 72 73 74
	    return undef;
	}
    }

    if( defined( $uid ) ) {
75 76 77 78 79 80
	my $user = User->Lookup( $uid );
	if (!defined($user)) {
	    print STDERR "Res->CreateCommon: no DB record for user: $uid\n";
	    return undef;
	}
	$uid_idx = $user->uid_idx();
81 82 83 84 85 86 87 88 89 90
    }
    
    my $self               = {};
    $self->{'PID'}         = $pid;
    $self->{'PID_IDX'}     = defined( $pid ) ? $project->pid_idx() : undef;
    $self->{'EID'}         = $eid;
    $self->{'START'}       = $start;
    $self->{'END'}         = $end;
    $self->{'TYPE'}        = $type;
    $self->{'NODES'}       = $nodes;
91 92
    $self->{'UID'}         = $uid,
    $self->{'UID_IDX'}     = $uid_idx,
93 94
    $self->{'NOTES'}       = undef;
    $self->{'ADMIN_NOTES'} = undef;
95 96
    $self->{'APPROVED'}    = undef;
    $self->{'APPROVER'}    = undef;
97
    $self->{'UUID'}        = undef;
98
    $self->{'CANCEL'}      = undef;
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
	
    bless($self, $class);
    
    return $self;
}

#
# Return an object representing a hypothetical future reservation.
#
# This DOES NOT actually check the feasibility of, guarantee,
# or record the reservation.
#
sub Create($$$$$$$)
{
    my ($class, $pid, $uid, $start, $end, $type, $nodes) = @_;

    return CreateCommon( $class, $pid, undef, $uid, $start, $end, $type,
			 $nodes );
}

#
120
# Return an object representing a hypothetical existing experiment.    
121 122 123 124
#
# This DOES NOT actually check the feasibility of, guarantee,
# or record the reservation.
#
125
sub CreateExisting($$$$$$$)
126 127 128 129 130 131
{
    my ($class, $pid, $eid, $uid, $end, $type, $nodes) = @_;

    return CreateCommon( $class, $pid, $eid, $uid, 0, $end, $type, $nodes );
}
    
132 133 134 135 136 137 138 139 140 141 142 143 144 145
#
# Return an object representing a hypothetical immediate experiment.    
#
# This DOES NOT actually check the feasibility of, guarantee,
# or record the reservation.
#
sub CreateImmediate($$$$$$$)
{
    my ($class, $pid, $eid, $uid, $end, $type, $nodes) = @_;

    return CreateCommon( $class, $pid, $eid, $uid, time(), $end, $type,
			 $nodes );
}
    
146
sub Lookup($$;$$$$)
147 148
{
    my ($class, $pid, $start, $end, $type, $nodes) = @_;
149 150 151 152 153 154 155 156
    my $query_result;
    
    if( defined( $start ) ) {
	# Look up by time and project.
	my $project = Project->Lookup( $pid );
	if( !defined( $project ) ) {
	    return undef;
	}
157

158
	my $pid_idx = $project->pid_idx();
159
    
160 161
	$query_result = DBQueryWarn( "SELECT *, UNIX_TIMESTAMP(start) AS s, " .
				     "UNIX_TIMESTAMP(end) AS e, " .
162
				     "UNIX_TIMESTAMP(created) AS c, " .
163 164
				     "UNIX_TIMESTAMP(approved) AS a, " .
				     "UNIX_TIMESTAMP(cancel) AS d " .
165
				     "FROM future_reservations " .
166 167 168 169 170 171 172 173 174
				     "WHERE pid_idx='$pid_idx' AND " .
				     "nodes='$nodes' AND " .
				     "type='$type' AND " .
				     "start=FROM_UNIXTIME($start) AND " .
				     "end=FROM_UNIXTIME($end)" );

	return undef
	    if (!$query_result || !$query_result->numrows);
    } else {
175 176 177 178 179 180 181 182 183 184 185 186
	# Look up by ID or UUID
	my $token = $_[ 1 ];
	my $clause;
	if ($token =~ /^\d*$/) {
	    $clause = "idx='$token'";
	}
	elsif (ValidUUID($token)) {
	    $clause = "uuid='$token'";
	}
	else {
	    return undef;
	}
187 188
	$query_result = DBQueryWarn( "SELECT *, UNIX_TIMESTAMP(start) AS s, " .
				     "UNIX_TIMESTAMP(end) AS e, " .
189
				     "UNIX_TIMESTAMP(created) AS c, " .
190 191
				     "UNIX_TIMESTAMP(approved) AS a, " .
				     "UNIX_TIMESTAMP(cancel) AS d " .
192
				     "FROM future_reservations " .
193
				     "WHERE $clause" );
194

195 196 197 198
	return undef
	    if (!$query_result || !$query_result->numrows);
    }
    
199 200 201
    my $record = $query_result->fetchrow_hashref();
    
    my $self               = {};
202
    $self->{'IDX'}         = $record->{'idx'};
203 204 205
    $self->{'PID'}         = $record->{'pid'};
    $self->{'PID_IDX'}     = $record->{'pid_idx'};
    $self->{'EID'}         = undef;
206 207 208
    $self->{'START'}       = $record->{'s'};
    $self->{'END'}         = $record->{'e'};
    $self->{'CREATED'}     = $record->{'c'};
209
    $self->{'CANCEL'}      = $record->{'d'};
210 211
    $self->{'TYPE'}        = $record->{'type'};
    $self->{'NODES'}       = $record->{'nodes'};
212 213 214 215
    $self->{'UID'}         = $record->{'uid'};
    $self->{'UID_IDX'}     = $record->{'uid_idx'};
    $self->{'NOTES'}       = $record->{'notes'};
    $self->{'ADMIN_NOTES'} = $record->{'admin_notes'};
216
    $self->{'APPROVED'}    = $record->{'a'};
217
    $self->{'APPROVER'}    = $record->{'approver'};
218
    $self->{'UUID'}        = $record->{'uuid'};
219 220 221
    $self->{'NOTIFIED'}    = $record->{'notified'};
    $self->{'NOTIFIED_UNUSED'} = $record->{'notified_unused'};
    $self->{'OVERRIDE_UNUSED'} = $record->{'override_unused'};
222 223
    # For compat with history entries.
    $self->{'DELETED'}     = undef;
224 225
    # Local temp datastore
    $self->{'DATA'}        = {};
226 227 228 229 230 231
	
    bless($self, $class);
    
    return $self;
}

232
sub idx($)         { return $_[0]->{"IDX"}; }
233 234 235 236 237
sub pid($)         { return $_[0]->{"PID"}; }
sub pid_idx($)     { return $_[0]->{"PID_IDX"}; }
sub eid($)         { return $_[0]->{"EID"}; }
sub start($)       { return $_[0]->{"START"}; }
sub end($)         { return $_[0]->{"END"}; }
238
sub cancel($)      { return $_[0]->{"CANCEL"}; }
239
sub created($)     { return $_[0]->{"CREATED"}; }
240 241 242 243 244 245
sub type($)        { return $_[0]->{"TYPE"}; }
sub nodes($)       { return $_[0]->{"NODES"}; }
sub uid($)         { return $_[0]->{"UID"}; }
sub uid_idx($)     { return $_[0]->{"UID_IDX"}; }
sub notes($)       { return $_[0]->{"NOTES"}; }
sub admin_notes($) { return $_[0]->{"ADMIN_NOTES"}; }
246 247
sub approved($)    { return $_[0]->{"APPROVED"}; }
sub approver($)    { return $_[0]->{"APPROVER"}; }
248
sub uuid($)        { return $_[0]->{"UUID"}; }
249 250 251
sub notified($)    { return $_[0]->{"NOTIFIED"}; }
sub notified_unused($) { return $_[0]->{"NOTIFIED_UNUSED"}; }
sub override_unused($) { return $_[0]->{"OVERRIDE_UNUSED"}; }
252 253
# For compat with history entries.
sub deleted($)     { return $_[0]->{"DELETED"}; }
254 255 256 257 258 259 260 261 262 263 264 265 266
# Get/Set some temporary extra data.
sub data($$;$)
{
    my ($self, $key, $val) = @_;

    if (defined($val)) {
	return $self->{'DATA'}->{$key} = $val;
    }
    if (exists($self->{'DATA'}->{$key})) {
	return $self->{'DATA'}->{$key};
    }
    return undef;
}
267 268 269 270

sub Stringify($)
{
    my ($self) = @_;
271 272 273 274

    my $idx = $self->idx();
    $idx = "xxx" if (!defined($idx));
    my $uid = $self->uid();
275
    my $pid = $self->pid();
276 277 278 279 280
    $pid = "(free)" if( !defined( $pid ) );
    
    if( defined( $self->eid() ) ) {
	$pid = $pid . "/" . $self->eid();
    }
281 282
    my $nodes = $self->nodes();
    my $type = $self->type();
283 284 285 286 287 288 289
    my $start = (defined( $self->start() ) ?
		 POSIX::strftime("%m/%d/20%y %H:%M:%S",
				 localtime($self->start())) : "epoch");
    my $end = (defined( $self->end() ) ?
		 POSIX::strftime("%m/%d/20%y %H:%M:%S",
				 localtime($self->end())) : "forever");
    return "[Reservation:$idx $pid/$uid, ${nodes}x${type}, ${start}-${end}]";
290 291
}

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
sub SetStart($$)
{
    my ($self, $start) = @_;

    $self->{'START'} = $start;
}  

sub SetEnd($$)
{
    my ($self, $end) = @_;

    $self->{'END'} = $end;
}  

sub SetNodes($$)
{
    my ($self, $nodes) = @_;

    $self->{'NODES'} = $nodes;
}  

313 314 315 316 317 318 319 320 321 322 323 324 325 326
sub SetNotes($$)
{
    my ($self, $notes) = @_;

    $self->{'NOTES'} = $notes;
}

sub SetAdminNotes($$)
{
    my ($self, $notes) = @_;

    $self->{'ADMIN_NOTES'} = $notes;
}

327 328 329 330 331 332 333 334 335 336 337 338 339
# Mark the reservation as approved.  This DOES NOT update the database
# state: to do so requires an admission control check!  See BeginTransaction(),
# IsFeasible(), Book(), etc.
sub Approve($;$)
{
    my ($self, $user) = @_;

    $user = User->ThisUser() if( !defined( $user ) );

    $self->{'APPROVED'} = time();
    $self->{'APPROVER'} = $user->uid() if defined( $user );
}

340 341 342 343 344 345 346 347 348 349 350 351 352
# Retrieve the current reservation database version.  This version must
# be retrieved and saved before validity checks on attempted updates,
# and then the same version supplied to BeginTransaction() before making
# any changes.
sub GetVersion($)
{
    my $query_result = DBQueryFatal( "SELECT * FROM reservation_version" );
    my $version;
    
    if( ($version) = $query_result->fetchrow_array() ) {
	return $version;
    }

353 354 355 356 357 358 359 360 361 362 363 364 365 366
    # Nothing in the reservation_version table.  The db update scripts
    # populated it, but I forgot to add the version when doing a db init
    # from scratch.  Rather than fix it there, it's better to cope with
    # the situation right here, because this will work no matter what
    # convoluted history the db has been through.
    DBQueryFatal( "LOCK TABLES reservation_version WRITE" );
    # Check existence again, with locking this time, to avoid race.
    $query_result = DBQueryFatal( "SELECT * FROM reservation_version" );    
    unless( ($version) = $query_result->fetchrow_array() ) {
	DBQueryFatal( "INSERT INTO reservation_version SET version=0" );
    }
    DBQueryFatal( "UNLOCK TABLES" );
    
    return 0;
367 368 369 370 371 372 373 374 375 376
}

# Attempt to commit database changes.  GetVersion() must have been called
# previously, and whatever version was obtained supplied as the parameter
# here.  Any necessary availability checks must have been performed
# after GetVersion() and BeginTransaction().  If BeginTransaction()
# returned undef, then concurrent modifications have been detected,
# possibly invalidating the checks already made, and the entire operation
# must be retried from the beginning.  Otherwise, the caller is free
# to proceed with the updates and then complete with EndTransaction().
377
sub BeginTransaction($$;@)
378
{
379 380 381 382 383 384 385
    my ($self, $old_version, @tables) = @_;
    my $moretables = "";

    if (@tables) {
	@tables = join(", ", map {"$_ write"} @tables);
	$moretables = ", @tables";
    }
386
    DBQueryFatal( "LOCK TABLES future_reservations WRITE, " .
387
		  "reservation_version WRITE $moretables" );
388 389 390 391 392 393 394 395 396 397
    
    my $version = GetVersion( $self );

    if( $old_version != $version ) {
	# Reservations have been altered by a concurrent operation.
	# Can't continue: the caller will have to retry.
	DBQueryFatal( "UNLOCK TABLES" );
	return undef;
    }

398 399 400 401 402 403 404
    # Eagerly update the version.  This isn't always strictly necessary,
    # but it is always safe.  And doing it now instead of at EndTransaction
    # time guards against undetected inconsistencies in the case where a
    # process applies persistent updates while it has the tables locked, but
    # then dies for some reason before it can EndTransaction.
    DBQueryFatal( "UPDATE reservation_version SET version=version+1" );
    
405 406 407 408
    # We're good.
    return 0;
}

409
sub EndTransaction($)
410 411 412 413 414 415 416 417 418
{
    DBQueryFatal( "UNLOCK TABLES" );
}

# Add a reservation record to the database (therefore committing ourselves
# to the guarantee it represents).  Because of the consequences and
# consistency requirements, this is permitted ONLY inside a
# BeginTransaction()/EndTransaction() pair, following either
# admission control satisfaction or admin override.
419
sub Book($;$)
420
{
421
    my ($self,$idx) = @_;
422 423 424 425 426 427 428 429 430 431 432

    my $pid = $self->pid();
    my $pid_idx = $self->pid_idx();
    my $nodes = $self->nodes();
    my $type = $self->type();
    my $start = $self->start();
    my $end = $self->end();
    my $uid = $self->uid();
    my $uid_idx = $self->uid_idx();
    my $notes = DBQuoteSpecial( $self->notes() );
    my $admin_notes = DBQuoteSpecial( $self->admin_notes() );
433 434
    my $approved = $self->approved();
    my $approver = $self->approver();
435

436
    my $base_query = "SET pid='$pid', " .
437 438 439 440 441 442 443
		     "pid_idx='$pid_idx', " .
		     "nodes='$nodes', " .
		     "type='$type', " .
		     "start=FROM_UNIXTIME($start), " .
		     "end=FROM_UNIXTIME($end), " .
		     "uid='$uid', " .
		     "uid_idx='$uid_idx' " .
444
		     ( defined($idx) ? "" : ", uuid=uuid()" ) .
445
		     ( defined( $notes ) ? ", notes=$notes" : "" ) .
446
		     ( defined( $admin_notes ) ?
447 448 449 450
		       ", admin_notes=$admin_notes" : "" ) .
		     ( defined( $approved ) ?
		       ", approved=FROM_UNIXTIME($approved)" : "" ) .
		     ( defined( $approver ) ? ", approver='$approver'" : "" );
451 452 453 454 455 456

    my $query_result =
	DBQueryWarn( defined( $idx ) ? "UPDATE future_reservations " .
		     $base_query . " WHERE idx='$idx'" :
		     "INSERT INTO future_reservations " . $base_query )
        or return -1;
457

458
    $self->{'IDX'} = $query_result->insertid();
459
    $self->{'CREATED'} = time();
460

461 462 463 464 465 466 467 468 469 470 471 472
    delete $cache{$type};
    
    return 0;
}

# Cancel a future reservation.  This could be enclosed within a transaction,
# but since cancellations can never cause concurrent operations to fail,
# the transaction is not mandatory.
sub Cancel($)
{
    my ($self) = @_;

473
    my $idx = $self->idx();
474
    my $type = $self->type();
475

476 477 478 479 480 481 482 483 484 485
    if (defined($self->approved())) {
 	DBQueryFatal("INSERT INTO reservation_history ".
		     "  (uuid, pid, pid_idx, nodes, type, deleted, canceled, " .
		     "   created, start, end, uid, uid_idx, ".
		     "   notes, admin_notes) " .
		     "SELECT uuid, pid, pid_idx, nodes, type, now(), ".
		     "  cancel, created,".
		     "  start, end, uid, uid_idx, notes, admin_notes ".
		     "FROM future_reservations WHERE idx='$idx'");
    }
486 487
    DBQueryWarn( "DELETE FROM future_reservation_attributes WHERE " . 
		 "reservation_idx=$idx" )
488 489
	or return -1;

490 491 492
    DBQueryWarn( "DELETE FROM future_reservations WHERE idx=$idx" )
	or return -1;

493 494 495 496 497
    delete $cache{$type};
    
    return 0;
}

498 499 500 501 502 503 504 505 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
sub SetAttribute($$$)
{
    my ($self, $key, $value) = @_;

    my $idx = $self->idx();
    $key = DBQuoteSpecial( $key );
    $value = DBQuoteSpecial( $value );
    
    DBQueryWarn( "REPLACE INTO future_reservation_attributes SET " .
		 "reservation_idx='$idx', " .
		 "attrkey='$key', " .
		 "attrvalue='$value'" )
	or return -1;

    return 0;
}

sub GetAttribute($$)
{
    my ($self, $key) = @_;

    my $idx = $self->idx();
    $key = DBQuoteSpecial( $key );

    my $query_result = DBQueryWarn( "SELECT attrvalue FROM " .
				    "future_reservation_attributes WHERE " .
				    "reservation_idx='$idx' AND " .
				    "attrkey='$key'" );
    return undef
	if( !$query_result || !$query_result->numrows );

    my ($value) = $query_result->fetchrow_array();

    return $value;
}

Gary Wong's avatar
Gary Wong committed
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
#
# Archive any reservations whose times have passed.  This should be
# called occasionally to maintain performance (avoid clogging up the
# future_reservations table with things that don't matter any more, and
# to keep proper records in the reservation_history table), but isn't
# actually required for correctness.
#
sub Tidy($)
{
    my ($class) = @_;

    my $query_result = DBQueryWarn( "SELECT now()" );
    return undef
	if( !$query_result || !$query_result->numrows );

    my ($stamp) = $query_result->fetchrow_array();
    
    $query_result = DBQueryWarn( "SELECT COUNT(*) FROM " .
				    "future_reservations WHERE " .
				    "end < '$stamp'" );
    return undef
	if( !$query_result || !$query_result->numrows );

    my ($count) = $query_result->fetchrow_array();

    if( !$count ) {
	# no tidying required
	return 0;
    }

    DBQueryFatal( "LOCK TABLES future_reservations WRITE, " .
		  "reservation_history WRITE, " .
		  "future_reservation_attributes AS a WRITE, " .
		  "future_reservations AS r READ" );
568 569 570
    DBQueryFatal( "INSERT INTO reservation_history( uuid, pid, pid_idx, ".
		  "nodes, type, deleted, canceled, " .
		  "created, start, end, uid, uid_idx, notes, admin_notes ) " .
Leigh Stoller's avatar
Leigh Stoller committed
571
		  "SELECT uuid, pid, pid_idx, nodes, type, null, ".
572
		  "cancel, created, start, end, uid, uid_idx, " .
573
		  "notes, admin_notes FROM future_reservations WHERE " .
574
		  "end < '$stamp' and approved is not null" );
Gary Wong's avatar
Gary Wong committed
575 576 577 578 579 580 581 582 583 584
    DBQueryFatal( "DELETE FROM future_reservations WHERE " .
		  "end < '$stamp'" );
    DBQueryFatal( "DELETE a FROM future_reservation_attributes AS a " .
		  "LEFT OUTER JOIN future_reservations AS r ON " .
		  "a.reservation_idx=r.idx WHERE r.idx IS NULL" );
    DBQueryFatal( "UNLOCK TABLES" );

    return 1;
}

585
sub LookupAll($$;$$)
586
{
587
    my ($class, $type, $include_pending, $details) = @_;
588 589 590

    $include_pending = 0 if( !defined( $include_pending ) );
    my $cachekey = $type . ":" . $include_pending;
591
    
592 593
    return $cache{$cachekey} if( exists( $cache{$cachekey} ) &&
				 !ref( $details ) );
594

Leigh Stoller's avatar
Leigh Stoller committed
595
    Tidy( $class );
596 597 598 599

    # Mysql 5.7 group by nonsense. Revisit later, like when hell freezes. 
    DBQueryWarn("SET SESSION sql_mode=(SELECT REPLACE(\@\@sql_mode,".
		"'ONLY_FULL_GROUP_BY',''))");
Gary Wong's avatar
Gary Wong committed
600
    
601 602
    my @reservations = ();

603 604
    my $query = $PGENISUPPORT ? "SELECT COUNT(*), e.pid, e.eid, " .
				"e.expt_swap_uid, " .
605 606
				"UNIX_TIMESTAMP( e.expt_expires ), ".
				"e.autoswap, " .
607
				"nr.pid, UNIX_TIMESTAMP( s.expires ), " .
608 609 610 611
				"s.lockdown as slice_lockdown, ".
				"n.reserved_pid, " .
				"UNIX_TIMESTAMP( pr.end ), ".
				"e.lockdown, e.swappable " .
612
				"FROM nodes AS n " .
613 614 615
				"LEFT OUTER JOIN " .
				"reserved AS r ON n.node_id=r.node_id " .
				"LEFT OUTER JOIN experiments AS e ON " .
616 617
				"r.pid=e.pid AND r.eid=e.eid " .
				"LEFT OUTER JOIN experiment_stats AS stats ON ".
618
				"e.idx=stats.exptidx LEFT " .
619 620
				"OUTER JOIN next_reserve AS nr ON " .
				"n.node_id=nr.node_id LEFT OUTER JOIN " .
621 622 623 624
				"project_reservations AS pr ON " .
				"n.reserved_pid=pr.pid AND " .
				"n.reservation_name=pr.name " .
				"LEFT OUTER JOIN" .
625 626 627
				"`geni-cm`.geni_slices AS s ON " .
				"e.eid_uuid=s.uuid " .
				"WHERE n.type='$type' GROUP BY " .
628 629
				"e.pid, e.eid, n.reserved_pid, nr.pid, " .
				"UNIX_TIMESTAMP( pr.end )" :
630 631
				"SELECT COUNT(*), e.pid, e.eid, " .
				"e.expt_swap_uid, " .
632 633
				"UNIX_TIMESTAMP( e.expt_expires ), " .
				"e.autoswap, " .
634
				"nr.pid, NULL, " .
635
				"NULL, n.reserved_pid, " .
636 637
				"UNIX_TIMESTAMP( pr.end ), " .
				"e.lockdown, e.swappable " .
638
				"FROM nodes AS n " .
639 640 641
				"LEFT OUTER JOIN " .
				"reserved AS r ON n.node_id=r.node_id " .
				"LEFT OUTER JOIN experiments AS e ON " .
642 643 644
				"r.pid=e.pid AND r.eid=e.eid " .
				"LEFT OUTER JOIN experiment_stats AS stats ON ".
				"r.pid=stats.pid AND r.eid=stats.eid LEFT " .
645
				"OUTER JOIN next_reserve AS nr ON " .
646 647 648 649 650 651 652 653
				"n.node_id=nr.node_id " .
				"LEFT OUTER JOIN " .
				"project_reservations AS pr ON " .
				"n.reserved_pid=pr.pid AND " .
				"n.reservation_name=pr.name " .
				"WHERE n.type='$type' " .
				"GROUP BY e.pid, e.eid, n.reserved_pid, " .
				"nr.pid, UNIX_TIMESTAMP( pr.end )";
654
    my $query_result = DBQueryWarn( $query );
655 656

    $$details = "--- Node usage:\n" if( ref( $details ) );
657
    
658
    while( my($count, $pid, $eid, $uid, $end, $autoswap, $next_reserve,
659 660
	      $slice_expire, $slice_lockdown, $reserved_pid, $pr_end,
	      $expt_lockdown, $swappable) =
661 662
	   $query_result->fetchrow_array() ) {
	my $endtime;
663

664 665 666 667 668 669 670
	if( ref( $details ) ) {
	    no warnings 'uninitialized';
	    $$details = $$details . "$count, $pid, $eid, $uid, $end, " .
		"$autoswap, $next_reserve, $slice_expire, $slice_lockdown, " .
		"$reserved_pid, $pr_end, $expt_lockdown, $swappable\n";
	}

671
	if( defined( $slice_expire ) ) {
672 673 674 675
	    # Node(s) allocated to a GENI slice.  Treat as unavailable
	    # if locked down, otherwise assume released at slice expiry
	    # time.
	    $endtime = $slice_lockdown ? undef : $slice_expire;
676
	} else {
677 678
	    # A non-GENI slice.  Use the computed autoswap duration,
	    # if autoswap is enabled.
679 680
	    $endtime = ($expt_lockdown || !$swappable ? undef :
			$autoswap ? $end : undef);
681
	}
682 683 684 685 686 687 688 689 690

	# If next_reserve is set, assume unavailable indefinitely.
	# FIXME can we obtain more precise predictions by doing a
	# CreateExisting() for the current experiment then something
	# else at $endtime?
	if( defined( $next_reserve ) ) {
	    $endtime = undef;
	}

691
	# If reserved_pid is set, assume the node is assigned to the
692 693 694 695 696 697
	# project forever, unless there's an end time in a corresponding
	# project_reservations entry.
	if( defined( $reserved_pid ) &&
	    ( !defined( $pr_end ) || !defined( $endtime ) ||
	      $pr_end > $endtime ) ) {
	    $endtime = $pr_end;
698 699
	}

700 701 702 703 704 705
	# Consider nodes in reloading to be available.  One important
	# reason for doing so is that if a project has a current reservation
	# and swaps one experiment out and a replacement in, then during
	# the transition period, sufficient nodes must be considered available
	# for assignment to that project.
	if( defined( $pid ) && ( $pid ne "emulab-ops" ||
706 707
				 ( $eid ne "reloading" &&
				   $eid ne "reloadpending" ) ) ) {
708 709
	    # Handle the case where an experiment is swapped in.  The
	    # nodes aren't free right now, but at some time in the
710
	    # future they could become so.
711 712
	    my $res = CreateExisting( $class, $pid, $eid, $uid, $endtime,
				      $type, $count );
713
	    push( @reservations, $res );
714
	} elsif( !defined( $reserved_pid ) ) {
715 716
	    # Physical nodes with no reservations whatsoever... treat
	    # them as free since the beginning of time.
717
	    my $res = CreateCommon( $class, undef, undef, undef, 0, undef,
718 719
				    $type, $count );
	    push( @reservations, $res );
720 721 722 723 724 725 726 727
	} elsif( defined( $endtime ) ) {
	    # The nodes have a reserved_pid, but there's a known	    
	    # end time (the current experiment end, or the
	    # project_reservations end, whichever is later)... mark
	    # them as available after that.
	    my $res = CreateCommon( $class, $pid, $eid, $uid, 0, $endtime,
				    $type, $count );
	    push( @reservations, $res );	    
728 729
	}
    }
730 731

    $$details = $$details . "\n--- Reservations:\n" if( ref( $details ) );
732 733
    
    $query_result = DBQueryWarn( "SELECT pid, uid, UNIX_TIMESTAMP( start ), " .
734
				 "UNIX_TIMESTAMP( end ), nodes, idx FROM " .
735 736 737 738
				 "future_reservations WHERE type='$type'" .
				 ( $include_pending ? "" :
				   " AND approved IS NOT NULL" ) );

739
    while( my ($pid, $uid, $start, $end, $nodes, $idx) =
740 741
	   $query_result->fetchrow_array() ) {
	my $res = Create( $class, $pid, $uid, $start, $end, $type, $nodes );
742
	$res->{'IDX'} = $idx;
743
	push( @reservations, $res );
744 745 746 747 748
	
	if( ref( $details ) ) {
	    no warnings 'uninitialized';
	    $$details = $$details . "$pid, $uid, $start, $end, $nodes, $idx\n";
	}
749 750
    }

751
    $cache{$cachekey} = \@reservations;
752
    
753
    return $cache{$cachekey};
754 755
}

756
sub IsFeasible($$;$$$$$)
757
{
758 759
    my ($class, $reservations, $error, $conflicttime, $conflictcount,
	$projlist, $forecast) = @_;
760 761

    my @timeline = ();
762
    my $free = 0;
763 764 765
    my %used = ();
    my %reserved = ();
    my $answer = 1;
766
    my $now = time();
767
    
768
    foreach my $reservation ( @$reservations ) {
769
	my $pid = $reservation->pid();
770 771 772 773
	my $start;
	my $end;

	if( defined( $reservation->eid() ) ) {
774 775 776 777 778 779
	    if( $reservation->start() ) {
		# An unmapped experiment.  Not yet using physical nodes.
		$start = { 'pid' => $reservation->pid(),
			   't' => $reservation->start(),
			   'used' => $reservation->nodes(),
			   'reserved' => 0 };
780 781 782 783 784 785 786
	    } else {
		# A mapped experiment.  Using physical nodes now.
		if( defined( $used{ $pid } ) ) {
		    $used{ $pid } += $reservation->nodes();
		} else {
		    $used{ $pid } = $reservation->nodes();
		}
787
	    }
788
	    
789
	    # Will later release real nodes.
790 791 792 793 794 795
	    $end = { 'pid' => $reservation->pid(),
		     't' => $reservation->end(),
		     'used' => -$reservation->nodes(),
		     'reserved' => 0 };
	} elsif( defined( $reservation->pid() ) ) {
	    # A reservation.  Uses then releases reserved nodes.
796 797 798

	    # Ignore reservations for listed projects.
	    next if( grep( $_ eq $reservation->pid(), @$projlist ) );
799 800 801 802 803 804 805

	    # Ignore past reservations.
	    next if( $reservation->end() < $now );
	    
	    my $starttime = $reservation->start();
	    $starttime = $now if( $starttime < $now );
	    
806
	    $start = { 'pid' => $reservation->pid(),
807
		       't' => $starttime,
808 809 810 811 812 813 814 815
		       'used' => 0,
		       'reserved' => $reservation->nodes() };
	    $end = { 'pid' => $reservation->pid(),
		     't' => $reservation->end(),
		     'used' => 0,
		     'reserved' => -$reservation->nodes() };
	} else {
	    # Available resources.  Provides nodes for all time.
816
	    $free += $reservation->nodes();
817 818 819 820 821 822
	}

	push( @timeline, $start ) if( defined( $start->{'t'} ) );
	push( @timeline, $end ) if( defined( $end->{'t'} ) );
    }

823 824 825 826 827 828 829 830
    if( defined( $forecast ) ) {
	my %origin = (
	    t => 0,
	    free => $free
	    );
	push( @$forecast, \%origin );
    }

831 832 833 834 835 836 837 838 839
    my @events = sort {
	if ($a->{'t'} == $b->{'t'}) {
	    return $a->{'reserved'} <=> $b->{'reserved'};
	}
	else {
	    return $a->{'t'} <=> $b->{'t'};
	}
    } @timeline;

840 841
    foreach my $event ( @events ) {
	my $pid = $event->{'pid'};
842 843 844

	$used{ $pid } = 0 if( !exists( $used{ $pid } ) );
	$reserved{ $pid } = 0 if( !exists( $reserved{ $pid } ) );
845

846 847
	my $oldsum = $used{ $pid } > $reserved{ $pid } ? $used{ $pid } :
	    $reserved{ $pid };
848 849 850 851

	$used{ $pid } += $event->{ 'used' };
	$reserved{ $pid } += $event->{ 'reserved' };

852 853
	my $newsum = $used{ $pid } > $reserved{ $pid } ? $used{ $pid } :
	    $reserved{ $pid };
854 855 856

	$free += $oldsum - $newsum;

857 858 859 860 861 862 863 864 865 866 867 868
	if( defined( $forecast ) ) {
	    my %used_ = %used;
	    my %reserved_ = %reserved;
	    my %stamp = (
		t => $event->{'t'},
		used => \%used_,
		reserved => \%reserved_,
		free => $free
		);
	    push( @$forecast, \%stamp );
	}
	
869 870 871 872 873 874 875 876
	if( $free < 0 ) {
	    # Insufficient resources.
	    if( ref( $error ) ) {
		my $time = localtime( $event->{'t'} );
		my $needed = -$free;
		$$error = "Insufficient free nodes at $time " .
		    "($needed more needed).";
	    }
877 878 879
	    if( ref( $conflicttime ) ) {
		$$conflicttime = $event->{'t'};
	    }
880 881 882
	    if( ref( $conflictcount ) ) {
		$$conflictcount = -$free;
	    }
883 884 885 886 887 888

	    if( defined( $forecast ) ) {
		$answer = 0;
	    } else {
		return 0;
	    }
889 890 891
	}
    }
    
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    return $answer;
}

#
# Generate a heuristic "count" of free nodes of a given type.  For each
# "free forever" physical node (i.e., a node never required for future
# reservations), the count is incremented by one.  Each node currently
# assigned to an experiment is ignored (doesn't affect the count).  Each
# node currently free but later required for a reservation increments the
# count by some fractional value depending how far into the future the
# reservation is.
#
# Reservation->FreeCount( $type, $projlist )
#
# $type must be a valid node type.
# $projlist is an optional reference to a list of PIDs, and reservations
#     for any projects in the list will be ignored (i.e., the nodes are
#     assumed free -- useful if a user wants to consider nodes reserved
#     to their own projects as available).
911
sub FreeCount($$;$) {
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
    my ($class, $type, $projlist) = @_;

    my $reservations = LookupAll( $class, $type );
    my @forecast = ();
    my $t = time();    
    
    IsFeasible( $class, $reservations, undef, undef, undef, $projlist,
		\@forecast );

    my $free = $forecast[ 0 ]->{'free'};
    my $answer = $free;

    foreach my $f ( @forecast ) {
	if( $f->{'free'} < $free ) {
	    my $deltat = $f->{'t'} - $t;

	    $deltat = 0 if( $deltat < 0 );

	    # Weight the nodes based on how far into the future the
	    # reservation is.  The 0x10000 is chosen so that a node available
	    # for the next 24 hours only is worth about half a node available
933
	    # indefinitely.
934 935 936 937 938 939 940
	    $answer -= ( ( $free - $f->{'free'} ) * exp( -$deltat / 0x10000 ) );
	    
	    $free = $f->{'free'};
	}
    }

    return $answer;
941 942
}

943
# Generate a time series of counts of nodes of a given type.
944 945 946
#
# The result is a list of (t, unavailable, held, free) tuples, where:
#
947 948
# * 't' is the timestamp at which the state in the remainder of the
# tuple becomes valid.
949 950 951 952 953 954
#
# * 'unavailable' is a count of nodes unavailable for allocation, either
# because they're already in use (including both those in use
# by experiments in the projects specified and those used by others),
# or because they're required for reservations to other projects.
#
955 956 957 958 959
# * 'held' is a count of nodes reserved to the project(s) queried, but
# NOT yet allocated to any experiment.  They could potentially be used by the
# user asking, but not to those outside the proper projects.  Since these
# resources are currently idle, the user (or one of their project partners)
# should try to use them ASAP!
960 961 962
#
# * 'free' is the number of nodes not allocated and not needed
# for reservations; available for general use subject to other constraints.
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
sub Forecast($$;$) {
    my ($class, $type, $projlist) = @_;

    my $reservations = LookupAll( $class, $type );
    my @forecast = ();
    my @answer = ();
    my $t = time();
    
    IsFeasible( $class, $reservations, undef, undef, undef, undef, \@forecast );

    foreach my $f ( @forecast ) {
	my $unavailable = 0;
	my $held = 0;
	my $free = $f->{'free'};

	foreach my $pid ( keys( %{$f->{'used'}} ) ) {
	    $unavailable += $f->{'used'}->{$pid};
	}
	
	foreach my $pid ( keys( %{$f->{'reserved'}} ) ) {
	    my $r = $f->{'reserved'}->{$pid};
	    my $u = $f->{'used'}->{$pid};

	    if( $r > $u ) {
		if( grep( $_ eq $pid, @$projlist ) ) {
		    $held += $r - $u;
		} else {
		    $unavailable += $r - $u;
		}
	    }
	}
	
	my %r = (
	    t => $f->{'t'},
	    unavailable => $unavailable,
	    held => $held,
	    free => $free
	    );

	if( $r{'t'} < $t ) {
	    # event in the past; overwrite initial result in list but do
	    # not append
	    $r{'t'} = $t;
	    $answer[ 0 ] = \%r;
	} else {
	    push( @answer, \%r );
	}
    }
    
    return @answer;
}

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
#
# Find any future periods with smaller predicted availability than the
# present.
sub FuturePressure($$;$) {
    my ($class, $typelist, $projlist) = @_;

    my @reservations = ();
    
    foreach my $type ( @$typelist ) {
	my $typeres = LookupAll( $class, $type );

	push( @reservations, @$typeres );
    }

    my @forecast = ();
    my @answer = ();
    my $t = time();
    my $maxused = 0;    
    my $under_pressure = 0;
    my $period;
    
    IsFeasible( $class, \@reservations, undef, undef, undef, undef,
		\@forecast );

    foreach my $f ( @forecast ) {
	my $unavailable = 0;
	my $held = 0;
	my $free = $f->{'free'};

	foreach my $pid ( keys( %{$f->{'used'}} ) ) {
	    $unavailable += $f->{'used'}->{$pid};
	}
	
	foreach my $pid ( keys( %{$f->{'reserved'}} ) ) {
	    my $r = $f->{'reserved'}->{$pid};
	    my $u = $f->{'used'}->{$pid};

	    if( $r > $u ) {
		if( grep( $_ eq $pid, @$projlist ) ) {
		    $held += $r - $u;
		} else {
		    $unavailable += $r - $u;
		}
	    }
	}

	if( $f->{'t'} <= $t ) {
	    $maxused = $unavailable if( $unavailable > $maxused );
	} elsif( $under_pressure ) {
	    if( $unavailable <= $maxused ) {
		$under_pressure = 0;
		push( @answer, [ $period, $f->{'t'} ] );
	    }
	} else {
	    if( $unavailable > $maxused ) {
		$under_pressure = 1;
		$period = $f->{'t'};
	    }
	}
    }

    return @answer;
}

#
# Find the earliest unfulfilled reservation for any of the specified projects.
# (If a project is using at least as many nodes as it has reserved,
# reservation(s) will be considered fulfilled and ignored as a possible
# result.)  Optionally limited to particular node type(s), otherwise
# reservations for any node type are returned.
#
# Returns a timestamp if any unfulfilled reservation exists, otherwise undef.
sub OutstandingReservation($$;$) {
    my ($class, $projlist, $typelist ) = @_;
    my $earliest = undef;
    
    foreach ( @$projlist ) {
	# reject illegal PIDs
	return undef unless /^[-\w]+$/;
    }
    
    my $query_result = DBQueryFatal( "SELECT DISTINCT(type) FROM " .
				     "future_reservations WHERE pid IN ('" .
				     join( "','", @$projlist ) . "')" );

    while( my($type) = $query_result->fetchrow_array() ) {
1101 1102
	next if( defined( $typelist ) && !grep( $_ eq $type, @$typelist ) );
	
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
	my $reservations = LookupAll( $class, $type );

	my @forecast = ();
    
	IsFeasible( $class, $reservations, undef, undef, undef, undef,
		    \@forecast );

	foreach my $f ( @forecast ) {
	    foreach my $pid ( keys ( %{$f->{'reserved'}} ) ) {
		if( grep( $_ eq $pid, @$projlist ) &&
		    ( !exists( $f->{'used'}->{$pid} ) ||
		      $f->{'used'}->{$pid} < $f->{'reserved'}->{$pid} ) ) {
		    # Found an unfulfilled reservation.
		    my $t = $f->{'t'};

		    $earliest = $t if( !defined( $earliest ) ||
				       $t < $earliest );
		}
	    }
	}
    }

    return $earliest;
}

1128 1129
# Return a list of (pid, nodetype, reserved, used) hashes for any currently
# active reservations belonging to a listed project.
1130 1131
sub CurrentReservations($;$$) {
    my ($class, $projlist, $activeonly) = @_;
1132
    my @answer = ();
1133 1134 1135 1136 1137 1138 1139 1140 1141
    my $pclause = "";
    $activeonly = 0 if (!defined($activeonly));

    if (defined($projlist) && @$projlist) {
	foreach ( @$projlist ) {
	    # reject illegal PIDs
	    return undef unless /^[-\w]+$/;
	}
	$pclause = "r.pid IN ('" . join( "','", @$projlist ) .	"') AND ";
1142 1143
    }

1144
    my $query_result = DBQueryFatal(
1145 1146
	"SELECT r.pid, r.type, SUM( r.nodes ), " .
	    "(SELECT COUNT(*) FROM reserved AS res, nodes AS n WHERE " .
1147 1148 1149 1150 1151 1152 1153
	    "res.pid=r.pid AND res.node_id=n.node_id AND n.type=r.type)," .
	    "(SELECT COUNT(*) FROM nodes AS n LEFT OUTER JOIN reserved " .
	    "AS res ON n.node_id=res.node_id WHERE n.type=r.type AND " .
	    "res.pid IS NULL)," .
	    "(SELECT COUNT(*) FROM nodes AS n, reserved AS res " .
	    "WHERE n.node_id=res.node_id AND res.pid='emulab-ops' AND " .
	    "res.eid IN ('reloading', 'reloadpending')) " .
1154 1155 1156 1157 1158
	"FROM future_reservations AS r WHERE $pclause ".
             "r.approved IS NOT NULL ".
	     ($activeonly ? 
	      "AND r.start < NOW() AND r.end > NOW() " : " ") .
        "GROUP BY r.pid, r.type" );
1159

1160
    while( my($pid, $type, $reserved, $used, $ready, $reloading) =
1161 1162
	   $query_result->fetchrow_array() ) {
	push( @answer, { 'pid' => $pid, 'nodetype' => $type,
1163 1164
			 'reserved' => $reserved, 'used' => $used,
			 'ready' => $ready, 'reloading' => $reloading } );
1165
    }
1166
    
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    return @answer;
}

# Return a list of (pid, nodetype, nodecount, starttime, endtime) hashes
# for any reservations belonging to a listed project starting within the
# next 24 hours.
sub UpcomingReservations($$) {
    my ($class, $projlist) = @_;
    my @answer = ();
    
    foreach ( @$projlist ) {
	# reject illegal PIDs
	return undef unless /^[-\w]+$/;
    }

    my $query_result = DBQueryFatal( "SELECT pid, type AS nodetype, " .
				     "nodes AS nodecount, " .
				     "UNIX_TIMESTAMP(start) AS starttime, " .
				     "UNIX_TIMESTAMP(end) AS endtime FROM " .
				     "future_reservations WHERE " .
1187
				     "approved IS NOT NULL AND " .
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
				     "start > NOW() AND " .
				     "start <= ADDDATE( NOW(), 1 ) AND " .
				     "pid IN ('" .
				     join( "','", @$projlist ) . "')" );

    while( my $record = $query_result->fetchrow_hashref() ) {
	push( @answer, $record );
    }

    return @answer;
}

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
#
# Return a list of project reservations. Optional type and activeonly.
# Type can be a single type or a list reference of types.
#
sub ProjectReservations($$$;$$) {
    my ($class, $project, $user, $type, $activeonly) = @_;
    my $typeclause   = "";
    my $activeclause = "";
    my $userclause   = "";
    my $pidclause    = "";
    my @answer = ();

    if (defined($type)) {
	if (ref($type)) {
	    my @types = @{$type};
	    $typeclause = "AND type IN ('" . join( "','", @types ) . "')" ;
	}
	else {
	    $typeclause = "AND type='$type'";
	}
    }
    if (defined($activeonly) && $activeonly) {
	$activeclause = "AND start < NOW() AND end > NOW()";
    }
    if (defined($user)) {
	my $uid = $user->uid();
	$userclause = "AND uid='$uid'";
    }
    if (defined($project)) {
	my $pid = ref($project) ? $project->pid() : $project;
	$pidclause = "AND pid='$pid'";
    }
    my $query_result =
	DBQueryFatal("select idx from future_reservations ".
		     "where approved IS NOT NULL $pidclause ".
		     "  $typeclause $activeclause $userclause ".
		     "order by created desc");

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $res = Reservation->Lookup($idx);
	push(@answer, $res)
	    if (defined($res));
    }
    return @answer;
}

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
#
# Fake up an object for a historical reservation entry.
#
sub LookupHistorical($$) {
    my ($class, $uuid) = @_;

    my $query_result =
	DBQueryWarn("select *,UNIX_TIMESTAMP(start) AS s, " .
		     "       UNIX_TIMESTAMP(end) AS e, ".
		     "       UNIX_TIMESTAMP(created) AS c, " .
		     "       UNIX_TIMESTAMP(canceled) AS d, " .
		     "       UNIX_TIMESTAMP(deleted) AS k " .
		     "  from reservation_history ".
		     "where uuid='$uuid'");

    return undef
	if (!defined($query_result) || !$query_result->numrows);

    my $record = $query_result->fetchrow_hashref();
    my $self               = {};
Leigh Stoller's avatar
Leigh Stoller committed
1266
    $self->{'IDX'}         = undef;
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
    $self->{'PID'}         = $record->{'pid'};
    $self->{'PID_IDX'}     = $record->{'pid_idx'};
    $self->{'EID'}         = undef;
    $self->{'START'}       = $record->{'s'};
    $self->{'END'}         = $record->{'e'};
    $self->{'CREATED'}     = $record->{'c'};
    $self->{'DELETED'}     = $record->{'k'};
    $self->{'CANCEL'}      = $record->{'d'};
    $self->{'TYPE'}        = $record->{'type'};
    $self->{'NODES'}       = $record->{'nodes'};
    $self->{'UID'}         = $record->{'uid'};
    $self->{'UID_IDX'}     = $record->{'uid_idx'};
    $self->{'NOTES'}       = $record->{'notes'};
    $self->{'ADMIN_NOTES'} = $record->{'admin_notes'};
    $self->{'APPROVED'}    = undef;
    $self->{'APPROVER'}    = undef;
    $self->{'UUID'}        = $record->{'uuid'};
1284 1285 1286
    $self->{'NOTIFIED'}    = undef;
    $self->{'NOTIFIED_UNUSED'} = undef;
    $self->{'OVERRIDE_UNUSED'} = 0;
1287
    bless($self, $class);
1288 1289
    # Local temp datastore
    $self->{'DATA'}        = {};
1290 1291 1292 1293

    return $self;
}

1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
#
# Return a list of historical project reservations. Optional type.
# Type can be a single type or a list reference of types.
#
sub HistoricalReservations($$$;$) {
    my ($class, $project, $user, $type) = @_;
    my $pid;
    my @clauses = ();
    my @answer  = ();

    if (defined($type)) {
	if (ref($type)) {
	    my @types = @{$type};
	    push(@clauses,
		 "type IN ('" . join( "','", @types ) . "')");
	}
	else {
	    push(@clauses, "type='$type'");
	}
    }
    if (defined($user)) {
	my $uid = $user->uid();
	push(@clauses, "uid='$uid'");
    }
    if (defined($project)) {
	my $pid = $project->pid();
	push(@clauses, "pid='$pid'");
    }
    my $query_result =
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
	DBQueryWarn("select uuid from reservation_history ".
		    "where " . join(" AND ", @clauses) . " " .
		    "order by start asc");

    return ()
	if (!defined($query_result) || !$query_result->numrows);

    while (my ($uuid) = $query_result->fetchrow_array()) {
	my $record = Reservation->LookupHistorical($uuid);
	push(@answer, $record)
	    if (defined($record));
1334 1335 1336 1337
    }
    return @answer;
}

1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
sub ExptTypes($) {
    my ($exptidx) = @_;
    
    my $query_result = DBQueryFatal( "SELECT DISTINCT( n.type ) FROM " .
				     "reserved AS r, nodes AS n WHERE " .
				     "r.node_id=n.node_id AND " .
				     "r.exptidx='$exptidx'" );

    my @types;
    while( my($type) = $query_result->fetchrow_array() ) {
	push( @types, $type );
    }

    return @types;
}

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
#
# Attempt to adjust the expiration time of an existing slice.
#
# Reservation->ExtendSlice( $slice, $new_expire, $error, $impotent, $force )
#
# $slice must be a reference to a GeniSlice object.
# $new_expire is a Unix time_t for the requested new expiration time
# (can be earlier or later than the current expiration time -- in principle
# an earlier time will always succeed, but a later time might fail
# depending on resource availability).
# $error (if defined) is a reference to a scalar; if defined and extension is
# not possible, a reason will be given here.
# $impotent (if defined and true) will attempt a hypothetical extension and
# return success or failure, but make no actual change to any state.
# $force (if defined and true) will make the change to the slice expiration
# even if it violates admission control constraints.
sub ExtendSlice($$$;$$$) {

    my ($class, $slice, $new_expire, $error, $impotent, $force) = @_;

    if( $new_expire <= str2time( $slice->expires() ) ) {
	if( $impotent ) {
	    return 0;
	} else {
1378 1379 1380 1381 1382 1383 1384
	    my $result = $slice->SetExpiration( $new_expire );

	    if( $result < 0 && ref( $error ) ) {
		$$error = "Couldn't update slice expiration";
	    }

	    return $result;
1385 1386 1387 1388 1389 1390
	}
    }

    my $exptidx = $slice->exptidx();
    my $expt = Experiment->Lookup( $exptidx );
	
1391
    my @types = ExptTypes( $exptidx );
1392 1393 1394 1395 1396
    
    while( 1 ) {
	my $version = GetVersion( $class );
	foreach my $type ( @types ) {
	    my $reservations = LookupAll( $class, $type );
1397
	    my $conflicttime;
1398 1399 1400 1401 1402 1403 1404 1405
	    foreach my $res ( @$reservations ) {
		if( defined( $res->pid() ) && defined( $res->eid() ) &&
		    $res->pid() eq $expt->pid() &&
		    $res->eid() eq $expt->eid() ) {
		    $res->{'END'} = $new_expire;
		    last;
		}
	    }
1406 1407
	    if( !$force && !IsFeasible( $class, $reservations, $error,
		\$conflicttime ) && $conflicttime < $new_expire ) {
1408
		return -1;
1409 1410 1411 1412 1413
	    }
	}
	return 0
	    if( $impotent );
	next if( !defined( BeginTransaction( $class, $version ) ) );
1414 1415 1416 1417 1418 1419 1420

	my $result = $slice->SetExpiration( $new_expire );

	if( $result < 0 && ref( $error ) ) {
	    $$error = "Couldn't update slice expiration";
	}
	
1421
	EndTransaction( $class );
1422 1423
	
	return $result;
1424 1425 1426
    }
}

1427
#
1428
# This is similar to above, but for experiment autoswap.
1429 1430 1431 1432 1433
#
sub AutoSwapTimeout($$$;$$$) {

    my ($class, $expt, $minutes, $error, $impotent, $force) = @_;

1434 1435 1436 1437 1438 1439 1440 1441
    #
    # So if the timeout is smaller then current, it is okay to just
    # change it: If autoswap is currently on, then this is safe. If
    # autoswap is currently off (and expt not locked down), then we
    # are going from no expiration set, so clearly that is safe too.
    #
    if ($minutes <= $expt->autoswap_timeout() || !$expt->autoswap()) {
	if ($impotent) {
1442
	    return 0;
1443 1444 1445
	}
	else {
	    my $expires;
1446

1447 1448
	    if ($expt->state() eq EXPTSTATE_ACTIVATING()) {
		$expires = $expt->tstamp();
1449
	    }
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
	    else {
		$expires = str2time($expt->swapin_last());
	    }
	    $expires += ($minutes * 60);
	    
	    if ($expt->SetExpiration($expires) ||
		$expt->SetAutoswapTimeout($minutes) ||
		$expt->SetAutoswap(1)) {
		if (ref($error)) {
		    $$error = "Could not update experiment autoswap_timeout";
		}
		return -1;
	    }
	    return 0;
1464 1465 1466
	}
    }
    my @types = ExptTypes( $expt->idx() );
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484

    #
    # We need a new expiration time, based on when the experiment actually
    # started. swapin_last does not work since it is set at the end of
    # swapin, which can take an arbitrary amount of time. We know that
    # autoswap() was already on (see above) so we can use the current
    # expiration time to compute a new expiration.
    #
    my $expires = $expt->expt_expires();
    if (!defined($expires)) {
	if (ref($error)) {
	    $$error = "experiment does not have expiration set";
	}
	return -1;
    }
    $expires = str2time($expires);
    # Add difference in autoswap_timeout to expiration;
    $expires += (($minutes - $expt->autoswap_timeout()) * 60);
1485 1486 1487 1488 1489 1490 1491 1492 1493
    
    while( 1 ) {
	my $version = GetVersion( $class );
	foreach my $type ( @types ) {
	    my $reservations = LookupAll( $class, $type );
	    foreach my $res ( @$reservations ) {
		if( defined( $res->pid() ) && defined( $res->eid() ) &&
		    $res->pid() eq $expt->pid() &&
		    $res->eid() eq $expt->eid() ) {
1494
		    $res->{'END'} = $expires;
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
		    last;
		}
	    }
	    if( !$force && !IsFeasible( $class, $reservations, $error ) ) {
		return -1;
	    }
	}
	return 0
	    if( $impotent );
	next if( !defined( BeginTransaction( $class, $version, "experiments")));

1506 1507 1508 1509 1510 1511 1512 1513 1514
	if ($expt->SetExpiration($expires) ||
	    # This must be after above line.
	    $expt->SetAutoswapTimeout($minutes) ||
	    $expt->SetAutoswap(1)) {
	    if (ref($error)) {
		$$error = "Couldn't update experiment autoswap_timeout";
	    }
	    EndTransaction($class);
	    return -1;
1515 1516 1517
	}
	EndTransaction( $class );
	
1518
	return 0;
1519 1520 1521
    }
}

1522
#
1523
# Estimate an upper bound for permissible expiry times on a slice.
1524
#
1525
# Reservation->MaxSliceExtension( $slice, $max, $error, $granularity )
1526 1527
#
# Will put the unix time stamp in $$max and return 0 if the slice can be
1528 1529 1530
# extended, or -1 with $$error set.  If $granularity is set, the returned
# time will be lowered to a multiple of $granularity (e.g.,
# $granularity = 3600 would give a time on an hour boundary).
1531 1532 1533 1534
#
# Of course, this comes with no guarantees... for instance, somebody else
# could make a conflicting reservation/extension before this call returns,
# or before the caller has a chance to do anything useful with the result...
1535
sub MaxSliceExtension($$$;$$) {
1536

1537
    my ($class, $slice, $max, $error, $granularity) = @_;
1538 1539 1540

    my $cur_expire = str2time( $slice->expires() );
    my $max_expire = $cur_expire + 60 * 60 * 24 * 180;
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

    my $expt = $slice->GetExperiment();
    if (!defined($expt)) {
	if( ref( $error ) ) {
	    $$error = "No experiment for slice, cannot compute max.";
	}
	return -1;
    }
    if (! $expt->NodeList(1)) {
	if( ref( $error ) ) {
	    $$error = "No physical nodes, no max to compute.";
	}
	return -1;
    }
    my $exptidx = $expt->idx();
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    my @types = ExptTypes( $exptidx );
    
    foreach my $type ( @types ) {
	my $reservations = LookupAll( $class, $type );
	foreach my $res ( @$reservations ) {
	    if( defined( $res->pid() ) && defined( $res->eid() ) &&
		$res->pid() eq $expt->pid() &&
		$res->eid() eq $expt->eid() ) {
		$res->{'END'} = $max_expire;
		last;
	    }
	}
	IsFeasible( $class, $reservations, undef, \$max_expire );
    }

    if( $max_expire <= $cur_expire ) {
	if( ref( $error ) ) {
	    $$error = "No extension possible.";
	}
	return -1;
    } else {
	$$max = $max_expire;
1578 1579 1580 1581 1582 1583

	if( defined( $granularity ) && $granularity > 1 ) {
	    $$max--;
	    $$max -= $$max % $granularity;
	}
	
1584 1585 1586 1587
	return 0;
    }
}

1588
#
1589
# Attempt to lock down an existing slice or experiment.
1590
#
1591
# Reservation->Lockdown( $target, $error, $impotent, $force )
1592
#
1593
# $target must be a reference to a GeniSlice object or Experiment object.
1594 1595 1596 1597 1598 1599 1600 1601
# $error (if defined) is a reference to a scalar; if defined and lockdown is
# not possible, a reason will be given here.
# $impotent (if defined and true) will attempt a hypothetical lockdown and
# return success or failure, but make no actual change to any state.
# $force (if defined and true) will turn on lockdown even if it violates
# admission control constraints.
sub Lockdown($$;$$$) {

1602 1603 1604
    my ($class, $target, $error, $impotent, $force) = @_;
    my $expt;
    
1605
    # It's always a successful no-op if already locked down.
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
    if (ref($target) eq "GeniSlice") {
	return 0 if( $target->lockdown() );
	$expt = Experiment->Lookup( $target->exptidx() );
	return -1
	    if (!defined($expt));
    }
    elsif (ref($target) eq "Experiment") {
	return 0 if( $target->lockdown() );
	$expt = $target;
    }
    else {
	$$error = "Do not know how to lockdown $target" if (defined($error));
	return -1;
    }
1620

1621 1622 1623
    my $coderef = sub {
	my ($error) = @_;
	my $result;
1624
	
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
	if (ref($target) eq "GeniSlice") {
	    $result = $target->SetLockdown( 0 );
	}
	else {
	    $result = $target->LockDown( 1 );
	}
	if( $result < 0 && ref( $error ) ) {
	    $$error = "Couldn't update slice or experiment lockdown";
	}
	return $result;
    };
    return LockdownAux($class, $expt, $coderef, $error, $impotent, $force);
}

#
# Ditto swappable and autoswap. We can use the same support function below.
#
sub DisableSwapping($$;$$$)
{
    my ($class, $experiment, $error, $impotent, $force) = @_;

    my $coderef = sub {
	my ($error) = @_;
	my $result;

	$result = $experiment->SetSwappable(0);

	if( $result < 0 && ref( $error ) ) {
	    $$error = "Couldn't update swappable";
	}
	return $result;
    };
    return LockdownAux($class, $experiment,
		       $coderef, $error, $impotent, $force);
}
sub DisableAutoSwap($$;$$$)
{
    my ($class, $experiment, $error, $impotent, $force) = @_;

    my $coderef = sub {
	my ($error) = @_;
	my $result;

1668 1669 1670 1671 1672
	if ($experiment->SetAutoswap(0) || $experiment->SetExpiration(undef)) {
	    if (ref($error)) {
		$$error = "Couldn't update autoswap";
	    }
	    return -1;
1673
	}
1674
	return 0;
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
    };
    return LockdownAux($class, $experiment,
		       $coderef, $error, $impotent, $force);
}

#
# Support for above.
#
sub LockdownAux($$$$$$)
{
    my ($class, $expt, $coderef, $error, $impotent, $force) = @_;
    my $exptidx = $expt->idx();
1687
    my @types = ExptTypes( $exptidx );
1688

1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
    while( 1 ) {
	my $version = GetVersion( $class );
	foreach my $type ( @types ) {
	    my $reservations = LookupAll( $class, $type );
	    foreach my $res ( @$reservations ) {
		if( defined( $res->pid() ) && defined( $res->eid() ) &&
		    $res->pid() eq $expt->pid() &&
		    $res->eid() eq $expt->eid() ) {
		    $res->{'END'} = undef; # lockdowns last forever
		    last;
		}
	    }
	    if( !$force && !IsFeasible( $class, $reservations, $error ) ) {
		return -1;
	    }
	}
	return 0
	    if( $impotent );
1707
	next if (!defined(BeginTransaction($class, $version, "experiments")));
1708

1709
	my $result = &$coderef($error);
1710 1711 1712 1713 1714 1715 1716
	
	EndTransaction( $class );
	
	return $result;
    }    
}

1717 1718 1719 1720 1721 1722 1723 1724
#
# Strictly for admission control in the mapper. For geni experiments,
# LookupAll uses the current slice expiration to determine when the
# experiment ends. But for mapper admission control we use experiment
# expires, since on the geni path you can both modify an expriment and
# change its expiration at the same time. We do not want to change the
# slice expiration until we confirm that the mapper allows it. 
#
1725 1726 1727
sub ExpectedEnd($$) {
    
    my ($class, $experiment) = @_;
1728

1729 1730 1731 1732 1733 1734
    #
    # Geni experiments are locked down and not swappable, so we want
    # to use the expt_expires instead.
    #
    if (($experiment->lockdown() || !$experiment->swappable()) &&
	!$experiment->geniflags()) {
1735
	return undef;
1736 1737 1738 1739 1740
    }
    elsif ($experiment->geniflags()) {
	if (!defined($experiment->expt_expires())) {
	    print STDERR "ExpectedEnd: No expiration for $experiment\n";
	    return undef;
1741
	}
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
	return str2time($experiment->expt_expires());
    }
    elsif (defined($experiment->expt_expires())) {
	return str2time($experiment->expt_expires());
    }
    #
    # This should not happen, execpt that we sometimes run the mapper in
    # debugging mode. So if we are here and the experiment is swapped, use
    # the current time.
    #
    print STDERR "ExpectedEnd: No expiration for $experiment\n";
    if ($experiment->state() eq EXPTSTATE_SWAPPED() &&
	$experiment->autoswap()) {
	return time() + ($experiment->autoswap_timeout() * 60);