Lease.pm.in 55.4 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
Mike Hibler's avatar
Mike Hibler committed
3
# Copyright (c) 2012-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
# 
# {{{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 Lease;

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

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

33 34 35 36
# Configure variables
use vars qw($TB $BSCONTROL);
$TB        = "@prefix@";
$BSCONTROL = "$TB/sbin/bscontrol";
37 38
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
my $OURDOMAIN     = "@OURDOMAIN@";
39

40 41
use libdb;
use libtestbed;
42 43 44 45
use EmulabConstants;
use User;
use Group;
use Project;
46
use Blockstore;
47 48 49 50 51
use English;
use Date::Parse;
use Data::Dumper;
use overload ('""' => 'Stringify');

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
my @LEASE_TYPES  = ("stdataset", "ltdataset");

#
# Per-type Lease sitevars:
#
# maxsize	Max size (MiB) of a dataset
#		(0 == unlimited)
# maxlease	Max time (days) from creation before lease is marked expired
#		(0 == unlimited)
# maxidle	Max time (days) from last use before lease is marked expired
#		(0 == unlimited)
# graceperiod	Time (days) before an expired dataset will be destroyed
#		(0 == no grace period, unlimited makes no sense here)
# autodestroy	If non-zero, destroy expired datasets after grace period
#		otherwise lock them
# usequotas	If non-zero, enforce per-project dataset quotas
# maxextend	Number of times a user can extend the lease
#		(0 == unlimited)
70
# extendperiod	Length (days) of each user-requested extension
71
#		(0 == do not allow extensions)
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
#
my @LEASE_VARS = (
    "maxsize",
    "maxlease",
    "maxidle",
    "graceperiod",
    "autodestroy",
    "usequotas",
    "maxextend",
    "extendperiod"
);

#
# Plausible defaults:
#
# Short-term datasets. Allow large datasets but with short lease and grace
# periods. They are not quota-controlled and there is not an idle limit.
# Users can extend their leases by small amounts for a little while.
# After the grace period, these are automatically destroyed.
#
# Long-term datasets. Allow any-sized dataset that fits within the quota.
# These are generally expired based on idle time but may have a really long
# lease time as well. They are quota-controlled and users cannot extend
# their leases. After the grace period, these are are just marked as locked
# and unavailable.
#
my %LEASE_VAR_DEFAULTS = (
    "stdataset/maxsize"      => 1048576,# 1 TiB
    "stdataset/maxlease"     => 7,	# 7 days
    "stdataset/maxidle"      => 0,	# none
    "stdataset/graceperiod"  => 1,	# 1 day
    "stdataset/autodestroy"  => 1,	# yes
    "stdataset/usequotas"    => 0,	# no
105 106
    "stdataset/maxextend"    => 2,	# 2 user extensions
    "stdataset/extendperiod" => 1,	# 1 day per extension
107 108 109 110 111 112 113

    "ltdataset/maxsize"      => 0,	# none
    "ltdataset/maxlease"     => 0,	# none, use idle time
    "ltdataset/maxidle"      => 180,	# 6 months
    "ltdataset/graceperiod"  => 180,	# 6 months
    "ltdataset/autodestroy"  => 0,	# no
    "ltdataset/usequotas"    => 1,	# yes
114
    "ltdataset/maxextend"    => 1,	# ignored because...
115
    "ltdataset/extendperiod" => 0,	# ...means no user extension
116
);
117 118 119 120 121 122 123 124

#
# Lease states.
#
# "unapproved".
#    All leases are in this state when they are created. No resources are
#    allocated in this state, but the desired resources may count against
#    a quota. A lease in this state can not be accessed other than to
125 126 127
#    destroy or approve it. The latter moves it to the valid state, a step
#    that triggers resource allocation. If the allocation fails, the lease
#    instead moves to the failed state.
128 129 130 131 132
#
# "valid"
#    A valid lease can be mapped into an experiment. A lease remains valid
#    unless it is explicitly or implicitly freed. Explicit would be if the
#    user deletes the lease, implicit if the lease reaches its expiration
133 134 135 136 137 138 139
#    date or has exceeded the "idle" limit. In the case of expiration or
#    idleness, a lease moves to the "grace" state. This transition may or
#    may not revoke permission from any experiment which has it mapped;
#    resources remain allocated. A valid lease may also transition into
#    the locked state if an admin administratively decides to prohibit
#    access to a resource. Again, it is not clear what happens if the
#    lease is currently mapped.
140
#
141 142 143 144 145 146
# "failed"
#    If resource allocation fails while approving a lease, the lease winds
#    up here. In the failed state, a lease has no resources assigned and
#    it can only transition back to the unapproved state (to try again) or
#    it can be destroyed. 
#
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
# "grace"
#    A lease in the grace state may still make resources available to
#    experiments, but in a "read-only" mode. For example, for storage
#    leases, the storage would be exported without write permissions.
#    When the grace period expires (or immediately if there was no grace
#    period), the lease will transition to either the "expired" or "locked"
#    state. The former is for resources where the policy is to immediately
#    reclaim and reuse the resources, suitable for an automatic reclamation
#    policy. The latter is for policies where a human should make the
#    reclamation decision. From here a lease can also go back into the
#    valid state (if the lease is extended).
#
# "locked"
#    In the locked state, a lease may not be mapped. Resources are still
#    allocated, and the lease may return to the valid state. The lease may
#    also be moved to the "expired" state so that the resources can be
#    reclaimed.
#
# "expired"
#    This is the "roach motel" for leases, they check in but they never
#    check out. Once in this state, a reaper will reclaim the resources
#    and destroy the lease.
#
my @LEASE_STATES = (
    "unapproved",
    "valid",
173
    "failed",
174 175 176 177 178 179
    "grace",
    "locked",
    "expired");

# Valid transitions for each state.
my %LEASE_TRANSITIONS = (
180
    "unapproved" => { "valid" => 1, "failed" => 1, "DEAD" => 1 },
181
    "valid"      => { "grace" => 1, "locked" => 1 },
182
    "failed"     => { "unapproved" => 1, "DEAD" => 1 },
183 184 185 186 187
    "grace"      => { "valid" => 1, "expired" => 1, "locked" => 1 },
    "locked"     => { "valid" => 1, "expired" => 1 },
    "expired"    => { "unapproved" => 1, "DEAD" => 1 },
);
    
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

my $debug	= 0;

# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
	if ($debug);
    return system($command);
}

#
# Accessors
#
204
sub lease_id($)        {return $_[0]->{'DBROW'}->{'lease_id'}; }
205
sub uuid($)            {return $_[0]->{'DBROW'}->{'uuid'}; }
206
sub pid($)             {return $_[0]->{'DBROW'}->{'pid'}; }
207
sub gid($)             {return $_[0]->{'DBROW'}->{'gid'}; }
208 209
sub idx($)             {return $_[0]->{'DBROW'}->{'lease_idx'}; }
sub lease_idx($)       {return $_[0]->idx(); }
210
sub owner($)           {return $_[0]->{'DBROW'}->{'owner_uid'}; }
211
sub owner_urn($)       {return $_[0]->{'DBROW'}->{'owner_urn'}; }
212 213
sub type($)            {return $_[0]->{'DBROW'}->{'type'}; }
sub inception($)       {return str2time($_[0]->{'DBROW'}->{'inception'}); }
214 215
sub lease_end($)       {return str2time($_[0]->{'DBROW'}->{'lease_end'}); }
sub expiration($)      {return $_[0]->lease_end(); }
216
sub last_used($)       {return str2time($_[0]->{'DBROW'}->{'last_used'}); }
217
sub last_checked($)    {return str2time($_[0]->{'DBROW'}->{'last_checked'}); }
218 219
sub origin_urn($)      {return $_[0]->{'DBROW'}->{'origin_urn'}; }
sub origin_uuid($)     {return $_[0]->{'DBROW'}->{'origin_uuid'}; }
220 221
sub state($)           {return $_[0]->{'DBROW'}->{'state'}; }
sub statestamp($)      {return str2time($_[0]->{'DBROW'}->{'statestamp'}); }
222
sub renewals($)	       {return $_[0]->{'DBROW'}->{'renewals'}; }
223
sub locktime($)        {return str2time($_[0]->{'DBROW'}->{'locked'}); }
224
sub locked($)          {return $_[0]->{'DBROW'}->{'locked'}; }
225
sub lockpid($)         {return $_[0]->{'DBROW'}->{'locker_pid'}; }
226 227
sub allow_modify($;$)  {if (defined($_[1])) {$_[0]->{'allow_modify'} = $_[1];}
			return $_[0]->{'allow_modify'}; }
228 229 230 231

#
# Lookup a lease in the DB and return an object representing it.
#
232
sub Lookup($$;$$)
233
{
234
    my ($class, $arg1, $arg2, $arg3) = @_;
235 236
    my ($wclause);

237 238 239 240 241 242 243 244 245
    if (!defined($arg2)) {
	# idx, or pid/lease or pid/gid/lease
	if ($arg1 =~ /^\d+$/) {
	    $wclause = "lease_idx='$arg1'";
	}
	elsif ($arg1 =~ /^([-\w]+)\/([-\w]+)$/) {
	    $wclause = "pid='$1' and gid='$1' and lease_id='$2'";	
	}
	elsif ($arg1 =~ /^([-\w]+)\/([-\w]+)\/([-\w]+)$/) {
246
	    $wclause = "pid='$1' and gid='$2' and lease_id='$3'";	
247 248
	}
	else {
249 250
	    return undef;
	}
251 252 253 254 255
    }
    elsif (!defined($arg3)) {
	# arg2 is the lease id.
	return undef
	    if ($arg2 !~ /^[-\w]+$/);
256

257 258 259 260 261 262 263 264 265 266
	# arg1 is pid or pid/gid
	if ($arg1 =~ /^[-\w]+$/) {
	    $wclause = "pid='$arg1' and gid='$arg1' and lease_id='$arg2'";	
	}
	elsif ($arg1 =~ /^([-\w]+)\/([-\w]+)$/) {
	    $wclause = "pid='$1' and gid='$2' and lease_id='$arg2'";	
	}
	else {
	    return undef;
	}
267
    }
268 269 270 271 272 273
    else {
	# arg3 is the lease id.
	return undef
	    if ($arg3 !~ /^[-\w]+$/);
	# arg1 is pid and arg2 is gid
	return undef
274
	    if ($arg1 !~ /^[-\w]+$/ || $arg2 !~ /^[-\w]+$/);
275

276 277 278
	$wclause = "pid='$arg1' and gid='$arg2' and lease_id='$arg3'";	
    }
    
279 280 281 282
    my $self              = {};
    $self->{"LOCKED"}     = 0;
    $self->{"LOCKER_PID"} = 0;
    $self->{"ATTRS"}      = undef;  # load lazily
283 284 285

    # Load lease from DB, if it exists. Otherwise, return undef.
    my $query_result =
286
	DBQueryWarn("select * from project_leases where $wclause");
287 288 289 290

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

291 292
    $self->{'DBROW'} = $query_result->fetchrow_hashref();;
    bless($self, $class);
293 294 295 296 297 298 299

    return $self;
}

#
# Force a reload of the data.
#
300 301
sub LookupSync($$;$$) {
    my ($class, $arg1, $arg2, $arg3) = @_;
302

303
    return Lookup($class, $arg1, $arg2, $arg3);
304 305 306 307 308 309 310 311
}

#
# explicit object destructor to ensure we get rid of circular refs.
#
sub DESTROY($) {
    my ($self) = @_;

312 313
    $self->{'LOCKED'} = undef;
    $self->{'LOCKER_PID'} = undef;
314 315 316 317 318 319 320 321 322 323
    $self->{'ATTRS'} = undef;
    $self->{'DBROW'} = undef;
}

#
# Create a new lease.
#
sub Create($$;$) {
    my ($class, $argref, $attrs) = @_;

324
    my ($lease_id, $pid, $gid, $uid, $type, $lease_end, $state, $group);
325 326 327 328

    return undef
	if (!ref($argref));

329 330
    $lease_id  = $argref->{'lease_id'};
    $pid       = $argref->{'pid'};
331
    $gid       = $argref->{'gid'};
332 333 334 335
    $uid       = $argref->{'uid'};
    $type      = $argref->{'type'};
    $lease_end = $argref->{'lease_end'};
    $state     = $argref->{'state'};
336
    
337
    if (!($lease_id && $pid && $type &&
338
	  defined($lease_end) && $state)) {
339 340 341 342 343 344
	print STDERR "Lease->Create: Missing required parameters in argref\n";
	return undef;
    }

    # Sanity checks for incoming arguments
    if (!TBcheck_dbslot($lease_id, "project_leases", "lease_id")) {
345
	print STDERR "Lease->Create: Bad data for lease id: ".
346
	    TBFieldErrorString() ."\n";
347 348 349
	return undef;
    }

350 351 352 353 354 355 356 357 358 359 360 361 362
    if (ref($pid) eq "Project") {
	$group = $pid->GetProjectGroup();
	$pid   = $gid = $group->pid();
    }
    elsif (ref($pid) eq "Group") {
	$group = $pid;
	$gid   = $group->gid();
	$pid   = $group->pid();
    }
    else {
	if (!defined($gid)) {
	    $gid = $pid;
	}
Leigh Stoller's avatar
Leigh Stoller committed
363
	$group = Group->Lookup("$pid/$gid");
364 365
	if (!defined($group)) {
	    print STDERR "Lease->Create: Bad/Unknown project: $pid/$gid\n";
366 367 368 369 370 371 372
	    return undef;
	}
    }

    if (ref($uid) ne "User") {
	my $nuid = User->Lookup($uid);
	if (!defined($nuid)) {
373
	    print STDERR "Lease->Create: Bad/unknown owner: $uid\n";
374 375 376 377 378 379 380 381
	    return undef;
	}
	$uid = $nuid
    }

    # User must belong to incoming project.  The code calling into Create()
    # should have already checked to be sure that the caller has permission
    # to create the lease in the first place.
382 383 384
    if (!$group->LookupUser($uid)) {
	print STDERR
	    "Lease->Create: Owner $uid is not a member of project $pid/$gid\n";
385 386 387 388 389 390 391 392 393 394
	return undef;
    }
    
    # If lease types ever grow to be many and complex, then this info will
    # have to come from a DB table instead of a static list in this module.
    if (!grep {/^$type$/} @LEASE_TYPES) {
	print STDERR "Lease->Create: Unknown lease type: $type\n";
	return undef;
    }

395 396
    if ($lease_end !~ /^\d+$/) {
	print "Lease->Create: Invalid lease end time: $lease_end\n";
397 398
	return undef;
    }
399
    if ($lease_end && $lease_end < time()) {
Kirk Webb's avatar
Kirk Webb committed
400
	print STDERR "Lease->Create: Lease end cannot be in the past\n";
401 402 403 404 405 406 407 408
	return undef;
    }

    if (!grep {/^$state$/} @LEASE_STATES) {
	print STDERR "Lease->Create: Unknown lease state: $state\n";
	return undef;
    }

409
    #
410
    # Get a unique lease index and slam this stuff into the DB.
411 412 413 414
    # Note that lease_end == 0 means unlimited, for which we use the
    # DB default value of 2037-01-19 03:14:07, one year before the
    # (Unix) universe ends.
    #
415 416 417 418
    my $lease_idx = TBGetUniqueIndex('next_leaseidx');
    DBQueryWarn("insert into project_leases set ".
		"lease_idx=$lease_idx,".
		"lease_id='$lease_id',".
419
		"pid='$pid',gid='$gid', ".
420 421
		"owner_uid='". $uid->uid() ."',".
		"type='$type',".
422
		($lease_end ? "lease_end=FROM_UNIXTIME($lease_end)," : "").
423
		"state='$state',".
424
		"uuid=uuid(), ".
425
		"statestamp=NOW(),".
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
		"inception=NOW()")
	or return undef;

    # Now add attributes, if passed in.
    if ($attrs) {
	while (my ($key,$valp) = each %{$attrs}) {
	    my ($val, $type);
	    if (ref($valp) eq "HASH") {
		$val  = DBQuoteSpecial($valp->{'value'});
		$type = $valp->{'type'} || "string";
	    } else {
		$val  = DBQuoteSpecial($valp);
		$type = "string";
	    }
	    DBQueryWarn("insert into lease_attributes set ".
			"lease_idx=$lease_idx,".
			"attrkey='$key',".
443
			"attrval=$val,".
444 445 446 447
			"attrtype='$type'")
		or return undef;
	}
    }
448
    return Lookup($class, $group->pid(), $group->gid(), $lease_id);
449 450 451 452 453 454 455 456
}

#
# Delete an existing lease.
#
sub Delete($) {
    my ($self) = @_;

457
    return LEASE_ERROR_FAILED()
458
	if (!ref($self));
459

460
    my $idx  = $self->idx();
461 462
    my $uuid = $self->uuid();

Leigh Stoller's avatar
Leigh Stoller committed
463
    DBQueryWarn("delete from web_tasks where object_uuid='$uuid'")
464
	or return LEASE_ERROR_FAILED();
465 466

    DBQueryWarn("delete from project_leases where lease_idx=$idx")
467
	or return LEASE_ERROR_FAILED();
468
    
469
    DBQueryWarn("delete from lease_attributes where lease_idx=$idx")
470
	or return LEASE_ERROR_FAILED();
471 472

    DBQueryWarn("delete from lease_permissions where lease_idx=$idx")
473
	or return LEASE_ERROR_FAILED();
474 475 476 477

    return 0
}

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
sub urn($)
{
    my ($self) = @_;

    return undef
	if (! $PGENISUPPORT);    

    require GeniHRN;
    my $pid    = $self->pid();
    my $gid    = $self->gid();
    my $name   = $self->lease_id();
    my $domain = $OURDOMAIN;
    $domain .= ":${pid}";
    $domain .= ":${gid}" if ($pid ne $gid);
	
    return GeniHRN::Generate($domain, $self->type(), $name);
}    

496 497 498 499 500 501 502 503 504 505 506 507
#
# Is the underlying blockstore resource mapped in RW currently?
# XXX: blockstore-specific lease function.  Should be in a subclass.
#
sub InUseReadWrite() {
    my ($self) = @_;

    my $rw = 0;

    return LEASE_ERROR_FAILED()
	if (!ref($self));

508
    my $resvref = $self->GetReservations();
509 510
    if ($resvref) {
	foreach my $ref (@$resvref) {
511
	    if (!$ref->IsReadOnly() && !$ref->IsRWClone()) {
512 513 514 515
		$rw = 1;
		last;
	    }
	}
516 517 518 519 520
    }

    return $rw;
}

521 522
sub InUse($) {
    my ($self) = @_;
523 524 525 526

    return LEASE_ERROR_FAILED()
	if (!ref($self));

527
    my $lref = $self->GetReservations();
528 529 530 531 532 533 534
    if (!$lref) {
	return 0;
    }

    return ((@$lref > 0) ? 1 : 0);
}

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
sub IsExclusiveUse($) {
    my ($self) = @_;

    # Every lease is exclusive use unless sitevar is set non-zero
    if (!TBSiteVarExists("storage/simultaneous_ro_datasets") ||
	TBGetSiteVar("storage/simultaneous_ro_datasets") == 0) {
	return 1;
    }

    # Otherwise, no lease is exclusive use unless attribute is set non-zero
    my $rv = $self->GetAttribute("exclusive_use");
    return $rv ? 1 : 0;
}

sub SetExclusiveUse($) {
    my ($self) = @_;

    return $self->SetAttribute("exclusive_use", 1, "integer");
}

sub ClearExclusiveUse($) {
    my ($self) = @_;

    return $self->SetAttribute("exclusive_use", 0, "integer");
}

561
#
562 563 564
# Returns a list of blockstore reservations that are currently using the
# resources associated with this lease. XXX: this is a blockstore-specific
# function.
565
#
566
sub GetReservations($) {
567 568 569 570
    my ($self) = @_;

    return undef
	if (!ref($self));
571

572
    my @resvlist = ();
573

574 575 576 577
    #
    # Before doing a big honkin query, see if the lease has resources
    # allocated to it.
    #
578 579
    if ($self->type() =~ /dataset$/ &&
	!($self->state() eq "unapproved" || $self->state() eq "failed")) {
580 581 582
	my $lidx = $self->lease_idx();

	my $query_result =
583
	    DBQueryWarn("select r.vnode_id from blockstores as b,".
584
			"   reserved_blockstores as r,project_leases as l ".
585
			"where b.bsidx=r.bsidx ".
586 587
			"   and b.lease_idx=l.lease_idx ".
			"   and l.lease_idx='$lidx'");
588 589 590 591 592 593 594
	return undef 
	    if (!$query_result);

	while (my ($vnode_id,) = $query_result->fetchrow_array()) {
	    next if (!$vnode_id);
	    push(@resvlist, 
		 Blockstore::Reservation->LookupByNodeid($vnode_id));
595
	}
596 597
    }

598
    return \@resvlist;
599 600 601 602 603 604 605
}

#
# Allocate resources to a lease and transition to the indicated state.
# Note that this could take a long time. It is up to the caller to lock
# the lease if atomicity is a concern.
#
606 607
sub AllocResources($;$$) {
    my ($self,$state,$interruptable) = @_;
608 609 610 611 612 613 614 615 616 617 618

    $state = "valid"
	if (!defined($state));

    return LEASE_ERROR_FAILED()
	if (!ref($self));

    #
    # Lease must be in the unapproved state to allocate resources.
    # Any other state implies that resources have been allocated already.
    #
619
    if ($self->state() ne "unapproved") {
620 621 622 623 624 625
	print STDERR "$self: AllocResources: must be in state 'unapproved'.\n";
	return LEASE_ERROR_FAILED();
    }
    if (!$self->ValidTransition($state)) {
	print STDERR "$self: AllocResources: cannot transition to state '$state' from unapproved.\n";
	return LEASE_ERROR_FAILED();
626 627 628 629 630 631 632 633 634 635 636 637
    }

    #
    # Force allocation of storage for dataset leases.
    # XXX this should be in Lease::Blockstore object!
    #
    if ($self->type() =~ /dataset$/) {
	#
	# Must be an associated size attribute.
	#
	my $size = $self->GetAttribute("size");
	if ($size == 0 || $size !~ /^\d+$/) {
638 639
	    print STDERR "$self: AllocResources: no valid 'size' attribute\n";
	    return LEASE_ERROR_FAILED();
640 641
	}

642 643 644 645 646 647 648 649 650 651 652 653
	#
	# There may also be an associated fstype attribute.
	# Note: we let caller or bscontrol do checking on the vaildity
	# of the type.
	#
	my $fstype = $self->GetAttribute("fstype");
	if (defined($fstype) && $fstype ne "") {
	    $fstype = "-f $fstype";
	} else {
	    $fstype = "";
	}

654 655 656 657 658 659 660 661 662 663 664 665 666
	#
	# XXX hack, hack
	# XXX this doesn't belong here
	#
	if ($fstype) {
	    print STDERR "NOTE: FS creation could take 5 minutes or longer, ";
	    if ($interruptable) {
		print STDERR "please be patient!\n";
	    } else {
		print STDERR "disabling SIGINT.\n";
	    }
	}

667 668 669 670 671 672
	#
	# Call the blockstore control program to handle all things
	# blockstore related (e.g., the actual allocation of storage
	# on the storage servers).
	#
	my $idx = $self->lease_idx();
673 674 675 676 677 678 679 680 681
	my $cmd = "$BSCONTROL -l $idx -s $size $fstype create lease-$idx";
	my $rv;
	if (!$interruptable) {
	    local $SIG{INT} = "IGNORE";
	    $rv = system($cmd);
	} else {
	    $rv = system($cmd);
	}
	if ($rv) {
682
	    print STDERR "$self: AllocResources: could not allocate storage.\n";
683 684 685 686
	    # XXX why is this here? Should already be unapproved.
	    # XXX perhaps because of the potential long duration of bscontrol
	    #     and non-atomicity allowing for a change of state? Seems
	    #     like that should be the caller's concern.
687
	    $self->UpdateState("unapproved");
688 689

	    return LEASE_ERROR_ALLOCFAILED();
690
	}
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

	#
	# XXX create an initial snapshot too. If this fails, we just warn;
	# a snapshot can always be created with bscontrol later.
	#
	if (!$self->IsExclusiveUse()) {
	    my $tstamp = time();
	    $rv = system("$BSCONTROL snapshot lease-$idx $tstamp");
	    if ($rv) {
		print STDERR "$self: AllocResources: ".
		    "WARNING: could not create initial snapshot.\n";
	    } else {
		$self->SetAttribute("last_snapshot", $tstamp, "integer");
	    }
	}
706 707 708
    }

    # It all worked!
709 710
    $self->UpdateState($state);

711
    return 0;
712
}
713

714 715 716 717 718 719 720
sub DeallocResources($) {
    my ($self) = @_;

    return LEASE_ERROR_FAILED()
	if (!ref($self));

    #
721
    # If lease is unapproved or failed, assume there is nothing to do.
722
    #
723
    if ($self->state() eq "unapproved" || $self->state eq "failed") {
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
	return 0;
    }

    #
    # For a dataset lease, we must free up the server storage.
    # XXX this should be in Lease::Blockstore object!
    #
    if ($self->type() =~ /dataset$/) {
	my $idx = $self->lease_idx();
	my $sarg = "";

	#
	# For efficiency, lookup the server in the blockstores table.
	# Saves gathering info from every storage server.
	#
	my $bstore = Blockstore->LookupByLease($idx);
	if ($bstore) {
	    $sarg = "-S " . $bstore->node_id();
	}

	#
	# Call the blockstore control program to handle all things blockstore
	# related (e.g., the actual deallocation of storage on the servers).
	#
	if (system("$BSCONTROL $sarg destroy lease-$idx")) {
	    print STDERR
		"$self: DeallocResources: could not deallocate storage.\n";
	    return LEASE_ERROR_FAILED();
	}
    }

    $self->UpdateState("unapproved");
    $self->SetLastUsedTime(0);
    return 0;
758 759
}

760 761 762 763 764 765 766
sub CreateResourceSnapshot($$) {
    my ($self,$exclusive) = @_;

    return LEASE_ERROR_FAILED()
	if (!ref($self));

    #
767
    # If lease is unapproved or failed, assume there is nothing to do.
768
    #
769
    if ($self->state() eq "unapproved" || $self->state eq "failed") {
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
	return 0;
    }

    my $tstamp = time();

    #
    # For a dataset lease, we call over to the server to take a snapshot
    # XXX this should be in Lease::Blockstore object!
    #
    if ($self->type() =~ /dataset$/) {
	my $idx = $self->lease_idx();
	my $sarg = "";

	#
	# For efficiency, lookup the server in the blockstores table.
	# Saves gathering info from every storage server.
	#
	my $bstore = Blockstore->LookupByLease($idx);
	if ($bstore) {
	    $sarg = "-S " . $bstore->node_id();
	}

	#
	# If we want an "exclusive" snapshot, we remove all others.
	# We don't return any errors, this is just best effort.
	#
	if (system("$BSCONTROL $sarg desnapshot lease-$idx")) {
	    print STDERR "$self: CreateResourceSnapshot: ".
		"WARNING! Could not remove all old storage snapshots\n";
	}

	#
	# Call the blockstore control program to handle all things blockstore
	# related (e.g., the actual deallocation of storage on the servers).
	#
	if (system("$BSCONTROL $sarg snapshot lease-$idx $tstamp")) {
	    print STDERR "$self: CreateResourceSnapshot: ".
		"Could not snapshot storage.\n";
	    return LEASE_ERROR_FAILED();
	}
    }

    $self->SetAttribute("last_snapshot", $tstamp, "integer");
    return 0;
}

sub DestroyResourceSnapshot($$) {
    my ($self,$tstamp) = @_;

    return LEASE_ERROR_FAILED()
	if (!ref($self));

    #
823
    # If lease is unapproved or failed, assume there is nothing to do.
824
    #
825
    if ($self->state() eq "unapproved" || $self->state eq "failed") {
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
	return 0;
    }

    #
    # For a dataset lease, we call over to the server to take a snapshot
    # XXX this should be in Lease::Blockstore object!
    #
    if ($self->type() =~ /dataset$/) {
	my $idx = $self->lease_idx();
	my $sarg = "";

	#
	# For efficiency, lookup the server in the blockstores table.
	# Saves gathering info from every storage server.
	#
	my $bstore = Blockstore->LookupByLease($idx);
	if ($bstore) {
	    $sarg = "-S " . $bstore->node_id();
	}

	# If tstamp is not set, then clear all snapshots
	$tstamp = ""
	    if (!defined($tstamp));

	#
	# Call the blockstore control program to handle all things blockstore
	# related (e.g., the actual deallocation of storage on the servers).
	#
	# Note that we only fail if bscontrol fails to remove a specific
	# snapshot. Otherwise it may have failed due to snapshots that
	# were still in use.
	#
	if (system("$BSCONTROL $sarg desnapshot lease-$idx $tstamp") &&
	    $tstamp ne "") {
	    print STDERR
		"$self: DestroySnapshot: could not remove storage snapshot(s).\n";
	    return LEASE_ERROR_FAILED();
	}
    }

    $self->DeleteAttribute("last_snapshot");
    return 0;
}

sub LastResourceSnapshot($) {
    my ($self) = @_;

    # XXX we don't call over to the server to get a list--too expensive
    my $tstamp = $self->GetAttribute("last_snapshot");

    return (defined($tstamp) ? int($tstamp) : 0);
}

sub HasResourceSnapshot($) {
    my ($self) = @_;

    return ($self->LastResourceSnapshot() != 0);
}

885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
#
# Extend (renew) a lease by the indicated amount.
# Also increments the renewal count and transitions the lease back into
# the valid state. Returns 0 on success, non-zero otherwise.
#
# N.B. The caller is responsible for locking the lease during this operation.
#
sub Extend($$)
{
    my ($self,$addtime) = @_;

    #
    # Lease must be in some state other than unapproved/valid but that
    # can transition to valid.
    #
    my $cstate = $self->state();
901
    if ($cstate eq "unapproved" || $cstate eq "failed" || $cstate eq "valid" ||
902 903 904 905 906 907 908 909
	!$self->ValidTransition("valid")) {
	print STDERR
	    "$self: Extend: cannot transition from '$cstate' -> 'valid'\n";
	return LEASE_ERROR_FAILED();
    }

    #
    # If the expiration time has been reached, extend it by the
910
    # indicated time (from the current time).
911 912
    #
    if ($self->IsExpired()) {
913
	if ($self->SetEndTime(time() + $addtime)) {
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
	    print STDERR
		"$self: Extend: could not extend lease\n";
	    return LEASE_ERROR_FAILED();
	}
    }
    #
    # Otherwise we assume that the lease went idle and we bump
    # the last_used time so it is no longer idle.
    #
    else {
	if ($self->BumpLastUsed()) {
	    print STDERR
		"$self: Extend: could not extend lease\n";
	    return LEASE_ERROR_FAILED();
	}
    }

    #
    # Increment the renewal count and put lease back into the valid state.
    #
    my $idx = $self->idx();
    DBQueryWarn("update project_leases set renewals=renewals+1 ".
		"where lease_idx=$idx")
	or return LEASE_ERROR_FAILED();
    if ($self->UpdateState("valid")) {
	print STDERR
	    "$self: Extend: could not extend lease\n";
	return LEASE_ERROR_FAILED();
    }

    return 0;
}

947 948 949 950
#
# Return a hashref of sitevars for the indicated lease type.
# Why not let the caller make individual GetSiteVar calls? Well, efficiency
# mostly. There are a lot of em, and they are generally needed all together.
951 952 953
#
# XXX by having them all fetched from here, I can also avoid putting these
# into the database until we decide for sure on the right set; i.e., by using
954 955 956 957 958 959 960 961 962 963
# LEASE_VAR_DEFAULTS.
#
sub SiteVars($$) {
    my ($class, $ltype) = @_;
    my %vars = ();

    if (!grep {/^$ltype$/} @LEASE_TYPES) {
	return undef;
    }

964 965 966 967 968 969
    # XXX tmp til sitevariables are settled upon
    foreach my $var (@LEASE_VARS) {
	if (exists($LEASE_VAR_DEFAULTS{"$ltype/$var"})) {
	    $vars{$var} = $LEASE_VAR_DEFAULTS{"$ltype/$var"};
	}
    }
970

971
    my $hdr = "storage/$ltype";
972 973 974 975 976 977
    my $query = DBQueryWarn("select name,value,defaultvalue ".
			    "from sitevariables where name like '$hdr/%%'");
    return undef
	if (!$query);

    while (my ($var,$val,$defval) = $query->fetchrow_array()) {
978
	if ($var =~ /^$hdr\/([-\w]+)$/) {
979 980 981 982
	    $vars{$1} = defined($val) ? $val : $defval;
	}
    }

983 984 985
    # Convert day values to seconds
    foreach my $n ("maxlease", "maxidle", "graceperiod", "extendperiod") {
	if (exists($vars{$n})) {
Mike Hibler's avatar
Mike Hibler committed
986
	    $vars{$n} = int($vars{$n} * (24 * 60 * 60));
987 988 989
	}
    }

990 991 992
    return \%vars;
}

993
#
994
# Check to see if a lease type is a valid one
995
#
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
sub _validLeaseType($) {
    my ($type) = @_;

    # Make sure something was actually passed in.
    if (!defined($type) || !$type) {
	return 0;
    }

    if (grep {/^$type$/} @LEASE_TYPES) {
	return 1;
    }

    # Not valid (not found in @LEASE_TYPES).
    return 0;
}

#
# Return a list of all leases (optionally of a particular type).
#
sub AllLeases($;$)
1016
{
1017
    my ($class, $type)  = @_;
1018
    my @pleases = ();
1019 1020 1021 1022 1023 1024

    my $tclause = "";
    if (defined($type)) {
	if (_validLeaseType($type)) {
	    $tclause = "where type='$type'";
	} else {
1025
	    print STDERR "Lease->AllLeases: Invalid lease type: $type\n";
1026 1027 1028
	    return undef;
	}
    }
1029 1030
    
    my $query_result =
1031
	DBQueryWarn("select lease_idx from project_leases $tclause".
1032
		    " order by lease_idx");
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    
    return ()
	if (!$query_result || !$query_result->numrows);

    while (my ($lease_idx) = $query_result->fetchrow_array()) {
	my $lease = Lookup($class, $lease_idx);

	# Something went wrong?
	return ()
	    if (!defined($lease));
	
	push(@pleases, $lease);
    }
    return @pleases;
}

1049 1050
#
# Return a list of all leases belonging to a particular project.
1051 1052
# Optionally, only those of the given type.
# The list will be ordered by increasing lease_idx.
1053
#
1054
sub AllProjectLeases($$;$)
1055
{
1056
    my ($class, $pid, $type)  = @_;
1057
    my @pleases = ();
1058 1059 1060
    
    return undef
	if !defined($pid);
1061 1062 1063 1064

    if (ref($pid) eq "Project") {
	$pid = $pid->pid();
    }
1065
    
1066 1067
    my $tclause = "";
    if (defined($type)) {
1068 1069 1070
	if (_validLeaseType($type)) {
	    $tclause = "and type='$type'";
	} else {
1071
	    print STDERR "Lease->AllProjectLeases: Invalid lease type: $type\n";
1072 1073 1074 1075
	    return undef;
	}
    }

1076
    my $query_result =
1077
	DBQueryWarn("select lease_idx from project_leases where ".
1078
		    "pid='$pid' $tclause order by lease_idx");
1079 1080 1081 1082
    
    return ()
	if (!$query_result || !$query_result->numrows);

1083 1084
    while (my ($lease_idx) = $query_result->fetchrow_array()) {
	my $lease = Lookup($class, $lease_idx);
1085 1086 1087 1088 1089

	# Something went wrong?
	return ()
	    if (!defined($lease));
	
1090
	push(@pleases, $lease);
1091
    }
1092
    return @pleases;
1093 1094
}

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
#
# Return a list of all leases belonging to a particular group.
# Optionally, only those of the given type.
# The list will be ordered by increasing lease_idx.
#
sub AllGroupLeases($$;$)
{
    my ($class, $group, $type)  = @_;
    my @gleases = ();
    
    return undef
	if !defined($group);

    if (ref($group) ne "Group") {
1109 1110
	print STDERR "Lease->AllGroupLeases: Input object must be of type \"Group\"";
	return undef;
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    }
    
    my $pid = $group->pid();
    my $gid = $group->gid();

    my $tclause = "";
    if (defined($type)) {
	if (_validLeaseType($type)) {
	    $tclause = "and type='$type'";
	} else {
1121
	    print STDERR "Lease->AllGroupLeases: Invalid lease type: $type\n";
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
	    return undef;
	}
    }

    my $query_result =
	DBQueryWarn("select lease_idx from project_leases where ".
		    "pid='$pid' and gid='$gid' $tclause order by lease_idx");
    
    return ()
	if (!$query_result || !$query_result->numrows);

    while (my ($lease_idx) = $query_result->fetchrow_array()) {
	my $lease = Lookup($class, $lease_idx);

	# Something went wrong?
	return ()
	    if (!defined($lease));
	
	push(@gleases, $lease);
    }
    return @gleases;
}


1146 1147 1148
#
# Grab all leases belonging to a particular user
#
1149
sub AllUserLeases($$;$)
1150
{
1151
    my ($class, $uid, $type)  = @_;
1152
    my @uleases = ();
1153 1154 1155 1156
    
    return undef
	if !defined($uid);

1157
    # If uid is a User object extract the user name
1158 1159 1160
    if (ref($uid) eq "User") {
	$uid = $uid->uid();
    }
1161 1162 1163 1164 1165 1166

    my $tclause = "";
    if (defined($type)) {
	if (_validLeaseType($type)) {
	    $tclause = "and type='$type'";
	} else {
1167
	    print STDERR "Lease->AllUserLeases: Invalid lease type: $type\n";
1168 1169 1170
	    return undef;
	}
    }
1171 1172
    
    my $query_result =
1173 1174
	DBQueryWarn("select lease_idx from project_leases".
		    " where owner_uid='$uid' $tclause");
1175 1176 1177 1178
    
    return ()
	if (!$query_result || !$query_result->numrows);

1179 1180
    while (my ($lease_idx) = $query_result->fetchrow_array()) {
	my $lease = Lookup($class, $lease_idx);
1181 1182 1183 1184 1185

	# Something went wrong?
	return ()
	    if (!defined($lease));
	
1186
	push(@uleases, $lease);
1187
    }
1188
    return @uleases;
1189 1190
}

1191
#
1192
# Return a list of leases for which a user OR group has access.  
1193 1194 1195 1196 1197 1198 1199
#
# Permissions are determined as follows:
# * The owner of a lease always has full (RW) access
# * Users in a project with group_root or above trust always have full (RW) 
#   access to leases associated with that project.
# * Explicitly granted per-user and per-project permissions are extracted 
#   from the lease_permissions tables.
1200 1201 1202 1203 1204 1205 1206
# * Global permissions (only RO).
#
# Note: Greatest privilege is returned when a principle matches more than
#       one lease permissions condition.
#
# Note: Non-local users will only be allowed access to leases that have
#       global "anonymous read-only" permissions enabled on them.
1207 1208
#
# Arguments:
1209
# * principal - User OR Group object to lookup lease access for.
1210 1211 1212
# * type - Optional lease type selector.  Restrict results to this type 
#          of lease.
#
1213
# Returns: Array of lease objects the given principal (user or group) has 
1214 1215 1216
#          access to.  To each of these lease objects, an "allow_modify"
#          boolean is set, accessible via $leaseobj->allow_modify().
#
1217 1218
sub AllowedLeases($$;$) {
    my ($class, $principal, $type)  = @_;
1219
    my $wclause = "";
1220 1221 1222
    my %lease_indexes = ();
    my @leases = ();

1223
    # Gather up lease permissions for Users and Groups.  The logic for users
1224
    # is much more complicated...
1225 1226 1227
    if (ref($principal) eq "User") {
	my $uid = $principal->uid();
	my $uid_idx = $principal->uid_idx();
1228 1229
	my @ugroups = ();
	my $gid_idx_list = "";
1230
	my %admin_pids = ();
1231 1232 1233
	my $admin_pid_list = "";

	# Get group information for input User.
1234 1235
	if ($principal->GroupMembershipList(\@ugroups) == 0 && 
	    int(@ugroups) > 0) {
1236 1237 1238 1239
	    # Determine set of projects for which the input User has
	    # group_root or above trust.
	    foreach my $group (@ugroups) {
		if ($group->IsProjectGroup() &&
1240
		    TBMinTrust($group->Trust($principal),
1241
			       PROJMEMBERTRUST_GROUPROOT())) {
1242
		    $admin_pids{$group->pid()} = 1;
1243 1244
		}
	    }
1245 1246 1247 1248 1249 1250 1251 1252
	    if (@ugroups) {
		$gid_idx_list = join "','", map {$_->gid_idx()} @ugroups;
		$gid_idx_list = "'" . $gid_idx_list . "'";
	    }
	    if (keys %admin_pids) {
		$admin_pid_list = join "','", keys %admin_pids;
		$admin_pid_list = "'" . $admin_pid_list . "'";
	    }
1253
	} else {
1254 1255
	    print STDERR "Lease->AllowedLeases: Failed to lookup ".
		"group membership for user: $principal\n";
1256 1257 1258
	    return undef;
	}

1259 1260 1261 1262 1263 1264 1265
	# Local user stuff.
	# XXX: This needs revision based on how we should handle non-local
	#      Geni-type users.
	if ($principal->IsLocal()) {
	    # Users have full access to leases they own, and for leases in
	    # projects that they have group_root (or above) trust in.
	    my $uclause = "where owner_uid='$uid'";
1266
	    if ($admin_pid_list) {
1267
		$uclause .= " or pid in ($admin_pid_list)";
1268 1269 1270
	    }
	    my $query_result =
		DBQueryWarn("select lease_idx from project_leases".
1271
			    " $uclause order by lease_idx"); 
1272 1273 1274 1275 1276 1277
	    if ($query_result) {
		while (my ($lease_idx) = $query_result->fetchrow_array()) {
		    $lease_indexes{$lease_idx} = 1; # "modify rights" == 1
		}
	    }

1278 1279
	    # Conjure "where" clause for lease_permissions table query below.
	    #
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
	    # User is local to site - look for several conditions:
	    # * Any global permissions.
	    # * Leases with user permissions matching input user.
	    # * Leases with group permissions matching any group user is in.
	    $wclause = "where (permission_type='global'".
		       " or (permission_type='user' and".
		       "     permission_idx='$uid_idx')";
	    if ($gid_idx_list) {
		$wclause .=
		       " or (permission_type='group' and".
		       "     permission_idx in ($gid_idx_list))";
	    }
	    $wclause .= ")";
	} else {
	    # User is non-local - only look for anonymous RO permissions.
1295
	    my $idxstr = GLOBAL_PERM_ANON_RO_IDX();
1296 1297
	    $wclause = "where (permission_type='global' and".
		       " permission_idx='$idxstr')";
1298 1299
	}
    }
1300
    # The case for Group principals is easy: just construct a "where"
1301
    # clause for the lease_permissions table query below.
1302 1303
    elsif (ref($principal) eq "Group") {
	my $gid_idx = $principal->gid_idx();
1304 1305
	$wclause = "where (permission_type='global'".
	           " or (permission_type='group' and".
1306
		   "     permission_idx='$gid_idx'))";
1307
    }
1308
    # Input principal argument must be either a User or Group object.
1309
    else {
1310 1311
	print STDERR "Lease->AllowedLeases: Unknown access object: ".
	             "$principal\n";
1312 1313 1314
	return undef;
    }

1315
    # Build up type selector clause, if requested.
1316 1317 1318 1319 1320
    my $tclause = "";
    if (defined($type)) {
	if (_validLeaseType($type)) {
	    $tclause = "and pl.type='$type'";
	} else {
1321
	    print STDERR "Lease->AllowedLeases: Invalid lease type: $type\n";
1322 1323 1324 1325
	    return undef;
	}
    }

1326
    # Grab all lease permissions entries that pertain to the user or project
1327
    my $query_result =
1328
	DBQueryWarn("select lease_idx, allow_modify".
1329 1330
		    " from lease_permissions".
		    " $wclause $tclause order by lease_idx");
1331 1332 1333 1334 1335 1336
    
    # Loop through result set and process.  Augment permissions for
    # lease owners and users with group_root in lease's owning project.
    # There will be duplicate lease_idx values in the results if there
    # are multiple entries for the lease in the lease_permissions table.
    # Handle this by storing the result set in a hash table.
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    if ($query_result) {
	while (my ($lease_idx, $modify) = $query_result->fetchrow_array()) {
	    if (!exists($lease_indexes{$lease_idx})) {
		$lease_indexes{$lease_idx} = 0;
	    }
	    # If _any_ permissions found for a lease allow for
	    # modification, then it is allowed (greatest privilege for
	    # the same lease wins out).
	    $modify = ($modify || $lease_indexes{$lease_idx}) ? 1 : 0;
	    $lease_indexes{$lease_idx} = $modify;
1347
	}
1348
    }
1349

1350 1351 1352 1353
    # Fetch all of the leases and send them back to caller.
    while (my ($lease_idx, $modify) = each %lease_indexes) {
	my $lease = Lookup($class, $lease_idx);
	if (!$lease) {
1354
	    print STDERR "Lease->AllowedLeases: unable to lookup lease with index $lease_idx!\n";
1355
	    next;
1356 1357
	}
	$lease->allow_modify($modify);
1358
	push (@leases, $lease);
1359 1360
    }

1361
    return @leases;
1362 1363
}

1364 1365 1366 1367 1368 1369 1370 1371
#
# Update fields in the project_leases table, as requested.
#
sub Update($$)
{
    my ($self, $argref) = @_;

    # Must be a real reference. 
1372
    return LEASE_ERROR_FAILED()
1373 1374 1375 1376 1377 1378 1379 1380 1381
	if (! ref($self));

    my $idx = $self->idx();
    my @sets   = ();

    foreach my $key (keys(%{$argref})) {
	my $val = $argref->{$key};

	# Don't let caller update the lease's index - that would be bad.
1382
	return LEASE_ERROR_FAILED()
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
	    if ($key eq "lease_idx");

	# Treat NULL special.
	push (@sets, "${key}=" . ($val eq "NULL" ?
				  "NULL" : DBQuoteSpecial($val)));
    }

    my $query = "update project_leases set " . join(",", @sets) .
	" where lease_idx='$idx'";

1393
    return LEASE_ERROR_FAILED()
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
	if (! DBQueryWarn($query));

    return Refresh($self);
}

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

1406
    return LEASE_ERROR_FAILED()
1407 1408 1409 1410 1411 1412 1413 1414
	if (! ref($self));

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

    my $query_result =
	DBQueryWarn("select * from project_leases".
		    " where lease_idx='$idx'");

1415
    return LEASE_ERROR_FAILED()
1416 1417 1418
	if (!$query_result);
    return LEASE_ERROR_GONE()
	if (!$query_result->numrows);
1419 1420 1421 1422 1423 1424 1425

    $self->{"DBROW"}    = $query_result->fetchrow_hashref();
    $self->{"ATTRS"}    = undef;

    return 0;
}

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
#
# Flush from our little cache, as for the lease daemon.
#
sub Flush($)
{
}

sub FlushAll($)
{
}

1437 1438 1439 1440 1441 1442
#
# Update to the given state and bump timestamp.
#
sub UpdateState($$) {
    my ($self, $state) = @_;

1443
    return LEASE_ERROR_FAILED()
1444 1445
	if (!ref($self));

1446
    return LEASE_ERROR_FAILED()
1447 1448
	if (!defined($state));

1449
    if (!grep {/^$state$/} @LEASE_STATES) {
1450
	print STDERR "Lease->UpdateState: Invalid state: $state\n";
1451
	return LEASE_ERROR_FAILED();
1452 1453 1454 1455 1456
    }

    my $idx = $self->idx();
    DBQueryWarn("update project_leases set state='$state',statestamp=NOW() ".
		"where lease_idx=$idx")
1457
	or return LEASE_ERROR_FAILED();
1458

1459
    $self->Refresh();
1460 1461 1462 1463 1464 1465 1466 1467 1468
    return 0;
}

#
# Bump last_used column
#
sub BumpLastUsed($) {
    my ($self) = @_;

1469
    return LEASE_ERROR_FAILED()
1470 1471 1472 1473
	if (!ref($self));

    my $idx = $self->idx();
    DBQueryWarn("update project_leases set last_used=NOW() where lease_idx=$idx");
1474
    $self->Refresh();
1475 1476 1477
    return 0;
}

1478 1479 1480 1481 1482 1483
#
# Set last_used to a specific time
#
sub SetLastUsedTime($$) {
    my ($self, $ntime) = @_;

1484
    return LEASE_ERROR_FAILED()
1485 1486 1487 1488
	if (!ref($self));

    if ($ntime > time()) {
	print STDERR "Lease->SetLastUsedTime: Can't set lease last-used time in the future.\n";
1489
	return LEASE_ERROR_FAILED();
1490
    }
Mike Hibler's avatar
Mike Hibler committed
1491 1492 1493 1494 1495
    my $estr;
    if ($ntime == 0 || $ntime < $self->inception()) {
	$estr = "DEFAULT(last_used)";
    } else {
	$estr = "FROM_UNIXTIME($ntime)";
1496 1497 1498
    }

    my $idx = $self->idx();
Mike Hibler's avatar
Mike Hibler committed
1499
    DBQueryWarn("update project_leases set last_used=$estr where lease_idx=$idx")
1500
	or return LEASE_ERROR_FAILED();
1501 1502 1503 1504 1505

    $self->Refresh();
    return 0;
}

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
#
# Bump last_checked column
#
sub BumpLastChecked($) {
    my ($self) = @_;

    return LEASE_ERROR_FAILED()
	if (!ref($self));

    my $idx = $self->idx();
    DBQueryWarn("update project_leases set last_checked=NOW() where lease_idx=$idx");
    $self->Refresh();
    return 0;
}

1521 1522 1523 1524 1525 1526
#
# Add time to an existing lease
#
sub AddTime($$) {
    my ($self, $ntime) = @_;

1527
    return LEASE_ERROR_FAILED()
1528 1529
	if (!ref($self));

Mike Hibler's avatar
Mike Hibler committed
1530
    if ($ntime !~ /^\d+$/ || $ntime < 1) {
1531
	print STDERR "Lease->AddTime: Time to add must be a positive number of seconds.\n";
1532
	return LEASE_ERROR_FAILED()
1533 1534 1535
    }

    my $idx = $self->idx();
1536 1537
    my $newend = $self->lease_end() + $ntime;
    DBQueryWarn("update project_leases set lease_end=FROM_UNIXTIME($newend) where lease_idx=$idx")
1538
	or return LEASE_ERROR_FAILED();
1539

1540
    $self->Refresh();
1541 1542 1543 1544
    return 0;
}

#
1545 1546 1547
# Set a specific lease end time.
# A value of zero means "unlimited" which is represented by a very large
# value in the DB (the default value).
1548 1549 1550 1551
#
sub SetEndTime($$) {
    my ($self, $ntime) = @_;

1552
    return LEASE_ERROR_FAILED()
1553 1554
	if (!ref($self));

1555
    if ($ntime != 0 && $ntime < time()) {
1556
	print STDERR "Lease->SetEndTime: Can't move lease end time into the past.\n";
1557
	return LEASE_ERROR_FAILED();
1558 1559
    }

1560 1561 1562 1563 1564 1565 1566
    my $estr;
    if ($ntime == 0) {
	$estr = "DEFAULT(lease_end)";
    } else {
	$estr = "FROM_UNIXTIME($ntime)";
    }

1567
    my $idx = $self->idx();
1568
    DBQueryWarn("update project_leases set lease_end=$estr where lease_idx=$idx")
1569
	or return LEASE_ERROR_FAILED();
1570

1571
    $self->Refresh();
1572 1573 1574
    return 0;
}

1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
#
# Deterimines if a lease can transtion into the indicated state.
# Returns 1 if so, 0 otherwise.
#
sub ValidTransition($$) {
    my ($self,$nstate) = @_;

    return 0
	if (!ref($self));

    my $state = $self->state();
    return (exists($LEASE_TRANSITIONS{$state}{$nstate}) ? 1 : 0);
}

1589 1590 1591 1592 1593 1594
#
# Check to see if the lease has expired.
#
sub IsExpired($) {
    my ($self) = @_;
    
1595
    if ($self->lease_end() <= time()) {
1596 1597 1598 1599 1600 1601
	return 1;
    }

    return 0;
}

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
#
# Check Lease permissions for a specific user.
#
sub AccessCheck($$$) {
    my ($self, $user, $access_type) = @_;
    my $user_access = 0;

    if (ref($user) ne "User") {
	print STDERR "Lease->AccessCheck: 'user' argument must be a valid User object.\n";
	return 0;
    }

1614 1615
    if ($access_type < LEASE_ACCESS_MIN() || 
	$access_type > LEASE_ACCESS_MAX()) {
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
	print STDERR "Lease->AccessCheck: Invalid access type: $access_type\n";
	return 0;
    }

    # Testbed admins have all privs.
    if ($user->IsAdmin() || $UID == 0 || $UID eq "root") {
	return 1;
    }

    # Some special cases
1626
    if ($user->uid() eq $self->owner()) {