libvnode_blockstore.pm 42.2 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2013-2016 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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
# 
# {{{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/>.
# 
# }}}
#
# Implements the libvnode API for blockstore pseudo-VMs on FreeNAS 8
#
# Note that there is no distinguished first or last call of this library
# in the current implementation.  Every vnode creation (through mkvnode.pl)
# will invoke all the root* and vnode* functions.  It is up to us to make
# sure that "one time" operations really are executed only once.
#
# Some notes about the current implementation in this module:
#
# * No module-specific persistent state
#
#  This module does not store anything persistently outside of what
#  FreeNAS itself stores.  In other words, it refreshes it's idea of
#  what pools exist, what slices are present, etc., on demand via the
#  CLI each time it requires this information.  Slower, but more simple
#  and accurate.
#
# * Minimal parallelization
#
#  Some read-only calls don't try to grab a global lock, but everything else
#  does.  Concurrent setup requests should be pretty rare anyway.  The idea
#  here is twofold: 1) avoid hammering on the FreeNAS interface and 2)
#  ensure data about existing resources is consistent/accurate.
#
package libvnode_blockstore;
use Exporter;
@ISA    = "Exporter";
@EXPORT = qw( init setDebug rootPreConfig
              rootPreConfigNetwork rootPostConfig
	      vnodeCreate vnodeDestroy vnodeState
	      vnodeBoot vnodePreBoot vnodeHalt vnodeReboot
	      vnodeUnmount
	      vnodePreConfig vnodePreConfigControlNetwork
              vnodePreConfigExpNetwork vnodeConfigResources
              vnodeConfigDevices vnodePostConfig vnodeExec vnodeTearDown
	    );

%ops = ( 'init' => \&init,
         'setDebug' => \&setDebug,
         'rootPreConfig' => \&rootPreConfig,
         'rootPreConfigNetwork' => \&rootPreConfigNetwork,
         'rootPostConfig' => \&rootPostConfig,
         'vnodeCreate' => \&vnodeCreate,
         'vnodeDestroy' => \&vnodeDestroy,
	 'vnodeTearDown' => \&vnodeTearDown,
         'vnodeState' => \&vnodeState,
         'vnodeBoot' => \&vnodeBoot,
         'vnodeHalt' => \&vnodeHalt,
         'vnodeUnmount' => \&vnodeUnmount,
         'vnodeReboot' => \&vnodeReboot,
         'vnodeExec' => \&vnodeExec,
         'vnodePreConfig' => \&vnodePreConfig,
         'vnodePreConfigControlNetwork' => \&vnodePreConfigControlNetwork,
         'vnodePreConfigExpNetwork' => \&vnodePreConfigExpNetwork,
         'vnodeConfigResources' => \&vnodeConfigResources,
         'vnodeConfigDevices' => \&vnodeConfigDevices,
         'vnodePostConfig' => \&vnodePostConfig,
       );


use strict;
use English;
use Data::Dumper;
use Socket;
use File::Basename;
use File::Path;
use File::Copy;

# Pull in libvnode and other Emulab stuff
BEGIN { require "/etc/emulab/paths.pm"; import emulabpaths; }
use libutil;
use libgenvnode;
use libvnode;
use libtestbed;
use libsetup;
use libfreenas;

#
# Constants
#
my $GLOBAL_CONF_LOCK     = "blkconf";
my $ZPOOL_LOW_WATERMARK  = 2 * 2**10; # 2GiB, expressed in MiB
my $FREENAS_MNT_PREFIX   = "/mnt";
my $ISCSI_GLOBAL_PORTAL  = 1;
my $SER_PREFIX           = "d0d0";
my $VLAN_IFACE_PREFIX    = "vlan";
my $MAX_RETRY_COUNT      = 5;
my $SLICE_BUSY_WAIT      = 10;
my $SLICE_GONE_WAIT      = 5;
my $IFCONFIG             = "/sbin/ifconfig";
my $ALIASMASK            = "255.255.255.255";
115 116
my $ISTGT                = "/usr/local/bin/istgt";
my $ISTGT_CONFIG_FILE    = "/usr/local/etc/istgt/istgt.conf";
117
my $ISTGT_PID_FILE       = "/var/run/istgt.pid";
118
my $ISTGT_MAXWAIT        = 30; # 30 seconds
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

# storageconfig constants
# XXX: should go somewhere more general
my $BS_CLASS_SAN         = "SAN";
my $BS_PROTO_ISCSI       = "iSCSI";
my $BS_UUID_TYPE_IQN     = "iqn";

#
# Global variables
#
my %vnstates = ();
my $_gFirstOnLAN = 0;
my $debug  = 0;

#
# Local Functions
#
sub getSliceList();
137
sub restartIstgt();
138 139 140 141
sub getIfConfig($);
sub getVlan($);
sub getNextAuthITag();
sub genSerial();
Mike Hibler's avatar
Mike Hibler committed
142
sub findAuthITag($;$);
143
sub findAuthIId($);
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 285 286
sub createVlanInterface($$);
sub removeVlanInterface($$);
sub setupIPAlias($;$);
sub runBlockstoreCmds($$$);
sub allocSlice($$$$);
sub exportSlice($$$$);
sub deallocSlice($$$$);
sub unexportSlice($$$$);

# Dispatch table for storage configuration commands.
my %setup_cmds = (
    "SLICE"  => \&allocSlice,
    "EXPORT" => \&exportSlice
);

my %teardown_cmds = (
    "SLICE"  => \&deallocSlice,
    "EXPORT" => \&unexportSlice
);

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

sub setDebug($)
{
    $debug = shift;
    libvnode::setDebug($debug);
    print "libvnode_blockstore: debug=$debug\n"
	if ($debug);
}

#
# Called by mkvnode.pl shortly after the module is loaded.
#
sub init($) {
    # XXX: doesn't seem to be passed in presently...
    my ($pnode,) = @_;

    # Nothing to do globally (yet).
    return 0;
}

#
# Do once-per-hypervisor-boot activities.
#
# Note that this function is called for each VM, so use a marker to
# tell whether or not we've already been here, done that.  
#
# NB: Since FreeNAS uses memory filesystems for pretty much
# everything, we don't have to worry about removing the flag file on
# shutdown/reboot.
#
sub rootPreConfig() {
    #
    # Haven't been called yet, grab the lock and double check that someone
    # didn't do it while we were waiting.
    #
    if (! -e "/var/run/blockstore.ready") {
	my $locked = TBScriptLock($GLOBAL_CONF_LOCK,
				  TBSCRIPTLOCK_GLOBALWAIT(), 900);
	if ($locked != TBSCRIPTLOCK_OKAY()) {
	    return 0
		if ($locked == TBSCRIPTLOCK_IGNORE());
	    print STDERR "Could not get the blkinit lock after a long time!\n";
	    return -1;
	}
    }
    if (-e "/var/run/blockstore.ready") {
        TBScriptUnlock();
        return 0;
    }
    
    print "Configuring root vnode context\n";

    # XXX: Put in consistency checks (maybe - they may go elsewhere.)

    mysystem("touch /var/run/blockstore.ready");
    TBScriptUnlock();
    return 0;    
}

# Nothing to do ...
sub rootPreConfigNetwork($$$$)
{
    my ($vnode_id, undef, $vnconfig, $private) = @_;
    my @node_ifs = @{ $vnconfig->{'ifconfig'} };
    my @node_lds = @{ $vnconfig->{'ldconfig'} };

    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
	print STDERR "Could not get the blknet lock after a long time!\n";
	return -1;
    }

    # XXX: Nothing to do?

    TBScriptUnlock();
    return 0;
}

# Nothing to do.
sub rootPostConfig($)
{
    return 0;
}

#
# Report back the current status of the blockstore slice.
#
sub vnodeState($$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    # Initialize our state if necessary.
    if (!exists($vnstates{$vnode_id})) {
	# This looks strange, but if we don't yet know what state the
	# blockstore is in and this file exists, then assume it exists
	# and is "stopped".  We do this to fake out the vnode "boot"
	# code in mkvnode.pl
	if (-e CONFDIR() . "/running") {
	    $vnstates{$vnode_id} = VNODE_STATUS_STOPPED();
	} else {
	    # We don't seem to exist...
	    $vnstates{$vnode_id} = VNODE_STATUS_UNKNOWN();
	}
    }

    # Once initialized, further state management happens elsewhere.

    return $vnstates{$vnode_id};
}

# All the creation heavy lifting is coordinated from here for blockstores.
sub vnodeCreate($$$$)
{
    my ($vnode_id, undef, $vnconfig, $private) = @_;
    my $vninfo = $private;
    my $bsconf = $vnconfig->{'storageconfig'};
    my $cleanup = 0;

    # Create vmid from the vnode's name.
    my $vmid;
287
    if ($vnode_id =~ /^[-\w]+\-(\d+)$/) {
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
	$vmid = $1;
    } else {
	fatal("blockstore_vnodeCreate: ".
	      "bad vnode_id $vnode_id!");
    }
    $vninfo->{'vmid'} = $vmid;
    $private->{'vndir'} = VNODE_PATH($vnode_id);

    # Grab the global lock to prevent concurrency.
    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
	fatal("blockstore_vnodeCreate: ".
	      "Could not get the blkalloc lock after a long time!");
    }

    # Create blockstore slice
    if (runBlockstoreCmds($vnode_id, $vnconfig, $private) != 0) {
	$cleanup = 1;
	warn("*** ERROR: blockstore_vnodeCreate: ".
	     "Blockstore slice creation failed!");
    }

    # Rain or shine, the creation attempt is done, so unlock.
    TBScriptUnlock();

    # Try to cleanup if something failed above.  Existing callers
    # appear to assume that if vnodeCreate() fails, then they don't
    # need to do anything to clean up ...
    if ($cleanup) {
	vnodeDestroy($vnode_id, $vmid, $vnconfig, $private);
	fatal("blockstore_vnodeCreate: ".
	      "Failed creation attempt aborted.");
    }

    return $vmid;
}

# Nothing to do presently.
sub vnodePreConfig($$$$$){
    my ($vnode_id, $vmid, $vnconfig, $private, $callback) = @_;

    return 0;
}

# Blockstore pseudo-VMs do not have a control network to setup.
sub vnodePreConfigControlNetwork($$$$$$$$$$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private,
	$ip,$mask,$mac,$gw, $vname,$longdomain,$shortdomain,$bossip) = @_;

    return 0;
}

# Setup IP alias for this blockstore pseudo-VM.
sub vnodePreConfigExpNetwork($$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

345
    # Create the experimental net (tagged vlan) interface, if not present.
346
    return -1
347 348 349 350 351 352
	if (createVlanInterface($vnode_id, $vnconfig) != 0);


    # Push this vnode's IP address onto the vlan interface.
    return -1
	if (setupIPAlias($vnconfig) != 0);
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 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 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 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538

    return 0;
}

# Nothing to do.
sub vnodeConfigResources($$$$){
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    return 0;
}

# Nothing to do.
sub vnodeConfigDevices($$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    return 0;
}

# The blockstore slice should be setup, the vlan interface created and
# plumbed, and the export in place by now.  Just signal "ISUP".
sub vnodeBoot($$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
    my $vninfo = $private;

    # notify Emulab that we are up.  Have to go through the proper
    # state transitions...
    libutil::setState("BOOTING");
    libutil::setState("ISUP");

    return 0;
}

# Just a wee smidge of state management here.  Mark that the
# blockstore pseudo-VM is up and running since 'vnodeBoot' is run
# inside a forked process, where such memory state changes are lost.
sub vnodePostConfig($)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    $vnstates{$vnode_id} = VNODE_STATUS_RUNNING();
    return 0;
}

# blockstores don't "reboot", but we'll signal that we've gone through
# the motions anyway.  Hopefully this rapid firing of events doesn't freak
# out stated.
sub vnodeReboot($$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    libutil::setState("SHUTDOWN");
    libutil::setState("BOOTING");
    libutil::setState("ISUP");

    return 0;
}

# Nothing to see here folks.  Move along!
sub vnodeTearDown($$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    return 0;
}

# Reverse the list of 'storageconfig' setup directives, then run the
# corresponding teardown commands.  Hold the lock while we do this
# to avoid concurrency here.
sub vnodeDestroy($$$$){
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;
    my $sconfigs = $vnconfig->{'storageconfig'};

    my @revconfigs = sort {$b->{'IDX'} <=> $a->{'IDX'}} @$sconfigs;

    # Mark this node as no longer running/existing (for vnodeState())
    unlink(CONFDIR() . "/running");
    $vnstates{$vnode_id} = VNODE_STATUS_UNKNOWN();

    # Grab the global lock to prevent concurrency.
    if (TBScriptLock($GLOBAL_CONF_LOCK, 0, 900) != TBSCRIPTLOCK_OKAY()) {
	fatal("blockstore_vnodeDestroy: ".
	      "Could not get the blkalloc lock after a long time!");
    }

    # Run through blockstore removal commands (reversed creation list).
    my $failed = 0;
    foreach my $sconf (@revconfigs) {
	my $cmd = $sconf->{'CMD'};
	if (exists($teardown_cmds{$cmd})) {
	    if ($teardown_cmds{$cmd}->($vnode_id, $sconf, 
				       $vnconfig, $private) != 0) {
		warn("*** ERROR: blockstore_vnodeDestroy: ".
		     "Teardown command failed: $cmd");
		# Don't die yet.  We want to try removing the
		# interface first.  Do jump out of this loop however
		# since subsequent commands here may also fail (and
		# perhaps cause worse fallout).
		$failed = 1;
		last;
	    }
	} else {
	    # Escape hatch for unknown command.
	    TBScriptUnlock();
	    fatal("blockstore_vnodeDestroy: ".
		  "Don't know how to execute: $cmd");
	}
    }

    # Lastly, remove the vlan inteface.  That we only have one interface
    # and that it has the correct params was established at creation time.
    if (removeVlanInterface($vnode_id, $vnconfig) != 0) {
	TBScriptUnlock();
	fatal("blockstore_vnodeDestroy: ".
	      "Could not remove the vlan interface!");
    }

    TBScriptUnlock();
    die() if $failed;      # If the command loop above failed, die now.
    return 0;
}

# blockstores don't "halt", but we'll signal that we did anyway.  Also
# remove the IP alias.
sub vnodeHalt($$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    setupIPAlias($vnconfig,1);

    libutil::setState("SHUTDOWN");
    $vnstates{$vnode_id} = VNODE_STATUS_STOPPED();

    return 0;
}

# Nothing to do...
sub vnodeExec($$$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private, $command) = @_;

    return 0;
}

# On the surface it would seem like this might apply to blockstore pseudo-VMs.
# Teardown and destroy do the work that this might do.
sub vnodeUnmount($$$$)
{
    my ($vnode_id, $vmid, $vnconfig, $private) = @_;

    return 0;
}

#######################################################################
# package-local functions
#

#
# Run through list of storage commands and execute them, checking
# for errors.  (Should have a lock before doing this.)
#
sub runBlockstoreCmds($$$) {
    my ($vnode_id, $vnconfig, $private) = @_;
    my $sconfigs = $vnconfig->{'storageconfig'};
    
    foreach my $sconf (@$sconfigs) {
	my $cmd = $sconf->{'CMD'};
	if (exists($setup_cmds{$cmd})) {
	    if ($setup_cmds{$cmd}->($vnode_id, $sconf, 
				    $vnconfig, $private) != 0) {
		warn("*** ERROR: blockstore_runBlockstoreCmds: ".
		     "Failed to execute setup command: $cmd");
		return -1;
	    }
	} else {
	    warn("*** ERROR: blockstore_runBlockstoreCmds: ".
		 "Don't know how to execute: $cmd");
	    return -1;
	}
    }

    return 0;
}

sub getSliceList() {
Mike Hibler's avatar
Mike Hibler committed
539
    return freenasSliceList();
540 541
}

542 543
# Helper function - restart the ISTGT process to reconfigure iSCSI stuff.
sub restartIstgt() {
544
    if (! -e $ISTGT_PID_FILE) {
545
	warn("*** WARNING: blockstore_restartIstgt: ".
546 547 548 549
	     "ISTGT PID file missing! Is it not running?");
	return -1;
    }
    if (!open(ISTPID, "<$ISTGT_PID_FILE")) {
550
	warn("*** WARNING: blockstore_restartIstgt: ".
551 552 553 554 555 556 557
	     "Could not open ISTGT PID file for reading!");
	return -1;
    }
    my $pid = <ISTPID>;
    close(ISTPID);
    chomp $pid;
    if (!$pid || $pid !~ /^(\d+)$/) {
558
	warn("*** WARNING: blockstore_restartIstgt: ".
559 560 561 562 563
	     "ISTGT PID does not look like a number!");
	return -1;
    }
    $pid = $1; # untaint

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    # Kill the istgt process.
    if (kill("TERM", $pid) != 1) {
	warn("*** WARNING: blockstore_restartIstgt: ".
	     "Could not send KILL signal to ISTGT: $!");
	return -1;
    }

    # Wait for the istgt process to die.
    my $dead = 0;
    for (my $i = 0; $i < $ISTGT_MAXWAIT; $i++) {
	sleep(1);
	if (!kill(0, $pid)) {
	    $dead = 1;
	    last;
	}
    }

    if (!$dead) {
	warn("*** WARNING: blockstore_restartIstgt: ".
	     "ISTGT still alive after $ISTGT_MAXWAIT seconds!");
	return -1;
    }

    # Restart istgt.
Kirk Webb's avatar
fix.  
Kirk Webb committed
588
    if (system("$ISTGT -c $ISTGT_CONFIG_FILE") != 0) {
589 590
	warn("*** WARNING: blockstore_restartIstgt: ".
	     "Could not start ISTGT!");
591 592 593 594 595 596
	return -1;
    }

    return 0;
}

597 598 599 600 601 602 603 604 605 606 607 608 609
# Allocate a slice based on information from Emulab Central
# XXX: Do 'sliceconfig' parameter checking.
sub allocSlice($$$$) {
    my ($vnode_id, $sconf, $vnconfig, $priv) = @_;

    my $bsid = $sconf->{'BSID'};
    my $volname = $sconf->{'VOLNAME'};
    $volname = "UNKNOWN" if (!$volname);
    my $size = $sconf->{'VOLSIZE'};

    #
    # If this is a use of a persistent store, the BSID is a unique
    # volume name based on the lease ID. Look up the volume to make
610 611
    # sure it exists, but do nothing else other than stash away some
    # state for exportSlice.
612 613
    #
    if ($bsid =~ /^lease-\d+$/) {
614 615 616 617 618 619 620 621
	# XXX we no longer share mappings so don't need iname info
	#my $volumes = freenasVolumeList(1, 1);
	my $volumes = freenasVolumeList(0, 1);
	my $vref = $volumes->{$bsid};
	if (!defined($vref)) {
	    warn("*** ERROR: blockstore_allocSlice: $volname: ".
		 "Requested volume not found: $bsid!");
	    return -1;
622
	}
623

624
	#
625
	# For possible later cloning, find the highest numbered snapshot
626 627 628
	# Note that the 'snapshots' list returned by freenasVolumeList is
	# already sorted from newest to oldest, so we just grab the first one.
	#
629
	if (exists($vref->{'snapshots'})) {
630 631 632
	    my $snap = (split(',', $vref->{'snapshots'}))[0];
	    if ($snap =~ /@(\d+)$/) {
		$priv->{'lastsnapshot'} = $1;
633
	    }
634 635 636 637 638 639 640 641 642
	}

	$priv->{'pool'} = $vref->{'pool'};
	$priv->{'volume'} = $vref->{'volume'};
	# XXX we no longer share mappings
	#if (exists($vref->{'iname'})) {
	#    $priv->{'iname'} = $vref->{'iname'};
	#}
	return 0;
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
    }

    $priv->{'pool'} = $bsid;
    $priv->{'volume'} = $vnode_id;
    return freenasVolumeCreate($bsid, $vnode_id, $size);
}

# Setup device export.
sub exportSlice($$$$) {
    my ($vnode_id, $sconf, $vnconfig, $priv) = @_;

    # Should only be one ifconfig entry - checked earlier.
    my $ifcfg   = (@{$vnconfig->{'ifconfig'}})[0];
    my $nmask   = $ifcfg->{'IPMASK'};
    my $cmask   = libutil::CIDRmask($nmask);
    my $network = libutil::ipToNetwork($ifcfg->{'IPADDR'}, $nmask);
    if (!$cmask || !$network) {
	warn("*** ERROR: blockstore_exportSlice: ".
	     "Error calculating ip network information.");
	return -1;
    }
664

665 666 667 668 669 670 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
    my $volname = $sconf->{'VOLNAME'};
    $volname = "UNKNOWN" if (!$volname);

    # Extract volume/pool as stashed away in prior setup.
    my $pool = $priv->{'pool'};
    my $volume = $priv->{'volume'};

    if (!defined($pool) || !defined($volume)) {
	warn("*** ERROR: blockstore_exportSlice: $volname: ".
	     "volume/pool not found!");
	return -1;
    }

    # Scrub request - we only support SAN/iSCSI at this point.
    if (!exists($sconf->{'CLASS'}) || $sconf->{'CLASS'} ne $BS_CLASS_SAN) {
	warn("*** ERROR: blockstore_exportSlice: $volname: ".
	     "invalid or missing blockstore class!");
	return -1;
    }

    if (!exists($sconf->{'PROTO'}) || $sconf->{'PROTO'} ne $BS_PROTO_ISCSI) {
	warn("*** ERROR: blockstore_exportSlice: $volname: ".
	     "invalid or missing blockstore protocol!");
	return -1;
    }

    if (!exists($sconf->{'UUID'}) || 
	!exists($sconf->{'UUID_TYPE'}) ||
	$sconf->{'UUID_TYPE'} ne $BS_UUID_TYPE_IQN)
    {
	warn("*** ERROR: blockstore_exportSlice: $volname: ".
	     "bad UUID information!");
	return -1;
    }
    # Check (and untaint) the UUID.
    if ($sconf->{'UUID'} !~ /^([-\.:\w]+)$/) {
	warn("*** ERROR: blockstore_exportSlice: $volname: ".
	     "bad characters in UUID!");
	return -1;
    }
    # XXX we lowercase the IQN since the ist_assoc will blow up with caps!
    my $iqn = lc($1);

708
    my $isro = "false";
709
    if (exists($sconf->{'PERMS'}) && $sconf->{'PERMS'} eq "RO") {
710
	$isro = "true";
711 712
    }

713 714 715 716 717 718
    #
    # XXX hack temporary support for RO sharing of persistent blockstores.
    #
    # If the mapping to a persistent store is RO, then we will create
    # an ephemeral clone for each such mapping.
    #
719
    if ($volume =~ /^lease-\d+$/ && $isro eq "true") {
720 721 722 723 724 725 726 727 728 729 730
	#
	# If no snapshot exists, create one. VolumeClone must have
	# a snapshot to hang the clone on. If a snapshot already exists
	# we assume another mapping has already gone through here and
	# we just use the same snapshot.
	#
	# XXX could this race with another vnode setup? If so, we could
	# wind up creating multiple snapshots for the same volume.
	# That does not matter right now, but something to watch out for.
	#
	my $tstamp;
731 732 733 734
	if (!exists($priv->{'lastsnapshot'})) {
	    # XXX this will be an error
	    warn("*** WARNING: blockstore_exportSlice: $volname: ".
		 "no snapshot found; created one for now");
735 736 737 738 739 740
	    $tstamp = time();
	    if (freenasVolumeSnapshot($pool, $volume, $tstamp)) {
		warn("*** ERROR: blockstore_exportSlice: $volname: ".
		     "Could not create snapshot for RO mapping");
		return -1;
	    }
741 742
	} else {
	    $tstamp = $priv->{'lastsnapshot'};
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
	}

	#
	# Create a clone with the same name as an ephemeral blockstore
	# would have. Note that it is in a different pool however,
	# since snapshot/clone must be in the same pool as the origin.
	# Clone will use the most recent snapshot (though there should
	# only be one anyway).
	#
	if (freenasVolumeClone($pool, $volume, $vnode_id)) {
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Could not create clone for RO mapping");
	    if ($tstamp) {
		freenasVolumeDesnapshot($pool, $volume, $tstamp);
	    }
	    return -1;
	}
	$volume = $vnode_id;
    }

763 764 765 766
    # If operating on a lease, we use the lease id as the iSCSI
    # initiator group identifier instead of the vnode_id because this
    # entry may end up being shared (simultaneous RO use).
    my $tag_ident = $vnode_id;
767 768 769 770
    # XXX we no longer share mappings
    #if ($priv->{'volume'} =~ /^lease-\d+$/) {
    #    $tag_ident = $priv->{'volume'};
    #}
771

772
    #
773 774 775
    # Go through the whole iSCSI extent/target setup if it hasn't been
    # done yet for this volume.  (If this is a persistent lease, it
    # may already be exported and in use.)
776
    #
777 778 779 780 781
    # XXX note that the API doc indicates that you would just specify
    # type 'ZVOL' but that doesn't work. You have to set:
    #      iscsi_target_extent_type=='Disk' and
    #      iscsi_target_extent_disk=='zvol/...'
    #
782 783 784
    # XXX currently iname will never exist since we don't share mappings.
    # The "else" code is left just in case we need it again in the future.
    #
785
    if (!exists($priv->{'iname'})) {
Mike Hibler's avatar
Mike Hibler committed
786
	#
787
	# Create iSCSI extent.
Mike Hibler's avatar
Mike Hibler committed
788 789 790 791
	#
	my $res = freenasRequest($FREENAS_API_RESOURCE_IST_EXTENT,
				 "POST", undef,
				 {"iscsi_target_extent_name" => $iqn,
792
				  "iscsi_target_extent_serial" => genSerial(),
Mike Hibler's avatar
Mike Hibler committed
793
				  "iscsi_target_extent_type" => "Disk",
794 795
				  "iscsi_target_extent_disk" => "zvol/$pool/$volume",
				  "iscsi_target_extent_ro" => $isro});
Mike Hibler's avatar
Mike Hibler committed
796
	if (!$res) {
797 798 799 800 801
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Failed to create iSCSI extent: $@");
	    return -1;
	}

Mike Hibler's avatar
Mike Hibler committed
802 803 804
	# save the index for making a target association
	my $eindex = $res->{'id'};

805 806 807 808 809 810 811 812
	# Create iSCSI auth group
	my $tag = getNextAuthITag();
	if ($tag !~ /^(\d+)$/) {
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "bad tag returned from getNextAuthITag: $tag");
	    return -1;
	}
	$tag = $1; # untaint.
Mike Hibler's avatar
Mike Hibler committed
813 814 815 816 817 818 819 820 821

	#
	# Create an authorized initiator.
        #
	# XXX sigh...once again the FreeNAS API does not work, it just
	# returns status 302 with reason "FOUND" which is normally a
	# redirect to a new location (but it returns the same location
	# in this case).
	#
822 823 824 825 826 827 828 829
	eval { freenasRunCmd($FREENAS_CLI_VERB_IST_AUTHI,
			     "add $tag ALL $network/$cmask $tag_ident") };
	if ($@) {
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Failed to create iSCSI auth group: $@");
	    return -1;
	}

Mike Hibler's avatar
Mike Hibler committed
830 831 832
	#
	# Create iSCSI target.
	#
833
	# XXX ugh, this used to all be done with iscsi/target, but now
834 835 836
	# they have broken it into two pieces: create the target, create
	# a target group.
	#
Mike Hibler's avatar
Mike Hibler committed
837 838
	$res = freenasRequest($FREENAS_API_RESOURCE_IST_TARGET,
			      "POST", undef,
839
			      {"iscsi_target_name" => $iqn});
Mike Hibler's avatar
Mike Hibler committed
840
	if (!$res) {
841 842 843 844
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Failed to create iSCSI target: $@");
	    return -1;
	}
Mike Hibler's avatar
Mike Hibler committed
845 846 847 848 849 850
	if (!exists($res->{'id'})) {
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "No index for iSCSI target we just created!?");
	    return -1;
	}
	my $tindex = $res->{'id'};
851

852 853 854
	# XXX we need the authinit index, not tag
	my $aindex = findAuthIId($tag);

855 856 857
	$res = freenasRequest($FREENAS_API_RESOURCE_IST_TGTGROUP,
			      "POST", undef,
			      {"iscsi_target" => $tindex,
858
			       "iscsi_target_initiatorgroup" => $aindex,
859 860 861 862 863 864 865 866 867
			       "iscsi_target_portalgroup" => $ISCSI_GLOBAL_PORTAL,
			       "iscsi_target_authgroup" => undef,
			       "iscsi_target_authtype" => "None"});
	if (!$res) {
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Failed to create iSCSI targetgroup: $@");
	    return -1;
	}

868
	# Bind iSCSI target to slice (extent)
Mike Hibler's avatar
Mike Hibler committed
869 870 871 872 873
	$res = freenasRequest($FREENAS_API_RESOURCE_IST_ASSOC,
			      "POST", undef,
			      {"iscsi_target" => $tindex,
			       "iscsi_extent" => $eindex});
	if (!$res) {
874 875 876 877 878 879 880 881 882 883
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Failed to associate iSCSI target with extent: $@");
	    return -1;
	}
    }
    # The iSCSI target/extent setup is already in place, so just
    # modify the authorized networks.  Check that the incoming
    # requested perms are RO, and validate that the dataset isn't
    # currently in use RW.
    else {
884 885 886 887
	# XXX for now
	warn("*** ERROR: unexpected arrival in shared dataset code!");
	return -1;

888
	# Check requested perms.
889
	if ($isro eq "false") {
890 891 892 893 894 895 896
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Cannot re-export in-use dataset as RW!");
	    return -1;
	}

	# Check current use mode - must not be RW.  Searching for the
	# target entry serves as a sanity check as well.
Mike Hibler's avatar
Mike Hibler committed
897 898
	my $targets = freenasTargetList(1);
	if (!exists($targets->{$iqn})) {
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
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Couldn't find the iSCSI target while attempting re-export!");
	    return -1;
	}

	# Grab the current iSCSI initiator group so we can modify it.
	my $authent = findAuthITag($tag_ident);
	if (!$authent) {
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Couldn't find the iSCSI auth group entry while attempting re-export!");
	    return -1;
	}
	if ($authent->{'tag'} !~ /^(\d+)$/) {
	    warn("*** ERROR: blockstore_exportSlice: $volname: ".
		 "Malformed tag returned for current authentication group entry while attempting re-export!");
	    return -1;
	}
	my $curtag = $1; # untaint;
	my @auth_networks = split(/\s+/, $authent->{'auth_network'});
	# The incoming network shouldn't already be there, but let's check.
	if (grep(/^$network\/$cmask$/, @auth_networks)) {
	    warn("*** WARNING: blockstore_exportSlice: $volname: ".
		 "Our network is already present in iSCSI auth group: $network/$cmask");
	} else {
	    push @auth_networks, "$network/$cmask";
	    my $auth_network_str = join(' ', @auth_networks);
	    eval { freenasRunCmd($FREENAS_CLI_VERB_IST_AUTHI, 
				 "edit $curtag ALL ".
				 "'$auth_network_str' $tag_ident") };
	    if ($@) {
		warn("*** ERROR: blockstore_exportSlice: $volname: ".
		     "Failed to modify iSCSI auth group (re-export): $@");
		return -1;
	    }
	}
934

935 936 937
	# Restart ISTGT to pull in change.  We have to do this because
	# the IST_AUTHI command above doesn't do it for us...
	if (restartIstgt() != 0) {
938
		warn("*** ERROR: blockstore_exportSlice: $volname: ".
939
		     "restartIstgt failed!  ISTGT may not be running!");
940 941
		return -1;
	}
942 943 944 945 946 947 948
    }

    # All setup and exported!
    return 0;
}

# Helper function.
949
# Locate and return tag for given identifier, if it exists.
Mike Hibler's avatar
Mike Hibler committed
950 951
sub findAuthITag($;$) {
    my ($ident,$idxp) = @_;
952 953

    return undef
954
	if !defined($ident);
955

Mike Hibler's avatar
Mike Hibler committed
956
    my $aiinfo = freenasAuthInitList();
957

Mike Hibler's avatar
Mike Hibler committed
958 959 960 961 962 963 964 965
    foreach my $ai (keys %{$aiinfo}) {
	my $aient = $aiinfo->{$ai};
	if (exists($aient->{'comment'}) && $aient->{'comment'} eq $ident &&
	    exists($aient->{'tag'})) {
	    if ($idxp) {
		$$idxp = $aient->{'id'};
	    }
	    return $aient;
966 967 968 969 970 971
	}
    }

    return undef;
}

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
# Helper function.
# Locate and return ID for given auth tag, if it exists
sub findAuthIId($) {
    my ($tag) = @_;

    return undef
	if !defined($tag);

    my $aiinfo = freenasAuthInitList();

    foreach my $ai (keys %{$aiinfo}) {
	my $aient = $aiinfo->{$ai};
	if (exists($aient->{'tag'}) && $aient->{'tag'} eq $tag) {
	    return $aient->{'id'};
	}
    }

    return undef;
}

992 993 994
# Helper function.
# Locate and return next unused tag ID for iSCSI initiator groups.
sub getNextAuthITag() {
Mike Hibler's avatar
Mike Hibler committed
995
    my $aiinfo = freenasAuthInitList();
996

Mike Hibler's avatar
Mike Hibler committed
997 998 999 1000 1001
    my @taglist = ();
    foreach my $ai (keys %{$aiinfo}) {
	my $tag = $aiinfo->{$ai}->{'tag'};
	if (defined($tag) && $tag =~ /^(\d+)$/) {
	    push(@taglist, $1);
1002
	}
Mike Hibler's avatar
Mike Hibler committed
1003 1004 1005 1006 1007 1008 1009
    }

    my $freetag = 1;
    foreach my $curtag (sort {$a <=> $b} @taglist) {
	last
	    if ($freetag < $curtag);
	$freetag++;
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    }

    return $freetag;
}

# Helper function - Generate a random serial number for an iSCSI target
sub genSerial() {
    my $rand_hex = join "", map { unpack "H*", chr(rand(256)) } 1..6;
    return $SER_PREFIX . $rand_hex;
}

# Helper function - get the _single_ ifconfig line passed in via tmcd.
# If there is more than one, then there is a problem.
sub getIfConfig($) {
    my ($vnconfig,) = @_;

    my $ifconfigs = $vnconfig->{'ifconfig'};
    
    if (@$ifconfigs != 1) {
	warn("*** ERROR: blockstore_getIfConfig: ".
	     "Wrong number of network interfaces.  There can be only one!");
	return undef;
    }

    my $ifc = @$ifconfigs[0];

    if ($ifc->{'ITYPE'} ne "vlan") {
	warn("*** ERROR: blockstore_getIfConfig: ".
	     "Interface must be of type 'vlan'!");
	return undef;
    }

    return $ifc;
}

# Helper function - search output of FreeNAS vlan CLI command for the
# presence of the vlan name passed in.  Return what is found.
sub getVlan($) {
    my ($vtag,) = @_;
1049 1050
    my $retval = {};
    my $notexist = 0;
1051 1052 1053 1054

    return undef
	if (!defined($vtag) || $vtag !~ /^(\d+)$/);

1055 1056 1057 1058 1059 1060
    my $vlanif = $VLAN_IFACE_PREFIX . $vtag;    
    if (!open(IFPIPE,"$IFCONFIG $vlanif 2>&1 |")) {
	warn("*** ERROR: blockstore_getVlan: ".
	     "Could not run ifconfig: $!");
	return undef;
    }
1061

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    while (my $ln = <IFPIPE>) {
	chomp $ln;
        IFLINE: for ($ln) {
	    /description: (.+)/ && do {
		$retval->{'description'} = $1;
		last IFLINE;
	    };
	    /vlan: (\d+) parent interface: (\w+)/ && do {
		$retval->{'tag'}  = $1;
		$retval->{'pint'} = $2;
		last IFLINE;
	    };
	    /does not exist/ && do {
		$notexist = 1;
		last IFLINE;
	    };
1078 1079
	}
    }
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090

    close(IFPIPE);

    if ($? != 0) {
	if (!$notexist) {
	    warn("*** ERROR: blockstore_getVlan: ".
		 "ifconfig returned an error: $?");
	}
	return undef;
    }

1091 1092 1093
    return $retval;
}

1094 1095 1096
#
# Does _any_ IPv4 address exist on a given network interface?
#
1097 1098 1099 1100
sub addressExists($) {
    my ($iface,) = @_;
    my $retval = 0;
    
1101
    my $ifc_out = `$IFCONFIG $iface 2>&1`;
1102 1103
    if ($? != 0) {
	warn("*** ERROR: blockstore_addressExists: ".
1104 1105
	     "Problem running ifconfig: $ifc_out");
	$retval = 0;
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    } elsif ($ifc_out =~ /inet \d+\.\d+\.\d+\.\d+/) {
	$retval = 1;
    } 

    return $retval;
}

#
# Make a vlan interface for this node (tagged, vlan).
#
sub createVlanInterface($$) {
    my ($vnode_id, $vnconfig) = @_;

    my $ifc    = getIfConfig($vnconfig);
    if (!defined($ifc)) {
	warn("*** ERROR: blockstore_createVlanInterface: ".
	     "No valid interface record found!");
	return -1;
    }

    my $vtag   = $ifc->{'VTAG'};
    my $pmac   = $ifc->{'PMAC'};
    my $piface = $ifc->{'IFACE'};
    my $lname  = $ifc->{'LAN'};

    my $viface = $VLAN_IFACE_PREFIX . $vtag;

    # Untaint stuff.
    if ($piface !~ /^([-\w]+)$/) {
	warn("*** ERROR: blockstore_createVlanInterface: ". 
	     "bad data physical interface name!");
	return -1;
    }
    $piface = $1;

    if ($pmac !~ /^([a-fA-F0-9:]+)$/) {
	warn("*** ERROR: blockstore_createVlanInterface: ". 
	     "bad data in physical mac address!");
	return -1;
    }
    $pmac = $1;

    if ($vtag !~ /^(\d+)$/) {
	warn("*** ERROR: blockstore_createVlanInterface: ". 
	     "bad data in vlan tag!");
	return -1;
    }
    $vtag = $1;

    # see if vlan already exists.  do sanity checks to make sure this
    # is the correct vlan for this interface, and then create it.
    my $vlan = getVlan($vtag);
    if ($vlan) {
	my $vlabel = $vlan->{'description'};
	# This is not a fool-proof consistency check, but the odds of
	# having an existing vlan with the same LAN name and vlan tag
	# as one in a different experiment are vanishingly small.
	if ($vlabel ne $lname) {
	    warn("*** ERROR: blockstore_createVlanInterface: ".
		 "Mismatched vlan: $lname != $vlabel");
	    return -1;
	}
    }
    # vlan does not exist.
    else {
1171 1172 1173 1174 1175 1176
	# Create the vlan entry directly.  FreeNAS 9 nukes network
	# interface addresses/aliases it doesn't know about, so we can't
	# use its API directly. :-(  See also the comment
	# in setupIPAliases().
	if (system("$IFCONFIG $viface create vlan $vtag".
		   " vlandev $piface description $lname") != 0) {
1177
	    warn("*** ERROR: blockstore_createVlanInterface: ". 
1178
		 "failure while creating vlan interface: $!");
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
	    return -1;
	}
    }

    # All done.
    return 0;
}

# Create (or remove) the ephemeral IP alias for this blockstore.
sub setupIPAlias($;$) {
    my ($vnconfig, $teardown) = @_;

    my $ifc    = getIfConfig($vnconfig);
    if (!defined($ifc)) {
	warn("*** ERROR: blockstore_createVlanInterface: ".
	     "No valid interface record found!");
	return -1;
    }

    my $vtag   = $ifc->{'VTAG'};
    my $ip     = $ifc->{'IPADDR'};
    my $qmask  = $ifc->{'IPMASK'};

    my $viface = $VLAN_IFACE_PREFIX . $vtag;

    if ($ip !~ /^([\.\d]+)$/) {
	warn("*** ERROR: blockstore_createVlanInterface: ". 
	     "bad data in IP address!");
	return -1;
    }
    $ip = $1;

    if ($qmask !~ /^([\.\d]+)$/) {
	warn("*** ERROR: blockstore_createVlanInterface: ". 
	     "bad characters in subnet!");
	return -1;
    }
    # If this is the first blockstore on the lan, then use the real netmask,
    # otherwise this is yet another alias on the same interface, so use the
    # all 1's mask.
    $qmask = addressExists($viface) ? $ALIASMASK : $1;

    if ($teardown) {
	if (system("$IFCONFIG $viface -alias $ip") != 0) {
	    warn("*** ERROR: blockstore_createVlanInterface: ".
		 "ifconfig failed while setting IP alias parameters: $?");
	}
    } else {
1227
	# Add an alias for this pseudo-VM.  Have to do this underneath FreeNAS
1228
	# because it makes adding and removing them ridiculously impractical.
1229 1230 1231 1232
	# To be more specific, it does various bad things, like remove ALL
	# configuration across ALL interfaces when an address/alias is
	# removed from an interface.  It then re-configs everything from
	# it's DB. This is very disruptive to say the least!
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	if (system("$IFCONFIG $viface alias $ip netmask $qmask") != 0) {
	    warn("*** ERROR: blockstore_createVlanInterface: ".
		 "ifconfig failed while clearing IP alias parameters: $?");
	}
    }

    return 0;
}

#
# Remove previously created VLAN interface.  Will only actually do
# something if all IP aliases have been removed.  I.e., the last
# pseudo-VM in the vlan on this blockstore host that passes through
# here will result in interface removal.
#
sub removeVlanInterface($$) {
    my ($vnode_id, $vnconfig) = @_;

    # Fetch the interface record for this pseudo-VM
    my $ifc    = getIfConfig($vnconfig);
    if (!defined($ifc)) {
	warn("*** ERROR: blockstore_removeVlanInterface: ".
	     "No valid interface record found!");
	return -1;
    }

    my $vtag   = $ifc->{'VTAG'};
    my $viface = $VLAN_IFACE_PREFIX . $vtag;

1262
    # Does the vlan interface exist?  Nothing to do if it doesn't!
1263 1264
    if (!getVlan($vtag)) {
	warn("*** WARNING: blockstore_removeVlanInterface: ".
Mike Hibler's avatar
Mike Hibler committed
1265
	     "Vlan entry for $vtag does not exist...");
1266 1267 1268 1269
	return 0;
    }

    if (!addressExists($viface)) {
1270
	if (system("$IFCONFIG $viface destroy") != 0) {
1271
	    warn("*** ERROR: blockstore_removeVlanInterface: ".
Mike Hibler's avatar
Mike Hibler committed
1272
		 "failure while removing $viface interface: $?");
1273 1274 1275 1276 1277 1278
	}
    }

    return 0;
}

1279 1280 1281
#
# Reverse counterpart to exportSlice().
#
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
sub unexportSlice($$$$) {
    my ($vnode_id, $sconf, $vnconfig, $priv) = @_;

    my $volname = $sconf->{'VOLNAME'};
    $volname = "UNKNOWN" if (!$volname);

    # All of the sanity checking was done when we first created and
    # exported this blockstore.  Assume nothing has changed...
    $sconf->{'UUID'} =~ /^([-\.:\w]+)$/;
    my $iqn = lc($1); # untaint and lowercase.

1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    # There should only be one ifconfig entry - checked earlier.
    my $ifcfg   = (@{$vnconfig->{'ifconfig'}})[0];
    my $nmask   = $ifcfg->{'IPMASK'};
    my $cmask   = libutil::CIDRmask($nmask);
    my $network = libutil::ipToNetwork($ifcfg->{'IPADDR'}, $nmask);
    if (!$cmask || !$network) {
	warn("*** ERROR: blockstore_unexportSlice: ".
	     "Error calculating ip network information.");
	return -1;
    }

    # If operating on a lease, we use the lease name as the
    # iSCSI auth group identifier instead of the vnode_id because
    # this entry may be shared (simultaneous RO use).
    my $tag_ident = $vnode_id;
1308 1309 1310 1311
    # XXX we no longer share mappings
    #if ($sconf->{'UUID'} =~ /:(lease-\d+)$/) {
    #    $tag_ident = $1; # untaint
    #}
1312

1313 1314 1315 1316 1317 1318 1319 1320
    # Fetch the authorized initators entry associated with this slice,
    # and yank its network entry out of the list.  It this is the last
    # remaining entry, we tear down the export. If any network entries
    # remain, this tells us that other experiments are still using
    # this iSCSI target (simultaneous RO). In that case we only
    # modify the set of authorized initiators.
    my $authtag = 0;
    my @pruned_networks = ();
Mike Hibler's avatar
Mike Hibler committed
1321 1322
    my $authidx;
    my $curtag = findAuthITag($tag_ident,\$authidx);
1323 1324 1325
    if ($curtag && $curtag->{'tag'} =~ /^(\d+)$/) {
	$authtag = $1; # untaint;
	@pruned_networks = grep {!/^$network\/$cmask$/} split(/\s+/, $curtag->{'auth_network'});
1326 1327
    }

1328 1329 1330
    # If there are no networks left in the authorized initiators list, then
    # we are completely done with this export - tear it down!
    if (!@pruned_networks) {
1331
	my ($associd,$targetid,$extentid,$tgroupid,$msg);
Mike Hibler's avatar
Mike Hibler committed
1332 1333 1334 1335 1336 1337 1338 1339 1340
	my $assocs = freenasAssocList();
	foreach my $aid (keys %$assocs) {
	    if (exists($assocs->{$aid}->{'target_name'}) &&
		$assocs->{$aid}->{'target_name'} eq $iqn &&
		exists($assocs->{$aid}->{'extent_name'}) &&
		$assocs->{$aid}->{'extent_name'} eq $iqn) {
		$associd = $aid;
		$targetid = $assocs->{$aid}->{'target'};
		$extentid = $assocs->{$aid}->{'extent'};
1341
		$tgroupid = $assocs->{$aid}->{'target_group'};
Mike Hibler's avatar
Mike Hibler committed
1342 1343 1344
		last;
	    }
	}
Mike Hibler's avatar
Mike Hibler committed
1345 1346 1347

	# Remove association
	$msg = "assoc for $iqn not found\n";
Mike Hibler's avatar
Mike Hibler committed
1348 1349 1350
	if (!$associd ||
	    !freenasRequest("$FREENAS_API_RESOURCE_IST_ASSOC/$associd",
			    "DELETE", undef, undef, undef, \$msg)) {
1351
	    warn("*** WARNING: blockstore_unexportSlice: $volname: ".
Mike Hibler's avatar
Mike Hibler committed
1352
		 "Failed to disassociate iSCSI target with extent:\n$msg");
1353 1354
	}

1355 1356 1357 1358 1359 1360 1361 1362
	# Remove target group.
	if (!$tgroupid ||
	    !freenasRequest("$FREENAS_API_RESOURCE_IST_TGTGROUP/$tgroupid",
			    "DELETE", undef, undef, undef, \$msg)) {
	    warn("*** WARNING: blockstore_unexportSlice: $volname: ".
		 "Failed to remove iSCSI target group:\n$msg");
	}

1363
	# Remove iSCSI target.
Mike Hibler's avatar
Mike Hibler committed
1364 1365 1366
	if (!$targetid ||
	    !freenasRequest("$FREENAS_API_RESOURCE_IST_TARGET/$targetid",
			    "DELETE", undef, undef, undef, \$msg)) {
1367
	    warn("*** WARNING: blockstore_unexportSlice: $volname: ".
Mike Hibler's avatar
Mike Hibler committed
1368
		 "Failed to remove iSCSI target:\n$msg");
1369 1370 1371
	}

	# Remove iSCSI auth group
Mike Hibler's avatar
Mike Hibler committed
1372 1373 1374 1375 1376
	if (!$authidx ||
	    !freenasRequest("$FREENAS_API_RESOURCE_IST_AUTHI/$authidx",
			    "DELETE", undef, undef, undef, \$msg)) {
	    warn("*** WARNING: blockstore_unexportSlice: $volname: ".
		 "Failed to remove iSCSI auth group:\n$msg");
1377 1378
	}

1379
	# Remove iSCSI extent.
Mike Hibler's avatar
Mike Hibler committed
1380 1381 1382
	if (!$extentid ||
	    !freenasRequest("$FREENAS_API_RESOURCE_IST_EXTENT/$extentid",
			    "DELETE", undef, undef, undef, \$msg)) {
1383
	    warn("*** WARNING: blockstore_unexportSlice: $volname: ".
Mike Hibler's avatar
Mike Hibler committed
1384
		 "Failed to remove iSCSI extent:\n$msg");
1385 1386 1387 1388 1389
	}
    }
    # This export is still referenced, so leave export but update the
    # authorized initiators list.
    else {
1390 1391 1392 1393
	# XXX for now
	warn("*** ERROR: unexpected arrival in shared dataset code!");
	return -1;

1394 1395 1396 1397 1398 1399 1400 1401 1402
	my $auth_network_str = join(' ', @pruned_networks);
	eval { freenasRunCmd($FREENAS_CLI_VERB_IST_AUTHI,
			     "edit $authtag ALL '$auth_network_str' ".
			     "$tag_ident") };
	if ($@) {
	    warn("*** ERROR: blockstore_unexportSlice: $volname: ".
		 "Failed to modify iSCSI auth group (re-export): $@");
	    return -1;
	}
1403

1404 1405 1406 1407 1408 1409
	# Restart ISTGT to pull in change.  We have to do this because
	# the IST_AUTHI command above doesn't do it for us...
	if (restartIstgt() != 0) {
		warn("*** ERROR: blockstore_unexportSlice: $volname: ".
		     "restartIstgt failed!  ISTGT may not be running!");
		return -1;
1410
	}
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    }

    # All torn down and unexported!
    return 0;
}

sub deallocSlice($$$$) {
    my ($vnode_id, $sconf, $vnconfig, $priv) = @_;

    my $bsid = $sconf->{'BSID'};
    my $volname = $sconf->{'VOLNAME'};
    $volname = "UNKNOWN" if (!$volname);

    #
    # If this is a use of a persistent store, the BSID is a unique
    # volume name based on the lease ID. Look up the volume to make
    # sure it exists, but do nothing else.
    #
    if ($bsid =~ /^lease-\d+$/) {
1430 1431 1432 1433 1434 1435 1436 1437 1438
	my $volumes = freenasVolumeList(0, 1);

	#
	# Check for clone volumes. A clone will have our (vnode_id)
	# name and be a "cloneof" a snapshot of this lease.
	#
	if (exists($volumes->{$vnode_id})) {
	    my $vref = $volumes->{$vnode_id};
	    my $pool = $vref->{'pool'};
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
	    my $cloneof = $vref->{'cloneof'};
	    if (defined($cloneof) && $cloneof =~ /^$bsid\@\d+/ &&
		exists($volumes->{$bsid})) {
		my $snaps = $volumes->{$bsid}->{'snapshots'};

		#
		# If we are a clone of the most recent snapshot, just Destroy
		# which leaves the clone; otherwise Declone and attempt to
		# remove the old snapshot.
		#
		# Note that we do not use the cached 'lastsnapshot' in our
		# private data since that was saved back when we were created
		# which could be a long time ago (and hence very stale).
		#
		if (defined($snaps) && $cloneof eq (split(',', $snaps))[0]) {
		    return freenasVolumeDestroy($pool, $vnode_id);
		}
		return freenasVolumeDeclone($pool, $vnode_id);
1457 1458
	    }
	    warn("*** WARNING: blockstore_deallocSlice: $volname: ".
1459
		 "Found stale clone volume '$pool/$vnode_id'");
1460 1461
	}

1462 1463 1464 1465 1466 1467 1468 1469
	if (exists($volumes->{$bsid})) {
	    return 0;
	}
	warn("*** ERROR: blockstore_deallocSlice: $volname: ".
	     "Requested volume not found: $bsid!");
	return -1;
    }

1470
    #
1471 1472 1473 1474
    # Ephemeral volume. We use Declone here rather than Destroy since someday
    # we will have clones of ephemeral volumes. In that case we will not have
    # to worry about keeping the latest snapshot as there will only be one
    # and it should go away on last use.
1475
    #
1476
    return freenasVolumeDeclone($bsid, $vnode_id);
1477 1478 1479 1480
}

# Required perl foo
1;