liblocstorage.pm 45.8 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2013-2014 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 48 49 50 51 52 53 54 55 56
# 
# {{{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/>.
# 
# }}}
#

#
# FreeBSD specific routines and constants for client storage setup.
#
package liblocstorage;
use Exporter;
@ISA = "Exporter";
@EXPORT =
    qw (
	os_init_storage os_check_storage os_create_storage os_remove_storage
       );

sub VERSION()	{ return 1.0; }

# Must come after package declaration!
use English;

# Load up the paths. Its conditionalized to be compatabile with older images.
# Note this file has probably already been loaded by the caller.
BEGIN
{
    if (-e "/etc/emulab/paths.pm") {
	require "/etc/emulab/paths.pm";
	import emulabpaths;
    }
    else {
	my $ETCDIR  = "/etc/testbed";
	my $BINDIR  = "/etc/testbed";
	my $VARDIR  = "/etc/testbed";
	my $BOOTDIR = "/etc/testbed";
    }
}

57
my $MKDIR	= "/bin/mkdir";
58 59
my $MOUNT	= "/sbin/mount";
my $UMOUNT	= "/sbin/umount";
60 61
my $MKFS	= "/sbin/newfs";
my $FSCK	= "/sbin/fsck";
62 63 64
my $ISCSI	= "/sbin/iscontrol";
my $ISCSICNF	= "/etc/iscsi.conf";
my $SMARTCTL	= "/usr/local/sbin/smartctl";
65 66 67
my $GEOM	= "/sbin/geom";
my $GPART	= "/sbin/gpart";
my $GVINUM	= "/sbin/gvinum";
68 69 70 71 72 73 74 75 76 77 78 79
my $ZPOOL	= "/sbin/zpool";
my $ZFS		= "/sbin/zfs";

#
# We orient the FS blocksize toward larger files.
# (64K/8K is the largest that UFS supports).
#
# Note that we also set the zfs zvol blocksize to match.
# We currently only use zvols when the user does NOT specify a mountpoint
# (we use a native zfs otherwise), but in case they do create a filesystem
# on it later, it will be well suited to that use.
#
80
my $UFSBS	= "65536";
81 82 83 84 85 86 87
my $ZVOLBS	= "64K";

#
# For gvinum, it is recommended that the stripe size not be a power of two
# to avoid FS metadata (which use power-of-two alignment) all winding up
# on the same disk.
#
88
my $VINUMSS	= "81920";
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

#
# To find the block stores exported from a target portal:
#
#   iscontrol -d -t <storage-host>
#
# To use a remote iSCSI target, the info has to be in /etc/iscsi.conf:
#
#   <bsid> {
#     initiatorname = <our hostname>
#     targetname    = <iqn>
#     targetaddress = <storage-host>
#   }
#
# To login to a remote iSCSI target:
# 
#   iscontrol -c /etc/iscsi.conf -n <bsid>
# 
# The session ID for the resulting session can be determined from the
# sysctl net.iscsi_initiator info:
#
#   net.iscsi_initiator.<session>.targetname: <iqn>
#   net.iscsi_initiator.<session>.targeaddress: <storage-host-IP>
#
# To stop a session (logout) you must first determine its pid from
# the net.iscsi_initiator info:
#
#   net.iscsi_initiator.<session>.pid: <pid>
#
# and then send it a HUP:
#
#   kill -HUP <pid>
#
# Once a blockstore is added, it will appear as a /dev/da? device.
# I have not found a straight-forward way to map session to device.
# What we do now is to use the session ID to match up info from
# "camcontrol identify da<N> -v". camcontrol will return output like:
#
#   (pass3:iscsi0:0:0:0): ATAPI_IDENTIFY. ACB: ...
#   ...
#
130 131 132
# where N in "iscsiN" will be the session. Note that even if this command
# causes an error, the -v will ensure that SCSI sense code data is dumped
# and that will contain the magic string!
133 134 135 136 137 138 139 140 141 142 143 144 145
# 

sub iscsi_to_dev($)
{
    my ($session) = @_;

    #
    # XXX this is a total hack
    #
    my @lines = `ls /dev/da* 2>&1`;
    foreach (@lines) {
	if (m#^/dev/(da\d+)$#) {
	    my $dev = $1;
146 147 148 149 150 151
	    my @out = `camcontrol identify $dev -v 2>&1`;
	    foreach my $line (@out) {
		if ($line =~ /^\(pass\d+:iscsi(\d+):/) {
		    if ($1 == $session) {
			return $dev;
		    }
152 153 154 155 156 157 158 159
		}
	    }
	}
    }

    return undef;
}

160
sub find_serial($)
161
{
162
    my ($dev) = @_;
163 164

    #
165
    # Try using "smartctl -i" first
166
    #
167 168 169 170 171 172 173
    if (-x "$SMARTCTL") {
	@lines = `$SMARTCTL -i /dev/$dev 2>&1`;
	foreach (@lines) {
	    if (/^Serial Number:\s+(\S.*)/) {
		return $1;
	    }
	}
174 175
    }

176 177 178
    # XXX for "mfi" devices we can use mfiutil to get SNs
    # but have to be able to relate that info to /dev/* devices.

179 180 181 182 183 184 185 186 187 188 189 190 191
    # XXX Parse dmesg output?

    return undef;
}

#
# Do a one-time initialization of a serial number -> /dev/sd? map.
#
sub init_serial_map()
{
    my %snmap = ();

    my @lines = `ls /dev/ad* /dev/da* /dev/mfid* /dev/mfisyspd* 2>&1`;
192
    foreach (@lines) {
193 194 195 196 197
	# XXX just use the /dev/ad? traditional names for now
	if (m#^/dev/ada\d+$#) {
	    next;
	}
	if (m#^/dev/((?:da|ad|mfid|mfisyspd)\d+)$#) {
198
	    my $dev = $1;
199 200 201 202 203 204
	    $sn = find_serial($dev);
	    if ($sn) {
		$snmap{$sn} = $dev;
	    } else {
		# XXX just so we know how many disks we found
		$snmap{$dev} = $dev;
205 206 207 208
	    }
	}
    }

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    if (0) {
	print STDERR "SN map:\n";
	foreach my $sn (keys %snmap) {
	    print STDERR "$sn -> $snmap{$sn}\n";
	}
    }

    return \%snmap;
}

sub serial_to_dev($$)
{
    my ($so, $sn) = @_;

    if (defined($so->{'LOCAL_SNMAP'})) {
	my $snmap = $so->{'LOCAL_SNMAP'};
	if (exists($snmap->{$sn})) {
	    return $snmap->{$sn};
	}
    }
229 230 231
    return undef;
}

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
#
# Returns one if the indicated device is an iSCSI-provided one
# XXX another total hack
#
sub is_iscsi_dev($)
{
    my ($dev) = @_;

    if ($dev !~ /^da\d+$/) {
	return 0;
    }
    if (!open(FD, "$GEOM disk list $dev|")) {
	return 0;
    }
    my $descr = "";
    while (<FD>) {
	if (/^\s+descr:\s+(.*)$/) {
	    $descr = $1;
	    last;
	}
    }
    close(FD);
    if ($descr !~ /^FreeBSD iSCSI Disk/) {
	return 0;
    }

    return 1;
}

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

    my @lines = `sysctl net.iscsi_initiator 2>&1`;
    foreach (@lines) {
	if (/net\.iscsi_initiator\.(\d+)\.targetname: $uuid/) {
	    return $1;
	}
    }

    return undef;
}

sub uuid_to_daemonpid($)
{
    my ($uuid) = @_;
    my $session;

    my @lines = `sysctl net.iscsi_initiator 2>&1`;
    foreach (@lines) {
	if (/net\.iscsi_initiator\.(\d+)\.targetname: $uuid/) {
	    $session = $1;
	    next;
	}
	if (/net\.iscsi_initiator\.(\d+)\.pid: (\d+)/) {
	    if (defined($session) && $1 == $session) {
		return $2;
	    }
	}
    }

    return undef;
}

#
# Return the name (e.g., "da0") of the boot disk, aka the "system volume".
#
sub get_bootdisk()
{
    my $disk = undef;
    my $line = `$MOUNT | grep ' on / '`;

    if ($line && $line =~ /^\/dev\/(\S+)s1a on \//) {
	$disk = $1;
306 307 308 309 310 311 312 313 314 315
	#
	# FreeBSD 9+ changed the naming convention.
	# But there will be a symlink to the real device.
	#
	if ($disk =~ /^ad\d+$/) {
	    $line = `ls -l /dev/$disk`;
	    if ($line =~ /${disk} -> (\S+)/) {
		$disk = $1;
	    }
	}
316 317 318 319
    }
    return $disk;
}

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 401 402 403 404 405
#
# Return a list of the physical drives (partitions) that are part of
# the current gvinum config.
#
sub get_vinum_drives()
{
    my @drives = ();

    if (open(FD, "$GVINUM ld 2>/dev/null|")) {
	while (<FD>) {
	    if (/^D emulab_(\S+)/) {
		push(@drives, $1);
	    }
	}
	close(FD);
    }

    return @drives;
}

#
# In FreeBSD 9+, zpool has a -v command so we could do:
#   zpool list -vH -o name
# but alas, FreeBSD 8 doesn't have it. So we do:
#   zpool iostat -v
# which is the only other way I have found to list the vdevs of a pool.
#
sub get_zpool_vdevs($)
{
    my ($pool) = @_;
    my @vdevs = ();

    if (open(FD, "$ZPOOL iostat -v $pool 2>/dev/null|")) {
	while (<FD>) {
	    if (/^\s+(\w+)/) {
		push(@vdevs, $1);
	    }
	}
	close(FD);
    }

    return @vdevs;
}

#
# Return the name of any datasets in the given pool.
# Returns an empty list if there is not such pool or no datasets.
#
sub get_zpool_datasets($)
{
    my ($pool) = @_;
    my @dsets = ();

    if (open(FD, "$ZFS list -Hr $pool 2>/dev/null|")) {
	while (<FD>) {
	    if (/^($pool\/\S+)\s/) {
		push(@dsets, $1);
	    }
	}
	close(FD);
    }

    return @dsets;
}

#
# Returns 1 if the volume manager has been initialized.
# For ZFS this means that the "emulab" zpool exists.
# For gvinum this means that the emulab_* drives exist.
#
sub is_lvm_initialized($)
{
    my ($usezfs) = @_;

    if ($usezfs) {
	if (mysystem("$ZPOOL list emulab >/dev/null 2>&1") == 0) {
	    return 1;
	}
    } else {
	if (get_vinum_drives() > 0) {
	    return 1;
	}
    }
    return 0;
}

406
#
407 408 409 410 411 412 413
#
# Get information about local disks.
#
# Ideally, this comes from the list of ELEMENTs passed in.
#
# But if that is not available, we figure it out outselves by using
# the GEOM subsystem:
414 415 416
# For FreeBSD 8- we have to go fishing using geom commands.
# For FreeBSD 9+ there is a convenient sysctl mib that gives us everything.
#
417
sub get_diskinfo($)
418
{
419
    my ($usezfs) = @_;
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    my %geominfo = ();

    my @lines = `sysctl -n kern.geom.conftxt`;
    chomp(@lines);
    if (@lines > 0) {
	# FBSD9 and above.
	foreach (@lines) {
	    next if ($_ eq "");
	    my @vals = split /\s/;

	    # assume 2k sector size means a CD drive
	    if ($vals[0] == 0 && $vals[1] eq "DISK" && $vals[4] == 2048) {
		next;
	    }

	    my $dev = $vals[2];
	    $geominfo{$dev}{'level'} = $vals[0];
	    $geominfo{$dev}{'type'} = $vals[1];
	    # size is in bytes, convert to MiB
	    $geominfo{$dev}{'size'} = int($vals[3] / 1024 / 1024);
	    if ($vals[1] eq "DISK") {
		$geominfo{$dev}{'inuse'} = 0;
442 443
	    } else {
		$geominfo{$dev}{'inuse'} = 1;
444 445 446 447 448 449 450
	    }
	}
    } else {
	# FBSD8: no sysctl, have to parse geom output
	my ($curdev,$curpart,$skipping);

	# first find all the disks
451
	if (!open(FD, "$GEOM disk list|")) {
452
	    warn("*** get_diskinfo: could not execute geom command\n");
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
	    return undef;
	}
	while (<FD>) {
	    if (/^\d+\.\s+Name:\s+(\S+)$/) {
		$curdev = $1;
		$geominfo{$curdev}{'level'} = 0;
		$geominfo{$curdev}{'type'} = "DISK";
		$geominfo{$curdev}{'inuse'} = 0;
		next;
	    }
	    if (/\sMediasize:\s+(\d+)\s/) {
		if ($curdev) {
		    $geominfo{$curdev}{'size'} = int($1 / 1024 / 1024);
		    $curdev = undef;
		}
		next;
	    }
	    $curdev = undef;
	}
	close(FD);

	# now find all the partitions on those disks
475
	if (!open(FD, "$GEOM part list|")) {
476
	    warn("*** get_diskinfo: could not execute geom command\n");
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
	    return undef;
	}
	$skipping = 1;
	$curdev = $curpart = undef;
	while (<FD>) {
	    if (/^Geom name:\s+(\S+)/) {
		$curdev = $1;
		if (exists($geominfo{$curdev})) {
		    $skipping = 2;
		}
		next;
	    }
	    next if ($skipping < 2);

	    if (/^Providers:/) {
		$skipping = 3;
		next;
	    }
	    next if ($skipping < 3);

	    if (/^\d+\.\s+Name:\s+(\S+)$/) {
		$curpart = $1;
		$geominfo{$curpart}{'level'} = $geominfo{$curdev}{'level'} + 1;
		$geominfo{$curpart}{'type'} = "PART";
501
		$geominfo{$curpart}{'inuse'} = -1;
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
		next;
	    }
	    if (/\sMediasize:\s+(\d+)\s/) {
		$geominfo{$curpart}{'size'} = int($1 / 1024 / 1024);
		next;
	    }

	    if (/^Consumers:/) {
		$skipping = 1;
		next;
	    }
	}
	close(FD);

	# and finally, vinums
517 518
	if (!$usezfs) {
	    if (!open(FD, "$GEOM vinum list|")) {
519
		warn("*** get_diskinfo: could not execute geom command\n");
520
		return undef;
521
	    }
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
	    $curpart = undef;
	    $skipping = 1;
	    while (<FD>) {
		if (/^Providers:/) {
		    $skipping = 2;
		    next;
		}
		next if ($skipping < 2);

		if (/^\d+\.\s+Name:\s+(\S+)$/) {
		    $curpart = $1;
		    $geominfo{$curpart}{'level'} = 2;
		    $geominfo{$curpart}{'type'} = "VINUM";
		    $geominfo{$curpart}{'inuse'} = -1;
		    next;
		}
		if (/\sMediasize:\s+(\d+)\s/) {
		    $geominfo{$curpart}{'size'} = int($1 / 1024 / 1024);
		    next;
		}
542

543 544 545 546
		if (/^Consumers:/) {
		    $skipping = 1;
		    next;
		}
547
	    }
548 549 550
	    close(FD);
	}
    }
551

552 553 554
    #
    # Note that disks are "in use" if they are part of a zpool.
    #
555 556 557 558 559
    if ($usezfs) {
	my @vdevs = get_zpool_vdevs("emulab");
	foreach my $dev (@vdevs) {
	    if (exists($geominfo{$dev}) && $geominfo{$dev}{'type'} eq "DISK") {
		$geominfo{$dev}{'inuse'} = 1;
560 561
	    }
	}
562 563 564
    }

    #
565 566 567
    # Find any ZFS datasets and their characteristics.
    # Again, FreeBSD 9+ zfs get has a handy "-t filesystem" or "-t volume"
    # option that would allow:
568 569 570 571
    #
    # zfs get -o name,property,value -Hp -t filesystem quota
    # zfs get -o name,property,value -Hp -t volume volsize
    #
572 573 574 575 576 577
    # but FreeBSD 8 does not, so we do:
    #
    # zfs get -o name,property,value -Hp quota,volsize
    #
    # zvols will have a quota of '-', zfses will have a volsize of '-'
    #
578
    if ($usezfs) {
579 580
	if (!open(FD, "$ZFS get -o name,property,value -Hp quota,volsize|")) {
	    warn("*** get_diskinfo: could not execute ZFS command\n");
581 582 583
	    return undef;
	}
	while (<FD>) {
584
	    my ($zdev,$prop,$size) = split /\s/;
585
	    next if ($zdev eq "emulab");
586
	    next if ($size eq "-");
587 588
	    $geominfo{$zdev}{'size'} = int($size / 1024 / 1024);
	    $geominfo{$zdev}{'level'} = 2;
589 590 591 592 593
	    if ($prop eq "quota") {
		$geominfo{$zdev}{'type'} = "ZFS";
	    } else {
		$geominfo{$zdev}{'type'} = "ZVOL";
	    }
594 595
	    $geominfo{$zdev}{'inuse'} = -1;
	}
596 597 598 599 600
	close(FD);
    }

    #
    # Make a pass through and mark disks that are in use where "in use"
601
    # means "has a partition" or is an iSCSI disk.
602 603
    #
    foreach my $dev (keys %geominfo) {
604 605 606 607 608 609
	my $type = $geominfo{$dev}{'type'};
	if ($type eq "DISK" && is_iscsi_dev($dev)) {
	    $geominfo{$dev}{'type'} = "iSCSI";
	    $geominfo{$dev}{'inuse'} = -1;
	}
	elsif ($type eq "PART" && $geominfo{$dev}{'level'} == 1 &&
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
	    $dev =~ /^(.*)s\d+$/) {
	    if (exists($geominfo{$1})) {
		$geominfo{$1}{'inuse'} = 1;
	    }
	}
    }

    return \%geominfo;
}

#
# Handle one-time operations.
# Return a cookie (object) with current state of storage subsystem.
#
sub os_init_storage($)
{
    my ($lref) = @_;
    my $gotlocal = 0;
    my $gotnonlocal = 0;
    my $gotelement = 0;
    my $gotslice = 0;
    my $gotiscsi = 0;
    my $needavol = 0;
    my $needall = 0;

    my %so = ();

637 638 639 640 641 642
    # we rely heavily on GEOM
    if (! -x "$GEOM") {
	warn("*** storage: $GEOM does not exist, cannot continue\n");
	return undef;
    }

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
    foreach my $href (@{$lref}) {
	if ($href->{'CMD'} eq "ELEMENT") {
	    $gotelement++;
	} elsif ($href->{'CMD'} eq "SLICE") {
	    $gotslice++;
	    if ($href->{'BSID'} eq "SYSVOL" ||
		$href->{'BSID'} eq "NONSYSVOL") {
		$needavol = 1;
	    } elsif ($href->{'BSID'} eq "ANY") {
		$needall = 1;
	    }
	}
	if ($href->{'CLASS'} eq "local") {
	    $gotlocal++;
	} else {
	    $gotnonlocal++;
	    if ($href->{'PROTO'} eq "iSCSI") {
		$gotiscsi++;
	    }
	}
    }

    # check for local storage incompatibility
    if ($needall && $needavol) {
	warn("*** storage: Incompatible local volumes.\n");
	return undef;
    }
	
671 672 673 674 675
    # initialize mapping of serial numbers to devices
    if ($gotlocal && $gotelement) {
	$so{'LOCAL_SNMAP'} = init_serial_map();
    }

676 677
    # initialize volume manage if needed for local slices
    if ($gotlocal && $gotslice) {
678 679 680 681 682 683 684 685 686

	# we use ZFS only on 64-bit versions of the OS
	my $usezfs = 0;
	if (-x "$ZPOOL") {
	    my $un = `uname -rm`;
	    if ($un =~ /^(\d+)\.\S+\s+(\S+)/) {
		$usezfs = 1 if ($1 >= 8 && $2 eq "amd64");
	    }
	}
687 688 689
	$so{'USEZFS'} = $usezfs;

	#
690
	# zfs: see if pool already exists, set zfs_enable in /etc/rc.conf.
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
	if ($usezfs) {
	    #
	    # XXX we create the empty SPACEMAP so we don't try to initialize
	    # it later. ZFS never uses the SPACEMAP once the pool is created.
	    #
	    if (is_lvm_initialized(1)) {
		$so{'ZFS_POOLCREATED'} = 1;
		$so{'SPACEMAP'} = ();
	    }

	    if (mysystem("grep -q 'zfs_enable=\"YES\"' /etc/rc.conf")) {
		if (!open(FD, ">>/etc/rc.conf")) {
		    warn("*** storage: could not enable zfs in /etc/rc.conf\n");
		    return undef;
		}
		print FD "# added by $BINDIR/rc/rc.storage\n";
		print FD "zfs_enable=\"YES\"\n";
		close(FD);

		# and do a one-time start
		if (-x "/etc/rc.d/zfs") {
		    mysystem("/etc/rc.d/zfs start");
		}
	    }
716
	}
717

718 719 720 721
	#
	# gvinum: put module load in /boot/loader.conf so that /etc/fstab
	# mounts will work.
	#
722 723 724
	else {
	    if (is_lvm_initialized(0)) {
		$so{'VINUM_DRIVES'} = 1;
725
	    }
726 727 728 729 730 731 732 733
	    if (mysystem("grep -q 'geom_vinum_load=\"YES\"' /boot/loader.conf")) {
		if (!open(FD, ">>/boot/loader.conf")) {
		    warn("*** storage: could not enable gvinum in /boot/loader.conf\n");
		    return undef;
		}
		print FD "# added by $BINDIR/rc/rc.storage\n";
		print FD "geom_vinum_load=\"YES\"\n";
		close(FD);
734

735 736 737
		# and do a one-time start
		mysystem("$GVINUM start");
	    }
738 739 740 741 742 743
	}

	#
	# Grab the bootdisk and current GEOM state
	#
	my $bdisk = get_bootdisk();
744 745
	my $dinfo = get_diskinfo($usezfs);
	if (!exists($dinfo->{$bdisk}) || $dinfo->{$bdisk}->{'inuse'} == 0) {
746 747 748 749
	    warn("*** storage: bootdisk '$bdisk' marked as not in use!?\n");
	    return undef;
	}
	$so{'BOOTDISK'} = $bdisk;
750
	$so{'DISKINFO'} = $dinfo;
751
	if (0) {
752 753 754 755 756 757
	    print STDERR "BOOTDISK='$bdisk'\nUSEZFS='$usezfs'\nDISKINFO=\n";
	    foreach my $dev (keys %$dinfo) {
		my $type = $dinfo->{$dev}->{'type'};
		my $lev = $dinfo->{$dev}->{'level'};
		my $size = $dinfo->{$dev}->{'size'};
		my $inuse = $dinfo->{$dev}->{'inuse'};
758
		print STDERR "name=$dev, type=$type, level=$lev, size=$size, inuse=$inuse\n";
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
	    }
	    return undef;
	}
    }

    if ($gotiscsi) {
	my $redir = ">/dev/null 2>&1";

	if (! -x "$ISCSI") {
	    warn("*** storage: $ISCSI does not exist, cannot continue\n");
	    return undef;
	}

	#
	# XXX load initiator driver
	#
	if (mysystem("kldstat | grep -q iscsi_initiator") &&
	    mysystem("kldload iscsi_initiator.ko $redir")) {
	    warn("*** storage: Could not load iscsi_initiator kernel module\n");
	    return undef;
	}
    }

    $so{'INITIALIZED'} = 1;
    return \%so;
}

#
# os_check_storage(sobject,confighash)
#
#   Determines if the storage unit described by confighash exists and
#   is properly configured. Returns zero if it doesn't exist, 1 if it
#   exists and is correct, -1 otherwise.
#
793
#   Side-effect: Creates the hash member $href->{'LVDEV'} with the /dev
794 795 796 797 798 799
#   name of the storage unit.
#
sub os_check_storage($$)
{
    my ($so,$href) = @_;

800
    if (0) {
801 802 803 804 805 806 807
	my $dinfo = get_diskinfo($so->{'USEZFS'});
	print STDERR "DISKINFO=\n";
	foreach my $dev (keys %$dinfo) {
	    my $type = $dinfo->{$dev}->{'type'};
	    my $lev = $dinfo->{$dev}->{'level'};
	    my $size = $dinfo->{$dev}->{'size'};
	    my $inuse = $dinfo->{$dev}->{'inuse'};
808 809 810 811
	    print STDERR "name=$dev, type=$type, level=$lev, size=$size, inuse=$inuse\n";
	}
    }

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 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
    if ($href->{'CMD'} eq "ELEMENT") {
	return os_check_storage_element($so,$href);
    }
    if ($href->{'CMD'} eq "SLICE") {
	return os_check_storage_slice($so,$href);
    }
    return -1;
}

sub os_check_storage_element($$)
{
    my ($so,$href) = @_;
    my $CANDISCOVER = 0;
    my $redir = ">/dev/null 2>&1";

    #
    # iSCSI:
    #  make sure iscsi_initiator kernel module is loaded
    #  make sure the IQN exists
    #  make sure there is an entry in /etc/iscsi.conf.
    #
    if ($href->{'CLASS'} eq "SAN" && $href->{'PROTO'} eq "iSCSI") {
	my $hostip = $href->{'HOSTIP'};
	my $uuid = $href->{'UUID'};
	my $bsid = $href->{'VOLNAME'};
	my @lines;
	my $cmd;

	#
	# See if the block store exists on the indicated server.
	# If not, something is very wrong, return -1.
	#
	# Note that the server may not support discovery. If not, we don't
	# do it since it is only a sanity check anyway.
	#
	if ($CANDISCOVER) {
	    @lines = `$ISCSI -d -t $hostip 2>&1`;
	    if ($? != 0) {
		warn("*** could not find exported iSCSI block stores\n");
		return -1;
	    }
	    my $taddr = "";
	    for (my $i = 0; $i < scalar(@lines); $i++) {
		# found target, look at next
		if ($lines[$i] =~ /^TargetName=$uuid/ &&
		    $lines[$i+1] =~ /^TargetAddress=($hostip.*)/) {
		    $taddr = $1;
		    last;
		}
	    }
	    if (!$taddr) {
		warn("*** could not find iSCSI block store '$uuid'\n");
		return -1;
	    }
	}

	#
	# See if it is in the config file.
	# If not, we have not done the one-time initialization, return 0.
	#
	if (! -r "$ISCSICNF" || mysystem("grep -q '$uuid' $ISCSICNF")) {
	    return 0;
	}

	#
	# XXX hmm...FreeBSD does not have an /etc/rc.d script for starting
	# up iscontrol instances. So we have to do it everytime right now.
	#
	# First, check and see if there is a session active for this
	# blockstore. If not we must start one.
	#
	my $session = uuid_to_session($uuid);
	if (!defined($session)) {
	    if (mysystem("$ISCSI -c $ISCSICNF -n $bsid $redir")) {
		warn("*** $bsid: could not create iSCSI session\n");
		return -1;
	    }
	    sleep(1);
	    $session = uuid_to_session($uuid);
	}

	#
894
	# Figure out the device name from the session.
895 896
	#
	my $dev = iscsi_to_dev($session);
897 898 899
	if (!defined($dev)) {
	    warn("*** $bsid: found iSCSI session but could not find device\n");
	    return -1;
900
	}
901
	$href->{'LVDEV'} = "/dev/$dev";
902 903

	#
904
	# If there is a mount point, see if it is mounted.
905
	#
906 907 908 909 910 911 912 913 914
	# XXX because mounts in /etc/fstab happen before iSCSI and possibly
	# even the network are setup, we don't put our mounts there as we
	# do for local blockstores. Thus, if the blockstore device is not
	# mounted, we do it here.
	#
	my $mpoint = $href->{'MOUNTPOINT'};
	if ($mpoint) {
	    my $line = `$MOUNT | grep '^/dev/$dev on '`;
	    if (!$line) {
915 916 917 918 919 920 921 922 923
		my $mopt = "";
		my $fopt = "-p";

		# check for RO export and adjust options accordingly
		if (exists($href->{'PERMS'}) && $href->{'PERMS'} eq "RO") {
		    $mopt = "-o ro";
		    $fopt = "-n";
		}

924 925 926 927 928 929
		# the mountpoint should exist
		if (! -d "$mpoint") {
		    warn("*** $bsid: no mount point $mpoint\n");
		    return -1;
		}
		# fsck it in case of an abrupt shutdown
930
		if (mysystem("$FSCK $fopt -t ufs /dev/$dev $redir")) {
931
		    warn("*** $bsid: fsck of /dev/$dev failed\n");
932 933
		    return -1;
		}
934
		if (mysystem("$MOUNT $mopt -t ufs /dev/$dev $mpoint $redir")) {
935 936 937 938 939 940 941 942 943 944 945
		    warn("*** $bsid: could not mount /dev/$dev on $mpoint\n");
		    return -1;
		}
	    }
	    elsif ($line !~ /^\/dev\/$dev on (\S+) / || $1 ne $mpoint) {
		warn("*** $bsid: mounted on $1, should be on $mpoint\n");
		return -1;
	    }
	}

	return 1;
946 947 948 949 950 951 952 953 954 955
    }

    #
    # local disk:
    #  make sure disk exists
    #
    if ($href->{'CLASS'} eq "local") {
	my $bsid = $href->{'VOLNAME'};
	my $sn = $href->{'UUID'};

956
	my $dev = serial_to_dev($so, $sn);
957
	if (defined($dev)) {
958
	    $href->{'LVDEV'} = "/dev/$dev";
959 960 961
	    return 1;
	}

962 963 964 965 966
	# XXX not an error for now, until we can be sure that we can
	# get SN info for all disks
	$href->{'LVDEV'} = "<UNKNOWN>";
	return 1;

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
	# for physical disks, there is no way to "create" it so return error
	warn("*** $bsid: could not find HD with serial '$sn'\n");
	return -1;
    }

    warn("*** $bsid: unsupported class/proto '" .
	 $href->{'CLASS'} . "/" . $href->{'PROTO'} . "'\n");
    return -1;
}

#
# Return 0 if does not exist
# Return 1 if exists and correct
# Return -1 otherwise
#
sub os_check_storage_slice($$)
{
    my ($so,$href) = @_;
    my $bsid = $href->{'BSID'};

    #
    # local storage:
    #  if BSID==SYSVOL:
    #    see if 4th part of boot disk exists (eg: da0s4) and
    #    is of type freebsd
    #  else if BSID==NONSYSVOL:
    #    see if there is a concat volume with appropriate name
    #  else if BSID==ANY:
    #    see if there is a concat volume with appropriate name
    #  if there is a mountpoint, see if it exists in /etc/fstab
    #
    # List all volumes:
    #   gvinum lv
    #
    #
    if ($href->{'CLASS'} eq "local") {
	my $lv = $href->{'VOLNAME'};
1004
	my ($dev, $devtype, $mdev, $slop);
1005

1006
	my $dinfo = $so->{'DISKINFO'};
1007 1008 1009 1010 1011 1012 1013 1014
	my $bdisk = $so->{'BOOTDISK'};

	# figure out the device of interest
	if ($bsid eq "SYSVOL") {
	    $dev = "${bdisk}s4";
	    $mdev = "${dev}a";
	    $devtype = "PART";
	} else {
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
	    if ($so->{'USEZFS'}) {
		$dev = "emulab/$lv";
		if ($href->{'MOUNTPOINT'}) {
		    # XXX
		    $mdev = $dev;
		    $devtype = "ZFS";
		} else {
		    $mdev = "zvol/emulab/$lv";
		    $devtype = "ZVOL";
		}
1025
		$slop = 0;
1026 1027 1028
	    } else {
		$dev = $mdev = "gvinum/$lv";
		$devtype = "VINUM";
1029 1030 1031 1032 1033 1034
		#
		# XXX due to round-off when allocating space from individual
		# gvinum drives, the actual size could be larger than what
		# was requested by up to 1MiB per disk.
		#
		$slop = scalar(get_vinum_drives());
1035
	    }
1036 1037 1038 1039
	}
	my $devsize = $href->{'VOLSIZE'};

	# if the device does not exist, return 0
1040
	if (!exists($dinfo->{$dev})) {
1041 1042 1043
	    return 0;
	}
	# if it exists but is of the wrong type, we have a problem!
1044
	my $atype = $dinfo->{$dev}->{'type'};
1045 1046 1047 1048 1049
	if ($atype ne $devtype) {
	    warn("*** $lv: actual type ($atype) != expected type ($devtype)\n");
	    return -1;
	}
	# ditto for size, unless this is the SYSVOL where we ignore user size
1050
	# or if the size was not specified.
1051 1052 1053
	my $asize = $dinfo->{$dev}->{'size'};
	if ($bsid ne "SYSVOL" && $devsize &&
	    !($asize >= $devsize && $asize <= $devsize + $slop)) {
1054 1055 1056 1057 1058 1059
	    warn("*** $lv: actual size ($asize) != expected size ($devsize)\n");
	    return -1;
	}

	# if there is a mountpoint, make sure it is mounted
	my $mpoint = $href->{'MOUNTPOINT'};
1060
	if ($mpoint && $devtype ne "ZFS") {
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
	    my $line = `$MOUNT | grep '^/dev/$mdev on '`;
	    if (!$line) {
		warn("*** $lv: is not mounted, should be on $mpoint\n");
		return -1;
	    }
	    if ($line !~ /^\/dev\/$mdev on (\S+) / || $1 ne $mpoint) {
		warn("*** $lv: mounted on $1, should be on $mpoint\n");
		return -1;
	    }
	}

1072 1073 1074 1075
	if ($devtype ne "ZFS") {
	    $mdev = "/dev/$mdev";
	}
	$href->{'LVDEV'} = "$mdev";
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
	return 1;
    }

    warn("*** $bsid: unsupported class '" . $href->{'CLASS'} . "'\n");
    return -1;
}

#
# os_create_storage(confighash)
#
#   Create the storage unit described by confighash. Unit must not exist
#   (os_check_storage should be called first to verify). Return one on
#   success, zero otherwise.
#
sub os_create_storage($$)
{
    my ($so,$href) = @_;
1093
    my $rv = 0;
1094

1095 1096 1097 1098
    # record all the output for debugging
    my $log = "/var/emulab/logs/" . $href->{'VOLNAME'} . ".out";
    mysystem("cp /dev/null $log");

1099
    if ($href->{'CMD'} eq "ELEMENT") {
1100
	$rv = os_create_storage_element($so, $href, $log);
1101
    }
1102
    elsif ($href->{'CMD'} eq "SLICE") {
1103
	$rv = os_create_storage_slice($so, $href, $log);
1104
    }
1105 1106 1107 1108
    if ($rv == 0) {
	return 0;
    }

1109 1110 1111
    my $mopt = "";
    my $fopt = "-p";

1112 1113 1114
    if (exists($href->{'MOUNTPOINT'}) && !exists($href->{'MOUNTED'})) {
	my $lv = $href->{'VOLNAME'};
	my $mdev = $href->{'LVDEV'};
1115 1116 1117 1118 1119 1120 1121 1122

	# record all the output for debugging
	my $redir = "";
	my $logmsg = "";
	if ($log) {
	    $redir = ">>$log 2>&1";
	    $logmsg = ", see $log";
	}
1123 1124

	#
1125 1126 1127
	# If this is a persistent iSCSI disk, we never create the filesystem!
	# Instead, we fsck it in case it was not shutdown cleanly in its
	# previous existence.
1128
	#
1129 1130
	if ($href->{'CLASS'} eq "SAN" && $href->{'PROTO'} eq "iSCSI" &&
	    $href->{'PERSIST'} != 0) {
1131 1132 1133 1134 1135 1136
	    # check for RO export and adjust options accordingly
	    if (exists($href->{'PERMS'}) && $href->{'PERMS'} eq "RO") {
		$mopt = "-o ro";
		$fopt = "-n";
	    }
	    if (mysystem("$FSCK $fopt -t ufs $mdev $redir")) {
1137 1138 1139 1140 1141 1142 1143 1144
		warn("*** $lv: fsck of persistent store $mdev failed\n");
		return 0;
	    }
	}
	#
	# Otherwise, create the filesystem
	#
	elsif (mysystem("$MKFS -b $UFSBS $mdev $redir")) {
1145
	    warn("*** $lv: could not create FS$logmsg\n");
1146 1147 1148 1149 1150 1151 1152
	    return 0;
	}

	#
	# Mount the filesystem
	#
	my $mpoint = $href->{'MOUNTPOINT'};
1153 1154
	if (! -d "$mpoint" && mysystem("$MKDIR -p $mpoint $redir")) {
	    warn("*** $lv: could not create mountpoint '$mpoint'$logmsg\n");
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
	    return 0;
	}

	#
	# XXX because mounts in /etc/fstab happen before iSCSI and possibly
	# even the network are setup, we don't put our mounts there as we
	# do for local blockstores. Instead, the check_storage call will
	# take care of these mounts.
	#
	if (!($href->{'CLASS'} eq "SAN" && $href->{'PROTO'} eq "iSCSI")) {
	    if (!open(FD, ">>/etc/fstab")) {
		warn("*** $lv: could not add mount to /etc/fstab\n");
		return 0;
	    }
1169
	    print FD "# $mdev added by $BINDIR/rc/rc.storage\n";
1170
	    print FD "$mdev\t$mpoint\tufs\trw\t2\t2\n";
1171 1172
	    close(FD);
	    if (mysystem("$MOUNT $mpoint $redir")) {
1173
		warn("*** $lv: could not mount on $mpoint$logmsg\n");
1174 1175 1176
		return 0;
	    }
	} else {
1177
	    if (mysystem("$MOUNT $mopt -t ufs $mdev $mpoint $redir")) {
1178
		warn("*** $lv: could not mount $mdev on $mpoint$logmsg\n");
1179 1180 1181 1182 1183 1184
		return 0;
	    }
	}
    }

    return 1;
1185 1186
}

1187
sub os_create_storage_element($$$)
1188
{
1189
    my ($so,$href,$log) = @_;
1190 1191 1192 1193 1194 1195 1196

    if ($href->{'CLASS'} eq "SAN" && $href->{'PROTO'} eq "iSCSI") {
	my $hostip = $href->{'HOSTIP'};
	my $uuid = $href->{'UUID'};
	my $bsid = $href->{'VOLNAME'};
	my $cmd;

1197
	# record all the output for debugging
1198 1199 1200 1201 1202 1203
	my $redir = "";
	my $logmsg = "";
	if ($log) {
	    $redir = ">>$log 2>&1";
	    $logmsg = ", see $log";
	}
1204

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
	#
	# Handle one-time setup of /etc/iscsi.conf.
	#
	if (! -r "$ISCSICNF" || mysystem("grep -q '$uuid' $ISCSICNF $redir")) {
	    if (!open(FD, ">>$ISCSICNF")) {
		warn("*** could not update $ISCSICNF\n");
		return 0;
	    }
	    my $hname = `hostname`;
	    chomp($hname);
	    print FD <<EOF;
$bsid {
    initiatorname = $hname
    targetname    = $uuid
    targetaddress = $hostip
}
EOF
	    close(FD);   
	} else {
	    warn("*** $bsid: trying to create but already exists!?\n");
	    return 0;
        }

	#
	# Everything has been setup, start the daemon.
	#
	if (mysystem("$ISCSI -c $ISCSICNF -n $bsid $redir")) {
	    warn("*** $bsid: could not create iSCSI session\n");
	    return 0;
	}
	sleep(1);

	#
	# Find the session ID and device name.
	#
	my $session = uuid_to_session($uuid);
	if (!defined($session)) {
	    warn("*** $bsid: could not find iSCSI session\n");
	    return 0;
	}
	my $dev = iscsi_to_dev($session);
	if (!defined($dev)) {
	    warn("*** $bsid: could not map iSCSI session to device\n");
	    return 0;
	}

1251
	$href->{'LVDEV'} = "/dev/$dev";
1252 1253 1254 1255 1256 1257 1258
	return 1;
    }

    warn("*** Only support SAN/iSCSI now\n");
    return 0;
}

1259
sub os_create_storage_slice($$$)
1260
{
1261
    my ($so,$href,$log) = @_;
1262 1263 1264 1265 1266 1267 1268 1269 1270
    my $bsid = $href->{'BSID'};

    #
    # local storage:
    #  if BSID==SYSVOL:
    #     create the 4th part of boot disk with type freebsd,
    #	  create a native filesystem (that imagezip would understand).
    #  else if BSID==NONSYSVOL:
    #	  make sure partition 1 exists on all disks and each has type
1271
    #	  freebsd, create stripe or concat volume with appropriate name
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    #  else if BSID==ANY:
    #	  make sure all partitions exist (4 on sysvol, 1 on all others)
    #     and have type freebsd, create a concat volume with appropriate
    #	  name across all available disks
    #  if there is a mountpoint:
    #     create a filesystem on device, mount it, add to /etc/fstab
    #
    if ($href->{'CLASS'} eq "local") {
	my $lv = $href->{'VOLNAME'};
	my $lvsize = $href->{'VOLSIZE'};
	my $mdev = "";

	my $bdisk = $so->{'BOOTDISK'};
1285
	my $dinfo = $so->{'DISKINFO'};
1286 1287

	# record all the output for debugging
1288 1289 1290 1291 1292 1293
	my $redir = "";
	my $logmsg = "";
	if ($log) {
	    $redir = ">>$log 2>&1";
	    $logmsg = ", see $log";
	}
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305

	#
	# System volume:
	#
	# gpart add -i 4 -t freebsd da0
	# gpart create -s BSD da0s4
	# gpart add -t freebsd-ufs da0s4
	#
	if ($bsid eq "SYSVOL") {
	    my $slice = "$bdisk" . "s4";
	    my $part = "$slice" . "a";

1306
	    if (mysystem("$GPART add -i 4 -t freebsd $bdisk $redir")) {
1307 1308 1309
		warn("*** $lv: could not create $slice$logmsg\n");
		return 0;
	    }
1310 1311
	    if (mysystem("$GPART create -s BSD $slice $redir") ||
		mysystem("$GPART add -t freebsd-ufs $slice $redir")) {
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
		warn("*** $lv: could not create $part$logmsg\n");
		return 0;
	    }
	    $mdev = $part;
	}

	#
	# Non-system volume or all space.
	#
	else {
	    #
	    # If partitions have not yet been initialized handle that:
	    #
	    # gpart add -i 4 -t freebsd da0	(ANY only)
	    # gpart create -s mbr da1
	    # gpart add -i 1 -t freebsd da1
	    #
1329
	    if (!exists($so->{'SPACEMAP'})) {
1330 1331
		my %spacemap = ();

1332 1333 1334 1335 1336
		if (exists($so->{'VINUM_DRIVES'})) {
		    foreach my $vdev (get_vinum_drives()) {
			if ($vdev =~ /^(.*)s(\d+)$/) {
			    $spacemap{$1}{'pnum'} = $2;
			}
1337 1338
		    }
		}
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
		else {
		    if ($bsid eq "ANY") {
			$spacemap{$bdisk}{'pnum'} = 4;
		    }
		    foreach my $dev (keys %$dinfo) {
			if ($dinfo->{$dev}->{'type'} eq "DISK" &&
			    $dinfo->{$dev}->{'inuse'} == 0) {
			    $spacemap{$dev}{'pnum'} = 0;
			}
		    }
		    if (keys(%spacemap) == 0) {
			warn("*** $lv: no space found\n");
			return 0;
		    }
1353 1354

		    #
1355
		    # Create partitions on each disk
1356
		    #
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
		    foreach my $disk (keys %spacemap) {
			my $pnum = $spacemap{$disk}{'pnum'};

			#
			# If pnum==0, we need an MBR first
			#
			if ($pnum == 0) {
			    if (mysystem("$GPART create -s mbr $disk $redir")) {
				warn("*** $lv: could not create MBR on $disk$logmsg\n");
				return 0;
			    }
			    $pnum = $spacemap{$disk}{'pnum'} = 1;
			}
			if (mysystem("$GPART add -i $pnum -t freebsd $disk $redir")) {
			    warn("*** $lv: could not create ${disk}s${pnum}$logmsg\n");
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
			    return 0;
			}
		    }
		}

		#
		# Refresh GEOM info and see how much space is available on
		# our disk partitions.
		# XXX we allow some time for changes to take effect.
		#
		sleep(1);
1383
		$dinfo = $so->{'DISKINFO'} = get_diskinfo($so->{'USEZFS'});
1384 1385

		my $total_size = 0;
1386
		my ($min_s,$max_s);
1387 1388
		foreach my $disk (keys %spacemap) {
		    my $part = $disk . "s" . $spacemap{$disk}{'pnum'};
1389 1390
		    if (!exists($dinfo->{$part}) ||
			$dinfo->{$part}->{'type'} ne "PART") {
1391 1392 1393
			warn("*** $lv: created partitions are wrong!?\n");
			return 0;
		    }
1394
		    my $dsize = $dinfo->{$part}->{'size'};
1395 1396 1397 1398
		    $spacemap{$disk}{'size'} = $dsize;
		    $total_size += $dsize;
		    $min_s = $dsize if (!defined($min_s) || $dsize < $min_s);
		    $max_s = $dsize if (!defined($max_s) || $dsize > $max_s);
1399 1400
		}

1401 1402 1403 1404
		#
		# See if we can stripe on the available devices.
		# XXX conservative right now, require all to be the same size.
		#
1405 1406
		if (scalar(keys(%spacemap)) > 1 &&
		    defined($min_s) && $min_s == $max_s) {
1407 1408 1409
		    $so->{'STRIPESIZE'} = $min_s;
		}

1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
		if (0) {
		    print STDERR "DISKINFO=\n";
		    foreach my $dev (keys %$dinfo) {
			my $type = $dinfo->{$dev}->{'type'};
			my $lev = $dinfo->{$dev}->{'level'};
			my $size = $dinfo->{$dev}->{'size'};
			my $inuse = $dinfo->{$dev}->{'inuse'};
			print STDERR "  name=$dev, type=$type, level=$lev, size=$size, inuse=$inuse\n";
		    }
		    my $ssize = "-";
		    if (defined($so->{'STRIPESIZE'})) {
			$ssize = $so->{'STRIPESIZE'};
		    }
		    print STDERR "total/stripe/min/max $total_size/$ssize/$min_s/$max_s, SPACEMAP=\n";
		    foreach my $disk (keys %spacemap) {
			my $pnum = $spacemap{$disk}{'pnum'};
			my $size = $spacemap{$disk}{'size'};
			print STDERR "  disk=$disk, pnum=$pnum, size=$size\n";
		    }
		}

1431 1432
		$so->{'SPACEAVAIL'} = $total_size;
		$so->{'SPACEMAP'} = \%spacemap;
1433
	    }
1434 1435
	    my $space = $so->{'SPACEMAP'};
	    my $total_size = $so->{'SPACEAVAIL'};
1436 1437

	    #
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
	    # ZFS: put all available space into a zpool, create zfs/zvol
	    # from that:
	    #
	    # zpool create -m none emulab /dev/da0s4 /dev/da1s1	(ANY)
	    # zpool create -m none emulab /dev/da1s1		(NONSYSVOL)
	    #
	    # zfs create -o mountpoint=/mnt -o quota=100M emulab/h2d2 (zfs)
	    # zfs create -b 64K -V 100M emulab/h2d2		      (zvol)
	    #
	    if ($so->{'USEZFS'}) {
		if (!exists($so->{'ZFS_POOLCREATED'})) {
1449 1450 1451 1452 1453
		    my @parts = ();
		    foreach my $disk (sort keys %$space) {
			my $pdev = $disk . "s" . $space->{$disk}->{'pnum'};
			push(@parts, $pdev);
		    }
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
		    if (mysystem("$ZPOOL create -f -m none emulab @parts $redir")) {
			warn("*** $lv: could not create ZFS pool$logmsg\n");
			return 0;
		    }
		    $so->{'ZFS_POOLCREATED'} = 1;
		}

		#
		# If a mountpoint is specified, create a ZFS filesystem
		# and mount it.
		#
		if (exists($href->{'MOUNTPOINT'})) {
		    my $opts = "-o mountpoint=" . $href->{'MOUNTPOINT'};
		    if ($lvsize > 0) {
			$opts .= " -o quota=${lvsize}M";
		    }
		    if (mysystem("$ZFS create $opts emulab/$lv")) {
			warn("*** $lv: could not create ZFS$logmsg\n");
			return 0;
		    }
		    $mdev = "emulab/$lv";
		    $href->{'MOUNTED'} = 1;
		} else {
		    #
		    # No size specified, use the free size of the pool.
		    # XXX Ugh, we have to parse out the available space of
		    # the root zfs and then leave some slop (5%).
		    #
		    if (!$lvsize) {
			my $line = `$ZFS get -Hp -o value avail emulab 2>/dev/null`;
			if ($line =~ /^(\d+)/) {
			    $lvsize = int(($1 * 0.95) / 1024 / 1024);
			}
			if (!$lvsize) {
			    warn("*** $lv: could not find size of pool\n");
			    return 0;
			}
		    }
		    my $opts = "-b $ZVOLBS -V ${lvsize}M";
		    if (mysystem("$ZFS create $opts emulab/$lv")) {
			warn("*** $lv: could not create ZFS$logmsg\n");
			return 0;
		    }
		    $mdev = "emulab/$lv";
		}
	    }

	    #
	    # VINUM: create a gvinum for the volume using the available space:
1503 1504
	    #
	    # cat > /tmp/h2d2.conf
1505 1506
	    # drive emulab_da0s4 device /dev/da0s4 (ANY only)
	    # drive emulab_da1s1 device /dev/da1s1
1507 1508
	    # volume h2d2
	    #   plex org concat
1509 1510
	    #     sd length NNNm drive emulab_da0s4 (ANY only)
	    #     sd length NNNm drive emulab_da1s1
1511 1512 1513
	    #
	    # gvinum create /tmp/h2d2.conf
	    #
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
	    else {
		#
		# See if we can stripe.
		# Take the same amount from each volume.
		#
		my $style;
		if (defined($so->{'STRIPESIZE'})) {
		    my $maxstripe = $so->{'STRIPESIZE'};
		    my $ndisks = scalar(keys %$space);
		    my $perdisk;
		    if ($lvsize > 0) {
			$perdisk = int(($lvsize / $ndisks) + 0.5);
		    } else {
			$perdisk = $maxstripe;
		    }
		    if ($perdisk <= $maxstripe) {
			foreach my $disk (keys %$space) {
			    $space->{$disk}->{'vsize'} = $perdisk;
			}
			$lvsize = $ndisks * $perdisk;
			$style = "striped $VINUMSS";
		    }
		}
1537

1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
		#
		# Otherwise we must concatonate.
		# Figure out how much space to take from each disk for this
		# volume. We take proportionally from each.
		#
		if (!$style) {
		    foreach my $disk (keys %$space) {
			if ($lvsize > 0) {
			    my $frac = $space->{$disk}->{'size'} / $total_size;
			    $space->{$disk}->{'vsize'} =
				int(($lvsize * $frac) + 0.5);
			} else {
			    $space->{$disk}->{'vsize'} =
				$space->{$disk}->{'size'};
			}
		    }
		    if ($lvsize == 0) {
			$lvsize = $total_size;
		    }
		    $style = "concat";
		}
1559

1560 1561 1562 1563 1564 1565 1566 1567 1568
		#
		# Create the gvinum config file.
		#
		my $cfile = "/tmp/$lv.conf";
		unlink($cfile);
		if (!open(FD, ">$cfile")) {
		    warn("*** $lv: could not create gvinum config\n");
		    return 0;
		}
1569
		if (!exists($so->{'VINUM_DRIVES'})) {
1570 1571
		    foreach my $disk (keys %$space) {
			my $pdev = $disk . "s" . $space->{$disk}->{'pnum'};
1572
			print FD "drive emulab_$pdev device /dev/$pdev\n";
1573 1574 1575 1576
		    }
		}
		print FD "volume $lv\n";
		print FD "  plex org $style\n";
1577 1578
		foreach my $disk (keys %$space) {
		    my $pdev = $disk . "s" . $space->{$disk}->{'pnum'};
1579
		    my $sdsize = $space->{$disk}->{'vsize'};
1580
		    print FD "    sd length ${sdsize}m drive emulab_$pdev\n";
1581
		}
1582
		close(FD);
1583

1584 1585 1586 1587 1588 1589
		# create the vinum
		if (mysystem("$GVINUM create $cfile $redir")) {
		    warn("*** $lv: could not create vinum$logmsg\n");
		    unlink($cfile);
		    return 0;
		}
1590
		#unlink($cfile);
1591

1592 1593
		# vinum drives exist at this point
		$so->{'VINUM_DRIVES'} = 1;
1594

1595 1596
		# XXX need some delay before accessing device?
		sleep(1);
1597

1598 1599
		$mdev = "gvinum/$lv";
	    }
1600 1601 1602 1603 1604
	}

	#
	# Update the geom info to reflect new devices
	#
1605 1606
	$dinfo = $so->{'DISKINFO'} = get_diskinfo($so->{'USEZFS'});
	if (!exists($dinfo->{$mdev})) {
1607 1608 1609 1610
	    warn("*** $lv: blockstore did not get created!?\n");
	    return 0;
	}

1611 1612 1613 1614
	if (!$href->{'MOUNTED'}) {
	    $mdev = "/dev/$mdev";
	}
	$href->{'LVDEV'} = $mdev;
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
	return 1;
    }

    warn("*** $bsid: unsupported class '" . $href->{'CLASS'} . "'\n");
    return 0;
}

sub os_remove_storage($$$)
{
    my ($so,$href,$teardown) = @_;

    if ($href->{'CMD'} eq "ELEMENT") {
	return os_remove_storage_element($so, $href, $teardown);
    }
    if ($href->{'CMD'} eq "SLICE") {
	return os_remove_storage_slice($so, $href, $teardown);
    }
    return 0;
}

sub os_remove_storage_element($$$)
{
    my ($so,$href,$teardown) = @_;
    #my $redir = "";
    my $redir = ">/dev/null 2>&1";

    if ($href->{'CLASS'} eq "SAN" && $href->{'PROTO'} eq "iSCSI") {
	my $uuid = $href->{'UUID'};
	my $bsid = $href->{'VOLNAME'};

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
	#
	# Unmount it
	#
	if (exists($href->{'MOUNTPOINT'})) {
	    my $mpoint = $href->{'MOUNTPOINT'};

	    if (mysystem("$UMOUNT $mpoint")) {
		warn("*** $bsid: could not unmount $mpoint\n");
	    }
	}

1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
	#
	# Find the daemon instance and HUP it.
	# XXX continue even if we could not kill it.
	#
	my $pid = uuid_to_daemonpid($uuid);
	if (defined($pid)) {
	    if (mysystem("kill -HUP $pid $redir")) {
		warn("*** $bsid: could not kill $ISCSI daemon\n");
	    }
	}

	#
	# Remove /etc/iscsi.conf entry for block store
	#
	if ($teardown && !mysystem("grep -q '$uuid' $ISCSICNF $redir")) {
	    if (open(OFD, "<$ISCSICNF") && open(NFD, ">$ISCSICNF.new")) {
		# parser!? we don't need no stinkin parser...
		my $inentry = 0;
		while (<OFD>) {
		    if (/^$bsid {/) {
			$inentry = 1;
			next;
		    }
		    if ($inentry && /^}/) {
			$inentry = 0;
			next;
		    }
		    if (!$inentry) {
			print NFD $_;
		    }
		}
		close(OFD);
		close(NFD);
		if (mysystem("mv -f $ISCSICNF.new $ISCSICNF")) {
		    warn("*** $bsid: could not update $ISCSICNF\n");
		    return 0;
		}
	    }
	}
	return 1;
    }

    #
    # Nothing to do (yet) for a local disk
    #
    if ($href->{'CLASS'} eq "local") {
	return 1;
    }

    warn("*** Only support SAN/iSCSI now\n");
    return 0;
}

#
# teardown==0 means we are rebooting: unmount and shutdown gvinum
# teardown==1 means we are reconfiguring and will be destroying everything
#
sub os_remove_storage_slice($$$)
{
    my ($so,$href,$teardown) = @_;

    if ($href->{'CLASS'} eq "local") {
	my $bsid = $href->{'BSID'};
	my $lv = $href->{'VOLNAME'};

1721
	my $dinfo = $so->{'DISKINFO'};
1722 1723 1724 1725 1726 1727 1728 1729
	my $bdisk = $so->{'BOOTDISK'};

	# figure out the device of interest
	my ($dev, $devtype);
	if ($bsid eq "SYSVOL") {
	    $dev = "${bdisk}s4a";
	    $devtype = "PART";
	} else {
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
	    if ($so->{'USEZFS'}) {
		$dev = "emulab/$lv";
		if ($href->{'MOUNTPOINT'}) {
		    $devtype = "ZFS";
		} else {
		    $devtype = "ZVOL";
		}
	    } else {
		$dev = "gvinum/$lv";
		$devtype = "VINUM";
	    }
1741 1742 1743
	}

	# if the device does not exist, we have a problem!
1744
	if (!exists($dinfo->{$dev})) {
1745 1746 1747 1748
	    warn("*** $lv: device '$dev' does not exist\n");
	    return 0;
	}
	# ditto if it exists but is of the wrong type
1749
	my $atype = $dinfo->{$dev}->{'type'};
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
	if ($atype ne $devtype) {
	    warn("*** $lv: actual type ($atype) != expected type ($devtype)\n");
	    return 0;
	}

	# record all the output for debugging
	my $log = "/var/emulab/logs/$lv.out";
	my $redir = ">>$log 2>&1";
	my $logmsg = ", see $log";
	mysystem("cp /dev/null $log");

	#
	# Unmount and remove mount info from fstab.
	#
	# On errors, we warn but don't stop. We do everything in our
	# power to take things down.
	#
1767
	if (exists($href->{'MOUNTPOINT'}) && $devtype ne "ZFS") {
1768 1769 1770 1771 1772 1773 1774 1775 1776
	    my $mpoint = $href->{'MOUNTPOINT'};

	    if (mysystem("$UMOUNT $mpoint")) {
		warn("*** $lv: could not unmount $mpoint\n");
	    }

	    if ($teardown) {
		my $tdev = "/dev/$dev";
		$tdev =~ s/\//\\\//g;
1777
		if (mysystem("sed -E -i -e '/^(# )?$tdev/d' /etc/fstab")) {
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
		    warn("*** $lv: could not remove mount from /etc/fstab\n");
		}
	    }
	}

	#
	# Remove LV
	#
	if ($teardown) {
	    #
	    # System volume:
	    #
	    # gpart destroy -F da0s4
	    # gpart delete -i 4 da0
	    #
	    if ($bsid eq "SYSVOL") {
		my $slice = "$bdisk" . "s4";

1796
		if (mysystem("$GPART destroy -F $slice $redir")) {
1797 1798
		    warn("*** $lv: could not destroy ${slice}a$logmsg\n");
		}
1799
		if (mysystem("$GPART delete -i 4 $bdisk $redir")) {
1800 1801 1802 1803 1804 1805
		    warn("*** $lv: could not destroy $slice$logmsg\n");
		}
		return 1;
	    }

	    #
1806
	    # Other, ZFS:
1807
	    #
1808
	    #   zfs destroy emulab/h2d2
1809
	    #
1810 1811 1812 1813
	    if ($so->{'USEZFS'}) {
		if (mysystem("$ZFS destroy emulab/$lv $redir")) {
		    warn("*** $lv: could not destroy$logmsg\n");
		}
1814

1815 1816 1817 1818 1819 1820 1821 1822
		#
		# If no volumes left:
		#
		#   zpool destroy emulab
		#
		#   gpart delete -i 4 da0 (ANY only)
		#   gpart destroy -F da1
		#
1823 1824
		my @vols = get_zpool_datasets("emulab");
		if (@vols > 0) {
1825 1826
		    return 1;
		}
1827

1828 1829 1830
		#
		# find devices that are a part of the pool
		#
1831 1832 1833
		my @slices = get_zpool_vdevs("emulab");
		if (@slices == 0) {
		    warn("*** $lv: could not find components of zpool\n");
1834
		}
1835

1836 1837 1838 1839 1840 1841
		#
		# Destroy the pool
		#
		if (mysystem("$ZPOOL destroy emulab $redir")) {
		    warn("*** $lv: could not destroy$logmsg\n");
		}
1842

1843 1844 1845 1846
		#
		# And de-partition the disks
		#
		foreach my $slice (@slices) {
1847
		    if ($slice eq "${bdisk}s4") {
1848
			if (mysystem("$GPART delete -i 4 $bdisk $redir")) {
1849 1850
			    warn("*** $lv: could not destroy $slice$logmsg\n");
			}
1851
		    } elsif ($slice =~ /^(.*)s1$/) {
1852 1853
			my $disk = $1;
			if ($disk eq $bdisk ||
1854
			    mysystem("$GPART destroy -F $disk $redir")) {
1855 1856 1857 1858
			    warn("*** $lv: could not destroy $slice$logmsg\n");
			}
		    }
		}
1859 1860 1861 1862 1863 1864 1865 1866 1867

		#
		# If we are the one that enabled ZFS, disable it
		#
		if (!mysystem("grep -q '^# added by.*rc.storage' /etc/rc.conf")) {
		    if (mysystem("sed -i -e '/^# added by.*rc.storage/,+1d' /etc/rc.conf")) {
			warn("*** $lv: could not remove zfs_enable from /etc/rc.conf\n");
		    }
		}
1868
	    }
1869 1870 1871 1872 1873 1874 1875 1876 1877
	    #
	    # Other, gvinum volume:
	    #
	    #   gvinum rm -r h2d2
	    #
	    else {
		if (mysystem("$GVINUM rm -r $lv $redir")) {
		    warn("*** $lv: could not destroy$logmsg\n");
		}
1878

1879 1880 1881
		#
		# If no volumes left:
		#
1882 1883
		#   gvinum rm -r emulab_da0s4 (ANY only)
		#   gvinum rm -r emulab_da1s1
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
		#
		#   gpart delete -i 4 da0 (ANY only)
		#   gpart destroy -F da1
		#
		my $line = `$GVINUM lv | grep 'volumes:'`;
		chomp($line);
		if (!$line || $line !~ /^0 volumes:/) {
		    return 1;
		}

1894 1895 1896 1897 1898 1899 1900 1901
		my @drives = get_vinum_drives();
		foreach my $slice (@drives) {
		    if (mysystem("$GVINUM rm emulab_$slice $redir")) {
			warn("*** $lv: could not destroy drive emulab_$slice$logmsg\n");
		    }
		    if ($slice eq "${bdisk}s4") {
			if (mysystem("$GPART delete -i 4 $bdisk $redir")) {
			    warn("*** $lv: could not destroy $slice$logmsg\n");
1902
			}
1903 1904 1905 1906 1907
		    } elsif ($slice =~ /^(.*)s1$/) {
			my $disk = $1;
			if ($disk eq $bdisk ||
			    mysystem("$GPART destroy -F $disk $redir")) {
			    warn("*** $lv: could not destroy $slice$logmsg\n");
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
			}
		    }
		}

		if (mysystem("$GVINUM stop $redir")) {
		    warn("*** $lv: could not stop gvinum$logmsg\n");
		}
		if (mysystem("sed -i -e '/^# added by.*rc.storage/,+1d' /boot/loader.conf")) {
		    warn("*** $lv: could not remove vinum load from /boot/loader.conf\n");
		}
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
	    }
	}

	return 1;
    }

    return 0;
}

sub mysystem($)
{
    my ($cmd) = @_;
    if (0) {
	print STDERR "CMD: $cmd\n";
    }
    return system($cmd);
}

sub mybacktick($)
{
    my ($cmd) = @_;
    if (0) {
	print STDERR "CMD: $cmd\n";
    }
    return `$cmd`;
}

1;