Lease.pm.in 52.3 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2012-2015 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 37
# Configure variables
use vars qw($TB $BSCONTROL);
$TB        = "@prefix@";
$BSCONTROL = "$TB/sbin/bscontrol";

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

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
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)
68
# extendperiod	Length (days) of each user-requested extension
69
#		(0 == do not allow extensions)
70 71 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
#
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
103 104
    "stdataset/maxextend"    => 2,	# 2 user extensions
    "stdataset/extendperiod" => 1,	# 1 day per extension
105 106 107 108 109 110 111

    "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
112
    "ltdataset/maxextend"    => 1,	# ignored because...
113
    "ltdataset/extendperiod" => 0,	# ...means no user extension
114
);
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

#
# 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
#    destroy or approve it. The latter moves it to the valid state, a
#    step that triggers resource allocation.
#
# "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
130 131 132 133 134 135 136
#    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.
137 138 139 140 141 142 143 144 145 146 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 173 174 175 176
#
# "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",
    "grace",
    "locked",
    "expired");

# Valid transitions for each state.
my %LEASE_TRANSITIONS = (
    "unapproved" => { "valid" => 1, "DEAD" => 1 },
    "valid"      => { "grace" => 1, "locked" => 1 },
    "grace"      => { "valid" => 1, "expired" => 1, "locked" => 1 },
    "locked"     => { "valid" => 1, "expired" => 1 },
    "expired"    => { "unapproved" => 1, "DEAD" => 1 },
);
    
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

my $debug	= 0;

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

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

#
# Accessors
#
193
sub lease_id($)        {return $_[0]->{'DBROW'}->{'lease_id'}; }
194
sub uuid($)            {return $_[0]->{'DBROW'}->{'uuid'}; }
195
sub pid($)             {return $_[0]->{'DBROW'}->{'pid'}; }
196
sub gid($)             {return $_[0]->{'DBROW'}->{'gid'}; }
197 198
sub idx($)             {return $_[0]->{'DBROW'}->{'lease_idx'}; }
sub lease_idx($)       {return $_[0]->idx(); }
199
sub owner($)           {return $_[0]->{'DBROW'}->{'owner_uid'}; }
200
sub owner_urn($)       {return $_[0]->{'DBROW'}->{'owner_urn'}; }
201 202
sub type($)            {return $_[0]->{'DBROW'}->{'type'}; }
sub inception($)       {return str2time($_[0]->{'DBROW'}->{'inception'}); }
203 204
sub lease_end($)       {return str2time($_[0]->{'DBROW'}->{'lease_end'}); }
sub expiration($)      {return $_[0]->lease_end(); }
205
sub last_used($)       {return str2time($_[0]->{'DBROW'}->{'last_used'}); }
206
sub last_checked($)    {return str2time($_[0]->{'DBROW'}->{'last_checked'}); }
207 208
sub state($)           {return $_[0]->{'DBROW'}->{'state'}; }
sub statestamp($)      {return str2time($_[0]->{'DBROW'}->{'statestamp'}); }
209
sub renewals($)	       {return $_[0]->{'DBROW'}->{'renewals'}; }
210
sub locktime($)        {return str2time($_[0]->{'DBROW'}->{'locked'}); }
211
sub locked($)          {return $_[0]->{'DBROW'}->{'locked'}; }
212
sub lockpid($)         {return $_[0]->{'DBROW'}->{'locker_pid'}; }
213 214
sub allow_modify($;$)  {if (defined($_[1])) {$_[0]->{'allow_modify'} = $_[1];}
			return $_[0]->{'allow_modify'}; }
215 216 217 218

#
# Lookup a lease in the DB and return an object representing it.
#
219
sub Lookup($$;$$)
220
{
221
    my ($class, $arg1, $arg2, $arg3) = @_;
222 223
    my ($wclause);

224 225 226 227 228 229 230 231 232
    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]+)$/) {
233
	    $wclause = "pid='$1' and gid='$2' and lease_id='$3'";	
234 235
	}
	else {
236 237
	    return undef;
	}
238 239 240 241 242
    }
    elsif (!defined($arg3)) {
	# arg2 is the lease id.
	return undef
	    if ($arg2 !~ /^[-\w]+$/);
243

244 245 246 247 248 249 250 251 252 253
	# 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;
	}
254
    }
255 256 257 258 259 260
    else {
	# arg3 is the lease id.
	return undef
	    if ($arg3 !~ /^[-\w]+$/);
	# arg1 is pid and arg2 is gid
	return undef
261
	    if ($arg1 !~ /^[-\w]+$/ || $arg2 !~ /^[-\w]+$/);
262

263 264 265
	$wclause = "pid='$arg1' and gid='$arg2' and lease_id='$arg3'";	
    }
    
266 267 268 269
    my $self              = {};
    $self->{"LOCKED"}     = 0;
    $self->{"LOCKER_PID"} = 0;
    $self->{"ATTRS"}      = undef;  # load lazily
270 271 272

    # Load lease from DB, if it exists. Otherwise, return undef.
    my $query_result =
273
	DBQueryWarn("select * from project_leases where $wclause");
274 275 276 277

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

278 279
    $self->{'DBROW'} = $query_result->fetchrow_hashref();;
    bless($self, $class);
280 281 282 283 284 285 286

    return $self;
}

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

290
    return Lookup($class, $arg1, $arg2, $arg3);
291 292 293 294 295 296 297 298
}

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

299 300
    $self->{'LOCKED'} = undef;
    $self->{'LOCKER_PID'} = undef;
301 302 303 304 305 306 307 308 309 310
    $self->{'ATTRS'} = undef;
    $self->{'DBROW'} = undef;
}

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

311
    my ($lease_id, $pid, $gid, $uid, $type, $lease_end, $state, $group);
312 313 314 315

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

316 317
    $lease_id  = $argref->{'lease_id'};
    $pid       = $argref->{'pid'};
318
    $gid       = $argref->{'gid'};
319 320 321 322
    $uid       = $argref->{'uid'};
    $type      = $argref->{'type'};
    $lease_end = $argref->{'lease_end'};
    $state     = $argref->{'state'};
323
    
324
    if (!($lease_id && $pid && $type &&
325
	  defined($lease_end) && $state)) {
326 327 328 329 330 331
	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")) {
332
	print STDERR "Lease->Create: Bad data for lease id: ".
333
	    TBFieldErrorString() ."\n";
334 335 336
	return undef;
    }

337 338 339 340 341 342 343 344 345 346 347 348 349
    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
350
	$group = Group->Lookup("$pid/$gid");
351 352
	if (!defined($group)) {
	    print STDERR "Lease->Create: Bad/Unknown project: $pid/$gid\n";
353 354 355 356 357 358 359
	    return undef;
	}
    }

    if (ref($uid) ne "User") {
	my $nuid = User->Lookup($uid);
	if (!defined($nuid)) {
360
	    print STDERR "Lease->Create: Bad/unknown owner: $uid\n";
361 362 363 364 365 366 367 368
	    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.
369 370 371
    if (!$group->LookupUser($uid)) {
	print STDERR
	    "Lease->Create: Owner $uid is not a member of project $pid/$gid\n";
372 373 374 375 376 377 378 379 380 381
	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;
    }

382 383
    if ($lease_end !~ /^\d+$/) {
	print "Lease->Create: Invalid lease end time: $lease_end\n";
384 385
	return undef;
    }
386
    if ($lease_end && $lease_end < time()) {
Kirk Webb's avatar
Kirk Webb committed
387
	print STDERR "Lease->Create: Lease end cannot be in the past\n";
388 389 390 391 392 393 394 395
	return undef;
    }

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

396
    #
397
    # Get a unique lease index and slam this stuff into the DB.
398 399 400 401
    # 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.
    #
402 403 404 405
    my $lease_idx = TBGetUniqueIndex('next_leaseidx');
    DBQueryWarn("insert into project_leases set ".
		"lease_idx=$lease_idx,".
		"lease_id='$lease_id',".
406
		"pid='$pid',gid='$gid', ".
407 408
		"owner_uid='". $uid->uid() ."',".
		"type='$type',".
409
		($lease_end ? "lease_end=FROM_UNIXTIME($lease_end)," : "").
410
		"state='$state',".
411
		"uuid=uuid(), ".
412
		"statestamp=NOW(),".
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
		"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',".
430
			"attrval=$val,".
431 432 433 434
			"attrtype='$type'")
		or return undef;
	}
    }
435
    return Lookup($class, $group->pid(), $group->gid(), $lease_id);
436 437 438 439 440 441 442 443
}

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

444
    return LEASE_ERROR_FAILED()
445
	if (!ref($self));
446

447
    my $idx  = $self->idx();
448 449
    my $uuid = $self->uuid();

Leigh Stoller's avatar
Leigh Stoller committed
450
    DBQueryWarn("delete from web_tasks where object_uuid='$uuid'")
451
	or return LEASE_ERROR_FAILED();
452 453

    DBQueryWarn("delete from project_leases where lease_idx=$idx")
454
	or return LEASE_ERROR_FAILED();
455
    
456
    DBQueryWarn("delete from lease_attributes where lease_idx=$idx")
457
	or return LEASE_ERROR_FAILED();
458 459

    DBQueryWarn("delete from lease_permissions where lease_idx=$idx")
460
	or return LEASE_ERROR_FAILED();
461 462 463 464

    return 0
}

465 466 467 468 469 470 471 472 473 474 475 476
#
# 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));

477 478 479 480 481
    my $resvref = $self->GetReservations();
    if ($resvref && @$resvref) {
	# We only need to check the first reservation in the list since no
	# concurrent mix of RO and RW is allowed.
	$rw = $resvref->[0]->IsReadOnly() ? 0 : 1;
482 483 484 485 486
    }

    return $rw;
}

487 488
sub InUse($) {
    my ($self) = @_;
489 490 491 492

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

493
    my $lref = $self->GetReservations();
494 495 496 497 498 499 500
    if (!$lref) {
	return 0;
    }

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

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

527
#
528 529 530
# Returns a list of blockstore reservations that are currently using the
# resources associated with this lease. XXX: this is a blockstore-specific
# function.
531
#
532
sub GetReservations($) {
533 534 535 536
    my ($self) = @_;

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

538
    my @resvlist = ();
539

540 541 542 543 544 545 546 547
    #
    # Before doing a big honkin query, see if the lease has resources
    # allocated to it.
    #
    if ($self->type() =~ /dataset$/ && $self->state() ne "unapproved") {
	my $lidx = $self->lease_idx();

	my $query_result =
548
	    DBQueryWarn("select r.vnode_id from blockstores as b,".
549
			"   reserved_blockstores as r,project_leases as l ".
550
			"where b.bsidx=r.bsidx ".
551 552
			"   and b.lease_idx=l.lease_idx ".
			"   and l.lease_idx='$lidx'");
553 554 555 556 557 558 559
	return undef 
	    if (!$query_result);

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

563
    return \@resvlist;
564 565 566 567 568 569 570
}

#
# 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.
#
571 572
sub AllocResources($;$$) {
    my ($self,$state,$interruptable) = @_;
573 574 575 576 577 578 579 580 581 582 583

    $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.
    #
584
    if ($self->state() ne "unapproved") {
585 586 587 588 589 590
	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();
591 592 593 594 595 596 597 598 599 600 601 602
    }

    #
    # 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+$/) {
603 604
	    print STDERR "$self: AllocResources: no valid 'size' attribute\n";
	    return LEASE_ERROR_FAILED();
605 606
	}

607 608 609 610 611 612 613 614 615 616 617 618
	#
	# 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 = "";
	}

619 620 621 622 623 624 625 626 627 628 629 630 631
	#
	# 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";
	    }
	}

632 633 634 635 636 637
	#
	# 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();
638 639 640 641 642 643 644 645 646
	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) {
647
	    print STDERR "$self: AllocResources: could not allocate storage.\n";
648
	    $self->UpdateState("unapproved");
649
	    return LEASE_ERROR_FAILED();
650
	}
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

	#
	# 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");
	    }
	}
666 667 668
    }

    # It all worked!
669 670
    $self->UpdateState($state);

671
    return 0;
672
}
673

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
sub DeallocResources($) {
    my ($self) = @_;

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

    #
    # If lease is in the unapproved state, assume there is nothing to do.
    #
    if ($self->state() eq "unapproved") {
	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;
718 719
}

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 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 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
sub CreateResourceSnapshot($$) {
    my ($self,$exclusive) = @_;

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

    #
    # If lease is in the unapproved state, assume there is nothing to do.
    #
    if ($self->state() eq "unapproved") {
	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));

    #
    # If lease is in the unapproved state, assume there is nothing to do.
    #
    if ($self->state() eq "unapproved") {
	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);
}

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 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
#
# 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();
    if ($cstate eq "unapproved" || $cstate eq "valid" ||
	!$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
    # indicated time.
    #
    if ($self->IsExpired()) {
	if ($self->AddTime($addtime)) {
	    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;
}

907 908 909 910
#
# 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.
911 912 913
#
# 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
914 915 916 917 918 919 920 921 922 923
# LEASE_VAR_DEFAULTS.
#
sub SiteVars($$) {
    my ($class, $ltype) = @_;
    my %vars = ();

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

924 925 926 927 928 929
    # 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"};
	}
    }
930

931
    my $hdr = "storage/$ltype";
932 933 934 935 936 937
    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()) {
938
	if ($var =~ /^$hdr\/([-\w]+)$/) {
939 940 941 942
	    $vars{$1} = defined($val) ? $val : $defval;
	}
    }

943 944 945
    # Convert day values to seconds
    foreach my $n ("maxlease", "maxidle", "graceperiod", "extendperiod") {
	if (exists($vars{$n})) {
Mike Hibler's avatar
Mike Hibler committed
946
	    $vars{$n} = int($vars{$n} * (24 * 60 * 60));
947 948 949
	}
    }

950 951 952
    return \%vars;
}

953
#
954
# Check to see if a lease type is a valid one
955
#
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
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($;$)
976
{
977
    my ($class, $type)  = @_;
978
    my @pleases = ();
979 980 981 982 983 984

    my $tclause = "";
    if (defined($type)) {
	if (_validLeaseType($type)) {
	    $tclause = "where type='$type'";
	} else {
985
	    print STDERR "Lease->AllLeases: Invalid lease type: $type\n";
986 987 988
	    return undef;
	}
    }
989 990
    
    my $query_result =
991
	DBQueryWarn("select lease_idx from project_leases $tclause".
992
		    " order by lease_idx");
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    
    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;
}

1009 1010
#
# Return a list of all leases belonging to a particular project.
1011 1012
# Optionally, only those of the given type.
# The list will be ordered by increasing lease_idx.
1013
#
1014
sub AllProjectLeases($$;$)
1015
{
1016
    my ($class, $pid, $type)  = @_;
1017
    my @pleases = ();
1018 1019 1020
    
    return undef
	if !defined($pid);
1021 1022 1023 1024

    if (ref($pid) eq "Project") {
	$pid = $pid->pid();
    }
1025
    
1026 1027
    my $tclause = "";
    if (defined($type)) {
1028 1029 1030
	if (_validLeaseType($type)) {
	    $tclause = "and type='$type'";
	} else {
1031
	    print STDERR "Lease->AllProjectLeases: Invalid lease type: $type\n";
1032 1033 1034 1035
	    return undef;
	}
    }

1036
    my $query_result =
1037
	DBQueryWarn("select lease_idx from project_leases where ".
1038
		    "pid='$pid' $tclause order by lease_idx");
1039 1040 1041 1042
    
    return ()
	if (!$query_result || !$query_result->numrows);

1043 1044
    while (my ($lease_idx) = $query_result->fetchrow_array()) {
	my $lease = Lookup($class, $lease_idx);
1045 1046 1047 1048 1049

	# Something went wrong?
	return ()
	    if (!defined($lease));
	
1050
	push(@pleases, $lease);
1051
    }
1052
    return @pleases;
1053 1054
}

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
#
# 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") {
1069 1070
	print STDERR "Lease->AllGroupLeases: Input object must be of type \"Group\"";
	return undef;
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    }
    
    my $pid = $group->pid();
    my $gid = $group->gid();

    my $tclause = "";
    if (defined($type)) {
	if (_validLeaseType($type)) {
	    $tclause = "and type='$type'";
	} else {
1081
	    print STDERR "Lease->AllGroupLeases: Invalid lease type: $type\n";
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
	    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;
}


1106 1107 1108
#
# Grab all leases belonging to a particular user
#
1109
sub AllUserLeases($$;$)
1110
{
1111
    my ($class, $uid, $type)  = @_;
1112
    my @uleases = ();
1113 1114 1115 1116
    
    return undef
	if !defined($uid);

1117
    # If uid is a User object extract the user name
1118 1119 1120
    if (ref($uid) eq "User") {
	$uid = $uid->uid();
    }
1121 1122 1123 1124 1125 1126

    my $tclause = "";
    if (defined($type)) {
	if (_validLeaseType($type)) {
	    $tclause = "and type='$type'";
	} else {
1127
	    print STDERR "Lease->AllUserLeases: Invalid lease type: $type\n";
1128 1129 1130
	    return undef;
	}
    }
1131 1132
    
    my $query_result =
1133 1134
	DBQueryWarn("select lease_idx from project_leases".
		    " where owner_uid='$uid' $tclause");
1135 1136 1137 1138
    
    return ()
	if (!$query_result || !$query_result->numrows);

1139 1140
    while (my ($lease_idx) = $query_result->fetchrow_array()) {
	my $lease = Lookup($class, $lease_idx);
1141 1142 1143 1144 1145

	# Something went wrong?
	return ()
	    if (!defined($lease));
	
1146
	push(@uleases, $lease);
1147
    }
1148
    return @uleases;
1149 1150
}

1151
#
1152
# Return a list of leases for which a user OR group has access.  
1153 1154 1155 1156 1157 1158 1159
#
# 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.
1160 1161 1162 1163 1164 1165 1166
# * 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.
1167 1168
#
# Arguments:
1169
# * principal - User OR Group object to lookup lease access for.
1170 1171 1172
# * type - Optional lease type selector.  Restrict results to this type 
#          of lease.
#
1173
# Returns: Array of lease objects the given principal (user or group) has 
1174 1175 1176
#          access to.  To each of these lease objects, an "allow_modify"
#          boolean is set, accessible via $leaseobj->allow_modify().
#
1177 1178
sub AllowedLeases($$;$) {
    my ($class, $principal, $type)  = @_;
1179
    my $wclause = "";
1180 1181 1182
    my %lease_indexes = ();
    my @leases = ();

1183
    # Gather up lease permissions for Users and Groups.  The logic for users
1184
    # is much more complicated...
1185 1186 1187
    if (ref($principal) eq "User") {
	my $uid = $principal->uid();
	my $uid_idx = $principal->uid_idx();
1188 1189
	my @ugroups = ();
	my $gid_idx_list = "";
1190
	my %admin_pids = ();
1191 1192 1193
	my $admin_pid_list = "";

	# Get group information for input User.
1194 1195
	if ($principal->GroupMembershipList(\@ugroups) == 0 && 
	    int(@ugroups) > 0) {
1196 1197 1198 1199
	    # Determine set of projects for which the input User has
	    # group_root or above trust.
	    foreach my $group (@ugroups) {
		if ($group->IsProjectGroup() &&
1200
		    TBMinTrust($group->Trust($principal),
1201
			       PROJMEMBERTRUST_GROUPROOT())) {
1202
		    $admin_pids{$group->pid()} = 1;
1203 1204
		}
	    }
1205 1206 1207 1208 1209 1210 1211 1212
	    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 . "'";
	    }
1213
	} else {
1214 1215
	    print STDERR "Lease->AllowedLeases: Failed to lookup ".
		"group membership for user: $principal\n";
1216 1217 1218
	    return undef;
	}

1219 1220 1221 1222 1223 1224 1225
	# 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'";
1226
	    if ($admin_pid_list) {
1227
		$uclause .= " or pid in ($admin_pid_list)";
1228 1229 1230
	    }
	    my $query_result =
		DBQueryWarn("select lease_idx from project_leases".
1231
			    " $uclause order by lease_idx"); 
1232 1233 1234 1235 1236 1237
	    if ($query_result) {
		while (my ($lease_idx) = $query_result->fetchrow_array()) {
		    $lease_indexes{$lease_idx} = 1; # "modify rights" == 1
		}
	    }

1238 1239
	    # Conjure "where" clause for lease_permissions table query below.
	    #
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
	    # 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.
1255
	    my $idxstr = GLOBAL_PERM_ANON_RO_IDX();
1256 1257
	    $wclause = "where (permission_type='global' and".
		       " permission_idx='$idxstr')";
1258 1259
	}
    }
1260
    # The case for Group principals is easy: just construct a "where"
1261
    # clause for the lease_permissions table query below.
1262 1263
    elsif (ref($principal) eq "Group") {
	my $gid_idx = $principal->gid_idx();
1264 1265
	$wclause = "where (permission_type='global'".
	           " or (permission_type='group' and".
1266
		   "     permission_idx='$gid_idx'))";
1267
    }
1268
    # Input principal argument must be either a User or Group object.
1269
    else {
1270 1271
	print STDERR "Lease->AllowedLeases: Unknown access object: ".
	             "$principal\n";
1272 1273 1274
	return undef;
    }

1275
    # Build up type selector clause, if requested.
1276 1277 1278 1279 1280
    my $tclause = "";
    if (defined($type)) {
	if (_validLeaseType($type)) {
	    $tclause = "and pl.type='$type'";
	} else {
1281
	    print STDERR "Lease->AllowedLeases: Invalid lease type: $type\n";
1282 1283 1284 1285
	    return undef;
	}
    }

1286
    # Grab all lease permissions entries that pertain to the user or project
1287
    my $query_result =
1288
	DBQueryWarn("select lease_idx, allow_modify".
1289 1290
		    " from lease_permissions".
		    " $wclause $tclause order by lease_idx");
1291 1292 1293 1294 1295 1296
    
    # 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.
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
    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;
1307
	}
1308
    }
1309

1310 1311 1312 1313
    # 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) {
1314
	    print STDERR "Lease->AllowedLeases: unable to lookup lease with index $lease_idx!\n";
1315
	    next;
1316 1317
	}
	$lease->allow_modify($modify);
1318
	push (@leases, $lease);
1319 1320
    }

1321
    return @leases;
1322 1323
}

1324 1325 1326 1327 1328 1329 1330 1331
#
# Update fields in the project_leases table, as requested.
#
sub Update($$)
{
    my ($self, $argref) = @_;

    # Must be a real reference. 
1332
    return LEASE_ERROR_FAILED()
1333 1334 1335 1336 1337 1338 1339 1340 1341
	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.
1342
	return LEASE_ERROR_FAILED()
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
	    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'";

1353
    return LEASE_ERROR_FAILED()
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
	if (! DBQueryWarn($query));

    return Refresh($self);
}

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

1366
    return LEASE_ERROR_FAILED()
1367 1368 1369 1370 1371 1372 1373 1374
	if (! ref($self));

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

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

1375
    return LEASE_ERROR_FAILED()
1376 1377 1378
	if (!$query_result);
    return LEASE_ERROR_GONE()
	if (!$query_result->numrows);
1379 1380 1381 1382 1383 1384 1385

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

    return 0;
}

1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
#
# Flush from our little cache, as for the lease daemon.
#
sub Flush($)
{
}

sub FlushAll($)
{
}

1397 1398 1399 1400 1401 1402
#
# Update to the given state and bump timestamp.
#
sub UpdateState($$) {
    my ($self, $state) = @_;

1403
    return LEASE_ERROR_FAILED()
1404 1405
	if (!ref($self));

1406
    return LEASE_ERROR_FAILED()
1407 1408
	if (!defined($state));

1409
    if (!grep {/^$state$/} @LEASE_STATES) {
1410
	print STDERR "Lease->UpdateState: Invalid state: $state\n";
1411
	return LEASE_ERROR_FAILED();
1412 1413 1414 1415 1416
    }

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

1419
    $self->Refresh();
1420 1421 1422 1423 1424 1425 1426 1427 1428
    return 0;
}

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

1429
    return LEASE_ERROR_FAILED()
1430 1431 1432 1433
	if (!ref($self));

    my $idx = $self->idx();
    DBQueryWarn("update project_leases set last_used=NOW() where lease_idx=$idx");
1434
    $self->Refresh();
1435 1436 1437
    return 0;
}

1438 1439 1440 1441 1442 1443
#
# Set last_used to a specific time
#
sub SetLastUsedTime($$) {
    my ($self, $ntime) = @_;

1444
    return LEASE_ERROR_FAILED()
1445 1446 1447 1448
	if (!ref($self));

    if ($ntime > time()) {
	print STDERR "Lease->SetLastUsedTime: Can't set lease last-used time in the future.\n";
1449
	return LEASE_ERROR_FAILED();
1450 1451 1452 1453 1454 1455 1456
    }
    if ($ntime < $self->inception()) {
	$ntime = 0;
    }

    my $idx = $self->idx();
    DBQueryWarn("update project_leases set last_used=FROM_UNIXTIME($ntime) where lease_idx=$idx")
1457
	or return LEASE_ERROR_FAILED();
1458 1459 1460 1461 1462

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

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
#
# 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;
}

1478 1479 1480 1481 1482 1483
#
# Add time to an existing lease
#
sub AddTime($$) {
    my ($self, $ntime) = @_;

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

Mike Hibler's avatar
Mike Hibler committed
1487
    if ($ntime !~ /^\d+$/ || $ntime < 1) {
1488
	print STDERR "Lease->AddTime: Time to add must be a positive number of seconds.\n";
1489
	return LEASE_ERROR_FAILED()
1490 1491 1492
    }

    my $idx = $self->idx();
1493 1494
    my $newend = $self->lease_end() + $ntime;
    DBQueryWarn("update project_leases set lease_end=FROM_UNIXTIME($newend) where lease_idx=$idx")
1495
	or return LEASE_ERROR_FAILED();
1496

1497
    $self->Refresh();
1498 1499 1500 1501
    return 0;
}

#
1502 1503 1504
# 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).
1505 1506 1507 1508
#
sub SetEndTime($$) {
    my ($self, $ntime) = @_;

1509
    return LEASE_ERROR_FAILED()
1510 1511 1512 1513
	if (!ref($self));

    if ($ntime < time()) {
	print STDERR "Lease->SetEndTime: Can't move lease end time into the past.\n";
1514
	return LEASE_ERROR_FAILED();
1515 1516
    }

1517 1518 1519 1520 1521 1522 1523
    my $estr;
    if ($ntime == 0) {
	$estr = "DEFAULT(lease_end)";
    } else {
	$estr = "FROM_UNIXTIME($ntime)";
    }

1524
    my $idx = $self->idx();
1525
    DBQueryWarn("update project_leases set lease_end=$estr where lease_idx=$idx")
1526
	or return LEASE_ERROR_FAILED();
1527

1528
    $self->Refresh();
1529 1530 1531
    return 0;
}

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
#
# 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);
}

1546 1547 1548 1549 1550 1551
#
# Check to see if the lease has expired.
#
sub IsExpired($) {
    my ($self) = @_;
    
1552
    if ($self->lease_end() <= time()) {
1553 1554 1555 1556 1557 1558
	return 1;
    }

    return 0;
}

1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
#
# 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;
    }

1571 1572
    if ($access_type < LEASE_ACCESS_MIN() || 
	$access_type > LEASE_ACCESS_MAX()) {
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
	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
1583
    if ($user->uid() eq $self->owner()) {
1584 1585 1586 1587 1588
	# Owning UID has all permissions.
	return 1;
    }

    # Need this for trust checks below.
1589 1590 1591 1592 1593
    my $pid = $self->pid();
    my $gid = $self->gid();
    $gid = $pid
	if ($gid eq "");
    my $group = Group->Lookup($pid, $gid);
1594

1595 1596 1597 1598
    # Members of the owning project have some implicit permissions, depending
    # on their project trust.
    my $gtrust = $group->Trust($user);
    if (TBMinTrust($gtrust, PROJMEMBERTRUST_GROUPROOT())) {
1599 1600
	return 1;
    }
1601 1602 1603 1604 1605
    # XXX: Need to decide what the right thing to do is here.
    #elsif (TBMinTrust($gtrust, PROJMEMBERTRUST_LOCALROOT())) {
    #	$user_access = LEASE_ACCESS_READ();
    #}
    elsif (TBMinTrust($gtrust, PROJMEMBERTRUST_USER())) {
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
	$user_access = LEASE_ACCESS_READINFO();
    }

    my $idx = $self->idx();
    my $qres = DBQueryWarn("select permission_type,permission_idx,allow_modify from lease_permissions where lease_idx=$idx");

    # If nothing was returned, just pass back the result based on the
    # special checks above.
    return (TBMinTrust($user_access, $access_type) ? 1 : 0)
	if !defined($qres);

    while (my ($perm_type, $perm_idx, $modify) = $qres->fetchrow_array()) {
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
	if ($perm_type eq "global") {
	    # A lease with anonymous global read-only access is available
	    # to everyone.  Force entry to be read-only.
	    if ($perm_idx == GLOBAL_PERM_ANON_RO_IDX()) {
		$modify = 0; # Force!
	    }
	    # A lease with global read-only access for registered users
	    # requires that the incoming user be a "real" user.  I.e.,
	    # not the geni user.  Force entry to be read-only.
	    elsif ($perm_idx == GLOBAL_PERM_USER_RO_IDX()) {
		next unless $user->IsLocal();
		$modify = 0; # Force!
	    }
	    else {
		# Unknown global permissions entry - skip!
1633
		print STDERR "Lease->AccessCheck: Unknown global permission type: $perm_idx\n";
1634 1635 1636
		next;
	    }
	} elsif ($perm_type eq "group") {
1637 1638 1639
	    # If the user is a member of this group and has a minimum of
	    # trust, then give them the access listed in the db.
	    my $dbgroup = Group->Lookup($perm_idx);
1640 1641 1642
	    next unless (defined($dbgroup) && 
			 TBMinTrust($dbgroup->Trust($user), 
				    PROJMEMBERTRUST_LOCALROOT()));
1643 1644 1645
	} elsif ($perm_type eq "user") {
	    # If this is a user permission, and the incoming user arg matches,
	    # then give them the privileges listed in this entry.
1646
	    my $dbusr = User->Lookup($perm_idx);
1647
	    next unless (defined($dbusr) && $dbusr->SameUser($user));
1648 1649 1650 1651
	} else {
	    print STDERR "Lease->AccessCheck: Unknown permission type in DB for lease index $idx: $perm_type\n";
	    return 0;
	}
1652 1653 1654 1655 1656 1657

	# Take the greater of the access found.
	my $this_access = 
	    $modify ? LEASE_ACCESS_MODIFY() : LEASE_ACCESS_READ();
	$user_access = $this_access
	    if ($this_access > $user_access);
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    }

    return (TBMinTrust($user_access, $access_type) ? 1 : 0);
}

#
# Grant permission to access a Lease.
#
sub GrantAccess($$$)
{
    my ($self, $target, $modify) = @_;
    $modify = ($modify ? 1 : 0);

1671
    my $idx      = $self->idx();
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
    my $lease_id = $self->lease_id();
    my ($perm_idx, $perm_id, $perm_type);

    if (ref($target) eq "User") {
	$perm_idx  = $target->uid_idx();
	$perm_id   = $target->uid();
	$perm_type = "user";
    } 
    elsif (ref($target) eq "Group") {
	$perm_idx  = $target->gid_idx();
	$perm_id   = $target->pid() . "/" . $target->gid();
	$perm_type = "group";
    } 
1685 1686 1687 1688 1689
    elsif (ref($target) eq "Project") {
	$perm_idx  = $target->gid_idx();
	$perm_id   = $target->pid() . "/" . $target->gid();
	$perm_type = "group";
    } 
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
    elsif ($target eq GLOBAL_PERM_ANON_RO()) {
	$perm_idx  = GLOBAL_PERM_ANON_RO_IDX();
	$perm_id   = GLOBAL_PERM_ANON_RO();
	$perm_type = "global";
	$modify = 0; # Force
    }
    elsif ($target eq GLOBAL_PERM_USER_RO()) {
	$perm_idx  = GLOBAL_PERM_USER_RO_IDX();
	$perm_id   = GLOBAL_PERM_USER_RO();
	$perm_type = "global";
	$modify = 0; # Force
    }
1702 1703
    else {
	print STDERR "Lease->GrantAccess: Bad target: $target\n";
1704
	return LEASE_ERROR_FAILED();
1705 1706
    }

1707
    return LEASE_ERROR_FAILED()
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
	if (!DBQueryWarn("replace into lease_permissions set ".
			 "  lease_idx=$idx, lease_id='$lease_id', ".
			 "  permission_type='$perm_type', ".
			 "  permission_id='$perm_id', ".
			 "  permission_idx='$perm_idx', ".
			 "  allow_modify='$modify'"));
    return 0;
}


#
# Revoke permission for a lease.
#
sub RevokeAccess($$)
{
    my ($self, $target) = @_;

    my $idx        = $self->idx();
    my ($perm_idx, $perm_type);

    if (ref($target) eq "User") {
	$perm_idx  = $target->uid_idx();
	$perm_type = "user";
    }
    elsif (ref($target) eq "Group") {
	$perm_idx  = $target->gid_idx();
	$perm_type = "group";
    }
1736 1737 1738 1739
    elsif (ref($target) eq "Project") {
	$perm_idx  = $target->gid_idx();
	$perm_type = "group";
    }
1740 1741