bscontrol.in 26.9 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2013-2017 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 40 41 42 43 44 45 46 47
# 
# {{{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/>.
# 
# }}}
#
use strict;
use English;
use Getopt::Std;

#
# Block storage server control utility.
#
# Contacts one or all available block storage servers to perform actions.
# Commands:
#
# bscontrol list
#	List all configured blockstore servers.
#
# bscontrol [ -S server [ -P pool ] ] avail
#	For the named servers (or all if none specified), print out
#	how much storage is available.
#
# bscontrol [ -S server [ -P pool ] ] info
#	Return detailed info the listed block servers (or all) including the
#	name of all existant blockstores and their sizes, attributes, etc.
#
# The following commands are for persistent blockstores.
# For these, a blockstore name, "bsname", had better be unique.
#
48
# bscontrol [ -S server [ -P pool ] ] [-f fstype] -l leaseidx -s size -t type create bsname
49 50 51 52
#	Create a blockstore of the given size with the given name.
#	If the server is not specified, we pick the "best" server,
#	based on availability of space.
#
53
# bscontrol snapshot [ -S server [ -P pool ] ] bsname [ tstamp ]
54 55 56
#	Create a snapshot of the named blockstore with the indicated
#	timestamp. If timestamp is not provided, it will use the
#	current time. bsname needs to be unique across all servers
57 58
#	or the server and pool need to be explicitly specified.
#
59
# bscontrol desnapshot [ -S server [ -P pool ] ] bsname [ tstamp ]
60 61 62 63 64
#	Delete the snapshot of the named blockstore with the indicated
#	timestamp. If timestamp is not provided, delete all snapshots
#	associated with the blockstore. bsname needs to be unique across
#	all servers or the server and pool need to be explicitly specified.
#
65
# bscontrol destroy [ -S server [ -P pool ] ] bsname
66 67 68 69
#	Destroy the named blockstore freeing up the space. Also destroys
#	any associated snapshots. bsname needs to be unique across all
#	servers or the server and pool need to be explicitly specified.
#
70 71 72 73 74 75
# bscontrol [ -S server [ -P pool ] ] copy from-bsname to-bsname
#	Do an efficient copy of one blockstore to another. Use the
#	server/pool arguments to force a specific placement of to-bsname.
#
sub usage()
{
76
    print STDERR "Usage: bscontrol [-hd] command args\n";
77 78
    print STDERR "   -h       This message\n";
    print STDERR "   -d       Print additional debug info\n";
79 80 81 82
    print STDERR "commands:\n";
    print STDERR "   list     List all blockstore servers\n";
    print STDERR "   avail    For each server, show available storage\n";
    print STDERR "   info     For each server, show all extant volumes\n";
83 84 85 86 87
    print STDERR "\nAdditional persistent blockstore commands.\n";
    print STDERR "bscontrol [-S server [-P pool]] [-f fstype] -l leaseidx -s size -t type create bsname\n";
    print STDERR "bscontrol [-S server -P pool] destroy bsname\n";
    print STDERR "bscontrol [-S server [-P pool]] snapshot bsname [tstamp]\n";
    print STDERR "bscontrol [-S server [-P pool]] desnapshot bsname [tstamp]\n";
88 89
    exit(-1);
}
90
my $optlist  = "hds:t:l:S:P:Ff:I";
91 92 93 94 95 96
my $debug = 0;
my $server;
my $pool;
my $size;
my $type = "stdataset";
my $leaseidx = 0;
97
my $fstype = "";
98
my $fakeit = 0;
99
my $ignoredb = 0;
100 101 102 103 104 105 106

# Protos
sub fatal($);
sub bs_list($$$@);
sub bs_avail($$$@);
sub bs_info($$$@);
sub bs_create($$$@);
107 108
sub bs_snapshot($$$@);
sub bs_desnapshot($$$@);
109 110 111 112 113 114 115
sub bs_destory($$$@);

#
# Configure variables
#
my $TB		 = "@prefix@";

116
my $PROXYCMD	 = "/usr/local/etc/emulab/bscontrol.proxy";
117 118 119 120 121 122 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
my $SSH		 = "ssh -n -o ConnectTimeout=2 -o Protocol=2 -o BatchMode=yes -o StrictHostKeyChecking=no";

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use emutil;
use Lease;
use Blockstore;
use Experiment;
use User;
use Project;

#
# Turn off line buffering on output
#
$| = 1;

#
# Untaint the path
# 
$ENV{'PATH'} = "/bin:/sbin:/usr/bin:";

#
# We don't want to run this script unless its the real version.
# That is, it must be setuid root. 
#
if ($EUID != 0) {
    die("*** $0:\n".
	"    Must be root! Maybe its a development version?\n");
}

# Commands
my %cmds = (
152 153 154 155 156 157 158
   "list"     => \&bs_list,
   "avail"    => \&bs_avail,
   "info"     => \&bs_info,
   "create"   => \&bs_create,
   "snapshot" => \&bs_snapshot,
   "desnapshot" => \&bs_desnapshot,
   "destroy"  => \&bs_destroy,
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
);

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{h})) {
    usage();
}
if (defined($options{d})) {
    $debug = 1;
}
if (defined($options{S})) {
    if ($options{S} =~ /^([-\w]+)$/) {
	$server = $1;
    }
}
if (defined($options{P})) {
    $pool = $options{P};
    if ($options{P} =~ /^([-\w]+)$/) {
	$pool = $1;
    }
}
if (defined($options{s})) {
Mike Hibler's avatar
Mike Hibler committed
187 188 189
    if ($options{s} =~ /^(\d+)$/) {
	$size = $1;
    }
190 191 192 193 194 195 196
}
if (defined($options{t})) {
    $type = $options{t};
}
if (defined($options{l})) {
    $leaseidx = $options{l};
}
197 198 199
if (defined($options{f})) {
    $fstype = $options{f};
}
200 201 202
if (defined($options{F})) {
    $fakeit = 1;
}
203 204 205
if (defined($options{I})) {
    $ignoredb = 1;
}
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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 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
if (@ARGV < 1) {
    usage();
}

my $cmd = shift;
if (!exists($cmds{$cmd})) {
    print STDERR "Unrecognized command '$cmd', should be one of:\n";
    print STDERR "  ", join(", ", keys %cmds), "\n";
    usage();
}

$fakeit = 1
    if (-e "$TB/etc/bs-servers.txt");
if ($fakeit) {
    print STDERR "WARNING: bscontrol operating in fake mode!\n";
}

exit(&{$cmds{$cmd}}($server, $pool, $size, @ARGV));

#
# Look in the database to find the storage servers
#
sub bsservers()
{
    my @bs = ();

    if ($fakeit) {
	if (-e "$TB/etc/bs-servers.txt") {
	    foreach my $bs (`cat $TB/etc/bs-servers.txt`) {
		# keep taint happy
		if ($bs =~ /^([-\w]+)$/) {
		    push @bs, $1;
		}
	    }
	}
	return @bs;
    }

    my $result =
	DBQueryFatal("SELECT node_id FROM reserved WHERE erole='storagehost'".
		     " order by node_id");
    while (my ($node) = $result->fetchrow_array) {
	push @bs, $node;
    }
    return @bs;
}

sub fake_change($$$)
{
    my ($file,$pool,$used) = @_;

    my $line = `grep 'pool=$pool ' $file`;
    if ($? == 0 && $line =~ /size=(\d+) avail=(\d+)/) {
	my $size = $1;
	my $oavail = $2;
	my $navail = $oavail - $used;
	if (system("sed -i '' -e 's/pool=$pool size=$size avail=$oavail/pool=$pool size=$size avail=$navail/' $file") == 0) {
	    return 1;
	}
    }
    return 0;
}

sub fake_cmd($$$)
{
    my ($host, $cmdstr, $outref) = @_;
    my @output = ();

    my ($fcmd,$fargs);
    if ($cmdstr =~ /^$PROXYCMD\s+(\S+)(?:\s+(.*))?$/) {
	$fcmd = $1;
	$fargs = $2;
    } else {
	push @output, "Unrecognized command string '$cmdstr'";
	$$outref = \@output;
	return -1;
    }
    if ($fcmd =~ /^(volumes|pools)$/) {
	if (-e "$TB/etc/bs-$fcmd-$host.txt") {
	    @output = `cat $TB/etc/bs-$fcmd-$host.txt`;
	    chomp @output;
	}
	$$outref = \@output;
	return 0;
    } elsif ($fcmd eq "create") {
	# in format: create pool volume size
	# out format: volume=lease-2 pool=rz-1 size=95
	if ($fargs =~ /^(\S+)\s+(\S+)\s+(\S+)/) {
	    my $pool = $1;
	    my $vol = $2;
	    my $size = $3;

	    my $vfile = "$TB/etc/bs-volumes-$host.txt";
	    my $pfile = "$TB/etc/bs-pools-$host.txt";
	    system("cp -f $vfile $vfile.new");
	    system("cp -f $pfile $pfile.new");

	    system("echo 'volume=$vol pool=$pool size=$size' >> $vfile.new");

	    if (fake_change("$pfile.new", $pool, $size) &&
		rename($pfile, "$pfile.old") &&
		rename("$pfile.new", $pfile) &&
		rename($vfile, "$vfile.old") &&
		rename("$vfile.new", $vfile)) {
		$$outref = \@output;
		return 0;
	    }
	}
	push @output, "create $fargs failed!";
	$$outref = \@output;
	return -1;
    } elsif ($fcmd eq "destroy") {
	# in format: destroy pool volume
	if ($fargs =~ /^(\S+)\s+(\S+)/) {
	    my $pool = $1;
	    my $volume = $2;
	    my $size;

	    my $vfile = "$TB/etc/bs-volumes-$host.txt";
	    my $pfile = "$TB/etc/bs-pools-$host.txt";
	    system("cp -f $vfile $vfile.new");
	    system("cp -f $pfile $pfile.new");

	    my $line = `grep 'volume=$volume pool=$pool' $vfile`;
	    if ($line =~ /size=(\d+)/) {
		$size = $1;
		if (fake_change("$pfile.new", $pool, -$size) &&
		    system("sed -i '' -e '/volume=$volume pool=$pool /d' $vfile.new") == 0 &&
		rename($pfile, "$pfile.old") &&
		rename("$pfile.new", $pfile) &&
		rename($vfile, "$vfile.old") &&
		rename("$vfile.new", $vfile)) {
		    $$outref = \@output;
		    return 0;
		}
	    }
	}
	push @output, "destroy $fargs failed!";
	$$outref = \@output;
	return -1;
    } else {
	push @output, "Cannot fake '$fcmd' right now";
	$$outref = \@output;
	return -1;
    }
}

#
# Execute a command on a remote blockstore server and return the output.
#
sub bsserver_cmd($$$)
{
    my ($host, $cmdstr, $outref) = @_;
    my @output = ();
    my $stat = 0;

    if ($fakeit) {
	print STDERR "Faking '$SSH $host $cmdstr'\n"
	    if ($debug);
	return fake_cmd($host, $cmdstr, $outref);
    }

    print STDERR "Doing '$SSH $host $cmdstr'\n"
	if ($debug);

    my $SAVEUID = $UID;
    $UID = 0;
    @output = `$SSH $host $cmdstr 2>&1`;
    $UID = $SAVEUID;
    if ($?) {
	$stat = $? >> 8;
	print STDERR "*** WARNING: ssh to $host failed ($stat)!\n";
    }

    print STDERR "Got output:\n", @output
	if ($debug > 1);
    chomp(@output);
    $$outref = \@output;
    return $stat;
}

sub parseattrs($)
{
    my ($line) = @_;
    my %attrs = ();

    foreach my $pair (split(/\s+/, $line)) {
	if ($pair =~ /^(\S+)=(\S+)$/) {
	    $attrs{$1} = $2;
	}
    }

    return \%attrs;
}

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
#
# Augment pool atrributes with Emulab blockstore attributes.
#
sub get_poolattrs($)
{
    my ($attrs) = @_;

    my $server = $attrs->{'server'};
    my $pool = $attrs->{'pool'};
    my $bstore = Blockstore->Lookup($server, $pool);
    if ($bstore) {
	my $bsidx = $bstore->bsidx();
	my $result =
	    DBQueryFatal("SELECT attrvalue FROM blockstore_attributes ".
			 "WHERE bsidx='$bsidx' and attrkey='allowed_bstores'");
	if ($result && $result->numrows) {
	    my ($allows) = $result->fetchrow_array;
	    $attrs->{'allowed'} = $allows;
	} else {
	    # XXX if nothing specified, assume non-persistent blockstores
	    $attrs->{'allowed'} = "volatile";
	}
    } else {
	print STDERR "WARNING: no blockstore object for $server/$pool\n";
    }

    return $attrs;
}

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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 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
#
# Augment volume attributes with Emulab blockstore attributes gleaned
# from the volume attributes.
#
sub get_bsattrs($)
{
    my ($attrs) = @_;

    #
    # iname info implies that the volume is exported via iSCSI
    # Parse out good stuff like the iqn, pid, eid, and vname.
    # Get even more good stuff from the experiment.
    #
    my $iname = $attrs->{'iname'};
    if ($iname) {
	my ($iqn,$pid,$eid,$vname) = split(':', $iname);

	$attrs->{'iqn'} = $iqn;
	$attrs->{'pid'} = $pid;
	$attrs->{'eid'} = $eid;
	$attrs->{'vname'} = $vname;
	$attrs->{'uname'} = "$pid/$eid/$vname";
	if (defined($pid) && defined($eid)) {
	    my $expt;

	    if (!($expt = Experiment->Lookup("$pid/$eid"))) {
		print STDERR "WARNING: no experiment info associated with $pid/$eid\n";
		$attrs->{'swapper'} = $attrs->{'owner'} = "??";
	    } else {
		$attrs->{'swapper'} = $expt->swapper();
		$attrs->{'owner'} = $expt->creator();
	    }
	}
	$attrs->{'active'} = 1;
    } else {
	$attrs->{'active'} = 0;
    }

    #
    # If the volume name is of the form 'lease-<id>' then this
    # is a persistent dataset. Extract more info from the lease.
    # Note that attributes from the lease override those from a
    # swapped in experiment using the lease (e.g., owner and uname).
    #
    my $volume = $attrs->{'volume'};
    if ($volume =~ /^lease-(\d+)$/) {
	my $lidx = $1;

	$attrs->{'lidx'} = $lidx;
	my $lease = Lease->Lookup($lidx);
	if (!$lease) {
	    print STDERR "WARNING: no lease info associated with persistent lease $lidx\n";
	    $attrs->{'lid'} = $attrs->{'owner'} = $attrs->{'lpid'} =
		$attrs->{'type'} = $attrs->{'expiration'} = "??";
	    $attrs->{'uname'} = $volume;
	} else {
	    $attrs->{'lid'} = $lease->lease_id();
	    $attrs->{'owner'} = $lease->owner();
	    $attrs->{'lpid'} = $lease->pid();
	    $attrs->{'type'} = $lease->type();
	    $attrs->{'expiration'} = $lease->expiration();
	    $attrs->{'uname'} = $attrs->{'lpid'} . "/" . $attrs->{'lid'};
	}
	$attrs->{'persist'} = 1;

    } else {
	$attrs->{'type'} = "volatile";
	$attrs->{'persist'} = 0;
    }

    return $attrs;
}

sub getpools($$)
{
    my ($dsrv,$dpool) = @_;
    my %pools = ();

    foreach my $srv (bsservers()) {
	next
	    if (defined($dsrv) && $dsrv ne $srv);

	my $outref;
	if (bsserver_cmd($srv, "$PROXYCMD pools", \$outref) == 0) {
	    foreach my $pstr (@$outref) {
		my $attrs = parseattrs($pstr);
516 517 518
		# XXX ignore bogus lines that don't include pool=...
		next
		    if (!exists($attrs->{'pool'}));
519 520 521
		my $pool = $attrs->{'pool'};
		if (!defined($dpool) || $dpool eq $pool) {
		    $attrs->{'server'} = $srv;
522
		    $attrs = get_poolattrs($attrs);
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
		    $pools{"$srv/$pool"} = $attrs;
		}
	    }
	} else {
	    print STDERR "*** could not get pools from $srv, error:\n";
	    foreach my $str (@$outref) {
		print STDERR "  $str\n";
	    }
	}
    }

    return \%pools;
}

sub getvolumes($$)
{
    my ($dsrv,$dpool) = @_;
    my %volumes = ();

    foreach my $srv (bsservers()) {
	next
	    if (defined($dsrv) && $dsrv ne $srv);

	my $outref;
	if (bsserver_cmd($srv, "$PROXYCMD volumes", \$outref) == 0) {
	    foreach my $vstr (@$outref) {
		my $attrs = parseattrs($vstr);
550 551 552
		# XXX ignore bogus lines that don't include volume=...
		next
		    if (!exists($attrs->{'volume'}));
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
		my $pool = $attrs->{'pool'};
		if (!defined($dpool) || $dpool eq $pool) {
		    $attrs->{'server'} = $srv;
		    my $vol = $attrs->{'volume'};
		    $volumes{"$srv/$pool/$vol"} = $attrs;
		}
	    }
	} else {
	    print STDERR "*** could not get volumes from $srv, error:\n";
	    foreach my $str (@$outref) {
		print STDERR "  $str\n";
	    }
	}
    }

568 569 570 571 572 573 574 575 576 577 578 579 580
    if ($debug && keys(%volumes) > 0) {
	print STDERR "Found volumes:\n";
	foreach my $v (keys(%volumes)) {
	    my $attrs = $volumes{$v};
	    print STDERR "  $v: ";
	    foreach my $k (keys(%$attrs)) {
		my $v = $attrs->{$k};
		print STDERR "$k=$v ";
	    }
	    print STDERR "\n";
	}
    }

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    return \%volumes;
}

sub getblockstores($$)
{
    my ($dsrv,$dpool) = @_;
    my %bstores = ();

    foreach my $srv (bsservers()) {
	next
	    if (defined($dsrv) && $dsrv ne $srv);

	my $outref;
	if (bsserver_cmd($srv, "$PROXYCMD volumes", \$outref) == 0) {
	    foreach my $vstr (@$outref) {
		my $attrs = get_bsattrs(parseattrs($vstr));
597 598 599
		# XXX ignore bogus lines that don't include volume=...
		next
		    if (!exists($attrs->{'volume'}));
600 601
		if (!defined($dpool) || $dpool eq $attrs->{'pool'}) {
		    $attrs->{'server'} = $srv;
602 603 604 605 606 607 608

		    if (!exists($attrs->{'uname'})) {
			$attrs->{'uname'} = "NON-EMULAB/$srv-" .
			    $attrs->{'pool'} . "-" . $attrs->{'volume'};
			$attrs->{'type'} = "--";
		    }

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
		    $bstores{$attrs->{'uname'}} = $attrs;
		}
	    }
	} else {
	    print STDERR "*** could not get blockstores from $srv, error:\n";
	    foreach my $str (@$outref) {
		print STDERR "  $str\n";
	    }
	}
    }

    return \%bstores;
}

sub bs_list($$$@)
{
    foreach my $srv (bsservers()) {
	print "$srv\n";
    }
}

sub bs_avail($$$@)
{
    my ($dsrv,$dpool,undef) = @_;

    my $poolref = getpools($dsrv, $dpool);

    if (keys(%{$poolref}) > 0) {
637 638
	printf("%-12s %-12s %10s %10s %-5s %-s\n",
	       "Server", "Pool", "Size", "Avail", "Free %", "Allows");
639 640 641 642 643

	foreach my $pstr (sort keys(%{$poolref})) {
	    my $attrs = $poolref->{$pstr};
	    my $size = ($attrs->{'size'} ? $attrs->{'size'} : 1);
	    my $pct = $attrs->{'avail'} / $size * 100;
644
	    printf("%-12s %-12s %10s %10s %5.1f %-s\n",
645
		   $attrs->{'server'}, $attrs->{'pool'},
646
		   $size, $attrs->{'avail'}, $pct, $attrs->{'allowed'});
647 648 649 650 651 652 653 654 655 656 657 658 659
	}
    }

    return 0;
}

sub bs_info($$$@)
{
    my ($dsrv,$dpool,undef) = @_;

    my $bsref = getblockstores($dsrv, $dpool);

    if (keys(%{$bsref}) > 0) {
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
	printf("%-32s %-24s %-10s %10s %4s %-s\n",
	       "Unique ID", "Server/Pool/Volume", "Type", "Size", "Snap", "Exported as");

	# create a snapshot to unique ID hash
	my %snaps = ();
	foreach my $bs (sort keys(%{$bsref})) {
	    my $attrs = $bsref->{$bs};
	    my $scount = 0;
	    if (exists($attrs->{'snapshots'})) {
		foreach my $sname (split(',', $attrs->{'snapshots'})) {
		    $snaps{$sname} = $bs;
		    $scount++;
		}
	    }
	    $bsref->{$bs}->{'snapcount'} = $scount;
	}
676 677 678

	foreach my $bs (sort keys(%{$bsref})) {
	    my $attrs = $bsref->{$bs};
679 680 681 682 683 684 685 686 687 688
	    my $tstr = $attrs->{'type'};
	    if (exists($attrs->{'cloneof'})) {
		$tstr = "clone (" . $snaps{$attrs->{'cloneof'}} . ")";
	    }
	    my $scount = 0;
	    if (exists($attrs->{'snapcount'})) {
		$scount = $attrs->{'snapcount'};
	    }

	    printf("%-32s %-24s %-10s %10s %4s %s\n", $bs,
689
		   $attrs->{'server'} . "/" . $attrs->{'pool'} . "/" . $attrs->{'volume'},
690
		   $tstr, $attrs->{'size'}, $scount,
691 692 693 694 695 696 697 698 699 700 701 702 703 704
		   ($attrs->{'active'} ? $attrs->{'iname'} : ""));
	}
    }

    return 0;
}

sub bs_create($$$@)
{
    my ($srv,$pool,$size,$name) = @_;

    if (!defined($size)) {
	fatal("create: must specify a size in MiB (-s)");
    }
Mike Hibler's avatar
Mike Hibler committed
705 706 707 708
    if (defined($name) && $name =~ /^([-\w]+)$/) {
	$name = $1;
    } else {
	fatal("create: must specify a valid volume name");
709 710 711 712 713
    }

    if ($leaseidx !~ /^\d+$/) {
	fatal("create: lease index must be an integer");
    }
714 715 716 717 718 719 720
    if ($fstype) {
	if ($fstype !~ /^(ext2|ext3|ext4|ufs)$/) {
	    fatal("create: fstype must be one of ext2|ext3|ext4|ufs");
	} else {
	    $fstype = $1;
	}
    }
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    if ($type !~ /^(st|lt)dataset$/) {
	fatal("create: type must be either 'stdataset' or 'ltdataset'");
    }

    # get all qualified pools
    my $poolref = getpools($srv, $pool);

    if ($debug) {
	print STDERR
	    "create(", ($srv ? $srv : "-"), "/", ($pool ? $pool : "-"),
	    ", $size, $name): found candidate pools:\n";
	foreach my $pstr (sort keys(%{$poolref})) {
	    my $attrs = $poolref->{$pstr};
	    print STDERR "  ", $attrs->{'server'}, "/", $attrs->{'pool'},
		": avail=", $attrs->{'avail'}, "\n";
	}
    }

739
    # eliminate those without enough space or that don't allow the type
740 741 742 743 744 745 746 747 748
    my %servercount = ();
    my @pools = ();
    foreach my $pstr (sort keys(%{$poolref})) {
	my $attrs = $poolref->{$pstr};
	if (!exists($servercount{$attrs->{'server'}})) {
	    $servercount{$attrs->{'server'}} = 1;
	} else {
	    $servercount{$attrs->{'server'}}++;
	}
749 750 751 752
	if ($attrs->{'size'} >= $size &&
	    $attrs->{'allowed'} =~ /$type/) {
	    push(@pools, $attrs);
	}
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
    }

    # if none qualify, quit
    if (@pools == 0) {
	if ($srv) {
	    print STDERR "$srv: not enough space in ",
	    ($pool ? "pool $pool" : "any pool"), "\n";
	} else {
	    print STDERR "No storage server has enough space\n";
	}
	exit(1);
    }

    #
    # Pick the best pool if more than one:
    #  - prefer pool with most available space
    # XXX should take number of blockstores in each pool into account.
    #
    my $bpoolattrs;
    foreach my $attrs (@pools) {
	if (!$bpoolattrs || $attrs->{'avail'} > $bpoolattrs->{'avail'}) {
	    $bpoolattrs = $attrs;
	    next;
	}
    }

    # we should have one, do some sanity checks
    if (!$bpoolattrs) {
	fatal("create: did not find a pool!?");
    }
    if ($srv) {
	if ($srv ne $bpoolattrs->{'server'}) {
	    fatal("create: found server is not the specified server!?");
	}
    } else {
	$srv = $bpoolattrs->{'server'};
    }

    if ($pool) {
	if ($pool ne $bpoolattrs->{'pool'}) {
	    fatal("create: found pool is not the specified pool!?");
	}
    } else {
	$pool = $bpoolattrs->{'pool'};
    }

    #
    # Now we can begin the task of actually creating the blockstore!
    # First, lookup the blockstore object for the underlying pool.
    #
803 804
    print STDERR "$name: size=$size, server=$srv, pool=$pool\n"
	if ($debug);
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    my $bstore = Blockstore->Lookup($srv, $pool);
    if (!$bstore) {
	fatal("create: could not find blockstore for $srv:$pool");
    }

    #
    # Create the new partition blockstore in the DB.
    #
    my $pbstore = $bstore->Partition($leaseidx, $name, $type, $size);
    if (!$pbstore) {
	fatal("create: could not create '$name' in DB");
    }

    # Call out to the server to allocate the actual storage.
    my $outref;
820
    if (bsserver_cmd($srv, "$PROXYCMD create $pool $name $size $fstype", \$outref)) {
821
	$pbstore->Delete();
Mike Hibler's avatar
Mike Hibler committed
822
	print STDERR "*** create: could not allocate storage for '$name' on $srv/$pool:\n";
823 824 825 826 827 828 829 830 831
	foreach my $str (@$outref) {
	    print STDERR "  $str\n";
	}
	exit(-1);
    }

    return 0;
}

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 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 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
sub dosnapshot($$$$$)
{
    my ($create,$srv,$pool,$name,$tstamp) = @_;
    my $cmd = ($create ? "snapshot" : "desnapshot");

    if (defined($name) && $name =~ /^([-\w]+)$/) {
	$name = $1;
    } else {
	fatal("$cmd: must specify a valid volume name");
    }
    if (defined($tstamp)) {
	if ($tstamp =~ /^(\d+)$/) {
	    $tstamp = $1;
	} else {
	    fatal("$cmd: must specify a numeric timestamp value");
	}
    } elsif ($create) {
	$tstamp = time();
    } else {
	$tstamp = "";
    }

    #
    # Find the blockstore based on info from the server(s).
    #
    my $volattrs;
    my $volref = getvolumes($srv, $pool);
    foreach my $vol (sort keys(%{$volref})) {
	my $attrs = $volref->{$vol};
	if ($name eq $attrs->{'volume'}) {
	    if ($volattrs) {
		fatal("$cmd: ".
		      "multiple volumes match '$name', must specify a server and pool");
	    }
	    $volattrs = $attrs;
	}
    }
    if (!$volattrs) {
	fatal("$cmd: no such volume '$name'");
    }
    if ($srv) {
	if ($srv ne $volattrs->{'server'}) {
	    fatal("$cmd: found server is not the specified server!?");
	}
    } else {
	$srv = $volattrs->{'server'};
    }
    if ($pool) {
	if ($pool ne $volattrs->{'pool'}) {
	    fatal("$cmd: found pool is not the specified pool!?");
	}
    } else {
	$pool = $volattrs->{'pool'};
    }

    #
    # See if the snapshot already exists
    #
    if ($tstamp && exists($volattrs->{'snapshots'})) {
	my @snaps = split(',', $volattrs->{'snapshots'});
	my $snapshot = "$name\@$tstamp";

	my $found = 0;
	foreach my $sname (@snaps) {
	    if ($snapshot eq $sname) {
		$found = 1;
		last;
	    }
	}
	if ($create && $found) {
	    fatal("$cmd: snapshot '$snapshot' already exists");
	} elsif (!$create && !$found) {
	    fatal("$cmd: no such snapshot '$snapshot'");
	}
    }

    #
    # Call out to the server to create/destroy the snapshot.
    #
    my $outref;
    if (bsserver_cmd($srv, "$PROXYCMD $cmd $pool $name $tstamp", \$outref)) {
	my $action = ($create ? "create" : "destroy");
	print STDERR "*** $cmd: ".
	    "could not $action snapshot for '$name' on $srv/$pool:\n";
	print STDERR "proxycmd: '$cmd $pool $name $tstamp'\n";
	print STDERR "output:\n";
	foreach my $str (@$outref) {
	    print STDERR "  $str\n";
	}
	exit(-1);
    }

    return 0;
}

sub bs_snapshot($$$@)
{
    my ($srv,$pool,undef,$name,$tstamp) = @_;

    return dosnapshot(1, $srv, $pool, $name, $tstamp);
}

sub bs_desnapshot($$$@)
{
    my ($srv,$pool,undef,$name,$tstamp) = @_;

    return dosnapshot(0, $srv, $pool, $name, $tstamp);
}

941 942
sub bs_destroy($$$@)
{
943
    my ($srv,$pool,undef,$name) = @_;
944

Mike Hibler's avatar
Mike Hibler committed
945 946 947
    if (defined($name) && $name =~ /^([-\w]+)$/) {
	$name = $1;
    } else {
948
	fatal("destroy: must specify a valid volume name");
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
    }

    #
    # Find the blockstore based on info from the server(s).
    #
    my $volattrs;
    my $volref = getvolumes($srv, $pool);
    foreach my $vol (sort keys(%{$volref})) {
	my $attrs = $volref->{$vol};
	if ($name eq $attrs->{'volume'}) {
	    if ($volattrs) {
		fatal("destroy: multiple volumes match '$name', specify a server and pool");
	    }
	    $volattrs = $attrs;
	}
    }
    if (!$volattrs) {
	fatal("destroy: no such volume '$name'");
    }
    if ($srv) {
	if ($srv ne $volattrs->{'server'}) {
	    fatal("destroy: found server is not the specified server!?");
	}
    } else {
	$srv = $volattrs->{'server'};
    }
    if ($pool) {
	if ($pool ne $volattrs->{'pool'}) {
	    fatal("destroy: found pool is not the specified pool!?");
	}
    } else {
	$pool = $volattrs->{'pool'};
    }

    #
984 985 986
    # Verify that the blockstore object exists and is of the right type.
    # We will delete the blockstore object *after* we destroy the server-side
    # object. See XXX below for rationale.
987 988
    #
    my $bstore = Blockstore->Lookup($srv, $name);
989
    if (!$bstore && !$ignoredb) {
990
	fatal("destroy: no blockstore '$srv/$name' in DB");
991
    }
992
    if ($bstore && $bstore->role() ne "partition") {
993 994 995 996 997 998 999
	fatal("destroy: wrong type of blockstore '$srv/$name'");
    }

    #
    # Call out to the server to delete the storage.
    #
    my $outref;
1000 1001

    #
1002
    # First destroy any snapshots.
1003
    #
1004 1005 1006 1007 1008 1009
    # We do this regardless of whether $volattrs indicates there are
    # any snapshots. That state only includes blockstore related snapshots
    # and we need to make sure all snapshots are gone, even explicitly
    # created ones (e.g., for backup purposes).
    #
    if (bsserver_cmd($srv, "$PROXYCMD desnapshotall $pool $name", \$outref)) {
1010 1011
	print STDERR "*** destroy: ".
	    "could not destroy snapshots for '$name' on $srv/$pool:";
1012
	goto fail;
1013 1014 1015 1016 1017 1018 1019 1020
    }

    #
    # Destroy the actual volume.
    #
    # N.B. if the volume is a clone, this call will not get rid of
    # the snapshot the volume was associated with.
    #
1021
    if (bsserver_cmd($srv, "$PROXYCMD destroy $pool $name", \$outref)) {
1022 1023
	print STDERR "*** destroy: ".
	    "could not deallocate storage for '$name' on $srv/$pool:";
1024
	goto fail;
1025 1026
    }

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    #
    # After everything else works, delete the actual blockstore object.
    #
    # XXX There is a nasty circular dependency here where if we were to
    # destroy the blockstore DB state first and then the object destruction
    # fails, we leave behind a dangling object and potentially Lease DB
    # state. But if we destroy the object first and the DB state removal
    # fails, we are left with a blockstore with no server object and thus
    # we cannot look it up in the future to retry the destruction.
    #
    # We choose to go with the latter and just create a tiny server-side
    # stub object if the DB state removal fails.
    #
    if ($bstore && $bstore->Delete()) {
	print STDERR "*** destroy: ".
	    "could not destroy Blockstore DB state, ".
	    "recreating a stub server-side object.\n";
	if (bsserver_cmd($srv, "$PROXYCMD create $pool $name 1", \$outref)) {
	    print STDERR "*** destroy: ".
		"re-creation of server-side object failed, ".
		"before you can destroy this blockstore ".
		"you must manually re-create the object with:\n";
	    print STDERR "    $PROXYCMD create $pool $name 1\n";
	    goto fail;
	}
	fatal("destroy: could not delete blockstore '$srv/$name' from DB");
    }


1056
    return 0;
1057 1058 1059 1060 1061 1062

  fail:
    foreach my $str (@$outref) {
	print STDERR "  $str\n";
    }
    exit(-1);
1063 1064 1065 1066 1067 1068 1069 1070 1071
}

sub fatal($)
{
    my ($mesg) = $_[0];

    die("*** $0:\n".
	"    $mesg\n");
}