Reservation.pm.in 56.2 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2016-2019 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 Node;
43
use NodeType;
44
use POSIX qw(strftime);
45 46 47 48
use overload ('""' => 'Stringify');

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

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

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

    %cache = ();
}
60 61 62 63

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

    if( defined( $uid ) ) {
76 77 78 79 80 81
	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();
82 83 84 85 86 87 88 89 90 91
    }
    
    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;
92 93
    $self->{'UID'}         = $uid,
    $self->{'UID_IDX'}     = $uid_idx,
94 95
    $self->{'NOTES'}       = undef;
    $self->{'ADMIN_NOTES'} = undef;
96 97
    $self->{'APPROVED'}    = undef;
    $self->{'APPROVER'}    = undef;
98
    $self->{'UUID'}        = undef;
99
    $self->{'CANCEL'}      = undef;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	
    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 );
}

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

    return CreateCommon( $class, $pid, $eid, $uid, 0, $end, $type, $nodes );
}
    
133 134 135 136 137 138 139 140 141 142 143 144 145 146
#
# 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 );
}
    
147
sub Lookup($$;$$$$)
148 149
{
    my ($class, $pid, $start, $end, $type, $nodes) = @_;
150 151 152 153 154 155 156 157
    my $query_result;
    
    if( defined( $start ) ) {
	# Look up by time and project.
	my $project = Project->Lookup( $pid );
	if( !defined( $project ) ) {
	    return undef;
	}
158

159
	my $pid_idx = $project->pid_idx();
160
    
161 162
	$query_result = DBQueryWarn( "SELECT *, UNIX_TIMESTAMP(start) AS s, " .
				     "UNIX_TIMESTAMP(end) AS e, " .
163
				     "UNIX_TIMESTAMP(created) AS c, " .
164 165
				     "UNIX_TIMESTAMP(approved) AS a, " .
				     "UNIX_TIMESTAMP(cancel) AS d " .
166
				     "FROM future_reservations " .
167 168 169 170 171 172 173 174 175
				     "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 {
176 177 178 179 180 181 182 183 184 185 186 187
	# 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;
	}
188 189
	$query_result = DBQueryWarn( "SELECT *, UNIX_TIMESTAMP(start) AS s, " .
				     "UNIX_TIMESTAMP(end) AS e, " .
190
				     "UNIX_TIMESTAMP(created) AS c, " .
191 192
				     "UNIX_TIMESTAMP(approved) AS a, " .
				     "UNIX_TIMESTAMP(cancel) AS d " .
193
				     "FROM future_reservations " .
194
				     "WHERE $clause" );
195

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

233
sub idx($)         { return $_[0]->{"IDX"}; }
234 235 236 237 238
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"}; }
239
sub cancel($)      { return $_[0]->{"CANCEL"}; }
240
sub created($)     { return $_[0]->{"CREATED"}; }
241 242 243 244 245 246
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"}; }
247 248
sub approved($)    { return $_[0]->{"APPROVED"}; }
sub approver($)    { return $_[0]->{"APPROVER"}; }
249
sub uuid($)        { return $_[0]->{"UUID"}; }
250 251 252
sub notified($)    { return $_[0]->{"NOTIFIED"}; }
sub notified_unused($) { return $_[0]->{"NOTIFIED_UNUSED"}; }
sub override_unused($) { return $_[0]->{"OVERRIDE_UNUSED"}; }
253 254
# For compat with history entries.
sub deleted($)     { return $_[0]->{"DELETED"}; }
255 256 257 258 259 260 261 262 263 264 265 266 267
# 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;
}
268 269 270 271

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

    my $idx = $self->idx();
    $idx = "xxx" if (!defined($idx));
    my $uid = $self->uid();
276
    my $pid = $self->pid();
277 278 279 280 281
    $pid = "(free)" if( !defined( $pid ) );
    
    if( defined( $self->eid() ) ) {
	$pid = $pid . "/" . $self->eid();
    }
282 283
    my $nodes = $self->nodes();
    my $type = $self->type();
284 285 286 287 288 289 290
    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}]";
291 292
}

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

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

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

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

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

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

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

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

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

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

328 329 330 331 332 333 334 335 336 337 338 339 340
# 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 );
}

341 342 343 344 345 346 347 348 349 350 351 352 353
# 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;
    }

354 355 356 357 358 359 360 361 362 363 364 365 366 367
    # 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;
368 369 370 371 372 373 374 375 376 377
}

# 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().
378
sub BeginTransaction($$;@)
379
{
380 381 382 383 384 385 386
    my ($self, $old_version, @tables) = @_;
    my $moretables = "";

    if (@tables) {
	@tables = join(", ", map {"$_ write"} @tables);
	$moretables = ", @tables";
    }
387
    DBQueryFatal( "LOCK TABLES future_reservations WRITE, " .
388
		  "reservation_version WRITE $moretables" );
389 390 391 392 393 394 395 396 397 398
    
    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;
    }

399 400 401 402 403 404 405
    # 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" );
    
406 407 408 409
    # We're good.
    return 0;
}

410
sub EndTransaction($)
411 412 413 414 415 416 417 418 419
{
    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.
420
sub Book($;$)
421
{
422
    my ($self,$idx) = @_;
423 424 425 426 427 428 429 430 431 432 433

    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() );
434 435
    my $approved = $self->approved();
    my $approver = $self->approver();
436

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

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

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

462 463 464 465 466 467 468 469 470 471 472 473
    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) = @_;

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

477 478 479 480 481 482 483 484 485 486
    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'");
    }
487 488
    DBQueryWarn( "DELETE FROM future_reservation_attributes WHERE " . 
		 "reservation_idx=$idx" )
489 490
	or return -1;

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

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

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 534
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
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
#
# 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" );
569 570 571
    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
572
		  "SELECT uuid, pid, pid_idx, nodes, type, null, ".
573
		  "cancel, created, start, end, uid, uid_idx, " .
574
		  "notes, admin_notes FROM future_reservations WHERE " .
575
		  "end < '$stamp' and approved is not null" );
Gary Wong's avatar
Gary Wong committed
576 577 578 579 580 581 582 583 584 585
    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;
}

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

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

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

    # 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
601
    
602 603
    my @reservations = ();

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

    $$details = "--- Node usage:\n" if( ref( $details ) );
663
    
664
    while( my($count, $pid, $eid, $uid, $end, $autoswap, $next_reserve,
665 666
	      $slice_expire, $slice_lockdown, $reserved_pid, $pr_end,
	      $expt_lockdown, $swappable) =
667 668
	   $query_result->fetchrow_array() ) {
	my $endtime;
669

670 671 672 673 674 675 676
	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";
	}

677
	if( defined( $slice_expire ) ) {
678 679 680 681
	    # 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;
682
	} else {
683 684
	    # A non-GENI slice.  Use the computed autoswap duration,
	    # if autoswap is enabled.
685 686
	    $endtime = ($expt_lockdown || !$swappable ? undef :
			$autoswap ? $end : undef);
687
	}
688 689 690 691 692 693 694 695 696

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

697
	# If reserved_pid is set, assume the node is assigned to the
698 699 700 701 702 703
	# 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;
704 705
	}

706 707 708 709 710 711
	# 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" ||
712 713
				 ( $eid ne "reloading" &&
				   $eid ne "reloadpending" ) ) ) {
714 715
	    # Handle the case where an experiment is swapped in.  The
	    # nodes aren't free right now, but at some time in the
716
	    # future they could become so.
717 718
	    my $res = CreateExisting( $class, $pid, $eid, $uid, $endtime,
				      $type, $count );
719
	    push( @reservations, $res );
720
	} elsif( !defined( $reserved_pid ) ) {
721 722
	    # Physical nodes with no reservations whatsoever... treat
	    # them as free since the beginning of time.
723
	    my $res = CreateCommon( $class, undef, undef, undef, 0, undef,
724 725
				    $type, $count );
	    push( @reservations, $res );
726 727 728 729 730 731 732 733
	} 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 );	    
734 735
	}
    }
736 737

    $$details = $$details . "\n--- Reservations:\n" if( ref( $details ) );
738 739
    
    $query_result = DBQueryWarn( "SELECT pid, uid, UNIX_TIMESTAMP( start ), " .
740
				 "UNIX_TIMESTAMP( end ), nodes, idx FROM " .
741 742 743 744
				 "future_reservations WHERE type='$type'" .
				 ( $include_pending ? "" :
				   " AND approved IS NOT NULL" ) );

745
    while( my ($pid, $uid, $start, $end, $nodes, $idx) =
746 747
	   $query_result->fetchrow_array() ) {
	my $res = Create( $class, $pid, $uid, $start, $end, $type, $nodes );
748
	$res->{'IDX'} = $idx;
749
	push( @reservations, $res );
750 751 752 753 754
	
	if( ref( $details ) ) {
	    no warnings 'uninitialized';
	    $$details = $$details . "$pid, $uid, $start, $end, $nodes, $idx\n";
	}
755 756
    }

757
    $cache{$cachekey} = \@reservations;
758
    
759
    return $cache{$cachekey};
760 761
}

762
sub IsFeasible($$;$$$$$)
763
{
764 765
    my ($class, $reservations, $error, $conflicttime, $conflictcount,
	$projlist, $forecast) = @_;
766 767

    my @timeline = ();
768
    my $free = 0;
769 770 771
    my %used = ();
    my %reserved = ();
    my $answer = 1;
772
    my $now = time();
773
    
774
    foreach my $reservation ( @$reservations ) {
775
	my $pid = $reservation->pid();
776 777 778 779
	my $start;
	my $end;

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

	    # Ignore reservations for listed projects.
	    next if( grep( $_ eq $reservation->pid(), @$projlist ) );
805 806 807 808 809 810 811

	    # Ignore past reservations.
	    next if( $reservation->end() < $now );
	    
	    my $starttime = $reservation->start();
	    $starttime = $now if( $starttime < $now );
	    
812
	    $start = { 'pid' => $reservation->pid(),
813
		       't' => $starttime,
814 815 816 817 818 819 820 821
		       '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.
822
	    $free += $reservation->nodes();
823 824 825 826 827 828
	}

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

829 830 831 832 833 834 835 836
    if( defined( $forecast ) ) {
	my %origin = (
	    t => 0,
	    free => $free
	    );
	push( @$forecast, \%origin );
    }

837 838 839 840 841 842 843 844 845
    my @events = sort {
	if ($a->{'t'} == $b->{'t'}) {
	    return $a->{'reserved'} <=> $b->{'reserved'};
	}
	else {
	    return $a->{'t'} <=> $b->{'t'};
	}
    } @timeline;

846 847
    foreach my $event ( @events ) {
	my $pid = $event->{'pid'};
848 849 850

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

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

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

858 859
	my $newsum = $used{ $pid } > $reserved{ $pid } ? $used{ $pid } :
	    $reserved{ $pid };
860 861 862

	$free += $oldsum - $newsum;

863 864 865 866 867 868 869 870 871 872 873 874
	if( defined( $forecast ) ) {
	    my %used_ = %used;
	    my %reserved_ = %reserved;
	    my %stamp = (
		t => $event->{'t'},
		used => \%used_,
		reserved => \%reserved_,
		free => $free
		);
	    push( @$forecast, \%stamp );
	}
	
875 876 877 878 879 880 881 882
	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).";
	    }
883 884 885
	    if( ref( $conflicttime ) ) {
		$$conflicttime = $event->{'t'};
	    }
886 887 888
	    if( ref( $conflictcount ) ) {
		$$conflictcount = -$free;
	    }
889 890 891 892 893 894

	    if( defined( $forecast ) ) {
		$answer = 0;
	    } else {
		return 0;
	    }
895 896 897
	}
    }
    
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
    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).
917
sub FreeCount($$;$) {
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    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
939
	    # indefinitely.
940 941 942 943 944 945 946
	    $answer -= ( ( $free - $f->{'free'} ) * exp( -$deltat / 0x10000 ) );
	    
	    $free = $f->{'free'};
	}
    }

    return $answer;
947 948
}

949
# Generate a time series of counts of nodes of a given type.
950 951 952
#
# The result is a list of (t, unavailable, held, free) tuples, where:
#
953 954
# * 't' is the timestamp at which the state in the remainder of the
# tuple becomes valid.
955 956 957 958 959 960
#
# * '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.
#
961 962 963 964 965
# * '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!
966 967 968
#
# * 'free' is the number of nodes not allocated and not needed
# for reservations; available for general use subject to other constraints.
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 1015 1016 1017 1018 1019 1020
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;
}

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 1101 1102 1103 1104 1105 1106
#
# 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() ) {
1107 1108
	next if( defined( $typelist ) && !grep( $_ eq $type, @$typelist ) );
	
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
	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;
}

1134 1135
# Return a list of (pid, nodetype, reserved, used) hashes for any currently
# active reservations belonging to a listed project.
1136 1137
sub CurrentReservations($;$$) {
    my ($class, $projlist, $activeonly) = @_;
1138
    my @answer = ();
1139 1140 1141 1142 1143 1144 1145 1146 1147
    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 ";
1148 1149
    }

1150
    my $query_result = DBQueryFatal(
1151
	"SELECT r.pid, r.type, SUM( r.nodes ), " .
1152 1153 1154 1155
	    "(SELECT COUNT(*) FROM reserved AS res, nodes AS n ".
            "WHERE res.pid=r.pid AND res.node_id=n.node_id AND ".
	    "      ((n.reservable=0 and n.type=r.type) or ".
	    "       (n.reservable=1 and n.node_id=r.type))), ".
1156
	    "(SELECT COUNT(*) FROM nodes AS n LEFT OUTER JOIN reserved " .
1157 1158 1159 1160
	    "AS res ON n.node_id=res.node_id ".
	    "WHERE ((n.reservable=0 and n.type=r.type) or ".
	    "       (n.reservable=1 and n.node_id=r.type)) and ".
	    "      res.pid IS NULL)," .
1161 1162 1163
	    "(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')) " .
1164 1165 1166 1167 1168
	"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" );
1169

1170
    while( my($pid, $type, $reserved, $used, $ready, $reloading) =
1171 1172
	   $query_result->fetchrow_array() ) {
	push( @answer, { 'pid' => $pid, 'nodetype' => $type,
1173 1174
			 'reserved' => $reserved, 'used' => $used,
			 'ready' => $ready, 'reloading' => $reloading } );
1175
    }
1176
    
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    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 " .
1197
				     "approved IS NOT NULL AND " .
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
				     "start > NOW() AND " .
				     "start <= ADDDATE( NOW(), 1 ) AND " .
				     "pid IN ('" .
				     join( "','", @$projlist ) . "')" );

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

    return @answer;
}

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
#
# 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;
}

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
#
# 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
1276
    $self->{'IDX'}         = undef;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    $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'};
1294 1295 1296
    $self->{'NOTIFIED'}    = undef;
    $self->{'NOTIFIED_UNUSED'} = undef;
    $self->{'OVERRIDE_UNUSED'} = 0;
1297
    bless($self, $class);
1298 1299
    # Local temp datastore
    $self->{'DATA'}        = {};
1300 1301 1302 1303

    return $self;
}

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
#
# 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 =
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
	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));
1344 1345 1346 1347
    }
    return @answer;
}

1348 1349
sub ExptTypes($) {
    my ($exptidx) = @_;
1350

1351
    my $query_result =
1352 1353 1354 1355
	DBQueryFatal("(SELECT DISTINCT( n.type ) FROM " .
		     " reserved AS r, nodes AS n WHERE " .
		     " r.node_id=n.node_id AND n.reservable=0 AND " .
		     " r.exptidx='$exptidx') ".
1356
		     "union ".
1357 1358 1359 1360
		     "(SELECT n.node_id FROM " .
		     " reserved AS r, nodes AS n WHERE " .
		     " r.node_id=n.node_id AND n.reservable=1 AND " .
		     " r.exptidx='$exptidx')");
1361 1362 1363 1364 1365 1366 1367 1368 1369

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

    return @types;
}

1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
#
# 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 {
1394 1395 1396 1397 1398 1399 1400
	    my $result = $slice->SetExpiration( $new_expire );

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

	    return $result;
1401 1402 1403 1404 1405 1406
	}
    }

    my $exptidx = $slice->exptidx();
    my $expt = Experiment->Lookup( $exptidx );
	
1407
    my @types = ExptTypes( $exptidx );
1408 1409 1410 1411 1412
    
    while( 1 ) {
	my $version = GetVersion( $class );
	foreach my $type ( @types ) {
	    my $reservations = LookupAll( $class, $type );
1413
	    my $conflicttime;
1414 1415 1416 1417 1418 1419 1420 1421
	    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;
		}
	    }
1422 1423
	    if( !$force && !IsFeasible( $class, $reservations, $error,
		\$conflicttime ) && $conflicttime < $new_expire ) {
1424
		return -1;
1425 1426 1427 1428 1429
	    }
	}
	return 0
	    if( $impotent );
	next if( !defined( BeginTransaction( $class, $version ) ) );
1430 1431 1432 1433 1434 1435 1436

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

	if( $result < 0 && ref( $error ) ) {
	    $$error = "Couldn't update slice expiration";
	}
	
1437
	EndTransaction( $class );
1438 1439
	
	return $result;
1440 1441 1442
    }
}

1443
#
1444
# This is similar to above, but for experiment autoswap.
1445 1446 1447 1448 1449
#
sub AutoSwapTimeout($$$;$$$) {

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

1450 1451 1452 1453 1454 1455 1456 1457
    #
    # 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) {
1458
	    return 0;
1459 1460 1461
	}
	else {
	    my $expires;
1462

1463 1464
	    if ($expt->state() eq EXPTSTATE_ACTIVATING()) {
		$expires = $expt->tstamp();
1465
	    }
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
	    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;
1480 1481 1482
	}
    }
    my @types = ExptTypes( $expt->idx() );
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500

    #
    # 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);
1501 1502 1503 1504 1505 1506 1507 1508 1509
    
    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() ) {
1510
		    $res->{'END'} = $expires;
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
		    last;
		}
	    }
	    if( !$force && !IsFeasible( $class, $reservations, $error ) ) {
		return -1;
	    }
	}
	return 0
	    if( $impotent );
	next if( !defined( BeginTransaction( $class, $version, "experiments")));

1522 1523 1524 1525 1526 1527 1528 1529 1530
	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;
1531 1532 1533
	}
	EndTransaction( $class );
	
1534
	return 0;
1535 1536 1537
    }
}

1538
#
1539
# Estimate an upper bound for permissible expiry times on a slice.
1540
#
1541
# Reservation->MaxSliceExtension( $slice, $max, $error, $granularity )
1542 1543
#
# Will put the unix time stamp in $$max and return 0 if the slice can be
1544 1545 1546
# 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).
1547 1548 1549 1550
#
# 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...
1551
sub MaxSliceExtension($$$;$$) {
1552

1553
    my ($class, $slice, $max, $error, $granularity) = @_;
1554 1555 1556

    my $cur_expire = str2time( $slice->expires() );
    my $max_expire = $cur_expire + 60 * 60 * 24 * 180;
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571

    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();
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    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;
1594 1595 1596 1597 1598 1599

	if( defined( $granularity ) && $granularity > 1 ) {
	    $$max--;
	    $$max -= $$max % $granularity;
	}
	
1600 1601 1602 1603
	return 0;
    }
}

1604
#
1605
# Attempt to lock down an existing slice or experiment.
1606
#
1607
# Reservation->Lockdown( $target, $error, $impotent, $force )
1608
#
1609
# $target must be a reference to a GeniSlice object or Experiment object.
1610 1611 1612 1613 1614 1615 1616 1617
# $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($$;$$$) {

1618 1619 1620
    my ($class, $target, $error, $impotent, $force) = @_;
    my $expt;
    
1621
    # It's always a successful no-op if already locked down.
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
    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;
    }
1636

1637 1638 1639
    my $coderef = sub {
	my ($error) = @_;
	my $result;
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 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
	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;

1684 1685 1686 1687 1688
	if ($experiment->SetAutoswap(0) || $experiment->SetExpiration(undef)) {
	    if (ref($error)) {
		$$error = "Couldn't update autoswap";
	    }
	    return -1;
1689
	}
1690
	return 0;
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    };
    return LockdownAux($class, $experiment,
		       $coderef, $error, $impotent, $force);
}

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

1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
    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 );
1723
	next if (!defined(BeginTransaction($class, $version, "experiments")));
1724

1725
	my $result = &$coderef($error);
1726 1727