From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id AE1471FF0B3 for ; Thu, 26 Nov 2026 16:11:42 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 6E19D21834; Thu, 26 Nov 2026 16:11:03 +0100 (CET) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=neatech-ar.20260707.gappssmtp.com; s=20260707; t=1795705811; x=1796310611; darn=lists.proxmox.com; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=yOWVZE0WiCWqSg4NTlzSpIR1EuYKG4VWXZv2do5MB88=; b=cgkiTAI317yG/i2XhC4ywyMo/92/RxaVGGsxlzStI8QVzRLt//cqR3pahGKpkomtVE Sibvcd+fWuejS+yI2JrujxiEudYx/1smofTusfyZyetQYqmZI9kSQcPg0veXeTXtDWpe hlmUZTSulX7a13tWvsxOwS9wnEfrvl/BzTDUD4GT13ObJsFXj9e8KMQYC374gJJG0/VJ tY4/q+Px9JFm5fu7u9UqQKQGwiQ2xFDtqLTNlNXQ+BPnEbJbiOuyA4z/Q2dFAYN/1PSH OAjKpJ6MToW8Lt0yjBr24pG8lPjquUze7a1AESiezEY1PaB62z6XPzCAbiIzCOcT1iwx 0+NQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795705811; x=1796310611; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=yOWVZE0WiCWqSg4NTlzSpIR1EuYKG4VWXZv2do5MB88=; b=Yuyujforcg4wEizC83JawpzUZQlW0e4MKm8qR4wPL0+ZbeO0BhpnDzUXZNiAazWBqx TYlS/NBOgWzy0Mmmlau3z0HVgL6q8RsykV3uQ/N4/o5wH0bnfw/rGQ4988wcMUtvRlwO y5iNhw2SwHUi1CgEt22F3pFyyHIwerS5a3QQsCs4DKK/z2Lj7PumfQ52oiQfR6j21S3e NPX+leajDWNem0vZi99r7qnv+AMN0zigsOgOyEQ1xotqtNKr/Eil/OEsme2CjZ375i6a +f177RXvhW8e8PrJOf1ghPuMUOwpzF8D+biJ6LwuSZRy0hyq2an/mk3bU1Eyw5wDzOv0 W4Tg== X-Gm-Message-State: APuU4Z8Lm1WslNttyF/uxM3xnNCHakrCa318ksuyHVLRdOW3VgQXPWf6 oHsAMDnR3oJ90e2BQa2PuMWeWyIqcvstwxj28SGZAJ2WwhzQPDi1p+kKeSi959JDKfkCZb667fe ltkXUkcg= X-Gm-Gg: AZFdTZcxhZkRoFbKxqozaid+YrRbi2s4uOC1DZkLiZelWJi7YCQFYym4450+FvKBLHa 6wKwSlEc5uGZKwlJWBwEZM3IOwOBZVSuLxz65kCMFeJiXyvFh7G/HGQpEY7p4F9nX1UgMQi+aw6 FLySYTgMlJbQsVCN3FfbGYps0kA67+dFLKFzAp7V1uLw3WEuqBx8yJfJ7lmnFyoZEqZRNzmNzFo dYCYXJQ2mnZhRMTun00rJL8eLacrN0IDPKF1p4jZYMBqvU4f4ykBLjn7OfF+Shvkdvr8LOCKwEL gVLSHNL+5/lT6Ocb2CTRtOZtxBcGFSOFQHd0xo8HdjhLH59okQtPLgUThwHK+ZwiBckBAM9SjYi TLegTORBWgG/9kB1lRmkHAIXG+wzrSVg/pBDQjh1hi/erBYxkBv6bNy1jVMcEg8WI2lJbrXjcxP py1fifGmv2Z+igF+2ggDlFbfcO7erMI9Br9MKZe1aKKN6Y5n9JHtqdQ0UOHrfAy3gX+FdN3e6tk ZuuYJENWJiSAXkfGF0EuiiLoTsQT/r8uV9DQ9A+MU4GATrDoBp0+aHkAXvIWsOC0IQ8rmwArY3f WyN2vX81II4uOmYurGmXCxXIPGJmmvxF5GrTadaCcfYXcv8CW9yz2yV7DgWvDoLIP28gUNjjre2 se+SaT31qFalGXqesuxpisPKf3B8boQ== X-Received: by 2002:a05:6102:8604:20b0:7d2:7784:23b5 with SMTP id ada2fe7eead31-7d72b3479fbmr13787460137.1.1795705810571; Thu, 26 Nov 2026 07:10:10 -0800 (PST) From: Joaquin Varela To: pve-devel@lists.proxmox.com Subject: [PATCH storage v5 07/13] test: zfsnvme: add configuration and volume tests Date: Thu, 26 Nov 2026 12:09:48 -0300 Message-ID: <20261126150956.310593-8-joaquinvarela@neatech.ar> X-Mailer: git-send-email 2.54.0.windows.1 In-Reply-To: <20261126150956.310593-1-joaquinvarela@neatech.ar> References: <20261126150956.310593-1-joaquinvarela@neatech.ar> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.267 Adjusted score from AWL reputation of From: address DKIM_SIGNED 0.1 Message has a DKIM or DK signature, not necessarily valid DKIM_VALID -0.1 Message has at least one valid DKIM or DK signature DMARC_PASS -0.1 DMARC pass policy RCVD_IN_DNSWL_NONE -0.0001 Sender listed at https://www.dnswl.org/, no trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: DUUOAQZPW5U6WSDZBD3EDWVZWFITCVVV X-Message-ID-Hash: DUUOAQZPW5U6WSDZBD3EDWVZWFITCVVV X-MailFrom: joaquinvarela@neatech.ar X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: Add zfsnvme_test.pm with tests for the schema and config checks, the key handling in the storage hooks and in pvesm, the SSH runner and the volume methods. Nothing in it connects to a target or touches a local NVMe device. Signed-off-by: Joaquin Varela --- src/test/run_plugin_tests.pl | 1 + src/test/zfsnvme_test.pm | 1266 ++++++++++++++++++++++++++++++++++ 2 files changed, 1267 insertions(+) create mode 100644 src/test/zfsnvme_test.pm diff --git a/src/test/run_plugin_tests.pl b/src/test/run_plugin_tests.pl index da0d0dea..19465c25 100755 --- a/src/test/run_plugin_tests.pl +++ b/src/test/run_plugin_tests.pl @@ -25,6 +25,7 @@ my $res = $harness->runtests( "plugin_isolation_test.pm", "plugin_load_test.pm", "plugin_properties_test.pm", + "zfsnvme_test.pm", ); exit -1 if !$res || $res->{failed} || $res->{parse_errors}; diff --git a/src/test/zfsnvme_test.pm b/src/test/zfsnvme_test.pm new file mode 100644 index 00000000..41991649 --- /dev/null +++ b/src/test/zfsnvme_test.pm @@ -0,0 +1,1266 @@ +package PVE::Storage::TestZFSNVMe; + +# Storage API and local NVMe host side of the zfsnvme plugin, the target side is in +# zfsnvme_target_test.pm. Every probe of the local host is mocked and the children that the +# plugin forks run inline, except where the child itself is tested. + +use v5.36; + +use lib qw(..); + +use Compress::Zlib qw(crc32); +use Config; +use Errno qw(EACCES ECONNREFUSED EINVAL ENOENT); +use Fcntl qw(O_NOCTTY O_RDWR); +use File::Temp qw(tempdir); +use MIME::Base64 qw(encode_base64); +use POSIX qw( + ECHO ECHONL ICANON OPOST SIG_BLOCK SIGALRM SIGHUP SIGINT SIGQUIT SIGTERM TCSANOW WNOHANG + sigprocmask +); +use Test::MockModule; +use Test::More; + +use PVE::NVMeOF; +use PVE::Storage; +use PVE::Storage::ZFSNVMePlugin; + +my $PLUGIN = 'PVE::Storage::ZFSNVMePlugin'; +my $NQN = 'nqn.2026-01.com.example:test'; +my $OTHER_NQN = 'nqn.2026-01.com.example:other'; +my $UUID = '12345678-1234-1234-1234-123456789abc'; +my $ROOT = '/sys/kernel/config/nvmet'; +my $hostnqn_a = 'nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-000000000001'; +my $hostnqn_b = 'nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-000000000002'; + +sub make_key($hash, $length, $seed = 1) { + my $raw = join('', map { chr(($_ * 131 + $seed * 17) % 256) } 1 .. $length); + return "DHHC-1:$hash:" . encode_base64($raw . pack('V', crc32($raw)), '') . ':'; +} +my $KEY = make_key('00', 32); +my $KEY_B = make_key('00', 32, 2); + +sub scfg(%override) { + return { + type => 'zfsnvme', + server => '192.0.2.10', + pool => 'tank', + subsysnqn => $NQN, + 'nvme-portals' => '192.0.2.21,192.0.2.22', + 'nvme-host-ifaces' => 'ens19,ens20', + 'nvme-host-nqns' => "$hostnqn_a,$hostnqn_b", + %override, + }; +} + +# Calls a plugin package sub by name, so a mocked sub is the one called. +sub nv($name, @args) { + my $code = $PLUGIN->can($name) // die "plugin has no sub '$name'\n"; + return $code->(@args); +} + +# Mocks. Target calls are answered by $TARGET and the ssh command of the runner by $COMMAND. Sysfs +# and key files come from %FILES and %DIRS, block devices are %BLOCK and symbolic links %LINKS. The +# host lock runs its steps inline and records their limit in @FORKS, waits advance $NOW. Only the +# runner tests, which set $COMMAND, may reach run_command. + +our ($TARGET, $COMMAND, $NOW, $TCP_LOADED); +our (%FILES, %DIRS, %CONFIG, %BLOCK, %LINKS, @TARGET_CALLS, @WARNINGS, @WRITES); +our (@SYSFS_WRITES, @CONNECTS, @ACTIVATIONS, @UNLINKED, @RESTRICTED, @DELETED, @FORKS); +our (%REFUSE, %CONNECT_STATE); +$NOW = 1_000_000; + +my $nvme_mock = Test::MockModule->new($PLUGIN); +my $file_mock = Test::MockModule->new('PVE::File'); +my $sysfs_mock = Test::MockModule->new('PVE::SysFSTools'); +my $tools_mock = Test::MockModule->new('PVE::Tools'); +my $network_mock = Test::MockModule->new('PVE::Network'); +my $storage_mock = Test::MockModule->new('PVE::Storage'); +my $parent_mock = Test::MockModule->new('PVE::Storage::Plugin'); + +$nvme_mock->redefine( + _nvmet_run => sub($scfg, $steps, %opts) { + push @TARGET_CALLS, { steps => $steps, %opts }; + die "unexpected NVMe target call '$opts{op}'\n" if !$TARGET; + return $TARGET->($steps, %opts); + }, +); +# also recorded in case the caller handles the error, the last test checks that there is none +our @COMMANDS; +my $no_command = sub($cmd, %opts) { + push @COMMANDS, $cmd; + die "test error: unexpected command '" . (ref($cmd) ? $cmd->[0] : $cmd) . "'\n"; +}; +$nvme_mock->redefine( + run_command => sub($cmd, %opts) { + return $COMMAND ? $COMMAND->($cmd, %opts) : $no_command->($cmd, %opts); + }, +); +$tools_mock->redefine(run_command => $no_command); +$nvme_mock->redefine(_now => sub () { return $NOW }); +$nvme_mock->redefine(_sleep => sub($seconds) { $NOW += $seconds; return }); +$nvme_mock->redefine(_block_device => sub($path) { return $BLOCK{$path} }); +$nvme_mock->redefine(_link_target => sub($path) { return $LINKS{$path} }); +$nvme_mock->redefine(_nvme_tcp_loaded => sub () { return $TCP_LOADED }); +$nvme_mock->redefine(_restrict_attr => sub($path) { push @RESTRICTED, $path; return }); +$nvme_mock->redefine(_unlink_file => sub($path) { push @UNLINKED, $path; return 1 }); +$nvme_mock->redefine(log_warn => sub($message) { push @WARNINGS, $message; return }); +$nvme_mock->redefine(file_read_firstline => sub($path) { return $FILES{$path} }); +$nvme_mock->redefine( + file_set_contents => sub($path, $data, $perm = undef, @rest) { + push @WRITES, { path => $path, data => $data, perm => $perm }; + return; + }, +); +$nvme_mock->redefine(make_path => sub(@args) { push @WRITES, { make_path => [@args] }; return }); +$nvme_mock->redefine(_local_iface_exists => sub($iface) { return 1 }); + +my $connect_mock = sub($options, $names) { + my %option = map { split(/=/, $_, 2) } split(/,/, $options); + push @CONNECTS, "$option{traddr}\@$option{host_iface}"; + die "connect failed: Connection refused\n" if $REFUSE{ $option{traddr} }; + my $instance = 70 + scalar(@CONNECTS); + add_controller( + "nvme$instance", + $option{traddr}, + $option{trsvcid}, + $option{host_iface}, + $CONNECT_STATE{ $option{traddr} } // 'live', + ); + return $instance; +}; +$nvme_mock->redefine(_fabrics_connect => $connect_mock); +my $delete_mock = sub($controllers) { + for my $controller ($controllers->@*) { + push @DELETED, $controller->{name}; + $DIRS{'/sys/class/nvme'} = + [grep { $_ ne $controller->{name} } ($DIRS{'/sys/class/nvme'} // [])->@*]; + } + return scalar($controllers->@*); +}; +$nvme_mock->redefine(_delete_controllers => $delete_mock); +# $code runs inline, @LOCKS records when the lock is held and $LOCK_BUSY makes it unavailable. +# $ON_LOCK runs once the lock is held, with the number of times it was taken, for a change that +# another process makes while this one waits. +our (@LOCKS, $LOCK_BUSY, $LOCK_HELD, $ON_LOCK); +my $nvmeof_mock = Test::MockModule->new('PVE::NVMeOF'); +my $lock_inline = sub($code, $limit = undef) { + push @FORKS, $limit; + die "NVMe over Fabrics is busy - another operation is still running\n" if $LOCK_BUSY; + die "test error: the host lock is not re-entrant\n" if $LOCK_HELD; + push @LOCKS, 'enter'; + local $LOCK_HELD = 1; + my $res = eval { + $ON_LOCK->(scalar(grep { $_ eq 'enter' } @LOCKS)) if $ON_LOCK; + $code->(); + }; + my $error = $@; + push @LOCKS, 'leave'; + die $error if $error; + return $res; +}; +$nvmeof_mock->redefine(with_lock => $lock_inline); +# host_identity reads the host files through its own file_read_firstline +$nvmeof_mock->redefine(file_read_firstline => sub($path) { return $FILES{$path} }); +$file_mock->redefine( + dir_glob_foreach => sub($dir, $regex, $func) { + for my $entry (($DIRS{$dir} // [])->@*) { + if (my @res = $entry =~ m/^($regex)$/) { + $func->(@res); + } + } + }, +); +my $sysfs_write = sub($path, $data, $allow_existing = undef) { + push @SYSFS_WRITES, [$path, $data]; + $FILES{$path} = $data =~ s/\n\z//r; + return 1; +}; +$sysfs_mock->redefine(file_write => $sysfs_write); +$network_mock->redefine(tcp_ping => sub($host, $port, $timeout = undef) { return 1 }); +$storage_mock->redefine(config => sub () { return { ids => {%CONFIG} } }); + +sub add_controller($name, $address, $port, $iface, $state = 'live', $nqn = $NQN) { + my $base = "/sys/class/nvme/$name"; + push $DIRS{'/sys/class/nvme'}->@*, $name; + $FILES{"$base/subsysnqn"} = $nqn; + $FILES{"$base/state"} = $state; + $FILES{"$base/address"} = "traddr=$address,trsvcid=$port,host_iface=$iface"; + $FILES{"$base/reconnect_delay"} //= '2'; + $FILES{"$base/ctrl_loss_tmo"} //= '600'; + $FILES{"$base/fast_io_fail_tmo"} //= 'off'; + return; +} + +sub reset_host() { + %DIRS = ('/sys/class/nvme-subsystem' => ['nvme-subsys7']); + %FILES = ( + '/sys/module/nvme_core/parameters/multipath' => 'Y', + '/etc/nvme/hostnqn' => $hostnqn_a, + '/etc/nvme/hostid' => '12345678-1234-1234-1234-123456789abc', + '/sys/class/nvme-subsystem/nvme-subsys7/subsysnqn' => $NQN, + ); + %BLOCK = %LINKS = %CONNECT_STATE = (); + @CONNECTS = @ACTIVATIONS = @SYSFS_WRITES = @WRITES = @WARNINGS = (); + @RESTRICTED = @UNLINKED = @DELETED = @FORKS = @LOCKS = (); + $LOCK_BUSY = 0; + $ON_LOCK = undef; + $TCP_LOADED = 1; + $NOW += 61; # a new minute: no storage is in its slow-path backoff + return; +} + +# [feature, volume, snapshot, running, expected] +for my $case ( + ['copy', 'base-100-disk-0', undef, 0, 1], + ['copy', 'vm-100-disk-0', undef, 0, 1], + ['copy', 'vm-100-disk-0', undef, 1, 1], + ['copy', 'base-100-disk-0/vm-101-disk-0', undef, 0, 1], + ['copy', 'vm-100-disk-0', 'snap', 0, undef], + ['clone', 'base-100-disk-0', undef, undef, 1], + ['clone', 'vm-100-disk-0', undef, undef, undef], + ['template', 'vm-100-disk-0', undef, undef, 1], + ['snapshot', 'vm-100-disk-0', undef, 0, 1], + ['snapshot', 'vm-100-disk-0', 'snap', 0, 1], +) { + my ($feature, $volname, $snap, $running, $expected) = $case->@*; + my @args = defined($running) ? ($snap, $running, {}) : (); + is( + $PLUGIN->volume_has_feature({}, $feature, 'nvmetest', $volname, @args), + $expected, + "$feature of $volname" + . ($snap ? '@' . $snap : '') + . ($running ? ' while running' : ''), + ); +} +ok(!$PLUGIN->storage_can_replicate({}, 'nvmetest'), 'no storage replication'); + +for my $case ( + ['vm-100-disk-0', ['vm-vol', 'vm-100-disk-0', 100, undef, undef, '', 'raw']], + ['vm-100-state-snap1', ['vm-state', 'vm-100-state-snap1', 100, undef, undef, '', 'raw']], + ['base-100-disk-0', ['vm-vol', 'base-100-disk-0', 100, undef, undef, 1, 'raw']], + ['subvol-100-disk-0', ['ct-vol', 'subvol-100-disk-0', 100, undef, undef, '', 'subvol']], + ['basevol-100-disk-0', ['ct-vol', 'basevol-100-disk-0', 100, undef, undef, 1, 'subvol']], + [ + 'base-100-disk-0/vm-200-disk-0', + ['vm-vol', 'vm-200-disk-0', 200, 'base-100-disk-0', 100, '', 'raw'], + ], + [ + 'basevol-100-disk-0/subvol-200-disk-0', + ['ct-vol', 'subvol-200-disk-0', 200, 'basevol-100-disk-0', 100, '', 'subvol'], + ], +) { + my ($name, $expected) = $case->@*; + is_deeply([$PLUGIN->parse_volname($name)], $expected, "parse_volname keeps the tuple of $name"); +} +for my $name ('not-a-volume', 'vm-no-id-disk-0', 'vm-100-disk 0', 'vm-100-') { + eval { $PLUGIN->parse_volname($name) }; + like($@, qr/unable to parse zfs volume name/, "rejects invalid volume name $name"); +} + +# as run_remote_command_tests.pl does for ZFS over iSCSI: such a name is refused before anything +# runs on the target, also with a trailing newline that $ would accept +for my $name ('vm-100-a b', 'vm-100-a:b', 'vm-100-a;b', 'vm-100-$(echo a)', "vm-100-a\n") { + (my $shown = $name) =~ s/\n/\\n/; + my $error = "unable to parse zfs volume name '$name'\n"; + local (@TARGET_CALLS, @COMMANDS) = (); + eval { $PLUGIN->parse_volname($name) }; + is($@, $error, "parse_volname refuses '$shown'"); + eval { $PLUGIN->parse_volname("base-100-disk-0/$name") }; + like($@, qr/^unable to parse zfs volume name/, "parse_volname refuses '$shown' in a clone"); + eval { $PLUGIN->alloc_image('nvmetest', scfg(), 100, 'raw', $name, 1024) }; + is($@, $error, "allocating '$shown' fails"); + is(scalar(@TARGET_CALLS) + scalar(@COMMANDS), 0, "nothing reaches the target for '$shown'"); +} +is($PLUGIN->get_parsed_format('vm-100-disk-0'), 'raw', 'the format of a raw volume'); +is($PLUGIN->volname_for_format('vm-100-disk-0', 'raw'), 'vm-100-disk-0', 'raw has no extension'); +eval { $PLUGIN->volname_for_format('vm-100-disk-0', 'qcow2') }; +like($@, qr/unsupported format 'qcow2'/, 'qcow2 volumes are not supported'); + +is_deeply( + \@PVE::Storage::ZFSNVMePlugin::ISA, + ['PVE::Storage::Plugin'], + 'the backend inherits directly from the storage plugin base', +); +for my $method (qw( + zfs_request zfs_get_lu_name zfs_create_lu zfs_resize_lu zfs_list_zvol zfs_parse_zvol_list + zfs_get_properties zfs_get_pool_stats zfs_create_zvol zfs_delete_zvol zfs_get_base +)) +{ + ok(!$PLUGIN->can($method), "the ZFS helper $method is private"); +} + +# the plugin isolates its properties, so each one in options() is declared except the common ones +{ + my $data = $PLUGIN->plugindata(); + my ($properties, $options) = ($PLUGIN->properties(), $PLUGIN->options()); + my $common = PVE::Storage::Plugin->base_properties(); + ok($data->{'isolate-properties'}, 'the plugin isolates its properties'); + is_deeply( + [grep { !$properties->{$_} && !$common->{$_} } sort keys $options->%*], + [], + 'options() lists no property that nobody declares', + ); + is_deeply( + [grep { !$options->{$_} } sort keys $properties->%*], + [], + 'and every property of the plugin, so each one can be set', + ); + is_deeply( + [grep { $common->{$_} } sort keys $properties->%*], + [], + 'the plugin declares no common property', + ); + is_deeply( + [grep { !$properties->{$_}->{title} } sort keys $properties->%*], + [], + 'every property has a title', + ); + + for my $kind (qw(advanced-properties hidden-properties)) { + is_deeply( + [grep { !$properties->{$_} && !$common->{$_} } sort keys $data->{$kind}->%*], + [], + "$kind names declared properties", + ); + } + is_deeply( + $data->{'sensitive-properties'}, + { 'dhchap-key' => 1 }, + 'the key stays out of storage.cfg', + ); + ok($properties->{'dhchap-key'}->{sensitive}, 'and is flagged in its schema'); + is_deeply($options->{'dhchap-key'}, { optional => 1 }, 'optional in options() for the hook'); + is_deeply( + $data->{content}, + [{ images => 1, 'vm-vol' => 1, 'vm-state' => 1 }, { images => 1 }], + 'the content types are images, VM disks and VM states, and images by default', + ); + + my $raw = + "zfsnvme: st\n\tserver 192.0.2.10\n\tpool tank\n\tblocksize 16k\n\tsparse 1\n" + . "\tsubsysnqn $NQN\n\tnvme-portals 192.0.2.21,192.0.2.22\n" + . "\tnvme-host-ifaces ens19,ens20\n\tnvme-host-nqns $hostnqn_a\n\tcontent images\n"; + my $cfg = PVE::Storage::Plugin->parse_config('storage.cfg', $raw); + is_deeply( + [map { $cfg->{ids}->{st}->{$_} } qw(server pool blocksize sparse subsysnqn)], + ['192.0.2.10', 'tank', '16k', 1, $NQN], + 'a storage section with the declared shared properties is read', + ); + my @warnings; + { + local $SIG{__WARN__} = sub($warning) { push @warnings, $warning }; + PVE::Storage::Plugin->parse_config('storage.cfg', $raw =~ s/16k/3k/r); + } + like( + join('', @warnings), + qr/unable to parse value of 'blocksize': invalid format/, + 'and they are checked with their own schema', + ); + + my $create = PVE::Storage::Plugin::add_sensitive_properties_to_schema( + PVE::Storage::Plugin->createSchema(), + ); + my $update = PVE::Storage::Plugin::add_sensitive_properties_to_schema( + PVE::Storage::Plugin->updateSchema(), 1, + ); + my %param = ( + type => 'zfsnvme', + storage => 'st', + server => '192.0.2.10', + pool => 'tank', + blocksize => '16k', + subsysnqn => $NQN, + 'nvme-portals' => '192.0.2.21,192.0.2.22', + 'nvme-host-ifaces' => 'ens19,ens20', + 'nvme-host-nqns' => $hostnqn_a, + 'dhchap-key' => $KEY, + ); + my $verify = sub($schema, %param) { + eval { PVE::JSONSchema::validate(\%param, $schema, '', {}) }; + return $@; + }; + is($verify->($create, %param), '', 'adding a storage takes its properties and the key'); + like( + $verify->($create, %param, pool => undef), + qr/pool: property is missing/, + 'and needs the required ones', + ); + my %changes = (storage => 'st', type => 'zfsnvme', 'nvme-iopolicy' => 'numa'); + is($verify->($update, %changes, 'dhchap-key' => $KEY), '', 'updating takes the key too'); + like( + $verify->($update, %changes, pool => 'other'), + qr/pool: property is not defined in schema/, + 'but not a property that cannot be changed', + ); +} + +is(nv('verify_nvme_nqn', $hostnqn_a), $hostnqn_a, 'accepts a standard NQN'); +ok(!nv('verify_nvme_nqn', 'not-an-nqn', 1), 'rejects an invalid NQN'); +ok(!nv('verify_nvme_nqn', 'nqn.x:' . ('a' x 220), 1), 'rejects a long NQN'); +is_deeply( + nv('parse_nvme_host_nqns', "$hostnqn_a, $hostnqn_b"), + [$hostnqn_a, $hostnqn_b], + 'parses the host allow-list', +); +ok(!nv('parse_nvme_host_nqns', "$hostnqn_a,$hostnqn_a", 1), 'rejects duplicate host NQNs'); +ok(!nv('parse_nvme_host_nqns', '', 1), 'requires a host NQN'); + +is_deeply( + nv('parse_nvme_portals', '198.51.100.11:4420,[2001:db8::11]:4421,198.51.100.12'), + [ + { address => '198.51.100.11', port => 4420, family => 'ipv4' }, + { address => '2001:db8::11', port => 4421, family => 'ipv6' }, + { address => '198.51.100.12', port => 4420, family => 'ipv4' }, + ], + 'parses IPv4 and IPv6 portals', +); +is_deeply( + [ + map { $_->{address} } + nv('parse_nvme_portals', '[2001:DB8:0:0::11],[2001:db8::0:12]:4421')->@* + ], + ['2001:db8::11', '2001:db8::12'], + 'IPv6 addresses are canonical', +); +eval { nv('parse_nvme_portals', '[2001:db8::11]:4420,[2001:db8:0::11]:4420'); }; +like($@, qr/duplicate NVMe\/TCP portal/, 'two spellings of one IPv6 portal are a duplicate'); +eval { nv('parse_nvme_portals', '198.51.100.11:4420,198.51.100.11:4420') }; +like($@, qr/duplicate NVMe\/TCP portal/, 'duplicate portal is rejected'); +eval { nv('parse_nvme_portals', '198.51.100.11,198.51.100.11:04420') }; +is($@, "duplicate NVMe/TCP portal '198.51.100.11:04420'\n", 'a port with a leading zero'); +eval { nv('parse_nvme_portals', '198.51.100.11:4421,[::ffff:198.51.100.11]:4421') }; +is( + $@, + "duplicate NVMe/TCP portal '[::ffff:198.51.100.11]:4421'\n", + 'an IPv4-mapped IPv6 address of an IPv4 portal', +); +is_deeply( + nv('parse_nvme_portals', '[::ffff:198.51.100.11]:4421'), + [{ address => '198.51.100.11', port => 4421, family => 'ipv4' }], + 'an IPv4-mapped IPv6 address is the IPv4 portal', +); +ok(!nv('parse_nvme_portals', '198.51.100.11:70000', 1), 'rejects an invalid port'); +ok(!nv('parse_nvme_portals', '[198.51.100.11]', 1), 'rejects IPv4 in brackets'); +# the addresses that PVE::NVMeOF::parse_portal refuses, also behind an IPv4-mapped IPv6 address +for my $portal ( + '0.0.0.0', + '0.0.0.0:4420', + '255.255.255.255', + '224.0.0.1', + '239.255.255.250:4420', + '[::]', + '[fe80::1]', + '[febf::1]:4420', + '[ff02::1]', + '[::ffff:0.0.0.0]', + '[::ffff:224.0.0.1]', +) { + ok(!nv('parse_nvme_portals', $portal, 1), "refuses the portal $portal"); +} +eval { nv('parse_nvme_portals', '198.51.100.11,0.0.0.0') }; +is($@, "invalid NVMe/TCP portal '0.0.0.0'\n", 'and names it in the error'); +my $too_many = join(',', map { "198.51.100.$_:4420" } 1 .. 17); +ok(!nv('parse_nvme_portals', $too_many, 1), 'limits the number of paths'); + +is_deeply( + nv( + '_configured_portals', + { + 'nvme-portals' => '198.51.100.11:4420,198.51.100.12:4421', + 'nvme-host-ifaces' => 'ens20,ens21', + }, + ), + [ + { address => '198.51.100.11', port => 4420, family => 'ipv4', host_iface => 'ens20' }, + { address => '198.51.100.12', port => 4421, family => 'ipv4', host_iface => 'ens21' }, + ], + 'binds each portal to its local interface', +); +eval { + nv( + '_configured_portals', + { + 'nvme-portals' => '198.51.100.11,198.51.100.12', + 'nvme-host-ifaces' => 'ens20', + }, + ); +}; +like($@, qr/one interface for each/, 'portal and interface counts must match'); +ok(!nv('parse_nvme_host_ifaces', 'ens20,not/an/interface', 1), 'rejects an invalid interface name'); +for my $name ('.', '..') { + ok(!nv('parse_nvme_host_ifaces', "ens20,$name", 1), "rejects the directory name '$name'"); +} +for my $option ('nvme-host-ifaces', 'nvme-host-nqns') { + my $opts = $PLUGIN->options()->{$option}; + ok(!$opts->{optional} && !$opts->{fixed}, "$option is required, and can be changed"); + my $config = scfg(type => 'zfsnvme', content => 'images', blocksize => '16k'); + delete $config->{$option}; + eval { $PLUGIN->check_config('st', $config, 1, 1) }; + like($@, qr/missing value for required option '\Q$option\E'/, "a new storage needs $option"); +} +$nvme_mock->redefine(_local_iface_exists => sub($iface) { return $iface eq 'ens20' }); +eval { nv('_validate_local_ifaces', [{ host_iface => 'ens20' }, { host_iface => 'ens21' }]); }; +like($@, qr/host interface 'ens21' does not exist/, 'a missing local interface fails preflight'); +$nvme_mock->redefine(_local_iface_exists => sub($iface) { return 1 }); + +my $listener_used = sub($address, $port, $storeid = 'existing') { + return "NVMe/TCP portal '$address' port $port is already used by storage '$storeid';" + . " give each storage its own address or port\n"; +}; +# [name, the existing storage, our overrides, error] +for my $case ( + [ + 'the NQN of another storage', + { server => '192.0.2.11', pool => 'tank/existing', subsysnqn => $NQN }, + {}, + qr/NQN is already used by storage 'existing'/, + ], + [ + 'the NQN and the listener of another storage', + { pool => 'data', subsysnqn => $NQN, 'nvme-portals' => '192.0.2.21' }, + {}, + "NVMe subsystem NQN is already used by storage 'existing'\n", + ], + [ + 'the pool of another storage', + { pool => 'tank' }, + {}, + qr/ZFS pool 'tank' on '192\.0\.2\.10' is already used/, + ], + [ + 'a pool inside ours', + { pool => 'tank/sub' }, + {}, + qr/ZFS pool 'tank' on '192\.0\.2\.10' overlaps the pool of storage 'existing'/, + ], + [ + 'a pool above ours', + { pool => 'tank' }, + { pool => 'tank/sub' }, + qr/overlaps the pool of storage 'existing'/, + ], + [ + 'a pool above ours on another server', + { pool => 'tank', server => '192.0.2.99' }, + { pool => 'tank/sub' }, + undef, + ], + ['a pool around ours', { pool => 'ta' }, {}, undef], + ['a parent pool', { pool => 'tan' }, {}, undef], + # one NVMe/TCP listener (family, address, port) per storage, on any server + [ + 'the listener of another storage', + { pool => 'data', 'nvme-portals' => '192.0.2.31,192.0.2.22' }, + {}, + $listener_used->('192.0.2.22', 4420), + ], + [ + 'the listener of another storage that names the default port', + { pool => 'data', 'nvme-portals' => '192.0.2.21:4420' }, + {}, + $listener_used->('192.0.2.21', 4420), + ], + [ + 'the listener of a disabled storage', + { pool => 'data', disable => 1, 'nvme-portals' => '192.0.2.21' }, + {}, + $listener_used->('192.0.2.21', 4420), + ], + [ + 'the listener of a storage that spells the server another way', + { server => 'nas.example', pool => 'data', 'nvme-portals' => '192.0.2.21' }, + {}, + $listener_used->('192.0.2.21', 4420), + ], + [ + 'the listener of a storage on another server', + { server => '192.0.2.99', pool => 'tank', 'nvme-portals' => '192.0.2.21' }, + {}, + $listener_used->('192.0.2.21', 4420), + ], + [ + 'an IPv6 listener written another way', + { pool => 'data', 'nvme-portals' => '[2001:db8:0::21]' }, + { 'nvme-portals' => '[2001:DB8::0021]:4420' }, + $listener_used->('2001:db8::21', 4420), + ], + [ + 'an IPv4 listener reached through an IPv4-mapped IPv6 address', + { pool => 'data', 'nvme-portals' => '[::ffff:192.0.2.21]' }, + {}, + $listener_used->('192.0.2.21', 4420), + ], + [ + 'an IPv4-mapped IPv6 address of an IPv4 listener', + { pool => 'data', 'nvme-portals' => '192.0.2.21' }, + { 'nvme-portals' => '[::FFFF:c000:215]' }, + $listener_used->('192.0.2.21', 4420), + ], + [ + 'the same addresses on other ports', + { pool => 'data', 'nvme-portals' => '192.0.2.21:4421,192.0.2.22:4421' }, + {}, + undef, + ], + [ + 'the same address on another port through another spelling of the server', + { + server => 'nas.example', + pool => 'data', + 'nvme-portals' => '192.0.2.31,192.0.2.22:4421', + }, + {}, + "storage 'existing' reaches target address '192.0.2.22' through server 'nas.example';" + . " use the same server value for both storages\n", + ], + [ + 'an IPv6 address written another way through another spelling of the server', + { server => 'nas.example', pool => 'data', 'nvme-portals' => '[2001:db8::0:21]:4421' }, + { 'nvme-portals' => '[2001:db8::21]' }, + qr/\Astorage 'existing' reaches target address '2001:db8::21' through server/, + ], + [ + 'other addresses on another server', + { server => 'nas.example', pool => 'tank', 'nvme-portals' => '192.0.2.31,192.0.2.32' }, + {}, + undef, + ], + [ + 'other addresses on the same server', + { pool => 'data', 'nvme-portals' => '192.0.2.31,[2001:db8::22]' }, + {}, + undef, + ], + ['a storage without portals', { pool => 'data' }, {}, undef], + # it cannot be activated, and is checked when its portals are fixed + [ + 'a storage whose portals do not parse', + { pool => 'data', 'nvme-portals' => '192.0.2.21,192.0.2.300' }, + {}, + undef, + ], + [ + 'the listener of another storage type', + { type => 'zfs', pool => 'tank', 'nvme-portals' => '192.0.2.21' }, + {}, + undef, + ], +) { + my ($name, $other, $ours, $error) = $case->@*; + my $existing = { + type => 'zfsnvme', + server => '192.0.2.10', + subsysnqn => $OTHER_NQN, + pool => 'x', + $other->%*, + }; + my $cfg = { ids => { existing => $existing } }; + eval { nv('_assert_unique_target', 'new', scfg($ours->%*), $cfg) }; + if (ref($error)) { + like($@, $error, "refuses $name"); + } elsif (defined($error)) { + is($@, $error, "refuses $name"); + } else { + is($@, '', "accepts $name"); + } +} + +{ + my $states = { + '198.51.100.11:4420' => [{ state => 'live', host_iface => 'eth0' }], + '198.51.100.12:4420' => [ + { state => 'connecting', host_iface => 'eth1' }, + { state => 'live', host_iface => 'ens21' }, + ], + '198.51.100.13:4420' => [{ state => 'dead', host_iface => 'ens22' }], + }; + my $portals = [ + { address => '198.51.100.11', port => 4420, host_iface => 'ens20' }, + { address => '198.51.100.12', port => 4420, host_iface => 'ens21' }, + { address => '198.51.100.13', port => 4420, host_iface => 'ens22' }, + ]; + is(nv('_live_portal_count', $states, $portals), 1, 'the wrong interface is not healthy'); + is(nv('_live_portal_count', $states, $portals, 1), 2, 'but it carries I/O'); +} + +# DHHC-1::: +for my $case (['00', 32], ['00', 48], ['00', 64], ['01', 32], ['02', 48], ['03', 64]) { + my $key = make_key($case->@*); + is(nv('_validate_secret', $key), $key, "accepts a $case->[1] byte key with hash $case->[0]"); +} +my $bad_crc = do { + my $raw = 'k' x 32; + 'DHHC-1:00:' . encode_base64($raw . pack('V', crc32($raw) ^ 1), '') . ':'; +}; +for my $case ( + ['a plaintext secret', 'plaintext'], + ['a key without the final colon', substr($KEY, 0, -1)], + ['an unknown hash', make_key('04', 32)], + ['a 48 byte key for SHA-256', make_key('01', 48)], + ['a 32 byte key for SHA-384', make_key('02', 32)], + ['a 32 byte key for SHA-512', make_key('03', 32)], + ['a 16 byte key', make_key('00', 16)], + ['a wrong CRC', $bad_crc], + ['truncated base64', substr($KEY, 0, -2) . ':'], + ['a key with a trailing newline', "$KEY\n"], +) { + my ($name, $key) = $case->@*; + eval { nv('_validate_secret', $key) }; + is($@, "invalid NVMe DH-HMAC-CHAP key representation\n", "rejects $name without echoing it"); +} +eval { nv('_validate_secret', undef) }; +is($@, "missing NVMe DH-HMAC-CHAP key\n", 'a missing key'); +# check_config only validates. Defaults are applied where they are used. +{ + $parent_mock->redefine( + check_config => sub($class, $id, $config, $create, $skip = undef) { return $config }, + ); + my $config = scfg(); + my $copy = { $config->%* }; + is_deeply($PLUGIN->check_config('st', $config, 1, 1), $copy, 'no defaults on create'); + is_deeply( + $PLUGIN->check_config('st', { 'nvme-host-ifaces' => 'ens20,ens21' }, 0), + { 'nvme-host-ifaces' => 'ens20,ens21' }, + 'a partial update is accepted', + ); + eval { $PLUGIN->check_config('st', scfg('nvme-fast-io-fail-tmo' => 700), 1, 1) }; + like($@, qr/must not exceed nvme-ctrl-loss-tmo/, 'validated against the default'); + eval { $PLUGIN->check_config('st', scfg('nvme-host-ifaces' => 'ens19'), 1, 1) }; + like($@, qr/one interface for each/, 'cross-field validation stays'); + # the pool is validated like every later use of it validates it + is( + $PLUGIN->check_config('st', scfg(pool => 'tank/nvme.1'), 1, 1)->{pool}, + 'tank/nvme.1', + 'a nested pool is accepted', + ); + for my $pool ('-rH', 'tank/vm 1', '') { + eval { $PLUGIN->check_config('st', scfg(pool => $pool), 1, 1) }; + is($@, "invalid ZFS pool name\n", "the pool name '$pool' is refused on create"); + eval { $PLUGIN->check_config('st', { pool => $pool }, 0) }; + is($@, "invalid ZFS pool name\n", 'and on update'); + } + $parent_mock->unmock('check_config'); +} +eval { + nv( + '_validate_fail_fast_timeout', + { 'nvme-ctrl-loss-tmo' => 30, 'nvme-fast-io-fail-tmo' => 31 }, + 600, + ); +}; +like($@, qr/must not exceed nvme-ctrl-loss-tmo/, 'fast I/O fail cannot outlive the loss timeout'); +eval { + nv( + '_validate_fail_fast_timeout', + { 'nvme-ctrl-loss-tmo' => -1, 'nvme-fast-io-fail-tmo' => 30 }, + 600, + ); +}; +is($@, '', 'fast I/O fail stays valid with infinite reconnects'); + +{ + my $secret = '/etc/pve/priv/storage/nvmetest.nvme-dhchap'; + local %CONFIG = (); + local %FILES = (); + local @WRITES = (); + eval { $PLUGIN->on_add_hook('nvmetest', scfg()) }; + is($@, "missing NVMe DH-HMAC-CHAP key\n", 'a new storage needs a key'); + eval { $PLUGIN->on_add_hook('nvmetest', scfg(), 'dhchap-key' => $KEY) }; + is($@, '', 'a new storage stores its key'); + is_deeply( + [grep { $_->{path} } @WRITES], + [{ path => $secret, data => "$KEY\n", perm => 0600 }], + 'readable by root only', + ); + is_deeply( + [map { $_->{make_path} } grep { $_->{make_path} } @WRITES], + [['/etc/pve/priv/storage', { mode => 0700 }]], + 'in a private directory', + ); + + local $FILES{$secret} = $KEY; + @WRITES = (); + eval { + $PLUGIN->on_update_hook_full( + 'nvmetest', + scfg(), + { 'nvme-host-ifaces' => 'ens21,ens22' }, + ); + }; + is($@, '', 'a partial update validates against the current configuration'); + eval { $PLUGIN->on_update_hook_full('nvmetest', scfg(), {}, undef, { 'dhchap-key' => $KEY }) }; + is($@, '', 'the same key is accepted'); + eval { + $PLUGIN->on_update_hook_full('nvmetest', scfg(), {}, undef, { 'dhchap-key' => $KEY_B }); + }; + like($@, qr/NVMe DH-HMAC-CHAP key rotation is not supported/, 'a different key is refused'); + eval { $PLUGIN->on_update_hook_full('nvmetest', scfg(), { 'nvme-host-nqns' => $hostnqn_a }) }; + like($@, qr/removing NVMe host NQN '\Q$hostnqn_b\E' is not supported/, 'no host removal'); + eval { $PLUGIN->on_update_hook_full('nvmetest', scfg(), {}, ['nvme-host-nqns']) }; + like($@, qr/at least one NVMe host NQN is required/, 'deleting the host list is refused'); + @WRITES = (); + eval { + my $update = { 'nvme-host-nqns' => "$hostnqn_a,$hostnqn_b,nqn.x:c" }; + $PLUGIN->on_update_hook_full('nvmetest', scfg(), $update); + }; + is($@, '', 'adding a host is accepted'); + is_deeply(\@WRITES, [], 'without storing the key again'); + + delete local $FILES{$secret}; + @WRITES = (); + eval { $PLUGIN->on_update_hook_full('nvmetest', scfg(), {}, undef, { 'dhchap-key' => $KEY }) }; + is($@, '', 'a storage without key file'); + is_deeply( + [grep { $_->{path} } @WRITES], + [{ path => $secret, data => "$KEY\n", perm => 0600 }], + 'stores the new key', + ); +} + +# nvmet keeps one key per host NQN, so storages of one target that share a host must share the key +{ + my $other = { + type => 'zfsnvme', + server => '192.0.2.10', + pool => 'data', + subsysnqn => $OTHER_NQN, + 'nvme-host-nqns' => $hostnqn_b, + }; + my $cfg = { ids => { other => $other, nvmetest => scfg() } }; + local %FILES = ('/etc/pve/priv/storage/other.nvme-dhchap' => $KEY_B); + eval { nv('_assert_shared_host_key', 'nvmetest', scfg(), $KEY, $cfg) }; + is( + $@, + "storage 'other' uses a different DH-HMAC-CHAP key for the same NVMe host NQNs" + . " on '192.0.2.10'\n", + 'a different key for a shared host is refused', + ); + for my $case ( + ['the same key', $KEY_B, {}], + ['another server', $KEY, { server => '192.0.2.11' }], + ['no shared host', $KEY, { 'nvme-host-nqns' => 'nqn.2026-01.com.example:other-host' }], + ['another storage type', $KEY, { type => 'zfs' }], + ) { + my ($name, $key, $change) = $case->@*; + my $ids = { ids => { other => { $other->%*, $change->%* } } }; + eval { nv('_assert_shared_host_key', 'nvmetest', scfg(), $key, $ids); }; + is($@, '', "accepts $name"); + } + { + local %FILES = (); + eval { nv('_assert_shared_host_key', 'nvmetest', scfg(), $KEY, $cfg); }; + is($@, '', 'a storage without a key file is skipped'); + } + + local %CONFIG = (other => $other); + local @WRITES = (); + eval { $PLUGIN->on_add_hook('nvmetest', scfg(), 'dhchap-key' => $KEY) }; + like($@, qr/storage 'other' uses a different DH-HMAC-CHAP key/, 'on_add_hook refuses it'); + unlike($@, qr/DHHC-1/, 'without naming a key'); + is_deeply([grep { $_->{path} } @WRITES], [], 'and stores no key'); + eval { $PLUGIN->on_add_hook('nvmetest', scfg(), 'dhchap-key' => $KEY_B) }; + is($@, '', 'the same key is accepted'); + + local $FILES{'/etc/pve/priv/storage/nvmetest.nvme-dhchap'} = $KEY; + my $current = scfg('nvme-host-nqns' => $hostnqn_a); + eval { + $PLUGIN->on_update_hook_full( + 'nvmetest', + $current, + { 'nvme-host-nqns' => "$hostnqn_a,$hostnqn_b" }, + ); + }; + like($@, qr/storage 'other' uses a different DH-HMAC-CHAP key/, 'nor shared by an update'); + eval { $PLUGIN->on_update_hook_full('nvmetest', $current, { 'nvme-iopolicy' => 'numa' }) }; + is($@, '', 'other updates are accepted'); +} + +# an update checks the new portals, and the current definition of the storage itself does not count +{ + my $secret = '/etc/pve/priv/storage/nvmetest.nvme-dhchap'; + my $other = scfg( + subsysnqn => $OTHER_NQN, + pool => 'data', + 'nvme-portals' => '192.0.2.23', + 'nvme-host-ifaces' => 'ens21', + ); + local %CONFIG = (other => $other); + local %FILES = (); + local @WRITES = (); + my $shared = scfg('nvme-portals' => '192.0.2.21,192.0.2.23'); + eval { $PLUGIN->on_add_hook('nvmetest', $shared, 'dhchap-key' => $KEY) }; + is($@, $listener_used->('192.0.2.23', 4420, 'other'), 'on_add_hook refuses a used listener'); + is_deeply([grep { $_->{path} } @WRITES], [], 'and stores no key'); + + %CONFIG = (other => $other, nvmetest => scfg()); + $FILES{$secret} = $KEY; + my $update = sub($current, $portals) { + eval { + $PLUGIN->on_update_hook_full('nvmetest', $current, { 'nvme-portals' => $portals }); + }; + return $@; + }; + is($update->(scfg(), '192.0.2.22,192.0.2.21'), '', 'an update keeps its own listeners'); + is( + $update->(scfg(), '192.0.2.21,192.0.2.23:4420'), + $listener_used->('192.0.2.23', 4420, 'other'), + 'on_update_hook_full refuses a used listener', + ); + is($update->(scfg(), '192.0.2.21,192.0.2.23:4421'), '', 'but not its address on another port'); + is($update->($shared, '192.0.2.21,192.0.2.22'), '', 'an update can leave a used listener'); + is_deeply([grep { $_->{path} } @WRITES], [], 'without storing the key again'); +} + +# a new storage cannot use a subsystem that an nvmeof storage lists, an existing one is not checked +{ + my $nvmeof = { type => 'nvmeof', subsysnqn => $NQN, portals => '192.0.2.21' }; + local %FILES = (); + local @WRITES = (); + local %CONFIG = (san => $nvmeof); + eval { $PLUGIN->on_add_hook('nvmetest', scfg(), 'dhchap-key' => $KEY) }; + is( + $@, + "NVMe subsystem NQN is already used by storage 'san'\n", + 'a new storage refuses the subsystem of an nvmeof storage', + ); + is_deeply([grep { $_->{path} } @WRITES], [], 'and stores no key'); + + %CONFIG = (san => { $nvmeof->%*, subsysnqn => $OTHER_NQN }); + eval { $PLUGIN->on_add_hook('nvmetest', scfg(), 'dhchap-key' => $KEY) }; + is($@, '', 'another subsystem is accepted'); + + %CONFIG = (nvmetest => $nvmeof); + eval { $PLUGIN->on_add_hook('nvmetest', scfg(), 'dhchap-key' => $KEY) }; + is($@, '', 'the storage itself does not count'); + + local $FILES{'/etc/pve/priv/storage/nvmetest.nvme-dhchap'} = $KEY; + %CONFIG = (san => $nvmeof); + eval { $PLUGIN->on_update_hook_full('nvmetest', scfg(), { 'nvme-iopolicy' => 'numa' }) }; + is($@, '', 'a storage that exists keeps working'); +} + +# pvesm reads the key from a file, so it never appears on a command line. +{ + require PVE::CLI::pvesm; + + my $dir = tempdir(CLEANUP => 1); + my $file = sub($name, $content) { + open(my $fh, '>', "$dir/$name") or die "open: $!\n"; + print {$fh} $content; + close($fh); + return "$dir/$name"; + }; + my $padded = $file->('padded', " $KEY \nsecond line\n"); + my $empty = $file->('empty', "\n"); + my %map = map { + my $command = $_; + ( + $command => ( + grep { $_->{name} eq 'dhchap-key' } + PVE::CLI::pvesm::param_mapping($command)->@* + )[0], + ) + } qw(create update); + ok($map{create} && $map{update}, 'pvesm create and update map dhchap-key'); + my $read = $map{create}->{func}; + eval { $read->($KEY) }; + is( + $@, + "dhchap-key expects the path of a file containing the key\n", + 'a key in place of the file name is refused without repeating it', + ); + is($read->($padded), $KEY, 'the first line of the file, trimmed'); + eval { $read->($empty) }; + like($@, qr/key file '.*' is empty/, 'an empty file is refused'); + eval { $read->('/dev/null') }; + like($@, qr/is empty/, 'a file that is not regular, like /dev/stdin, is read'); + eval { $read->($dir) }; + like($@, qr/expects the path of a file/, 'a directory is refused'); +} + +sub target(%answers) { + return sub($steps, %opts) { + my $answer = $answers{ $opts{op} } // die "unexpected NVMe target call '$opts{op}'\n"; + return $answer->($steps, %opts) if ref($answer) eq 'CODE'; + return { rc => 0, out => $answer, err => '' }; + }; +} + +my @volume_list = ( + "tank\t-\t-\tfilesystem", + "tank/vm-100-disk-0\t1048576\t-\tvolume", + "tank/vm-200-disk-0\t1048576\t-\tvolume", + "tank/vm-300-disk-0\t1048576\t-\tvolume", + "tank/vm-400-disk-0\t1048576\t-\tvolume", + "tank/base-90-disk-0\t1048576\t-\tvolume", + "tank/vm-101-disk-0\t1048576\ttank/base-90-disk-0\@__base__\tvolume", + "tank/vm-102-disk-0\t1048576\ttankXprod/base-90-disk-0\@__base__\tvolume", + "tank/subvol-103-disk-0\t-\t-\tfilesystem", + "tank/vm-104-disk-0\t-\t-\tfilesystem", +); +my @ownership = ( + "tank\t-\t-", + "tank/vm-100-disk-0\t$NQN\tlocal", + "tank/vm-200-disk-0\t-\t-", + "tank/vm-300-disk-0\t$NQN\tinherited from tank", + "tank/vm-400-disk-0\t$NQN\treceived", + "tank/base-90-disk-0\t$NQN\tlocal", + "tank/vm-101-disk-0\t$NQN\tlocal", + "tank/vm-102-disk-0\t$NQN\tlocal", + "tank/subvol-103-disk-0\t$OTHER_NQN\tlocal", + "tank/vm-104-disk-0\t$NQN\tlocal", +); +{ + local $TARGET = target('zfs list' => \@volume_list, 'zfs get' => \@ownership); + my $images = $PLUGIN->list_images('nvmetest', scfg()); + my %by_volid = map { $_->{volid} => $_ } $images->@*; + my %by_name = map { $_->{name} => $_ } $images->@*; + is_deeply( + [sort keys %by_name], + ['base-90-disk-0', 'vm-100-disk-0', 'vm-101-disk-0', 'vm-102-disk-0', 'vm-400-disk-0'], + 'listing requires a zvol with a local or received owner', + ); + is( + $by_name{'vm-102-disk-0'}->{parent}, + 'tankXprod/base-90-disk-0@__base__', + 'a foreign pool origin is not mistaken for a local parent', + ); + is_deeply( + $by_volid{'nvmetest:base-90-disk-0/vm-101-disk-0'}, + { + name => 'vm-101-disk-0', + size => 1048576, + parent => 'base-90-disk-0@__base__', + format => 'raw', + vmid => 101, + volid => 'nvmetest:base-90-disk-0/vm-101-disk-0', + }, + 'a linked clone keeps the volume ID format of the ZFS plugins', + ); + is_deeply( + [map { $_->{volid} } $PLUGIN->list_images('nvmetest', scfg(), 400)->@*], + ['nvmetest:vm-400-disk-0'], + 'filtered by VM', + ); + my $listed = $PLUGIN->list_images('nvmetest', scfg(), undef, ['nvmetest:vm-100-disk-0']); + is_deeply([map { $_->{volid} } $listed->@*], ['nvmetest:vm-100-disk-0'], 'by volume list'); + is( + $PLUGIN->find_free_diskname('nvmetest', scfg(), 200), + 'vm-200-disk-1', + 'a name held by an unowned zvol is not handed out', + ); + is($PLUGIN->find_free_diskname('nvmetest', scfg(), 90), 'vm-90-disk-1', 'nor one of a base'); + is( + $PLUGIN->find_free_diskname('nvmetest', scfg(), 104), + 'vm-104-disk-1', + 'nor one held by a filesystem', + ); + my @steps = map { $_->{steps}->@* } @TARGET_CALLS; + ok(!grep({ $_->[0] ne 'zfs' || $_->[1] !~ /\A(?:get|list)\z/ } @steps), 'listing only reads'); +} + +{ + my @warnings; + local $SIG{__WARN__} = sub($warning) { push @warnings, $warning }; + for my $case ( + [['100', '200'], [300, 100, 200, 1]], + [['-', '200'], [0, 0, 0, 0]], + [['1'], [0, 0, 0, 0]], + ) { + local $TARGET = target('zfs get' => $case->[0]); + is_deeply([$PLUGIN->status('nvmetest', scfg())], $case->[1], "status for '$case->[0]->@*'"); + } + local $TARGET = + target('zfs get' => sub(@args) { return { rc => 255, out => [], err => 'no route' } }); + is_deeply([$PLUGIN->status('nvmetest', scfg())], [0, 0, 0, 0], 'unreachable is inactive'); + is(scalar(@warnings), 3, 'and every inactive status warns'); + like($warnings[0], qr/unexpected ZFS pool usage for storage 'nvmetest'/, 'about the usage'); + is( + $warnings[-1], + "storage 'nvmetest': zfs error on '192.0.2.10': no route\n", + 'or naming the storage and the target', + ); +} + +{ + local @TARGET_CALLS = (); + local $TARGET = target(); + eval { $PLUGIN->volume_resize(scfg(), 'nvmetest', 'vm-100-disk-0', 2 * 1024**3, 1) }; + like( + $@, + qr/online resize is not supported for NVMe\/TCP block devices; stop the VM first/, + 'online resize is refused', + ); + eval { $PLUGIN->volume_resize(scfg(), 'nvmetest', 'vm-100-disk-0', 2 * 1024**3, 0, 'snap') }; + like($@, qr/resizing a snapshot is not supported/, 'as is resizing a snapshot'); + is_deeply(\@TARGET_CALLS, [], 'before any target call'); + for my $method (qw(volume_export volume_import rename_volume rename_snapshot)) { + eval { $PLUGIN->$method(scfg(), 'nvmetest', 'vm-100-disk-0') }; + like($@, qr/not supported/, "$method is not supported"); + } + for my $direction (qw(export import)) { + my $formats = "volume_${direction}_formats"; + is_deeply( + [$PLUGIN->$formats(scfg(), 'nvmetest', 'vm-100-disk-0')], + [], + "no $direction formats", + ); + } + is($PLUGIN->deactivate_volume('nvmetest', scfg(), 'vm-100-disk-0'), 1, 'no-op deactivation'); + eval { $PLUGIN->deactivate_volume('nvmetest', scfg(), 'vm-100-disk-0', 'snap') }; + like($@, qr/unable to deactivate snapshot/, 'snapshots cannot be deactivated'); +} + +{ + $nvme_mock->redefine(_nvmet_volume_uuid => sub($scfg, $name) { return $UUID }); + is_deeply( + $PLUGIN->qemu_blockdev_options(scfg(), 'nvmetest', 'vm-100-disk-0'), + { driver => 'host_device', filename => "/dev/disk/by-id/nvme-uuid.$UUID" }, + 'the QEMU host_device driver on the stable namespace UUID link', + ); + eval { + my $options = { 'snapshot-name' => 's' }; + $PLUGIN->qemu_blockdev_options(scfg(), 'nvmetest', 'vm-100-disk-0', undef, $options); + }; + like($@, qr/direct access to snapshots not implemented/, 'snapshots have no block device'); + $nvme_mock->unmock('_nvmet_volume_uuid'); +} + +{ + my $run = $nvme_mock->original('_nvmet_run'); + my @runs; + local $COMMAND = sub($cmd, %opts) { + push @runs, { cmd => $cmd, %opts }; + return 0; + }; + my $steps = [['zfs', 'get', '-H', 'type', 'tank'], ['printf', '%s\n', 'x y']]; + my $res = $run->(scfg(), $steps, op => 'test'); + is_deeply( + $runs[0]->{cmd}, + [ + '/usr/bin/ssh', + '-o', + 'BatchMode=yes', + '-o', + 'ConnectTimeout=10', + '-o', + 'LogLevel=ERROR', + '-i', + '/etc/pve/priv/zfs/192.0.2.10_id_rsa', + '--', + 'root@192.0.2.10', + q{zfs get -H type tank && printf '%s\n' 'x y'}, + ], + 'one ssh argv with the rendered command, and no login banner in errors', + ); + unlike(join(' ', $runs[0]->{cmd}->@*), qr/perl/, 'no Perl runs on the target'); + is($runs[0]->{timeout}, 15, 'reads time out after 15 seconds by default'); + ok(!$runs[0]->{noerr} && !exists($runs[0]->{input}), + 'failures are exceptions, stdin is closed'); + is_deeply($res, { rc => 0, out => [], err => '' }, 'a successful call'); + + @runs = (); + $run->( + scfg(), + [{ key => ["$ROOT/hosts/$hostnqn_a/dhchap_key"] }], + op => 'key', + input => "$KEY\n", + timeout => 7, + ); + is($runs[0]->{input}, "$KEY\n", 'the key goes to stdin'); + unlike(join(' ', $runs[0]->{cmd}->@*), qr/DHHC-1/, 'and never into the command line'); + is($runs[0]->{timeout}, 7, 'with the timeout of the caller'); + + for my $case ( + [ + 'output and the first error line', + sub(%o) { + $o{outfunc}->('a'); + $o{outfunc}->('b'); + $o{errfunc}->(''); + $o{errfunc}->('first'); + $o{errfunc}->('second'); + die "command 'ssh' failed: exit code 3\n"; + }, + { rc => 3, out => ['a', 'b'], err => 'first' }, + ], + [ + 'an exit code without message', + sub(%o) { die "command 'ssh' failed: exit code 2\n" }, + { rc => 2, out => [], err => 'exit code 2' }, + ], + [ + 'a timeout', + sub(%o) { die "command 'ssh' failed: got timeout\n" }, + { rc => -1, out => [], err => 'timeout' }, + ], + [ + 'an ssh that could not connect', + sub(%o) { die "command 'ssh' failed: exit code 255\n" }, + { rc => 255, out => [], err => 'exit code 255' }, + ], + [ + 'an ssh killed by a signal', + sub(%o) { die "command 'ssh' failed: got signal 9\n" }, + { rc => -1, out => [], err => 'ssh failed' }, + ], + ) { + my ($name, $behaviour, $expected) = $case->@*; + local $COMMAND = sub($cmd, %opts) { return $behaviour->(%opts) }; + is_deeply( + $run->(scfg(), [['cat', '/proc/mounts']], op => 'test'), + $expected, + "returns $name", + ); + } + for my $exception ("received interrupt\n", "command 'ssh $KEY' failed: received interrupt\n") { + local $COMMAND = sub($cmd, %opts) { $opts{outfunc}->('partial'); die $exception }; + eval { $run->(scfg(), [['cat', '/proc/mounts']], op => 'test') }; + is($@, "received interrupt\n", 'a stopped task dies with the task marker and nothing else'); + } + @runs = (); + eval { $run->(scfg(), [['cat', '/proc/mounts']]) }; + like($@, qr/NVMe target call without label/, 'every call has a label'); + eval { $run->(scfg(), [['printf', '%s', 'x' x 65536]], op => 'test') }; + like($@, qr/NVMe target command too long/, 'oversized calls are refused'); + is_deeply(\@runs, [], 'before running anything'); +} + +subtest 'vdisk_alloc dispatches under the shared storage lock' => sub { + my $cluster_mock = Test::MockModule->new('PVE::Cluster'); + my (@locks, @allocations); + $cluster_mock->redefine( + cfs_lock_storage => sub($storeid, $timeout, $func, @param) { + push @locks, [$storeid, $timeout]; + return $func->(@param); + }, + ); + $parent_mock->redefine(lookup => sub($class, $type) { return $PLUGIN }); + $storage_mock->redefine(activate_storage => sub($cfg, $storeid) { return 1 }); + $nvme_mock->redefine( + alloc_image => sub($class, $storeid, $scfg, $vmid, $fmt, $name, $size) { + push @allocations, [$storeid, $vmid, $fmt, $name, $size]; + return $name; + }, + ); + my $cfg = { ids => { nvmetest => scfg(shared => 1) } }; + is( + PVE::Storage::vdisk_alloc($cfg, 'nvmetest', 105, 'raw', 'vm-105-disk-0', 131_072), + 'nvmetest:vm-105-disk-0', + 'core allocation returns the allocated volume ID', + ); + is_deeply(\@locks, [['nvmetest', undef]], 'cfs_lock_storage gets the timeout of the core'); + is_deeply( + \@allocations, + [['nvmetest', 105, 'raw', 'vm-105-disk-0', 131_072]], + 'alloc_image runs once inside the lock', + ); + $nvme_mock->unmock('alloc_image'); + $storage_mock->unmock('activate_storage'); + $parent_mock->unmock('lookup'); +}; + +done_testing(); + +1; -- 2.54.0.windows.1