Blockstore.pm 23.9 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2012-2019 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
# 
# {{{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 Blockstore;

use strict;
use Carp;
use Exporter;
use vars qw(@ISA @EXPORT $AUTOLOAD);

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

use libdb;
use libtestbed;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

40
my @BLOCKSTORE_ROLES = ("element","compound","partition");
41 42 43 44 45 46 47 48 49 50 51
my $debug	= 0;

#
# Lookup a (physical) storage object type and create a class instance to 
# return.
#
sub Lookup($$$)
{
    my ($class, $nodeid, $bsid) = @_;

    return undef
52 53
	if (!($nodeid && $bsid) ||
	    !($nodeid =~ /^[-\w]+$/ && $bsid =~ /^[-\w]+$/));
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

    my $query_result =
	DBQueryWarn("select * from blockstores ".
		    "where node_id='$nodeid' and bs_id='$bsid'");

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

    my $self         = {};
    $self->{"HASH"}  = {};
    $self->{"DBROW"} = $query_result->fetchrow_hashref();

    bless($self, $class);
    return $self;
}

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
sub LookupByLease($$)
{
    my ($class, $leaseidx) = @_;

    return undef
	if (!($leaseidx && $leaseidx =~ /^\d+$/));

    my $query_result =
	DBQueryWarn("select * from blockstores where lease_idx='$leaseidx'");

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

    my $self         = {};
    $self->{"HASH"}  = {};
    $self->{"DBROW"} = $query_result->fetchrow_hashref();

    bless($self, $class);
    return $self;
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
# To avoid writing out all the methods.
AUTOLOAD {
    my $self  = $_[0];
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
    if (exists($self->{'DBROW'}->{$name})) {
	return $self->{'DBROW'}->{$name};
    }

    # Local storage slot.
    if ($name =~ /^_.*$/) {
	if (scalar(@_) == 2) {
	    return $self->{'HASH'}->{$name} = $_[1];
	}
	elsif (exists($self->{'HASH'}->{$name})) {
	    return $self->{'HASH'}->{$name};
	}
    }
Mike Hibler's avatar
Mike Hibler committed
111
    carp("No such slot '$name' in $self");
112 113 114 115 116 117 118 119 120 121 122
    return undef;
}

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{"DBROW"}    = undef;
    $self->{"HASH"}     = undef;
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
#
# Create a new blockstore.
#
sub Create($$;$) {
    my ($class, $argref, $attrs) = @_;

    my ($node_id, $bs_id, $lease_idx, $type, $role, $size, $exported);

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

    $node_id   = $argref->{'node_id'};
    $bs_id     = $argref->{'bs_id'};
    $lease_idx = $argref->{'lease_idx'};
    $type      = $argref->{'type'};
    $role      = $argref->{'role'};
    $size      = $argref->{'total_size'};
    $exported  = $argref->{'exported'};

    $lease_idx = 0 if (!defined($lease_idx));
    $size      = 0 if (!defined($size));
    $exported  = 0 if (!defined($exported));
    
    if (!($node_id && $bs_id && $type && $role)) {
	print STDERR "Blockstore->Create: Missing required parameters in argref\n";
	return undef;
    }

    # Sanity checks for incoming arguments
    if (!TBcheck_dbslot($node_id, "blockstores", "node_id")) {
	print STDERR "Blockstore->Create: Bad data for node_id: ".
	    TBFieldErrorString() ."\n";
	return undef;
    }
    if (!TBcheck_dbslot($bs_id, "blockstores", "bs_id")) {
	print STDERR "Blockstore->Create: Bad data for bs_id: ".
	    TBFieldErrorString() ."\n";
	return undef;
    }
    if ($lease_idx != 0) {
	my $lease_obj = Lease->Lookup($lease_idx);
	if (!defined($lease_obj)) {
	    print STDERR "Blockstore->Create: No lease for idx: $lease_idx\n";
	    return undef;
	}
    }
    if (!TBcheck_dbslot($bs_id, "blockstores", "type")) {
	print STDERR "Blockstore->Create: Bad data for type: ".
	    TBFieldErrorString() ."\n";
	return undef;
    }
    # If blockstore 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 {/^$role$/} @BLOCKSTORE_ROLES) {
	print STDERR "Blockstore->Create: Unknown blockstore role: $role\n";
	return undef;
    }
    if ($exported > 1) {
	$exported = 1;
    }

    # Get a unique blockstore index and slam this stuff into the DB.
    my $bs_idx = TBGetUniqueIndex('next_bsidx');

    DBQueryWarn("insert into blockstores set ".
		"bsidx=$bs_idx,".
		"node_id='$node_id',".
		"bs_id='$bs_id',".
		"lease_idx='$lease_idx',".
		"type='$type',".
		"role='$role',".
		"total_size='$size',".
		"exported='$exported',".
		"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 blockstore_attributes set ".
			"bsidx=$bs_idx,".
			"attrkey='$key',".
			"attrval=$val,".
			"attrtype='$type'")
		or return undef;
	}
    }

    return Lookup($class, $node_id, $bs_id);
}

#
# Delete an existing blockstore.
# XXX this only clears out blockstores and blockstores_attributes right now!
#
sub Delete($) {
    my ($self) = @_;

    return -1
	if (!ref($self));

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

    #
    # If this is a partition, we need to return our capacity to our
    # parent blockstore.
    # XXX maybe partitions should be a seperate blockstore object type?
    #
    if ($self->role() eq "partition") {
	my $query_result =
	    DBQueryWarn("select remaining_capacity from blockstore_state ".
			"where bsidx='$bsidx'");
	if ($query_result && $query_result->numrows) {
	    my ($psize) = $query_result->fetchrow_array();
	    if ($psize > 0) {
		my $qr =
		    DBQueryWarn("select aggidx from blockstore_trees ".
				"where bsidx='$bsidx'");
		if (!$qr || $qr->numrows != 1) {
		    print STDERR
			"Inconsistent state in blockstore_trees for ".
			"partition blockstore idx=$bsidx\n";
		    return -1;
		}
		my ($aggidx) = $qr->fetchrow_array();
		if (!DBQueryWarn("update blockstore_state as f,".
				 "       blockstore_state as t ".
				 "set t.remaining_capacity=t.remaining_capacity+$psize,".
				 "    f.remaining_capacity='0' ".
				 "where t.bsidx=$aggidx and f.bsidx=$bsidx")) {
		    print STDERR
			"Could not transfer capacity $psize from idx=$bsidx to idx=$aggidx\n";
		    return -1;
		}
	    }
	}

    }

    DBQueryWarn("delete from blockstores where bsidx=$bsidx")
	or return -1;
    
    DBQueryWarn("delete from blockstore_attributes where bsidx=$bsidx")
	or return -1;

    DBQueryWarn("delete from blockstore_state where bsidx=$bsidx")
	or return -1;

    DBQueryWarn("delete from blockstore_trees where bsidx=$bsidx")
	or return -1;

    return 0
}

285 286 287 288 289 290 291 292 293 294 295 296 297 298
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $bsidx   = $self->bsidx();
    my $bs_id   = $self->bs_id();
    my $node_id = $self->node_id();

    return "[BlockStore:$bsidx, $bs_id, $node_id]";
}

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
#
# Create a partition blockstore using space from the invoking blockstore.
# Returns a new blockstore object.
#
# In addition to atomically updating the base blockstore's blockstore_state
# entry, it creates new blockstores, blockstore_state, and blockstore_trees
# entries for the partition.
#
sub Partition($$$$$)
{
    my ($self, $lease_idx, $pbs_name, $pbs_type, $pbs_size) = @_;
    my $bsidx      = $self->bsidx();
    my $bs_id      = $self->bs_id();
    my $bs_node_id = $self->node_id();
    my $remaining_capacity;
    my $new_bs;

316 317 318 319 320 321 322 323
    #
    # Make sure it doesn't already exist
    #
    if (Blockstore->Lookup($bs_node_id, $pbs_name)) {
	print STDERR "Partition blockstore $bs_node_id/$pbs_name already exists\n";
	return undef;
    }

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
    #
    # Make sure we have an entry for the new blockstore.
    # XXX we do this before we lock the tables since Create accesses
    # other tables (e.g., table_regex) and we don't want to lock those.
    #
    my $args = {
	"node_id"    => $bs_node_id,
	"bs_id"      => $pbs_name,
	"lease_idx"  => $lease_idx,
	"type"       => $pbs_type,
	"role"       => "partition",
	"total_size" => $pbs_size,
	"exported"   => 1
    };
    $new_bs = Blockstore->Create($args);
    return undef
	if (!$new_bs);

    my $new_bsidx = $new_bs->bsidx();

    if (!DBQueryWarn("lock tables blockstores write, ".
		     "            blockstore_trees write, ".
		     "            blockstore_state write, ".
		     "            blockstore_state as f write, ".
		     "            blockstore_state as t write")) {
	$new_bs->Delete();
	return undef;
    }

    #
    # Need the remaining size to make sure we can allocate it.
    #
    my $query_result =
	DBQueryWarn("select remaining_capacity from blockstore_state ".
		    "where bsidx='$bsidx'");
    goto bad
	if (!$query_result);

    #
    # Just in case the state row is missing, okay to create it.
    #
    if (!$query_result->numrows) {
	$remaining_capacity = $self->total_size();

	DBQueryWarn("insert into blockstore_state set ".
		    "  bsidx='$bsidx', node_id='$bs_node_id', bs_id='$bs_id', ".
		    "  remaining_capacity='$remaining_capacity', ready='1'")
	    or goto bad;
    }
    else {
	($remaining_capacity) = $query_result->fetchrow_array();
    }
    if ($pbs_size > $remaining_capacity) {
	print STDERR "Not enough remaining capacity on $self\n";
	goto bad;
    }

    #
    # Establish the relationship between the partition and the base.
    #
    DBQueryWarn("insert into blockstore_trees set ".
		"  bsidx='$new_bsidx', aggidx='$bsidx', hint='PS'")
	or goto bad;

    #
    # Create a state table entry.
    #
    DBQueryWarn("insert into blockstore_state set ".
		"  bsidx='$new_bsidx', node_id='$bs_node_id', ".
		"  bs_id='$pbs_name', remaining_capacity='0', ready='1'")
	or goto bad;

    #
    # Now do an atomic update that changes both rows.
    #
    DBQueryWarn("update blockstore_state as f,blockstore_state as t ".
		"set f.remaining_capacity=f.remaining_capacity-${pbs_size},".
		"    t.remaining_capacity=$pbs_size ".
		"where f.bsidx='$bsidx' and t.bsidx='$new_bsidx'")
	or goto bad;
done:
    DBQueryWarn("unlock tables");
    return $new_bs;
  bad:
    DBQueryWarn("unlock tables");
    $new_bs->Delete();
    return undef;
}

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
#
# Blockstores are reserved to a pcvm; that is how we do the
# bookkeeping. When a node is released (nfree), we can find
# the reserved blockstores for that node, reset the capacity
# in the blockstore_state table, and delete the row(s).
#
sub Reserve($$$$$)
{
    my ($self, $experiment, $vnode_id, $bs_name, $bs_size) = @_;
    my $exptidx    = $experiment->idx();
    my $pid        = $experiment->pid();
    my $eid        = $experiment->eid();
    my $bsidx      = $self->bsidx();
    my $bs_id      = $self->bs_id();
    my $bs_node_id = $self->node_id();
    my $remaining_capacity;

    DBQueryWarn("lock tables blockstores read, ".
		"            reserved_blockstores write, ".
		"            blockstore_state write")
	or return -1;

    #
    # Need the remaining size to make sure we can allocate it.
    #
    my $query_result =
	DBQueryWarn("select remaining_capacity from blockstore_state ".
		    "where bsidx='$bsidx'");
    goto bad
	if (!$query_result);

    #
    # Just in case the state row is missing, okay to create it.
    #
    if (!$query_result->numrows) {
	$remaining_capacity = $self->total_size();

	DBQueryWarn("insert into blockstore_state set ".
		    "  bsidx='$bsidx', node_id='$bs_node_id', bs_id='$bs_id', ".
		    "  remaining_capacity='$remaining_capacity', 'ready=1'")
	    or goto bad;
    }
    else {
	($remaining_capacity) = $query_result->fetchrow_array();
    }
    if ($bs_size > $remaining_capacity) {
459
	print STDERR "Not enough remaining capacity on $self\n";
460 461 462 463 464 465 466 467
	goto bad;
    }

    #
    # If we do not have a reservation row, create one with a zero
    # size, to indicate nothing has actually been reserved in the
    # blockstore_state table.
    #
468 469 470 471 472 473
    # However, if this is a lease (dataset), then we are just going to
    # stuff the full size of it into the reserved_blockstores table
    # and forgo any other capacity accounting.  Also, its
    # 'remaining_capacity' is always its full size. This allows for
    # simultaneous read-only use (modes enforced elsewhere).
    #
474 475 476 477 478 479 480
    $query_result =
	DBQueryWarn("select size from reserved_blockstores ".
		    "where exptidx='$exptidx' and bsidx='$bsidx' and ".
		    "       vname='$bs_name'");
    goto bad
	if (!$query_result);

481 482 483 484 485
    my $newsize = 0;
    if ($self->lease_idx() > 0) {
	$newsize = $self->total_size();
    } 

486 487 488 489
    if (! $query_result->numrows) {
	if (! DBQueryWarn("insert into reserved_blockstores set ".
	        "  bsidx='$bsidx', node_id='$bs_node_id', bs_id='$bs_id', ".
	        "  vname='$bs_name', pid='$pid', eid='$eid', ".
490
		"  size='$newsize', vnode_id='$vnode_id', ".
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
	        "  exptidx='$exptidx', rsrv_time=now()")) {
	    goto bad;
	}
    }
    else {
	my ($current_size) = $query_result->fetchrow_array();

	#
	# At the moment, I am not going to allow the blockstore
	# to change size. 
	#
	if ($current_size && $current_size != $bs_size) {
	    print STDERR "Not allowed to change size of existing store\n";
	    goto bad;
	}

	#
	# If already have a reservation size, then this is most
	# likely a swapmod, and we can just return without doing
	# anything.
	#
	goto done
	    if ($current_size);
    }

    #
    # Now do an atomic update that changes both tables.
518 519 520 521 522 523 524 525 526 527 528 529
    # Note: leases do not require this.
    #
    if ($self->lease_idx() == 0 &&
	!DBQueryWarn("update blockstore_state,reserved_blockstores set ".
		     "     remaining_capacity=remaining_capacity-${bs_size}, ".
		     "     size='$bs_size' ".
		     "where ".
		     "  blockstore_state.bsidx=reserved_blockstores.bsidx and".
		     "  blockstore_state.bs_id=reserved_blockstores.bs_id and".
		     "  reserved_blockstores.bsidx='$bsidx' and ".
		     "  reserved_blockstores.exptidx='$exptidx' and ".
		     "  reserved_blockstores.vnode_id='$vnode_id'")) {
530 531 532 533
	goto bad;
    }
done:
    DBQueryWarn("unlock tables");
534 535 536 537 538 539 540 541 542 543 544 545 546 547

    #
    # If there is a lease associated with this blockstore, update the
    # last used time since this represents a mapping (aka swapin) of the
    # lease.
    #
    if ($self->lease_idx() != 0) {
	require Lease;

	my $lease = Lease->Lookup($self->lease_idx());
	$lease->BumpLastUsed()
	    if ($lease);
    }

548 549 550 551 552 553
    return 0;
  bad:
    DBQueryWarn("unlock tables");
    return -1;
}

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
#
# Return the remaining unallocated space
#
sub AvailableCapacity($)
{
    my ($self) = @_;
    my $bsidx = $self->bsidx();

    my $query_result =
	DBQueryWarn("select b.total_size,s.remaining_capacity ".
		    "from blockstores as b left join blockstore_state as s ".
		    "on b.bsidx=s.bsidx where b.bsidx='$bsidx'");
    return -1
	if (!$query_result || !$query_result->numrows);

    #
    # If remaining_capacity is NULL, then the blockstore is unused
    # and we just return the total size.
    #
    my ($size,$avail) = $query_result->fetchrow_array();
    return (defined($avail) ? $avail : $size);
}

577 578 579 580 581 582 583 584 585 586 587 588
# convert_to_mebi
# This takes a data size specifier in the form of <amt><unit> where
# <unit> is any of [B, KB, KiB, MB, MiB, GB, GiB, TB, TiB].  If no
# unit is given then bytes (B) is assumed.  It returns the size
# in Mebibytes.  Data sizes in bits (lowercase b) are not handled (yet).
#
sub ConvertToMebi($)
{
    my ($size) = @_;
    # Default to bytes
    my $unit   = "B";
    
589
    if ($size =~ /^([\.\d]+)(\w+)$/) {
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
	$size = $1;
	$unit = $2;
    }
    else {
	return -1;
    }
    SWITCH: for ($unit) {
	/^B$/ && do {
	    $size = int($size / 2**20);
	    last SWITCH;
	};
	/^KB$/ && do {
	    $size = int($size * 10**3 / 2**20);
	    last SWITCH;
	};
	/^KiB$/ && do {
	    $size = int($size / 2**10);
	    last SWITCH;
	};
	/^MB$/ && do {
	    $size = int($size * 10**6 / 2**20);
	    last SWITCH;
	};
	/^MiB$/ && do {
	    $size = int($size);
	    last SWITCH;
	};
	/^GB$/ && do {
	    $size = int($size * 10**9 / 2**20);
	    last SWITCH;
	};
	/^GiB$/ && do {
	    $size = int($size * 2**10);
	    last SWITCH;
	};
	/^TB$/ && do {
	    $size = int($size * 10**12 / 2**20);
	    last SWITCH;
	};
	/^TiB$/ && do {
	    $size = int($size * 2**20);
	    last SWITCH;
	};
	print STDERR "Illegal mebibytes unit: $unit\n";
	return -1;
    };
    return $size;
}

639 640 641 642 643 644 645
#
# Compute a load time estimate for an image backed dataset.
#
sub LoadEstimate($)
{
    my ($blockstore) = @_;
    my $bsname = $blockstore->vname();
646
    require OSImage;
647 648 649 650 651 652

    if (!exists($blockstore->{'attributes'}->{"dataset"})) {
	print STDERR "No dataset attribute for $bsname\n";
	return -1;
    }
    my $dataset = $blockstore->{'attributes'}->{"dataset"};
653
    my $image   = OSImage->Lookup($dataset);
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
    if (!defined($image)) {
	print STDERR "No image for dataset $dataset for $bsname\n";
	return -1;
    }
    # Bad, but don't want to use bignums to get MBs.
    my $size = int(($image->lba_high() - $image->lba_low()) *
		   ($image->lba_size() / (1024.0 * 1024.0)));
    
    #
    # Temporary approach; look for the size attribute and use that
    # to extend the waittime. Later we will use the amount of actual
    # data.
    #
    my $extratime = int($size / 100);
    return $extratime;
}

671 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 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
############################################################################
#
# Package to describe a specific reservation of a blockstore.
#
package Blockstore::Reservation;
use libdb;
use libtestbed;
use English;
use vars qw($AUTOLOAD);
use overload ('""' => 'Stringify');

#
# Lookup a blockstore reservation.
#
sub Lookup($$$$)
{
    my ($class, $blockstore, $experiment, $vname) = @_;

    return undef
	if (! ($vname =~ /^[-\w]+$/ && ref($blockstore) && ref($experiment)));

    my $exptidx = $experiment->idx();
    my $bsidx   = $blockstore->bsidx();

    my $query_result =
	DBQueryWarn("select * from reserved_blockstores ".
		    "where exptidx='$exptidx' and bsidx='$bsidx' and ".
		    "       vname='$vname'");

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

    my $self         = {};
    $self->{"HASH"}  = {};
    $self->{"DBROW"} = $query_result->fetchrow_hashref();

    bless($self, $class);
    return $self;
}

#
# Look for the blockstore associated with a pcvm. At the present
# time, one blockstore is mapped to one pcvm. 
#
sub LookupByNodeid($$)
{
    my ($class, $vnode_id) = @_;

    my $query_result =
	DBQueryWarn("select * from reserved_blockstores ".
		    "where vnode_id='$vnode_id'");

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

    if ($query_result->numrows != 1) {
	print STDERR "Too many blockstores for $vnode_id!\n";
	return -1;
    }

    my $self         = {};
    $self->{"HASH"}  = {};
    $self->{"DBROW"} = $query_result->fetchrow_hashref();

    bless($self, $class);
    return $self;
}

# To avoid writing out all the methods.
AUTOLOAD {
    my $self  = $_[0];
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
    if (exists($self->{'DBROW'}->{$name})) {
	return $self->{'DBROW'}->{$name};
    }
Mike Hibler's avatar
Mike Hibler committed
749
    carp("No such slot '$name' in $self");
750 751 752
    return undef;
}

753 754 755 756 757 758 759 760 761
#
# Is this reservation RO?
#
sub IsReadOnly($) {
    my ($self) = @_;

    return $self->HowUsed()->{'readonly'};
}

762 763 764 765 766 767 768 769 770
#
# Is this reservation a RW clone?
#
sub IsRWClone($) {
    my ($self) = @_;

    return $self->HowUsed()->{'rwclone'};
}

771 772 773 774 775
#
# How is the associated blockstore used in this reservation?
#
sub HowUsed($) {
    my ($self) = @_;
776
    require VirtExperiment;
777 778 779

    my $rethash = {
	'readonly' => 0,
780
	'rwclone' => 0,
781 782 783 784 785 786 787 788 789
    };

    my $virtexpt = VirtExperiment->Lookup(Experiment->Lookup($self->exptidx()));
    if (!$virtexpt) {
	print STDERR "Virtual experiment object could not be loaded for ${self}!";
	return undef;
    }

    my @attrs = ($self->vname(), "readonly");
790 791 792 793 794 795 796 797 798
    my $row = $virtexpt->Find("virt_blockstore_attributes", @attrs);
    if ($row) {
	$rethash->{'readonly'} = int($row->attrvalue());
    }

    @attrs = ($self->vname(), "rwclone");
    $row = $virtexpt->Find("virt_blockstore_attributes", @attrs);
    if ($row) {
	$rethash->{'rwclone'} = int($row->attrvalue());
799 800 801 802 803
    }

    return $rethash;
}

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{"DBROW"}    = undef;
    $self->{"HASH"}     = undef;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $bsidx   = $self->bsidx();
    my $bs_id   = $self->bs_id();
    my $node_id = $self->node_id();
    my $vname   = $self->vname();

Mike Hibler's avatar
Mike Hibler committed
824
    return "[BlockStore::Reservation:$bsidx, $bs_id, $node_id ($vname)]";
825 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
}

#
# Blockstores are reserved to a pcvm; that is how we do the
# bookkeeping. When a node is released (nfree), we can find
# the reserved blockstore for that node, reset the capacity
# in the blockstore_state table, and delete the row(s).
#
sub Release($)
{
    my ($self)     = @_;
    my $exptidx    = $self->exptidx();
    my $bsidx      = $self->bsidx();
    my $bs_id      = $self->bs_id();
    my $bs_node_id = $self->node_id();
    my $vnode_id   = $self->vnode_id();
    my $size       = $self->size();

    DBQueryWarn("lock tables blockstores read, ".
		"            reserved_blockstores write, ".
		"            blockstore_state write")
	or return -1;

    #
    # Need the remaining size to deallocate.
    #
    my $query_result =
	DBQueryWarn("select remaining_capacity from blockstore_state ".
		    "where bsidx='$bsidx'");
    goto bad
	if (!$query_result);

    if (!$query_result->numrows) {
	print STDERR "No blockstore state for $bsidx\n";
	goto bad;
    }

    #
863 864 865 866 867 868 869 870 871 872 873 874
    # See if there is an associated lease.
    #
    my $lease_idx = 0;
    $query_result =
	DBQueryWarn("select lease_idx from blockstores ".
		    "where bsidx='$bsidx'");
    if ($query_result && $query_result->numrows) {
	$lease_idx = $query_result->fetchrow_array();
    }

    #
    # We want to atomically update remaining_capacity and
875 876
    # set the size in the reservation to zero, so that if we fail,
    # nothing has changed.
877 878 879 880 881 882 883 884 885 886 887 888
    # Note: leases do not require this.
    #
    if ($lease_idx == 0 &&
	!DBQueryWarn("update blockstore_state,reserved_blockstores set ".
		     "     remaining_capacity=remaining_capacity+size, ".
		     "     size=0 ".
		     "where ".
		     "  blockstore_state.bsidx=reserved_blockstores.bsidx and".
		     "  blockstore_state.bs_id=reserved_blockstores.bs_id and".
		     "  reserved_blockstores.bsidx='$bsidx' and".
		     "  reserved_blockstores.exptidx='$exptidx' and".
		     "  reserved_blockstores.vnode_id='$vnode_id'")) {
889 890 891 892 893 894 895 896 897 898
	goto bad;
    }
    # That worked, so now we can delete the reservation row.
    DBQueryWarn("delete from reserved_blockstores ".
		"where reserved_blockstores.bsidx='$bsidx' and ".
		"      reserved_blockstores.exptidx='$exptidx' and ".
		"      reserved_blockstores.vnode_id='$vnode_id'")
	or goto bad;

    DBQueryWarn("unlock tables");
899 900 901 902 903 904

    #
    # If there is a lease associated with this blockstore, update the
    # last used time since this represents an unmapping (aka swapout)
    # of the lease.
    #
905
    # XXX currently, we also create a new snapshot of the blockstore
906 907
    # if the blockstore is marked as "multiuse" and is mapped RW and
    # not a clone.
908
    #
909
    if ($lease_idx != 0) {
910 911
	require Lease;

912
	my $lease = Lease->Lookup($lease_idx);
913 914
	if ($lease) {
	    $lease->BumpLastUsed();
915 916
	    if (!$lease->IsExclusiveUse() &&
		!$self->IsReadOnly() && !$self->IsRWClone() &&
917 918 919 920 921 922 923
		$lease->CreateResourceSnapshot(1)) {
		print STDERR "Blockstore->Release: ".
		    "Could not create snapshot for $bsidx ($lease); ".
		    "marking as exclusive-use\n";
		$lease->SetExclusiveUse();
	    }
	}
924 925
    }

926 927 928 929 930 931 932 933
    return 0;
  bad:
    DBQueryWarn("unlock tables");
    return -1;
}

# _Always_ make sure that this 1 is at the end of the file...
1;