* [PATCH proxmox-i18n v3] update Simplified Chinese translations
@ 2026-02-04 12:19 3% ` Kefu Chai
0 siblings, 0 replies; 43+ results
From: Kefu Chai @ 2026-02-04 12:19 UTC (permalink / raw)
To: pve-devel
Signed-off-by: Kefu Chai <k.chai@proxmox.com>
---
zh_CN.po | 2663 +++++++++++++++++++++---------------------------------
1 file changed, 1028 insertions(+), 1635 deletions(-)
diff --git a/zh_CN.po b/zh_CN.po
index 70ae51c..f4e7532 100644
--- a/zh_CN.po
+++ b/zh_CN.po
@@ -7,53 +7,48 @@ msgid ""
msgstr ""
"Project-Id-Version: proxmox translations\n"
"Report-Msgid-Bugs-To: <support@proxmox.com>\n"
-"POT-Creation-Date: 2025-12-10 15:47+0100\n"
-"PO-Revision-Date: 2025-07-19 10:22+0800\n"
-"Last-Translator: Try. <rov7@qq.com>\n"
-"Language-Team: Chinese (simplified) <tianmotrue@163.com>\n"
+"POT-Creation-Date: 2026-02-04 17:28+0800\n"
+"PO-Revision-Date: 2026-02-04 20:18+0800\n"
+"Last-Translator: Kefu Chai <k.chai@proxmox.com>\n"
+"Language-Team: Chinese (simplified) <support@proxmox.com>\n"
"Language: zh_CN\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
-"X-Generator: Poedit 3.4.4\n"
+"X-Generator: Poedit 3.6\n"
#: proxmox-datacenter-manager/ui/src/configuration/views.rs:147
-#, fuzzy
msgid "# Excluded"
-msgstr "排除"
+msgstr "排除个数"
#: proxmox-datacenter-manager/ui/src/configuration/views.rs:124
-#, fuzzy
msgid "# Included"
-msgstr "包括"
+msgstr "已包含个数"
#: proxmox-backup/www/window/VerifyAll.js:116
#: proxmox-backup/www/window/VerifyJobEdit.js:191
-#, fuzzy
msgid "# of Read Threads"
-msgstr "#工作线程"
+msgstr "读线程数"
#: proxmox-backup/www/window/VerifyAll.js:127
#: proxmox-backup/www/window/VerifyJobEdit.js:205
-#, fuzzy
msgid "# of Verify Threads"
-msgstr "#工作线程"
+msgstr "验证线程数"
#: proxmox-backup/www/tape/window/TapeBackup.js:129
#: proxmox-backup/www/tape/window/TapeBackupJob.js:184
msgid "# of Worker Threads"
-msgstr "#工作线程"
+msgstr "工作线程数"
#: pve-yew-mobile-gui/src/pages/page_node_status/dashboard_panel.rs:87
-#, fuzzy
msgid "% of one threads"
msgid_plural "% of {n} threads"
-msgstr[0] "#工作线程"
+msgstr[0] "%/{n}个线程"
#: pmg-gui/js/SystemOptions.js:88
msgid "'From:' for Admin Mail"
-msgstr "“来自于:”用于管理员邮件"
+msgstr "'From:' 用于 Admin Mail"
#: pve-manager/www/manager6/qemu/Options.js:103
msgid "(No boot device selected)"
@@ -61,7 +56,7 @@ msgstr "(没有选中启动设备)"
#: proxmox-yew-comp/src/form/pve/lxc_property/lxc_network_property.rs:91
msgid "(e.g. eth0)"
-msgstr ""
+msgstr "(例如 eth0)"
#: pve-manager/www/manager6/dc/AuthEditOpenId.js:98
msgid "(none)"
@@ -87,39 +82,36 @@ msgstr "/some/path"
#: pve-yew-mobile-gui/src/pages/page_node_status/dashboard_panel.rs:79
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_processor_property.rs:29
-#, fuzzy
msgid "1 Core"
msgid_plural "{n} Cores"
-msgstr[0] "核心"
+msgstr[0] "{n}个核心"
#: pve-yew-mobile-gui/src/pages/page_node_status/dashboard_panel.rs:80
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_processor_property.rs:30
#: proxmox-yew-comp/src/node_info.rs:238
-#, fuzzy
msgid "1 Socket"
msgid_plural "{n} Sockets"
-msgstr[0] "插槽"
+msgstr[0] "{n}个套接字"
#: proxmox-backup/www/datastore/OptionView.js:307
msgid "1048576 (0 disables cache)"
-msgstr ""
+msgstr "1048576 (0 禁用缓存)"
#: proxmox-backup/www/datastore/OptionView.js:299
msgid "1445 (24 hours 5 minutes)"
-msgstr ""
+msgstr "1445 (24 小时 5 分钟)"
#: pmg-gui/js/PBSConfig.js:39
msgid "5 Minutes"
-msgstr "5分钟"
+msgstr "5 分钟"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_connect.rs:244
-#, fuzzy
msgid "<IP/Hostname>:Port"
-msgstr "主机名/IP"
+msgstr "<IP/主机名>:端口"
#: proxmox-backup/www/window/TrafficControlEdit.js:306
msgid "A comma-separated list of networks to apply the (shared) limit."
-msgstr "要应用(共享)限制的以逗号分隔的网络列表。"
+msgstr "应用此共享限制的网络列表(逗号分隔)。"
#: proxmox-widget-toolkit/src/window/AddYubico.js:101
msgid "A currently valid Yubico OTP value"
@@ -146,12 +138,12 @@ msgstr "所选设备不在单独的 IOMMU 组中,请确保这是预期的。"
#: pve-manager/www/manager6/dc/RealmSyncJob.js:367
#: pve-manager/www/manager6/dc/SyncWindow.js:132
msgid "ACL"
-msgstr "ACL"
+msgstr "访问控制列表 (ACL)"
#: proxmox-yew-comp/src/auth_view.rs:447
#: proxmox-yew-comp/src/auth_edit_ldap.rs:241
msgid "ACLs"
-msgstr ""
+msgstr "访问控制列表"
#: proxmox-backup/www/config/CertificateView.js:63
#: proxmox-datacenter-manager/ui/src/certificates.rs:46
@@ -165,7 +157,7 @@ msgstr "ACME 账户/质询"
#: proxmox-yew-comp/src/acme/acme_plugins.rs:501
#: proxmox-yew-comp/src/acme/acme_plugins.rs:542
msgid "ACME DNS Plugin"
-msgstr "ACME DNS插件"
+msgstr "ACME DNS 插件"
#: proxmox-widget-toolkit/src/window/ACMEAccount.js:40
#: pve-manager/www/manager6/node/ACME.js:52
@@ -174,15 +166,13 @@ msgstr "ACME 目录"
#: proxmox-yew-comp/src/acme/acme_domains.rs:364
#: proxmox-yew-comp/src/acme/acme_domains.rs:385
-#, fuzzy
msgid "ACME Domain"
-msgstr "域名"
+msgstr "ACME 域名"
#. TRANSLATORS: ACME Stands for Automatic Certificate Management Environment
#: proxmox-datacenter-manager/ui/src/certificates.rs:34
-#, fuzzy
msgid "ACME Domains"
-msgstr "登录域"
+msgstr "ACME 域名"
#: proxmox-backup/www/Utils.js:479
msgid "ACME certificate renewal"
@@ -245,9 +235,8 @@ msgid "API Token"
msgstr "API 令牌"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_info.rs:340
-#, fuzzy
msgid "API Token Name"
-msgstr "令牌名称"
+msgstr "API 令牌名称"
#: pve-manager/www/manager6/dc/ACLView.js:40
#: pve-manager/www/manager6/dc/ACLView.js:227
@@ -265,9 +254,8 @@ msgid "API Tokens"
msgstr "API 令牌"
#: proxmox-yew-comp/src/apt_repositories.rs:571
-#, fuzzy
msgid "API call failed"
-msgstr "全部失败"
+msgstr "API 调用失败"
#: proxmox-widget-toolkit/src/panel/ACMEDomains.js:222
#: proxmox-widget-toolkit/src/panel/Certificates.js:91
@@ -278,7 +266,7 @@ msgstr "全部失败"
msgid ""
"API server will be restarted to use new certificates, please reload web-"
"interface!"
-msgstr "API 服务器将重新启动以使用新的凭证,请重新加载web界面!"
+msgstr "API 服务器将重启以使用新证书,请重新加载 Web 界面!"
#: proxmox-backup/www/window/TokenEdit.js:15
msgid "API token"
@@ -286,22 +274,20 @@ msgstr "API 令牌"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:146
msgid "APT Repositories"
-msgstr "APT 存储库"
+msgstr "APT 软件源"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:308
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_zone.rs:315
-#, fuzzy
msgid "ASN"
-msgstr "SDN"
+msgstr "ASN"
#: pve-manager/www/manager6/window/UploadToStorage.js:289
msgid "Abort"
msgstr "中止"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:19
-#, fuzzy
msgid "Accept"
-msgstr "接受服务条款"
+msgstr "接受"
#: proxmox-widget-toolkit/src/window/ACMEAccount.js:116
#: pve-manager/www/manager6/node/ACME.js:198
@@ -317,9 +303,8 @@ msgid "Access Control"
msgstr "访问控制"
#: proxmox-backup/www/window/S3ClientEdit.js:91
-#, fuzzy
msgid "Access Key"
-msgstr "密钥"
+msgstr "访问密钥"
#: pve-manager/www/manager6/lxc/DeviceEdit.js:89
msgid "Access Mode in CT"
@@ -341,7 +326,7 @@ msgstr "账户"
#: proxmox-yew-comp/src/acme/acme_register_account.rs:108
#: proxmox-yew-comp/src/acme/acme_domains.rs:460
msgid "Account Name"
-msgstr "账户名"
+msgstr "账户名称"
#: pmg-gui/js/LDAPConfig.js:161
msgid "Account attribute name"
@@ -365,16 +350,16 @@ msgstr "操作"
#: pmg-gui/js/controller/QuarantineController.js:102
msgid "Action '{0}' for '{1}' items"
-msgstr "对 '{1}' 项目采取 '{0}' 操作"
+msgstr "对'{1}'项目采取'{0}'操作"
#: pmg-gui/js/Utils.js:803 pmg-gui/js/Utils.js:937
msgid "Action '{0}' for '{1}' items successful"
-msgstr "对 '{1}' 项目的 '{0}' 操作成功"
+msgstr "对'{1}'项目的'{0}'操作成功"
#: pmg-gui/js/Utils.js:804 pmg-gui/js/Utils.js:938
#: pmg-yew-quarantine-gui/src/spam_list.rs:159
msgid "Action '{0}' successful"
-msgstr "动作 '{0}' 成功"
+msgstr "动作'{0}'成功"
#: pmg-gui/js/NavigationTree.js:22 pmg-gui/js/Utils.js:57
msgid "Action Objects"
@@ -396,7 +381,7 @@ msgstr "操作"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:105
msgid "Activate AES instruction set for HW acceleration."
-msgstr ""
+msgstr "启用 AES 指令集以进行硬件加速。"
#: proxmox-widget-toolkit/src/form/NetworkSelector.js:114
#: proxmox-widget-toolkit/src/node/NetworkView.js:310
@@ -416,7 +401,7 @@ msgstr "运行中"
#: pve-manager/www/manager6/Utils.js:726 proxmox-yew-comp/src/auth_view.rs:296
#: proxmox-yew-comp/src/auth_edit_ldap.rs:402
msgid "Active Directory Server"
-msgstr "活动目录服务器(AD)"
+msgstr "Active Directory 服务器"
#: proxmox-backup/www/tape/ChangerStatus.js:876
msgid "Activity"
@@ -514,17 +499,16 @@ msgstr "活动"
#: proxmox-yew-comp/src/token_panel.rs:189
#: proxmox-yew-comp/src/token_panel.rs:388
msgid "Add"
-msgstr "添加"
+msgstr "新增"
#: proxmox-widget-toolkit/src/panel/ACMEDomains.js:322
#: pve-manager/www/manager6/node/ACME.js:691
msgid "Add ACME Account"
-msgstr "添加 ACME 账户"
+msgstr "新增 ACME 账户"
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/mobile.rs:670
-#, fuzzy
msgid "Add CD/DVD drive"
-msgstr "CD/DVD 驱动器"
+msgstr "添加 CD/DVD 驱动器"
#: proxmox-backup/www/NavigationTree.js:130
msgid "Add Datastore"
@@ -543,27 +527,24 @@ msgid "Add Fabric"
msgstr "添加Fabric"
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/mobile.rs:653
-#, fuzzy
msgid "Add Hard Disk"
-msgstr "硬盘"
+msgstr "添加硬盘"
#: proxmox-widget-toolkit/src/panel/WebhookEditPanel.js:71
msgid "Add Header"
-msgstr "添加标题栏"
+msgstr "新增标题"
#: proxmox-yew-comp/src/configuration/pve/lxc_resources_panel/mobile.rs:378
-#, fuzzy
msgid "Add Mount Point"
-msgstr "挂载点"
+msgstr "添加挂载点"
#: proxmox-backup/www/datastore/Content.js:1366
msgid "Add Namespace"
msgstr "新增命名空间"
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/mobile.rs:684
-#, fuzzy
msgid "Add Network card"
-msgstr "IP 网络"
+msgstr "添加网卡"
#: pve-manager/www/manager6/sdn/FabricsView.js:107
#: pve-manager/www/manager6/sdn/FabricsView.js:168
@@ -585,9 +566,8 @@ msgid "Add Remote"
msgstr "添加远程"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:525
-#, fuzzy
msgid "Add Row"
-msgstr "添加远程"
+msgstr "添加行"
#: proxmox-widget-toolkit/src/panel/WebhookEditPanel.js:93
msgid "Add Secret"
@@ -621,46 +601,41 @@ msgid "Add Tape"
msgstr "添加磁带"
#: proxmox-backup/www/window/TrafficControlEdit.js:449
-#, fuzzy
msgid "Add Timeframe"
-msgstr "时间表"
+msgstr "添加时间段"
#: pve-manager/www/manager6/window/USBMapEdit.js:26
msgid "Add USB mapping"
msgstr "添加 USB 映射"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_vnet.rs:68
-#, fuzzy
msgid "Add VNet"
-msgstr "添加节点"
+msgstr "添加虚拟网络"
#: pve-manager/www/manager6/lxc/EnvEdit.js:157
-#, fuzzy
msgid "Add Variable"
-msgstr "可用"
+msgstr "添加变量"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:468
-#, fuzzy
msgid "Add Widget"
-msgstr "添加节点"
+msgstr "添加小部件"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_zone.rs:68
-#, fuzzy
msgid "Add Zone"
-msgstr "添加节点"
+msgstr "添加区域"
#: proxmox-widget-toolkit/src/window/AddTotp.js:11
#: proxmox-yew-comp/src/tfa/tfa_add_totp.rs:165
msgid "Add a TOTP login factor"
-msgstr "添加一个 TOTP 登录因子"
+msgstr "新增 TOTP 登录因子"
#: proxmox-widget-toolkit/src/window/AddWebauthn.js:10
msgid "Add a Webauthn login token"
-msgstr "添加 Webauthn 登录令牌"
+msgstr "新增 WebAuthn 登录令牌"
#: proxmox-widget-toolkit/src/window/AddYubico.js:10
msgid "Add a Yubico OTP key"
-msgstr "添加 Yubico OTP 密钥"
+msgstr "新增 Yubico OTP 密钥"
#: pve-manager/www/manager6/qemu/OSTypeEdit.js:158
msgid "Add additional drive for VirtIO drivers"
@@ -681,14 +656,12 @@ msgid "Add as Storage"
msgstr "添加存储"
#: proxmox-yew-comp/src/configuration/pve/lxc_resources_panel/reassign_volume_dialog.rs:151
-#, fuzzy
msgid "Add as mount point"
-msgstr "挂载点"
+msgstr "添加为挂载点"
#: proxmox-yew-comp/src/configuration/pve/lxc_resources_panel/reassign_volume_dialog.rs:149
-#, fuzzy
msgid "Add as unused volume"
-msgstr "基本卷"
+msgstr "添加为未使用卷"
#: proxmox-backup/www/form/GroupFilter.js:409
msgid "Add exclude"
@@ -713,9 +686,8 @@ msgstr "将新池添加到集群存储配置。"
#: pve-manager/www/manager6/lxc/CreateWizard.js:90
#: pve-manager/www/manager6/qemu/CreateWizard.js:104
#: pve-manager/www/manager6/window/Restore.js:250
-#, fuzzy
msgid "Add to HA"
-msgstr "添加存储"
+msgstr "添加到高可用"
#: proxmox-widget-toolkit/src/panel/EmailRecipientPanel.js:75
msgid "Additional Recipient(s)"
@@ -764,9 +736,8 @@ msgid "Advanced"
msgstr "高级"
#: pve-manager/www/manager6/dc/MetricServerView.js:675
-#, fuzzy
msgid "Advanced JSON Configuration"
-msgstr "显示配置"
+msgstr "高级 JSON 配置"
#: pve-manager/www/manager6/sdn/zones/EvpnEdit.js:73
msgid "Advertise Subnets"
@@ -774,14 +745,12 @@ msgstr "广播子网"
#: pve-manager/www/manager6/ha/rules/ResourceAffinityRuleEdit.js:13
#: pve-manager/www/manager6/ha/rules/ResourceAffinityRules.js:15
-#, fuzzy
msgid "Affinity"
-msgstr "CPU 绑定"
+msgstr "亲和性"
#: pve-manager/www/manager6/dc/Config.js:241
-#, fuzzy
msgid "Affinity Rules"
-msgstr "CPU 绑定"
+msgstr "亲和性规则"
#: proxmox-backup/www/tape/DriveStatus.js:402
msgid "Alert Flags"
@@ -841,14 +810,12 @@ msgid "All Functions"
msgstr "所有功能"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:570
-#, fuzzy
msgid "All Guests"
-msgstr "客户"
+msgstr "所有客户机"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:551
-#, fuzzy
msgid "All Nodes"
-msgstr "所有核心"
+msgstr "所有节点"
#: proxmox-backup/www/datastore/Content.js:1248
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:394
@@ -862,12 +829,12 @@ msgstr "全部 OK (旧的)"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:393
msgid "All OK, but some snapshots were not verified in last 30 days"
-msgstr ""
+msgstr "全部正常,但某些快照在过去 30 天内未验证"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:441
#: proxmox-yew-comp/src/apt_repositories.rs:300
msgid "All OK, you have production-ready repositories configured!"
-msgstr "一切正常,已经配置了生产就绪的存储库!"
+msgstr "一切正常,已配置适用于生产环境的软件源!"
#: pmg-gui/js/AuthEditOIDC.js:201
msgid "All auto-created users get audit role"
@@ -900,23 +867,20 @@ msgstr "全部匹配"
#: proxmox-yew-comp/src/form/pve/lxc_property/lxc_network_property.rs:262
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_network_property.rs:157
-#, fuzzy
msgid "All network devices in use."
-msgstr "无网络设备"
+msgstr "所有网络设备都在使用中。"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/tree.rs:709
-#, fuzzy
msgid "All nodes"
-msgstr "所有核心"
+msgstr "所有节点"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/tree.rs:666
-#, fuzzy
msgid "All remotes"
-msgstr "所有核心"
+msgstr "所有远程"
#: pve-yew-mobile-gui/src/pages/page_node_status/services_panel.rs:76
msgid "All required services are running"
-msgstr ""
+msgstr "所有必需的服务都在运行"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:506
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:900
@@ -925,16 +889,15 @@ msgstr "所有规则匹配"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:398
msgid "All snapshots verified at least once in last 30 days"
-msgstr ""
+msgstr "所有快照在过去 30 天内至少验证过一次"
#: pve-manager/www/manager6/node/ZFS.js:245 proxmox-backup/www/ZFSList.js:81
msgid "Allocated"
msgstr "已分配"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:254
-#, fuzzy
msgid "Allocation"
-msgstr "预分配"
+msgstr "分配"
#: proxmox-backup/www/tape/PoolConfig.js:121
#: proxmox-backup/www/tape/form/PoolSelector.js:30
@@ -949,7 +912,7 @@ msgstr "允许调试"
#: pve-manager/www/manager6/qemu/VirtiofsEdit.js:84
msgid "Allow Direct IO"
-msgstr ""
+msgstr "允许直接 IO"
#: pmg-gui/js/SpamQuarantineOptions.js:69
#: pmg-gui/js/VirusQuarantineOptions.js:20
@@ -957,9 +920,8 @@ msgid "Allow HREFs"
msgstr "允许超链接"
#: pve-manager/www/manager6/qemu/MemoryEdit.js:156
-#, fuzzy
msgid "Allow KSM"
-msgstr "允许SMT"
+msgstr "允许 KSM"
#: pve-manager/www/manager6/qemu/SevEdit.js:103
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_amd_sev_property.rs:54
@@ -969,16 +931,16 @@ msgstr "允许密钥共享"
#: pve-manager/www/manager6/qemu/SevEdit.js:114
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_amd_sev_property.rs:62
msgid "Allow SMT"
-msgstr "允许SMT"
+msgstr "允许 SMT"
#. TRANSLATORS: As in "a chain of volumes, each referencing the next one".
#: pve-manager/www/manager6/storage/Base.js:85
msgid "Allow Snapshots as Volume-Chain"
-msgstr "允许将快照作为Volume-Chain"
+msgstr "允许 Snapshots as Volume-Chain"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:102
msgid "Allow guest OS to use 1GB size pages, if host HW supports it"
-msgstr ""
+msgstr "如果主机硬件支持,允许客户操作系统使用 1 GB 大小的页面"
#: pve-manager/www/manager6/window/BulkAction.js:107
msgid "Allow local disk migration"
@@ -987,7 +949,7 @@ msgstr "允许本地磁盘迁移"
#: pve-manager/www/manager6/qemu/MemoryEdit.js:164
msgid ""
"Allow the Kernel Samepage Merging daemon to merge memory pages of this VM."
-msgstr ""
+msgstr "允许内核的 Samepage Merging 守护进程合并此虚拟机的内存页。"
#: proxmox-widget-toolkit/src/Toolkit.js:103
#: proxmox-widget-toolkit/src/Toolkit.js:116
@@ -997,11 +959,11 @@ msgstr "允许的字符"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:98
msgid "Allows improved Spectre mitigation with AMD CPUs"
-msgstr ""
+msgstr "允许在 AMD CPU 上改进 Spectre 缓解"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:96
msgid "Allows improved Spectre mitigation with Intel CPUs"
-msgstr ""
+msgstr "允许在 Intel CPU 上启用增强的 Spectre 漏洞缓解机制"
#: pve-manager/www/manager6/UIOptions.js:80
#: pve-manager/www/manager6/UIOptions.js:82
@@ -1009,15 +971,14 @@ msgid "Alphabetical"
msgstr "按字母顺序排列的"
#: proxmox-yew-comp/src/apt_repositories.rs:540
-#, fuzzy
msgid "Already configured"
-msgstr "{0} 已配置"
+msgstr "已配置"
#: pve-manager/www/manager6/window/ConfirmRemoveResource.js:19
msgid ""
"Also removes resource from HA rules and removes rule if there are no other "
"resources in it"
-msgstr ""
+msgstr "同时从 HA 规则中删除资源,如果规则中没有其他资源则删除该规则"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:373
#: proxmox-widget-toolkit/src/node/NetworkView.js:287
@@ -1048,7 +1009,7 @@ msgstr "令牌注册期间发生错误。"
#: pve-yew-mobile-gui/src/pages/page_dashboard.rs:182
msgid "Analytics"
-msgstr ""
+msgstr "分析"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:120
#: proxmox-yew-comp/src/auth_edit_ldap.rs:342
@@ -1070,12 +1031,11 @@ msgstr "应用"
#: pve-manager/www/manager6/VNCConsole.js:42
msgid "Application container detected - console might not be fully functional."
-msgstr ""
+msgstr "检测到应用容器 - 控制台可能无法完全正常工作。"
#: proxmox-backup/www/window/TrafficControlEdit.js:290
-#, fuzzy
msgid "Applies to all users"
-msgstr "应用于新编辑"
+msgstr "应用于所有用户"
#: pve-manager/www/manager6/dc/OptionView.js:532
msgid "Applies to new edits"
@@ -1105,9 +1065,8 @@ msgid "Apply Custom Scores"
msgstr "应用自定义分数"
#: proxmox-datacenter-manager/ui/src/tasks.rs:73
-#, fuzzy
msgid "Apply SDN configuration"
-msgstr "应用配置"
+msgstr "应用 SDN 配置"
#: pmg-gui/js/Utils.js:904
msgid "Apply custom SpamAssassin scores"
@@ -1121,7 +1080,7 @@ msgstr "适用于所有网络"
msgid ""
"Applying pending SDN changes will also apply any pending local node network "
"changes. Proceed?"
-msgstr "应用待定的 SDN 更改也将应用任何待定的本地节点网络更改。继续?"
+msgstr "应用待定的 SDN 更改也将应用任何待定的本地节点网络更改。是否继续?"
#: proxmox-widget-toolkit/src/Utils.js:66 proxmox-yew-comp/src/lib.rs:296
msgid "Arabic"
@@ -1141,23 +1100,22 @@ msgid "Are you sure to remove the subscription key?"
msgstr "确定要删除订阅密钥吗?"
#: proxmox-yew-comp/src/configuration/pve/guest.rs:25
-#, fuzzy
msgid "Are you sure you want to delete volume {0}."
-msgstr "确定要分离该项 {0} 吗?"
+msgstr "确定要删除卷 {0} 吗。"
#: pve-manager/www/manager6/lxc/Resources.js:246
#: pve-manager/www/manager6/qemu/HardwareView.js:532
#: proxmox-yew-comp/src/configuration/pve/guest.rs:6
msgid "Are you sure you want to detach entry {0}"
-msgstr "确定要分离该项 {0} 吗?"
+msgstr "确定要分离 {0} 吗"
#: pmg-gui/js/PBSSnapshotView.js:224
msgid "Are you sure you want to forget snapshot {0}"
-msgstr "确定要删除快照 {0} 吗?"
+msgstr "确定要删除快照 {0} 吗"
#: proxmox-backup/www/tape/window/Erase.js:14
msgid "Are you sure you want to format tape '{0}' ?"
-msgstr "确定要格式化磁带 {0} 吗?"
+msgstr "确定要格式化磁带'{0}'吗?"
#: proxmox-backup/www/tape/ChangerStatus.js:837
#: proxmox-backup/www/tape/DriveStatus.js:242
@@ -1166,26 +1124,25 @@ msgstr "确定要格式化插入的磁带吗?"
#: proxmox-datacenter-manager/ui/src/administration/node_status.rs:217
#: proxmox-yew-comp/src/node_status_panel.rs:228
-#, fuzzy
msgid "Are you sure you want to reboot the node?"
-msgstr "确定要删除此条目"
+msgstr "确定要重启该节点吗?"
#: pve-manager/www/manager6/tree/ResourceMapTree.js:109
#: proxmox-datacenter-manager/ui/src/configuration/views.rs:317
msgid "Are you sure you want to remove '{0}'"
-msgstr "是否确实要删除 '{0}'"
+msgstr "确实要删除'{0}'"
#: pve-manager/www/manager6/tree/ResourceMapTree.js:113
msgid "Are you sure you want to remove '{0}' entries for '{1}'"
-msgstr "是否确实要删除 '{1}' 的 '{0}' 项"
+msgstr "确实要删除'{1}'的'{0}'项"
#: pve-manager/www/manager6/tree/ResourceMapTree.js:117
msgid "Are you sure you want to remove '{0}' on '{1}' for '{2}'"
-msgstr "是否确实要为 '{2}' 删除 '{1}' 上的 '{0}'"
+msgstr "确实要为'{2}'删除'{1}'上的'{0}'"
#: pve-manager/www/manager6/tree/DhcpTree.js:102
msgid "Are you sure you want to remove DHCP mapping {0}"
-msgstr "是否确实要删除 DHCP 映射 {0}"
+msgstr "确实要删除 DHCP 映射 {0}"
#: proxmox-widget-toolkit/src/button/Button.js:141 pmg-gui/js/RuleInfo.js:41
#: pmg-gui/js/UserBlockWelcomeList.js:181
@@ -1199,7 +1156,7 @@ msgstr "是否确实要删除 DHCP 映射 {0}"
#: proxmox-yew-comp/src/confirm_button.rs:11
#: proxmox-yew-comp/src/configuration/pve/guest.rs:14
msgid "Are you sure you want to remove entry {0}"
-msgstr "确定要删除该项 {0} 吗?"
+msgstr "确定要删除 {0} 吗?"
#: proxmox-backup/www/datastore/Content.js:672
msgid "Are you sure you want to remove snapshot {0}"
@@ -1207,24 +1164,23 @@ msgstr "确定要删除快照 {0} 吗?"
#: proxmox-backup/www/tape/window/MediaRemoveWindow.js:13
msgid "Are you sure you want to remove tape '{0}' ?"
-msgstr "是否确实要删除磁带 '{0}'?"
+msgstr "确实要删除磁带'{0}'?"
#: proxmox-yew-comp/src/token_panel.rs:200
-#, fuzzy
msgid ""
"Are you sure you want to remove the API token? All existing users of the "
"token will lose access!"
msgstr ""
-"是否重新生成API令牌'{0}'的机密?之前令牌密钥的所有用户都将失去访问权限!"
+"是否重新生成 API 令牌'{0}'的密钥?之前令牌密钥的所有用户都将失去访问权限!"
#: proxmox-widget-toolkit/src/panel/Certificates.js:246
msgid "Are you sure you want to remove the certificate"
-msgstr "确定要删除该证书吗"
+msgstr "确定要删除此证书吗"
#: proxmox-widget-toolkit/src/panel/Certificates.js:242
#: proxmox-yew-comp/src/acme/certificate_list.rs:128
msgid "Are you sure you want to remove the certificate used for {0}"
-msgstr "确定要删除用于 {0} 的凭证吗?"
+msgstr "确定要删除用于 {0} 的证书吗?"
#: pve-manager/www/manager6/sdn/FabricsView.js:438
msgid "Are you sure you want to remove the fabric \"{0}\"?"
@@ -1233,7 +1189,7 @@ msgstr "确定要移除fabric \"{0}\"吗?"
#: pve-manager/www/manager6/sdn/FabricsView.js:448
msgid ""
"Are you sure you want to remove the node \"{0}\" from the fabric \"{1}\"?"
-msgstr "确定要从fabric \"{1}\"中移除节点\"{0}\"吗?"
+msgstr "确定要从fabric\"{1}\"中移除节点\"{0}\"吗?"
#: pmg-gui/js/PBSSnapshotView.js:152
msgid "Are you sure you want to remove the schedule for {0}"
@@ -1246,14 +1202,12 @@ msgid "Are you sure you want to remove the subscription key?"
msgstr "确定要删除订阅密钥吗?"
#: proxmox-yew-comp/src/acl/acl_view.rs:215
-#, fuzzy
msgid "Are you sure you want to remove this ACL entry?"
-msgstr "确定要删除此条目"
+msgstr "确定要删除此 ACL 条目吗?"
#: proxmox-yew-comp/src/tfa/tfa_confirm_remove.rs:44
-#, fuzzy
msgid "Are you sure you want to remove this TFA entry?"
-msgstr "确定要删除此条目"
+msgstr "确定要删除此双因素认证条目吗?"
#: pve-manager/www/manager6/dc/ACLView.js:163
#: pve-manager/www/manager6/sdn/VnetACLView.js:187
@@ -1261,14 +1215,12 @@ msgid "Are you sure you want to remove this entry"
msgstr "确定要删除此条目"
#: proxmox-yew-comp/src/confirm_button.rs:12
-#, fuzzy
msgid "Are you sure you want to remove this entry?"
-msgstr "确定要删除此条目"
+msgstr "确定要删除此条目吗?"
#: proxmox-datacenter-manager/ui/src/remotes/config.rs:209
-#, fuzzy
msgid "Are you sure you want to remove this remote?"
-msgstr "确定要删除此条目"
+msgstr "确定要删除此远程吗?"
#: proxmox-widget-toolkit/src/window/TfaEdit.js:143
msgid "Are you sure you want to remove this {0} entry?"
@@ -1280,9 +1232,8 @@ msgstr "确定要删除 {0} 条目吗"
#: proxmox-datacenter-manager/ui/src/administration/node_status.rs:228
#: proxmox-yew-comp/src/node_status_panel.rs:237
-#, fuzzy
msgid "Are you sure you want to shut down the node?"
-msgstr "确定要删除此条目"
+msgstr "确定要关闭该节点吗?"
#: proxmox-widget-toolkit/src/panel/DiskList.js:432
msgid "Are you sure you want to wipe {0}?"
@@ -1290,7 +1241,7 @@ msgstr "确定要擦除 {0} 吗?"
#: pve-manager/www/manager6/sdn/fabrics/ospf/FabricEdit.js:14
msgid "Area"
-msgstr ""
+msgstr "区域"
#: pve-manager/www/manager6/node/LVM.js:113
msgid "Assigned to LVs"
@@ -1313,21 +1264,22 @@ msgstr "至少有一个不匹配"
msgid ""
"At least one remote could not be queried and has an unknown subscription "
"status."
-msgstr ""
+msgstr "至少有一个远程无法查询,订阅状态未知。"
#: proxmox-datacenter-manager/ui/src/dashboard/subscription_info.rs:54
-#, fuzzy
msgid ""
"At least one remote does not have a valid subscription. Please visit <a "
"target=\"_blank\" href=\"https://www.proxmox.com\">www.proxmox.com</a> to "
"get a list of available options."
-msgstr "您没有此服务器的有效订阅。请访问 {0} 获取可用选项列表。"
+msgstr ""
+"至少有一个远程节点没有有效的订阅。请访问 <a target=\"_blank\" href=\"https://"
+"www.proxmox.com\">www.proxmox.com</a> 以获取可用选项列表。"
#: proxmox-datacenter-manager/ui/src/dashboard/subscription_info.rs:60
msgid ""
"At least one remote has mixed levels of subscription. These remotes fall "
"back to the lowest one."
-msgstr ""
+msgstr "至少有一个远程具有混合级别的订阅。这些远程将回退到最低级别。"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:504
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:902
@@ -1336,12 +1288,11 @@ msgstr "至少有一个规则不匹配"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_vnet.rs:185
msgid "At least one zone needs to be configured on a remote"
-msgstr ""
+msgstr "至少需要在远程上配置一个区域"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_vnet.rs:187
-#, fuzzy
msgid "At least one zone needs to be selected"
-msgstr "至少有一个不匹配"
+msgstr "至少需要选择一个区域"
#: pmg-gui/js/Utils.js:579
msgid "Attach orig. Mail"
@@ -1388,9 +1339,8 @@ msgid "Auth-Provider Default"
msgstr "身份验证提供程序默认值"
#: proxmox-datacenter-manager/ui/src/remotes/config.rs:336
-#, fuzzy
msgid "AuthId"
-msgstr "验证 ID"
+msgstr "认证 ID"
#: proxmox-widget-toolkit/src/panel/SmtpEditPanel.js:106
msgid "Authenticate"
@@ -1403,7 +1353,7 @@ msgstr "身份验证模式"
#: proxmox-widget-toolkit/src/panel/SendmailEditPanel.js:58
#: proxmox-widget-toolkit/src/panel/SmtpEditPanel.js:166
msgid "Author"
-msgstr "发起人"
+msgstr "作者"
#: pmg-gui/js/TFAView.js:60 pve-manager/www/manager6/dc/OptionView.js:301
#: proxmox-backup/www/config/WebauthnView.js:115
@@ -1488,13 +1438,12 @@ msgstr "可用对象"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:87
msgid "Available recovery keys: {0}"
-msgstr "可用的还原密钥: {0}"
+msgstr "可用的恢复密钥:{0}"
#: proxmox-widget-toolkit/src/form/RRDTypeSelector.js:95
#: proxmox-yew-comp/src/rrd_timeframe_selector.rs:229
-#, fuzzy
msgid "Average"
-msgstr "平均"
+msgstr "平均值"
#: pmg-gui/js/GeneralMailStatistics.js:119
#: pmg-gui/js/dashboard/MailProcessing.js:50
@@ -1568,9 +1517,8 @@ msgid "Backup Details"
msgstr "备份详情"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:100
-#, fuzzy
msgid "Backup Dir"
-msgstr "备份时间"
+msgstr "备份目录"
#: proxmox-backup/www/datastore/Content.js:972
msgid "Backup Group"
@@ -1614,14 +1562,12 @@ msgid "Backup Server"
msgstr "备份服务器"
#: proxmox-datacenter-manager/ui/src/dashboard/pbs_datastores_panel.rs:175
-#, fuzzy
msgid "Backup Server Datastores"
-msgstr "备份服务器"
+msgstr "备份服务器数据存储"
#: proxmox-datacenter-manager/ui/src/dashboard/node_status_panel.rs:166
-#, fuzzy
msgid "Backup Server Nodes"
-msgstr "备份服务器"
+msgstr "备份服务器节点"
#: pve-manager/www/manager6/window/Prune.js:169
#: proxmox-backup/www/datastore/Content.js:1138
@@ -1646,7 +1592,7 @@ msgstr "立即备份"
#: pmg-gui/js/PBSSnapshotView.js:250
msgid "Backup snapshots on '{0}'"
-msgstr "在 {0} 上备份快照"
+msgstr "在'{0}'上备份快照"
#: pve-manager/www/manager6/panel/BackupAdvancedOptions.js:218
msgid ""
@@ -1663,9 +1609,8 @@ msgid "Backups"
msgstr "备份"
#: proxmox-datacenter-manager/ui/src/tasks.rs:173
-#, fuzzy
msgid "Backups and Backup Jobs"
-msgstr "磁带备份作业"
+msgstr "备份和备份作业"
#: proxmox-backup/www/datastore/DataStoreListSummary.js:210
#: proxmox-backup/www/datastore/Summary.js:214
@@ -1716,7 +1661,7 @@ msgstr "群组的基本域名"
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:16
#: proxmox-yew-comp/src/auth_edit_ldap.rs:303
msgid "Base Domain Name"
-msgstr "基本域名"
+msgstr "基础域名"
#: pve-manager/www/manager6/storage/LVMEdit.js:155
msgid "Base storage"
@@ -1732,16 +1677,15 @@ msgstr "基本"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:99
msgid "Basis for \"Speculative Store Bypass\" protection for AMD models"
-msgstr ""
+msgstr "为 AMD 型号提供\"推测性存储绕过\"保护的基础"
#: proxmox-backup/www/window/InfluxDbEdit.js:98
msgid "Batch Size (b)"
msgstr "批次大小 (b)"
#: pve-manager/www/manager6/dc/MetricServerView.js:372
-#, fuzzy
msgid "Batch Size (bytes)"
-msgstr "批次大小 (b)"
+msgstr "批次大小(字节)"
#: pmg-gui/js/MailProxyOptions.js:96
msgid "Before Queue Filtering"
@@ -1781,9 +1725,8 @@ msgstr "阻止加密的档案和文档"
#: pmg-gui/js/UserBlockWelcomeList.js:207
#: pmg-yew-quarantine-gui/src/spam_list.rs:288
#: pmg-yew-quarantine-gui/src/page_mail_view.rs:140
-#, fuzzy
msgid "Blocklist"
-msgstr "黑名单"
+msgstr "阻止列表"
#: proxmox-widget-toolkit/src/panel/WebhookEditPanel.js:80
#: pmg-gui/js/Utils.js:574
@@ -1793,7 +1736,7 @@ msgstr "正文"
#: proxmox-widget-toolkit/src/node/NetworkView.js:355
#: proxmox-yew-comp/src/configuration/network_view.rs:481
msgid "Bond Mode"
-msgstr "Bond 模式"
+msgstr "绑定模式"
#: pmg-gui/js/dashboard/NodeInfo.js:105
#: pve-manager/www/manager6/node/StatusView.js:120
@@ -1837,21 +1780,19 @@ msgid "Bridge"
msgstr "桥接"
#: pve-manager/www/manager6/sdn/ZoneBridgesPanel.js:16
-#, fuzzy
msgid "Bridge Ports"
-msgstr "桥接端口"
+msgstr "网桥端口"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:135
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:150
#: proxmox-yew-comp/src/configuration/network_edit.rs:154
msgid "Bridge ports"
-msgstr "桥接端口"
+msgstr "网桥端口"
#: pve-manager/www/manager6/sdn/NetworkBrowser.js:120
#: pve-manager/www/manager6/sdn/ZoneBridgesPanel.js:5
-#, fuzzy
msgid "Bridges"
-msgstr "桥接"
+msgstr "网桥"
#: proxmox-backup/www/datastore/Content.js:1114
msgid "Browse"
@@ -1864,9 +1805,8 @@ msgid "Bucket"
msgstr "插槽"
#: proxmox-backup/www/form/S3BucketSelector.js:13
-#, fuzzy
msgid "Bucket Name"
-msgstr "插槽"
+msgstr "存储桶名称"
#: pmg-gui/js/ClamAVDatabase.js:88
msgid "Build time"
@@ -1960,9 +1900,8 @@ msgstr "批量启动虚拟机和容器"
#: proxmox-yew-comp/src/form/pve/firewall_property/log_ratelimit_property.rs:38
#: proxmox-yew-comp/src/firewall/log_ratelimit_field.rs:186
-#, fuzzy
msgid "Burst"
-msgstr "突发下载"
+msgstr "突发"
#: proxmox-backup/www/config/TrafficControlView.js:171
#: proxmox-backup/www/window/S3ClientEdit.js:157
@@ -2003,7 +1942,7 @@ msgid ""
"CD-ROM images cannot get imported, if required you can reconfigure the '{0}' "
"drive in the 'Advanced' tab."
msgstr ""
-"无法导入 CD-ROM 映像,如果需要,可以在 “高级” 选项卡中重新配置 '{0}' 驱动器。"
+"无法导入 CD-ROM 映像,如果需要,可以在\"高级\"选项卡中重新配置'{0}'驱动器。"
#: pve-manager/www/manager6/qemu/HardwareView.js:260
#: pve-manager/www/manager6/qemu/HardwareView.js:746
@@ -2016,15 +1955,13 @@ msgid "CD/DVD Drives"
msgstr "CD/DVD 驱动器"
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/desktop.rs:328
-#, fuzzy
msgid "CD/DVD drive"
msgstr "CD/DVD 驱动器"
#: pve-manager/www/manager6/qemu/TdxEdit.js:86
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_intel_tdx_property.rs:44
-#, fuzzy
msgid "CID"
-msgstr "CIDR"
+msgstr "CID"
#: proxmox-widget-toolkit/src/form/NetworkSelector.js:98
#: proxmox-widget-toolkit/src/node/NetworkView.js:381
@@ -2060,12 +1997,12 @@ msgstr "CPU 绑定"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:257
msgid "CPU Cores assigned"
-msgstr ""
+msgstr "已分配的 CPU 核心"
#: pve-manager/www/manager6/node/Summary.js:269
#: pve-manager/www/manager6/panel/GuestSummary.js:137
msgid "CPU Pressure Stall"
-msgstr ""
+msgstr "CPU 压力停滞"
#: pve-manager/www/manager6/window/GuestImport.js:547
msgid "CPU Type"
@@ -2079,12 +2016,11 @@ msgstr "CPU 类型"
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:349
#: proxmox-yew-comp/src/node_info.rs:163
msgid "CPU Usage"
-msgstr "CPU利用率"
+msgstr "CPU 利用率"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_processor_property.rs:218
-#, fuzzy
msgid "CPU flags"
-msgstr "CPU利用率"
+msgstr "CPU 标志"
#: pve-manager/www/manager6/lxc/ResourceEdit.js:78
#: pve-manager/www/manager6/qemu/ProcessorEdit.js:193
@@ -2137,7 +2073,7 @@ msgstr "CRM 状态"
#. https://datatracker.ietf.org/doc/html/draft-ietf-lsr-distoptflood#name-flooding-failures
#: pve-manager/www/manager6/sdn/fabrics/openfabric/FabricEdit.js:61
msgid "CSNP Interval"
-msgstr "CSNP间隔"
+msgstr "CSNP 间隔"
#: pve-manager/www/manager6/window/BulkAction.js:399
#: proxmox-backup/www/datastore/Summary.js:169
@@ -2154,9 +2090,8 @@ msgid "CT Volumes"
msgstr "CT 卷"
#: proxmox-datacenter-manager/ui/src/pve/lxc/mod.rs:66
-#, fuzzy
msgid "CT {0}"
-msgstr "ID {0}"
+msgstr "CT {0}"
#: pve-manager/www/manager6/qemu/HDEdit.js:309
#: pve-manager/www/manager6/qemu/VirtiofsEdit.js:51
@@ -2174,20 +2109,18 @@ msgstr "可以在通知匹配器中使用来匹配这项工作。"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_vnet.rs:197
msgid "Can only create the VNet once per remote!"
-msgstr ""
+msgstr "每个远程只能创建一次 VNet!"
#: proxmox-yew-widget-toolkit/src/touch/fab_menu.rs:264
#: proxmox-yew-widget-toolkit/src/widget/message_box.rs:128
-#, fuzzy
msgid "Cancel"
-msgstr "取消编辑"
+msgstr "取消"
#: pve-manager/www/manager6/form/TagEdit.js:351
msgid "Cancel Edit"
msgstr "取消编辑"
#: proxmox-datacenter-manager/ui/src/dashboard/status_row.rs:229
-#, fuzzy
msgid "Cancel Editing"
msgstr "取消编辑"
@@ -2212,33 +2145,30 @@ msgid "Cannot migrate VM with local resources: {0}"
msgstr "无法使用本地资源迁移虚拟机: {0}"
#: pve-manager/www/manager6/window/Migrate.js:445
-#, fuzzy
msgid "Cannot migrate VM, because {0}."
-msgstr "无法使用本地资源迁移虚拟机: {0}"
+msgstr "无法迁移虚拟机,因为 {0}。"
#: pve-manager/www/manager6/window/Migrate.js:397
msgid "Cannot migrate conntrack state, source node is lacking support."
-msgstr ""
+msgstr "无法迁移 conntrack 状态,源节点缺少支持。"
#: pve-manager/www/manager6/window/Migrate.js:406
msgid ""
"Cannot migrate conntrack state, target node is lacking support. Active "
"network connections might get dropped."
-msgstr ""
+msgstr "无法迁移 conntrack 状态,目标节点缺少支持。活动的网络连接可能会断开。"
#: pve-manager/www/manager6/window/Migrate.js:535
-#, fuzzy
msgid "Cannot migrate container, because {0}."
-msgstr "无法使用本地资源迁移虚拟机: {0}"
+msgstr "无法迁移容器,因为 {0}。"
#: pve-manager/www/manager6/window/Migrate.js:347
msgid "Cannot migrate running VM with mapped resources: {0}"
msgstr "无法迁移具有映射资源的正在运行的虚拟机: {0}"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:343
-#, fuzzy
msgid "Cannot migrate with local resource: {0}"
-msgstr "无法使用本地资源迁移虚拟机: {0}"
+msgstr "无法使用本地资源迁移:{0}"
#: pve-manager/www/manager6/storage/ImageView.js:56
msgid "Cannot remove disk image."
@@ -2246,7 +2176,7 @@ msgstr "无法删除磁盘映像。"
#: pve-manager/www/manager6/storage/ImageView.js:48
msgid "Cannot remove image, a guest with VMID '{0}' exists!"
-msgstr "无法删除映像,存在虚拟机 ID 为 '{0}' 的主机!"
+msgstr "无法删除映像,存在虚拟机 ID 为'{0}'的主机!"
#: pve-manager/www/manager6/node/ZFS.js:53
msgid "Cannot use reserved pool name"
@@ -2288,8 +2218,8 @@ msgid ""
"Caution: 'What Objects' match each mail part separately, so be careful with "
"any option besides 'Any matches'."
msgstr ""
-"警告:“哪些对象” 分别匹配每个邮件部分,因此要小心除 “任何匹配” 之外的任何选"
-"项。"
+"注意:“内容对象”会分别匹配邮件的每个部分,因此请谨慎使用除“任意匹配”外的其他"
+"选项。"
#: pve-manager/www/manager6/ceph/Pool.js:269
msgid "Ceph Pool"
@@ -2309,16 +2239,15 @@ msgstr "集群中的 Ceph"
#: pve-manager/www/manager6/window/CephInstall.js:38
msgid "Ceph is not initialized."
-msgstr "Ceph未初始化。"
+msgstr "Ceph 未初始化。"
#: pve-manager/www/manager6/window/CephInstall.js:43
msgid "Ceph is not installed on this node."
-msgstr "此节点上未安装Ceph。"
+msgstr "此节点上未安装 Ceph。"
#: proxmox-datacenter-manager/ui/src/tasks.rs:171
-#, fuzzy
msgid "Ceph related Tasks"
-msgstr "显示所有任务"
+msgstr "Ceph 相关任务"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:27
msgid "Ceph version to install"
@@ -2334,13 +2263,13 @@ msgstr "CephFS"
#: proxmox-yew-comp/src/acme/certificate_list.rs:338
#: proxmox-yew-comp/src/acme/certificate_list.rs:369
msgid "Certificate"
-msgstr "凭证"
+msgstr "证书"
#: proxmox-widget-toolkit/src/window/Certificates.js:168
#: pve-manager/www/manager6/node/Certificates.js:206
#: proxmox-yew-comp/src/acme/certificate_list.rs:272
msgid "Certificate Chain"
-msgstr "凭证链"
+msgstr "证书链"
#: pmg-gui/js/Certificates.js:5 pmg-gui/js/Certificates.js:30
#: pmg-gui/js/NavigationTree.js:96 pve-manager/www/manager6/node/Config.js:203
@@ -2350,7 +2279,7 @@ msgstr "凭证链"
#: proxmox-datacenter-manager/ui/src/certificates.rs:21
#: proxmox-datacenter-manager/ui/src/main_menu.rs:264
msgid "Certificates"
-msgstr "凭证"
+msgstr "证书"
#: proxmox-widget-toolkit/src/panel/ACMEPlugin.js:5
#: proxmox-datacenter-manager/ui/src/certificates.rs:58
@@ -2392,18 +2321,18 @@ msgstr "变更所有者"
#: proxmox-backup/www/datastore/Content.js:1060
msgid "Change owner of '{0}'"
-msgstr "变更所有者为 '{0}'"
+msgstr "变更所有者为'{0}'"
#: proxmox-backup/www/datastore/Content.js:1073
msgid "Change protection of '{0}'"
-msgstr "变更 '{0}' 的保护"
+msgstr "变更'{0}'的保护"
#: proxmox-widget-toolkit/src/node/APT.js:140
#: proxmox-widget-toolkit/src/node/APT.js:168
#: proxmox-yew-comp/src/apt_package_manager.rs:296
#: proxmox-yew-comp/src/apt_package_manager.rs:393
msgid "Changelog"
-msgstr "变更日志"
+msgstr "更新日志"
#: proxmox-backup/www/tape/ChangerStatus.js:682
#: proxmox-backup/www/tape/window/ChangerEdit.js:8
@@ -2425,7 +2354,7 @@ msgstr "更改依赖方可能会破坏现有的 WebauthnTFA 条目。"
#: pve-manager/www/manager6/lxc/Options.js:178
msgid "Changing the entrypoint command can lead to start failure!"
-msgstr ""
+msgstr "更改入口点命令可能导致启动失败!"
#: pmg-gui/js/SpamDetectorStatus.js:24
msgid "Channel"
@@ -2433,7 +2362,7 @@ msgstr "渠道"
#: proxmox-widget-toolkit/src/Schema.js:91
msgid "Character Device"
-msgstr "角色设备"
+msgstr "字符设备"
#: pmg-gui/js/Subscription.js:173
#: pve-manager/www/manager6/node/Subscription.js:167
@@ -2525,19 +2454,17 @@ msgid "Cleanup Storage Configuration"
msgstr "清理存储配置"
#: proxmox-datacenter-manager/ui/src/remotes/node_url_list.rs:284
-#, fuzzy
msgid "Clear"
-msgstr "清理"
+msgstr "清除"
#: proxmox-widget-toolkit/src/node/Tasks.js:198
#: proxmox-widget-toolkit/src/node/Tasks.js:252
msgid "Clear Filter"
-msgstr "清除筛选器"
+msgstr "清除过滤器"
#: proxmox-yew-comp/src/tasks.rs:385
-#, fuzzy
msgid "Clear Filter ({})"
-msgstr "清除筛选器"
+msgstr "清除筛选器({})"
#: pve-manager/www/manager6/window/BulkAction.js:496
msgid "Clear Filters"
@@ -2549,13 +2476,12 @@ msgid "Clear Status"
msgstr "清除状态"
#: proxmox-yew-widget-toolkit/src/widget/form/selector.rs:444
-#, fuzzy
msgid "Clear Value"
-msgstr "筛选值"
+msgstr "清除值"
#: proxmox-yew-comp/src/tfa/webauthn.rs:255
msgid "Click the button to start the authentication"
-msgstr ""
+msgstr "单击按钮开始身份验证"
#: pmg-gui/js/MailTracker.js:424
msgid "Client"
@@ -2581,7 +2507,7 @@ msgstr "客户端 ID"
#: pve-manager/www/manager6/dc/AuthEditOpenId.js:37
#: proxmox-yew-comp/src/auth_edit_openid.rs:131
msgid "Client Key"
-msgstr "客户端秘钥"
+msgstr "客户端密钥"
#: pmg-gui/js/MailProxyOptions.js:80
msgid "Client Message Rate Limit"
@@ -2634,9 +2560,8 @@ msgid "Cluster Administration"
msgstr "集群管理"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/ui_helpers.rs:69
-#, fuzzy
msgid "Cluster Firewall - {}"
-msgstr "启用防火墙"
+msgstr "集群防火墙 - {}"
#: pve-manager/www/manager6/dc/Cluster.js:53
msgid "Cluster Information"
@@ -2668,7 +2593,7 @@ msgstr "集群节点"
#: pve-manager/www/manager6/dc/OptionView.js:183
msgid "Cluster Resource Scheduling"
-msgstr "群集资源调度"
+msgstr "集群资源调度"
#: pmg-gui/js/Dashboard.js:497
msgid "Cluster Resources (average)"
@@ -2678,7 +2603,7 @@ msgstr "集群资源(平均)"
msgid ""
"Cluster has active subscriptions and would be eligible for using the "
"enterprise repository."
-msgstr "集群具有有效的订阅,并且有资格使用企业存储库。"
+msgstr "集群拥有有效订阅,可访问企业版软件源。"
#: pve-manager/www/manager6/dc/ClusterEdit.js:292
msgid ""
@@ -2703,21 +2628,19 @@ msgstr "颜色覆盖"
#: pmg-gui/js/QuarantineView.js:301 pve-manager/www/manager6/Workspace.js:434
#: proxmox-backup/www/MainView.js:271
msgid "Color Theme"
-msgstr "主题颜色"
+msgstr "主题配色"
#: proxmox-yew-widget-toolkit/src/widget/data_table/header_widget.rs:646
-#, fuzzy
msgid "Columns"
-msgstr "CT 卷"
+msgstr "列"
#: pve-manager/www/manager6/ha/Fencing.js:33
msgid "Command"
msgstr "命令"
#: pve-yew-mobile-gui/src/main.rs:33
-#, fuzzy
msgid "Command failed"
-msgstr "登录失败:"
+msgstr "命令失败"
#: proxmox-widget-toolkit/src/form/NetworkSelector.js:126
#: proxmox-widget-toolkit/src/form/UserSelector.js:41
@@ -2865,7 +2788,6 @@ msgstr "压缩"
#: proxmox-datacenter-manager/ui/src/pve/lxc/mod.rs:112
#: proxmox-datacenter-manager/ui/src/pve/qemu/mod.rs:111
-#, fuzzy
msgid "Config"
msgstr "配置"
@@ -2901,7 +2823,7 @@ msgstr "配置数据库"
#: proxmox-widget-toolkit/src/Utils.js:1420
msgid "Configuration Unsupported"
-msgstr "配置不支持"
+msgstr "配置不受支持"
#: proxmox-backup/www/datastore/OptionView.js:19
msgid "Configuration change only, no data will be deleted."
@@ -2933,7 +2855,7 @@ msgstr "在fabric中配置IP,而不是/etc/network/interface"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:48
#: proxmox-yew-comp/src/apt_repositories.rs:707
msgid "Configured"
-msgstr "配置"
+msgstr "已配置"
#: proxmox-widget-toolkit/src/button/Button.js:49
#: proxmox-widget-toolkit/src/window/ConfirmRemoveDialog.js:8
@@ -2979,7 +2901,7 @@ msgstr "确认二次验证"
#: proxmox-widget-toolkit/src/window/TfaEdit.js:99
msgid "Confirm TFA Removal"
-msgstr "确认移除 TFA"
+msgstr "确认移除双因素认证"
#: pmg-gui/js/UserEdit.js:89 pve-manager/www/manager6/dc/UserEdit.js:28
#: pve-manager/www/manager6/lxc/CreateWizard.js:120
@@ -2991,9 +2913,8 @@ msgstr "确认密码"
#. A message that conveys what will be confirmed.
#: proxmox-yew-widget-toolkit/src/widget/confirm_dialog.rs:26
-#, fuzzy
msgid "Confirm this action?"
-msgstr "配置"
+msgstr "确认此操作?"
#: proxmox-widget-toolkit/src/window/AddTfaRecovery.js:123
#: proxmox-widget-toolkit/src/window/AddTotp.js:270
@@ -3001,23 +2922,20 @@ msgstr "配置"
#: proxmox-widget-toolkit/src/window/AddYubico.js:123
#: proxmox-widget-toolkit/src/window/TfaEdit.js:224
msgid "Confirm your ({0}) password"
-msgstr "确认您的({0})密码"
+msgstr "确认您的 ({0}) 密码"
#: proxmox-yew-comp/src/tfa/mod.rs:45
-#, fuzzy
msgid "Confirm your ({}) password"
-msgstr "确认您的({0})密码"
+msgstr "确认您的({})密码"
#: proxmox-datacenter-manager/ui/src/remotes/add_wizard.rs:102
-#, fuzzy
msgid "Connection"
-msgstr "连接错误"
+msgstr "连接"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_connect.rs:85
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_nodes.rs:57
-#, fuzzy
msgid "Connection Certificate"
-msgstr "更新凭证"
+msgstr "连接证书"
#: proxmox-backup/www/window/DatastoreRepoInfo.js:6
msgid "Connection Information"
@@ -3025,9 +2943,8 @@ msgstr "连接信息"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:181
#: proxmox-yew-comp/src/firewall/options_edit.rs:423
-#, fuzzy
msgid "Connection Tracking Max"
-msgstr "连接信息"
+msgstr "连接跟踪最大值"
#: proxmox-widget-toolkit/src/Utils.js:411
#: proxmox-widget-toolkit/src/Utils.js:547
@@ -3043,20 +2960,19 @@ msgid "Connection failure. Network error or Proxmox VE services not running?"
msgstr "连接失败。 网络错误或 Proxmox VE 服务未运行?"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_summary.rs:132
-#, fuzzy
msgid "Connections"
-msgstr "连接错误"
+msgstr "连接"
#. TRANSLATORS: See https://www.kernel.org/doc/html/next/networking/netlink_spec/conntrack.html
#: pve-manager/www/manager6/window/Migrate.js:649
msgid "Conntrack state"
-msgstr ""
+msgstr "Conntrack 状态"
#: pve-manager/www/manager6/window/Migrate.js:415
msgid ""
"Conntrack state migration disabled. Active network connections might get "
"dropped."
-msgstr ""
+msgstr "Conntrack 状态迁移已禁用。活动的网络连接可能会断开。"
#: proxmox-widget-toolkit/src/window/ConsentModal.js:15
#: pve-yew-mobile-gui/src/pages/page_login.rs:75
@@ -3087,9 +3003,8 @@ msgid "Console"
msgstr "控制台"
#: proxmox-yew-comp/src/utils/mod.rs:243
-#, fuzzy
msgid "Console (xterm.js)"
-msgstr "控制台(JS)"
+msgstr "控制台(xterm.js)"
#: pve-manager/www/manager6/dc/OptionView.js:88
msgid "Console Viewer"
@@ -3116,9 +3031,8 @@ msgid "Container"
msgstr "容器"
#: proxmox-datacenter-manager/ui/src/tasks.rs:170
-#, fuzzy
msgid "Container related Tasks"
-msgstr "容器模板"
+msgstr "容器相关任务"
#: pve-manager/www/manager6/Utils.js:695
#: proxmox-datacenter-manager/ui/src/pve/utils.rs:296
@@ -3127,7 +3041,7 @@ msgstr "容器模板"
#: pve-manager/www/manager6/lxc/Config.js:229
msgid "Container {0} on node '{1}'"
-msgstr "节点 {1} 上的容器 {0}"
+msgstr "节点'{1}'上的容器 {0}"
#: pve-manager/www/manager6/dc/StorageView.js:119
#: pve-manager/www/manager6/sdn/Browser.js:36
@@ -3160,7 +3074,7 @@ msgstr "内容类型"
#: pmg-gui/js/Utils.js:400
msgid "Content Type Filter"
-msgstr "内容类型筛选"
+msgstr "内容类型筛选条件"
#: proxmox-backup/www/tape/form/AllocationSelector.js:7
#: proxmox-yew-widget-toolkit/src/widget/message_box.rs:115
@@ -3177,7 +3091,7 @@ msgstr "控制器"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:143
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:202
msgid "Controller of EVPN zone {} does not exist"
-msgstr ""
+msgstr "EVPN 区域 {} 的控制器不存在"
#: pve-manager/www/manager6/sdn/OptionsPanel.js:17
msgid "Controllers"
@@ -3214,12 +3128,12 @@ msgstr "复制密钥"
#: proxmox-datacenter-manager/ui/src/configuration/views.rs:346
msgid "Copy Layout from"
-msgstr ""
+msgstr "从以下位置复制布局"
#: proxmox-widget-toolkit/src/window/AddTfaRecovery.js:179
#: proxmox-yew-comp/src/tfa/tfa_add_recovery.rs:146
msgid "Copy Recovery Keys"
-msgstr "复制还原密钥"
+msgstr "复制恢复密钥"
#: pve-manager/www/manager6/dc/TokenEdit.js:163
#: proxmox-backup/www/window/TokenEdit.js:213
@@ -3251,15 +3165,13 @@ msgstr "复制到剪贴板"
#: proxmox-datacenter-manager/ui/src/administration/node_status.rs:78
#: proxmox-datacenter-manager/ui/src/administration/node_status.rs:139
-#, fuzzy
msgid "Copy to clipboard"
msgstr "复制到剪贴板"
#: proxmox-yew-comp/src/node_status_panel.rs:124
#: proxmox-yew-comp/src/token_panel.rs:366
-#, fuzzy
msgid "Copy token secret to clipboard."
-msgstr "将名称复制到剪贴板"
+msgstr "复制令牌密钥到剪贴板。"
#: pve-manager/www/manager6/lxc/ResourceEdit.js:113
#: pve-manager/www/manager6/lxc/Resources.js:75
@@ -3275,24 +3187,24 @@ msgstr "核心"
#: proxmox-datacenter-manager/ui/src/configuration/views.rs:235
msgid "Could not delete '{0}': '{1}'"
-msgstr ""
+msgstr "无法删除'{0}':'{1}'"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:81
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:114
msgid "Could not detect a ceph installation in the cluster"
-msgstr "无法在群集中检测到 ceph 安装"
+msgstr "无法在集群中检测到 ceph 安装"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:584
msgid "Could not fetch update status: {0}"
-msgstr ""
+msgstr "无法获取更新状态:{0}"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:179
msgid "Could not find Controller for EVPN zone {}"
-msgstr ""
+msgstr "找不到 EVPN 区域 {} 的控制器"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/ui_helpers.rs:47
msgid "Could not load status"
-msgstr ""
+msgstr "无法加载状态"
#: pmg-gui/js/DKIMSettings.js:41
msgid "Could not read private key - please create a selector first!"
@@ -3300,11 +3212,11 @@ msgstr "无法读取私钥-请先创建一个选择器!"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:434
msgid "Could not refresh update status."
-msgstr ""
+msgstr "无法刷新更新状态。"
#: proxmox-datacenter-manager/ui/src/dashboard/remote_panel.rs:82
msgid "Could reach all remotes."
-msgstr ""
+msgstr "可以访问所有远程。"
#: pmg-gui/js/ContactStatistics.js:168 pmg-gui/js/Dashboard.js:488
#: pmg-gui/js/DomainStatistics.js:94 pmg-gui/js/DomainStatistics.js:137
@@ -3401,19 +3313,16 @@ msgid "Create Device Nodes"
msgstr "创建设备节点"
#: proxmox-datacenter-manager/ui/src/tasks.rs:35
-#, fuzzy
msgid "Create EVPN VNet"
-msgstr "创建虚拟机"
+msgstr "创建 EVPN 虚拟网络"
#: proxmox-datacenter-manager/ui/src/tasks.rs:34
-#, fuzzy
msgid "Create EVPN Zone"
-msgstr "创建 CT"
+msgstr "创建 EVPN 区域"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_summary.rs:109
-#, fuzzy
msgid "Create Token"
-msgstr "创建 CT"
+msgstr "创建令牌"
#: pve-manager/www/manager6/Workspace.js:287
#: pve-manager/www/manager6/node/CmdMenu.js:9
@@ -3436,7 +3345,7 @@ msgstr "创建: OSD"
#: proxmox-yew-comp/src/tfa/tfa_view.rs:406
#: proxmox-yew-comp/src/tfa/tfa_confirm_remove.rs:56
msgid "Created"
-msgstr "已创建"
+msgstr "创建时间"
#: pve-manager/www/manager6/ceph/OSDDetails.js:266
msgid "Creation time"
@@ -3481,9 +3390,8 @@ msgid "Custom"
msgstr "自定义"
#: proxmox-datacenter-manager/ui/src/configuration/views.rs:151
-#, fuzzy
msgid "Custom Layout"
-msgstr "当前布局"
+msgstr "自定义布局"
#: pmg-gui/js/SpamDetectorCustom.js:118 pmg-gui/js/SpamDetectorCustom.js:165
msgid "Custom Rule Score"
@@ -3586,21 +3494,18 @@ msgstr "DNS 服务器"
#: proxmox-yew-comp/src/configuration/dns.rs:32
#: proxmox-yew-comp/src/configuration/dns.rs:64
-#, fuzzy
msgid "DNS server 1"
-msgstr "DNS 服务器"
+msgstr "DNS 服务器 1"
#: proxmox-yew-comp/src/configuration/dns.rs:40
#: proxmox-yew-comp/src/configuration/dns.rs:67
-#, fuzzy
msgid "DNS server 2"
-msgstr "DNS 服务器"
+msgstr "DNS 服务器 2"
#: proxmox-yew-comp/src/configuration/dns.rs:48
#: proxmox-yew-comp/src/configuration/dns.rs:68
-#, fuzzy
msgid "DNS server 3"
-msgstr "DNS 服务器"
+msgstr "DNS 服务器 3"
#: pve-manager/www/manager6/lxc/DNS.js:43
#: pve-manager/www/manager6/qemu/CloudInit.js:230
@@ -3649,9 +3554,8 @@ msgid "Dashboard Options"
msgstr "仪表板选项"
#: proxmox-datacenter-manager/ui/src/dashboard/status_row.rs:238
-#, fuzzy
msgid "Dashboard Settings"
-msgstr "仪表板选项"
+msgstr "仪表板设置"
#: pve-manager/www/manager6/window/Settings.js:179
msgid "Dashboard Storages"
@@ -3702,9 +3606,8 @@ msgid "Datastore"
msgstr "数据存储"
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:317
-#, fuzzy
msgid "Datastore (Proxmox Backup Server)"
-msgstr "Proxmox Backup Server 登录"
+msgstr "数据存储(Proxmox 备份服务器)"
#: proxmox-backup/www/tape/window/TapeRestore.js:517
msgid "Datastore Mapping"
@@ -3715,9 +3618,8 @@ msgid "Datastore Options"
msgstr "数据存储选项"
#: proxmox-backup/www/window/DataStoreEdit.js:58
-#, fuzzy
msgid "Datastore Type"
-msgstr "数据存储"
+msgstr "数据存储类型"
#: proxmox-backup/www/dashboard/DataStoreStatistics.js:56
msgid "Datastore Usage"
@@ -3738,9 +3640,8 @@ msgid "Datastore is not mounted"
msgstr "数据存储未挂载"
#: proxmox-datacenter-manager/ui/src/pbs/datastore.rs:51
-#, fuzzy
msgid "Datastore {0}"
-msgstr "数据存储"
+msgstr "数据存储 {0}"
#: proxmox-backup/www/datastore/DataStoreList.js:194
#: proxmox-datacenter-manager/ui/src/pbs/tree.rs:239
@@ -3782,7 +3683,7 @@ msgstr "停用 {0} 帐户"
#: proxmox-yew-comp/src/rrd_timeframe_selector.rs:160
msgid "Decade"
-msgstr ""
+msgstr "十年"
#: pmg-gui/js/ViewMailHeaders.js:106
msgid "Decode"
@@ -3857,14 +3758,12 @@ msgid "Default"
msgstr "默认"
#: proxmox-backup/www/datastore/OptionView.js:316
-#, fuzzy
msgid "Default # of Verification Readers"
-msgstr "上次验证"
+msgstr "默认验证读取器数量"
#: proxmox-backup/www/datastore/OptionView.js:326
-#, fuzzy
msgid "Default # of Verification Workers"
-msgstr "上次验证"
+msgstr "默认验证工作器数量"
#: pve-manager/www/manager6/node/NodeOptionsView.js:80
msgid "Default (80%)"
@@ -3928,17 +3827,15 @@ msgstr "可以通过编辑领域来设置默认同步选项。"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:401
msgid "Default user classes: inetorgperson, posixaccount, person, user"
-msgstr "默认用户类别:inetorgperson、posixaccount、person、user"
+msgstr "默认用户类:inetorgperson、posixaccount、person、user"
#: proxmox-backup/www/Utils.js:927
-#, fuzzy
msgid "Default verification readers"
-msgstr "验证码"
+msgstr "默认验证读取器"
#: proxmox-backup/www/Utils.js:921
-#, fuzzy
msgid "Default verification workers"
-msgstr "验证作业"
+msgstr "默认验证工作器"
#: proxmox-widget-toolkit/src/panel/SendmailEditPanel.js:71
msgid "Defaults to datacenter configuration, or root@$hostname"
@@ -3966,6 +3863,8 @@ msgid ""
"the cluster or single node. Fingerprints are only required for untrusted "
"certificates."
msgstr ""
+"定义一组地址,供 Proxmox 数据中心管理器用于连接集群或单个节点。仅当证书不受信"
+"任时才需要提供指纹。"
#: pmg-gui/js/PBSSnapshotView.js:182
msgid "Delay"
@@ -3989,7 +3888,7 @@ msgstr "删除"
#: pve-manager/www/manager6/node/Certificates.js:279
#: proxmox-yew-comp/src/acme/certificate_list.rs:126
msgid "Delete Custom Certificate"
-msgstr "删除自定义凭证"
+msgstr "删除自定义证书"
#: pve-manager/www/manager6/Utils.js:2128
#: pve-manager/www/manager6/Utils.js:2157
@@ -4000,7 +3899,6 @@ msgid "Delete Snapshot"
msgstr "删除快照"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:432
-#, fuzzy
msgid "Delete Source"
msgstr "删除源"
@@ -4014,17 +3912,15 @@ msgstr "删除所有信息"
#: pve-manager/www/manager6/node/Certificates.js:286
msgid "Delete custom certificate and switch to generated one?"
-msgstr "删除自定义凭证并切换到生成的凭证?"
+msgstr "删除自定义证书并切换到生成的证书?"
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/mobile.rs:228
-#, fuzzy
msgid "Delete device"
-msgstr "删除源"
+msgstr "删除设备"
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/mobile.rs:447
-#, fuzzy
msgid "Delete disk"
-msgstr "删除源"
+msgstr "删除磁盘"
#: pve-manager/www/manager6/storage/PBSEdit.js:310
msgid "Delete existing encryption key"
@@ -4032,7 +3928,7 @@ msgstr "删除现有加密密钥"
#: proxmox-yew-comp/src/pending_property_view/mod.rs:303
msgid "Delete property failed"
-msgstr ""
+msgstr "删除属性失败"
#: pve-manager/www/manager6/qemu/HDMove.js:84
#: proxmox-yew-comp/src/configuration/pve/move_disk_dialog.rs:98
@@ -4041,20 +3937,18 @@ msgstr "删除源"
#: proxmox-yew-comp/src/configuration/pve/lxc_resources_panel/mobile.rs:258
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/mobile.rs:395
-#, fuzzy
msgid "Delete volume"
-msgstr "删除源"
+msgstr "删除卷"
#: pmg-gui/js/PostfixMailQueue.js:100
-#, fuzzy
msgid "Delete {0} selected mails?"
-msgstr "未选择 {0}"
+msgstr "删除选定的 {0} 封邮件?"
#: pve-manager/www/manager6/storage/PBSEdit.js:441
msgid ""
"Deleting or replacing the encryption key will break restoring backups "
"created with it!"
-msgstr "删除或替换加密密钥将破坏用它创建的备份的还原!"
+msgstr "删除或替换加密密钥将导致用它创建的备份无法恢复!"
#: pmg-gui/js/AttachmentQuarantine.js:147
#: pmg-gui/js/QuarantineContextMenu.js:19 pmg-gui/js/SpamContextMenu.js:6
@@ -4069,9 +3963,8 @@ msgid "Deliver to"
msgstr "传送到"
#: pmg-gui/js/PostfixMailQueue.js:96
-#, fuzzy
msgid "Deliver {0} selected mails?"
-msgstr "未选择 {0}"
+msgstr "投递选定的 {0} 封邮件?"
#: pve-manager/www/manager6/UIOptions.js:75
msgid "Dense"
@@ -4079,9 +3972,8 @@ msgstr "密集"
#: pve-yew-mobile-gui/src/pages/page_settings.rs:41
#: proxmox-yew-comp/src/theme_dialog.rs:55
-#, fuzzy
msgid "Density"
-msgstr "磁带密度"
+msgstr "密度"
#: proxmox-widget-toolkit/src/node/APT.js:49
#: proxmox-widget-toolkit/src/node/APTRepositories.js:36
@@ -4120,7 +4012,7 @@ msgstr "磁带密度"
#: proxmox-yew-comp/src/tfa/tfa_confirm_remove.rs:60
#: proxmox-yew-comp/src/tasks.rs:151
msgid "Description"
-msgstr "说明"
+msgstr "描述"
#: pve-manager/www/manager6/dc/Backup.js:330
#: pve-manager/www/manager6/dc/RealmSyncJob.js:397
@@ -4172,7 +4064,7 @@ msgstr "销毁"
#: pve-manager/www/manager6/storage/ImageView.js:64
msgid "Destroy '{0}'"
-msgstr "销毁 '{0}'"
+msgstr "销毁'{0}'"
#: pve-manager/www/manager6/ceph/ServiceList.js:396
msgid "Destroy MON"
@@ -4180,7 +4072,7 @@ msgstr "销毁 MON"
#: proxmox-backup/www/window/NamespaceEdit.js:102
msgid "Destroy Namespace '{0}'"
-msgstr "销毁命名空间 '{0}'"
+msgstr "销毁命名空间'{0}'"
#: proxmox-backup/www/datastore/OptionView.js:24
msgid "Destroy all data (dangerous!)"
@@ -4210,9 +4102,8 @@ msgid "Detail"
msgstr "详情"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:453
-#, fuzzy
msgid "Detailed Mapping"
-msgstr "数据存储映射"
+msgstr "详细映射"
#: proxmox-widget-toolkit/src/window/TaskViewer.js:65
#: pve-manager/www/manager6/ceph/OSD.js:898
@@ -4413,18 +4304,16 @@ msgstr "磁盘操作"
#: proxmox-datacenter-manager/ui/src/pbs/datastore/overview.rs:245
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:379
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:388
-#, fuzzy
msgid "Disk I/O"
-msgstr "磁盘 IO"
+msgstr "磁盘 I/O"
#: pve-manager/www/manager6/panel/GuestSummary.js:129
msgid "Disk IO"
msgstr "磁盘 IO"
#: proxmox-datacenter-manager/ui/src/pve/utils.rs:291
-#, fuzzy
msgid "Disk Image"
-msgstr "磁盘映像"
+msgstr "磁盘镜像"
#: pve-manager/www/manager6/dc/OptionView.js:374
msgid "Disk Move"
@@ -4433,16 +4322,14 @@ msgstr "磁盘移动"
#: proxmox-datacenter-manager/ui/src/pbs/datastore/overview.rs:141
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:182
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:180
-#, fuzzy
msgid "Disk Read"
-msgstr "磁盘读取总额"
+msgstr "磁盘读取"
#: proxmox-datacenter-manager/ui/src/pbs/datastore/overview.rs:142
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:183
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:181
-#, fuzzy
msgid "Disk Write"
-msgstr "磁盘写入总额"
+msgstr "磁盘写入"
#: pve-manager/www/manager6/Utils.js:693
#: pve-manager/www/manager6/form/DiskStorageSelector.js:154
@@ -4494,29 +4381,27 @@ msgid "Do not use any media"
msgstr "不使用任何介质"
#: proxmox-yew-comp/src/token_panel.rs:209
-#, fuzzy
msgid ""
"Do you want to regenerate the secret of the selected API token? All existing "
"users of the token will lose access!"
msgstr ""
-"是否重新生成API令牌'{0}'的机密?之前令牌密钥的所有用户都将失去访问权限!"
+"是否重新生成 API 令牌'{0}'的密钥?之前令牌密钥的所有用户都将失去访问权限!"
#: proxmox-widget-toolkit/src/panel/NotificationConfigView.js:14
msgid "Do you want to reset {0} to its default settings?"
-msgstr "您想将 {0} 重置为其默认设置吗?"
+msgstr "是否要将 {0} 重置为默认设置?"
#: proxmox-widget-toolkit/src/panel/NotificationConfigView.js:120
msgid "Do you want to send a test notification to '{0}'?"
msgstr "是否要向'{0}'发送测试通知?"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_connect.rs:96
-#, fuzzy
msgid "Do you want to trust the certificate and save its fingerprint?"
-msgstr "您想将 {0} 重置为其默认设置吗?"
+msgstr "要信任该证书并保存其指纹吗?"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_nodes.rs:68
msgid "Do you want to trust them by saving their fingerprint?"
-msgstr ""
+msgstr "您想通过保存其指纹来信任它们吗?"
#: pmg-gui/js/MainView.js:195 pve-manager/www/manager6/Workspace.js:380
#: proxmox-backup/www/MainView.js:245
@@ -4526,7 +4411,7 @@ msgstr "文档"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:455
msgid "Does not look like a valid recovery key"
-msgstr "看起来不像是有效的还原密钥"
+msgstr "看起来不是有效的恢复密钥"
#: pve-manager/www/manager6/dc/ClusterEdit.js:334
msgid "Does not seem like a valid encoded Cluster Information!"
@@ -4582,7 +4467,7 @@ msgstr "下载"
#: proxmox-backup/www/datastore/Content.js:1106
msgid "Download '{0}'"
-msgstr "下载 '{0}'"
+msgstr "下载'{0}'"
#: proxmox-widget-toolkit/src/window/FileBrowser.js:322
msgid "Download as"
@@ -4642,7 +4527,7 @@ msgstr "驱动器"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:19
msgid "Drop"
-msgstr ""
+msgstr "丢弃"
#: proxmox-backup/www/panel/PrunePanel.js:65
msgid "Dry Run"
@@ -4697,7 +4582,7 @@ msgstr "动态"
#: proxmox-backup/www/window/UserEdit.js:162
#: proxmox-yew-comp/src/acme/acme_register_account.rs:111
msgid "E-Mail"
-msgstr "E-Mail"
+msgstr "电子邮件"
#: pmg-gui/js/Dashboard.js:423
msgid "E-Mail Processing"
@@ -4713,13 +4598,13 @@ msgstr "E-Mail 地址"
#: pmg-gui/js/LDAPConfig.js:318
msgid "E-Mail addresses of '{0}'"
-msgstr "'{0}' 的 E-Mail 地址"
+msgstr "'{0}'的 E-Mail 地址"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:351
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:246
#: proxmox-yew-comp/src/auth_edit_ldap.rs:220
msgid "E-Mail attribute"
-msgstr "E-Mail 属性"
+msgstr "电子邮件属性"
#: pve-manager/www/manager6/node/ACME.js:220
msgid "EAB Key"
@@ -4771,39 +4656,39 @@ msgstr "邮件属性名"
#: proxmox-datacenter-manager/ui/src/main_menu.rs:326
msgid "EVPN"
-msgstr ""
+msgstr "EVPN"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_vnet.rs:225
msgid "EVPN Zone has no VRF VNI configured!"
-msgstr ""
+msgstr "EVPN 区域未配置 VRF VNI!"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:280
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:160
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:219
msgid "EVPN Zone {} has no VRF VNI"
-msgstr ""
+msgstr "EVPN 区域 {} 没有 VRF VNI"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:192
msgid "EVPN Zone {} has no VXLAN ID defined!"
-msgstr ""
+msgstr "EVPN 区域 {} 未定义 VXLAN ID!"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_zone.rs:233
msgid "EVPN controller {} has no ASN"
-msgstr ""
+msgstr "EVPN 控制器 {} 没有 ASN"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:187
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:270
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:150
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:209
msgid "EVPN controller {} has no ASN defined!"
-msgstr ""
+msgstr "EVPN 控制器 {} 未定义 ASN!"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:166
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:250
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:130
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:189
msgid "EVPN zone {} has no controller defined!"
-msgstr ""
+msgstr "EVPN 区域 {} 未定义控制器!"
#: proxmox-widget-toolkit/src/Utils.js:697
#: proxmox-widget-toolkit/src/node/DNSView.js:50
@@ -4919,27 +4804,24 @@ msgid "Edit"
msgstr "编辑"
#: proxmox-yew-comp/src/firewall/options_edit.rs:170
-#, fuzzy
msgid "Edit Cluster Firewall"
-msgstr "启用防火墙"
+msgstr "编辑集群防火墙"
#: proxmox-yew-comp/src/firewall/options_edit.rs:240
-#, fuzzy
msgid "Edit Guest Firewall"
-msgstr "VNet 防火墙"
+msgstr "编辑客户机防火墙"
#: pve-manager/www/manager6/tree/ResourceMapTree.js:357
msgid "Edit Mapping '{0}'"
-msgstr "编辑映射 '{0}'"
+msgstr "编辑映射'{0}'"
#: pve-manager/www/manager6/tree/ResourceMapTree.js:359
msgid "Edit Mapping '{0}' for '{1}'"
-msgstr "编辑 '{1}' 的映射 '{0}'"
+msgstr "编辑'{1}'的映射'{0}'"
#: proxmox-yew-comp/src/firewall/options_edit.rs:221
-#, fuzzy
msgid "Edit Node Firewall"
-msgstr "VNet 防火墙"
+msgstr "编辑节点防火墙"
#: pve-manager/www/manager6/grid/BackupView.js:268
#: pve-manager/www/manager6/storage/BackupView.js:151
@@ -4952,9 +4834,8 @@ msgstr "编辑标记"
#: proxmox-yew-comp/src/acme/acme_domains.rs:244
#: proxmox-yew-comp/src/acme/acme_domains.rs:434
-#, fuzzy
msgid "Edit account settings"
-msgstr "编辑仪表板设置"
+msgstr "编辑账户设置"
#: proxmox-backup/www/Dashboard.js:243
msgid "Edit dashboard settings"
@@ -4966,7 +4847,7 @@ msgstr "编辑现有的加密密钥(危险!)"
#: proxmox-widget-toolkit/src/panel/NotesView.js:145
msgid "Edit notes"
-msgstr "编辑注释"
+msgstr "编辑备注"
#: pmg-gui/js/ActionList.js:147
#: pve-manager/www/manager6/form/CalendarEvent.js:6
@@ -4984,12 +4865,12 @@ msgstr "EiB"
#: proxmox-widget-toolkit/src/panel/EmailRecipientPanel.js:12
#: proxmox-widget-toolkit/src/panel/SendmailEditPanel.js:14
msgid "Either mailto or mailto-user must be set"
-msgstr "必须设置 mailto 或 mailto 用户"
+msgstr "必须设置 mailto 或 mailto-user"
#: proxmox-widget-toolkit/src/node/NetworkView.js:434
msgid ""
"Either reboot or use 'Apply Configuration' (needs ifupdown2) to activate"
-msgstr "重新启动或使用“应用配置”(需要 ifupdown2 )激活"
+msgstr "重启或使用“应用配置”(需安装 ifupdown2)以激活"
#: proxmox-backup/www/tape/BackupJobs.js:230
#: proxmox-backup/www/tape/DriveStatus.js:227
@@ -5016,9 +4897,8 @@ msgid "Email from address"
msgstr "来自地址的电子邮件"
#: pve-yew-mobile-gui/src/widgets/guest_backup_panel.rs:91
-#, fuzzy
msgid "Email to"
-msgstr "Email"
+msgstr "发送邮件至"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:197
#: proxmox-widget-toolkit/src/node/APTRepositories.js:571
@@ -5046,9 +4926,8 @@ msgstr "启用"
#: pve-manager/www/manager6/qemu/TdxEdit.js:73
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_intel_tdx_property.rs:37
-#, fuzzy
msgid "Enable Attestation"
-msgstr "启用配额"
+msgstr "启用认证"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:63
#: proxmox-yew-comp/src/firewall/options_edit.rs:339
@@ -5102,17 +4981,16 @@ msgstr "启用 TLS 日志"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:59
#: proxmox-yew-comp/src/firewall/options_edit.rs:283
-#, fuzzy
msgid "Enable ebtables"
-msgstr "启用配额"
+msgstr "启用 ebtables"
#: pve-manager/www/manager6/ha/ResourceEdit.js:120
msgid "Enable if HA resource should automatically adjust to HA rules."
-msgstr ""
+msgstr "如果 HA 资源应自动调整到 HA 规则,请启用。"
#: pve-manager/www/manager6/ha/rules/NodeAffinityRuleEdit.js:133
msgid "Enable if the HA Resources must be restricted to the nodes."
-msgstr ""
+msgstr "如果 HA 资源必须限制在这些节点上,请启用。"
#: pve-manager/www/manager6/storage/LVMEdit.js:235
msgid "Enable if the LVM is located on a shared LUN."
@@ -5200,7 +5078,7 @@ msgstr "为 Windows 启用"
#: pve-manager/www/manager6/window/Migrate.js:653
msgid "Enables live migration of conntrack entries for this VM."
-msgstr ""
+msgstr "为此虚拟机启用 conntrack 条目的实时迁移。"
#: pve-manager/www/manager6/ceph/OSD.js:101
msgid "Encrypt OSD"
@@ -5257,9 +5135,8 @@ msgstr "结束时间"
#: proxmox-backup/www/config/S3ClientView.js:115
#: proxmox-backup/www/form/S3ClientSelector.js:26
#: proxmox-backup/www/window/S3ClientEdit.js:46
-#, fuzzy
msgid "Endpoint"
-msgstr "端点名称"
+msgstr "端点"
#: proxmox-widget-toolkit/src/panel/GotifyEditPanel.js:17
#: proxmox-widget-toolkit/src/panel/SendmailEditPanel.js:28
@@ -5270,9 +5147,8 @@ msgstr "端点名称"
#: proxmox-datacenter-manager/ui/src/remotes/add_wizard.rs:125
#: proxmox-datacenter-manager/ui/src/remotes/edit_remote.rs:128
-#, fuzzy
msgid "Endpoints"
-msgstr "端点名称"
+msgstr "端点"
#: proxmox-widget-toolkit/src/Utils.js:72 proxmox-yew-comp/src/lib.rs:302
msgid "English"
@@ -5284,26 +5160,24 @@ msgstr "确保底层存储支持访问时间更新"
#: pve-manager/www/manager6/window/DownloadUrlToStorage.js:141
msgid "Enter URL to download"
-msgstr "输入 URL 下载"
+msgstr "输入下载URL"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:351
msgid "Enterprise (recommended)"
msgstr "企业(推荐)"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:717
-#, fuzzy
msgid "Enterprise repository configured, but missing subscription"
-msgstr "企业存储库需要有效订阅"
+msgstr "已配置企业仓库,但缺少订阅"
#: proxmox-widget-toolkit/src/Utils.js:1396
msgid "Enterprise repository needs valid subscription"
-msgstr "企业存储库需要有效订阅"
+msgstr "企业版软件源需要有效订阅"
#: proxmox-yew-comp/src/auth_view.rs:453
#: proxmox-yew-comp/src/auth_edit_ldap.rs:247
-#, fuzzy
msgid "Entries"
-msgstr "入口"
+msgstr "条目"
#: pve-manager/www/manager6/qemu/RNGEdit.js:47
msgid "Entropy source"
@@ -5315,17 +5189,16 @@ msgstr "熵源"
#: pve-manager/www/manager6/dc/RealmSyncJob.js:374
#: pve-manager/www/manager6/dc/SyncWindow.js:138
msgid "Entry"
-msgstr "入口"
+msgstr "条目"
#: pve-manager/www/manager6/lxc/Options.js:157
#: proxmox-yew-comp/src/form/pve/lxc_property/mod.rs:123
-#, fuzzy
msgid "Entrypoint"
-msgstr "端点名称"
+msgstr "入口点"
#: pve-manager/www/manager6/lxc/Options.js:163
msgid "Entrypoint Init Command"
-msgstr ""
+msgstr "入口点初始化命令"
#: pmg-gui/js/DKIMSettings.js:124
msgid "Envelope"
@@ -5335,7 +5208,7 @@ msgstr "信封"
#: pve-manager/www/manager6/lxc/Options.js:186
#: proxmox-yew-comp/src/form/pve/lxc_property/mod.rs:127
msgid "Environment"
-msgstr ""
+msgstr "环境变量"
#: pve-manager/www/manager6/Utils.js:2115
#: proxmox-datacenter-manager/ui/src/tasks.rs:44
@@ -5578,7 +5451,7 @@ msgstr "每 {0} 分钟"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:1303
msgid "Exact"
-msgstr "准确的"
+msgstr "精确匹配"
#: proxmox-widget-toolkit/src/Toolkit.js:11
#: proxmox-widget-toolkit/src/Toolkit.js:21
@@ -5657,7 +5530,7 @@ msgstr "实验性"
#: proxmox-yew-comp/src/token_panel.rs:454
#: proxmox-yew-comp/src/token_panel.rs:511
msgid "Expire"
-msgstr "有效期至"
+msgstr "过期时间"
#: proxmox-widget-toolkit/src/panel/Certificates.js:46
#: proxmox-widget-toolkit/src/window/Certificates.js:52
@@ -5667,7 +5540,7 @@ msgstr "有效期至"
#: proxmox-yew-comp/src/acme/certificate_list.rs:359
#: proxmox-yew-comp/src/acme/certificate_list.rs:410
msgid "Expires"
-msgstr "有效期至"
+msgstr "过期时间"
#: proxmox-backup/www/tape/BackupJobs.js:237
msgid "Export"
@@ -5679,18 +5552,16 @@ msgid "Export Media-Set"
msgstr "导出媒体集"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:395
-#, fuzzy
msgid "External"
-msgstr "外部 SMTP 端口"
+msgstr "外部"
#: pmg-gui/js/MailProxyPorts.js:42
msgid "External SMTP Port"
msgstr "外部 SMTP 端口"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_processor_property.rs:155
-#, fuzzy
msgid "Extra CPU Flags"
-msgstr "CPU利用率"
+msgstr "CPU 扩展标志"
#: pmg-gui/js/SpamDetectorOptions.js:26
msgid "Extract Text from Attachments"
@@ -5709,11 +5580,11 @@ msgstr "FS 名称"
#: pve-manager/www/manager6/sdn/controllers/EvpnEdit.js:44
#: pve-manager/www/manager6/sdn/zones/VxlanEdit.js:66
msgid "Fabric"
-msgstr ""
+msgstr "网络结构"
#: pve-manager/www/manager6/dc/Config.js:310
msgid "Fabrics"
-msgstr ""
+msgstr "网络结构"
#: pmg-gui/js/RuleConfiguration.js:180
msgid "Factory Defaults"
@@ -5721,9 +5592,8 @@ msgstr "出厂默认值"
#: pve-manager/www/manager6/ha/ResourceEdit.js:116
#: pve-manager/www/manager6/ha/Resources.js:148
-#, fuzzy
msgid "Failback"
-msgstr "回退"
+msgstr "故障回退"
#: pve-manager/www/manager6/Utils.js:295
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:440
@@ -5732,20 +5602,20 @@ msgstr "失败"
#: proxmox-datacenter-manager/ui/src/dashboard/remote_panel.rs:87
msgid "Failed to reach all remotes"
-msgstr ""
+msgstr "无法访问所有远程"
#: proxmox-datacenter-manager/ui/src/dashboard/remote_panel.rs:102
msgid "Failed to reach one of {0} remotes."
msgid_plural "Failed to reach {n} of {0} remotes."
-msgstr[0] ""
+msgstr[0] "无法访问 {0} 个远程中的 {n} 个。"
#: proxmox-datacenter-manager/ui/src/dashboard/remote_panel.rs:93
msgid "Failed to reach {0} out of {1} remotes"
-msgstr ""
+msgstr "无法访问 {1} 个远程中的 {0} 个"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:669
msgid "Failed to retrieve update status: {0}"
-msgstr ""
+msgstr "无法检索更新状态:{0}"
#: proxmox-widget-toolkit/src/window/DiskSmart.js:70
msgid "Failing"
@@ -5762,7 +5632,7 @@ msgstr "回退"
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:38
#: proxmox-yew-comp/src/auth_edit_ldap.rs:298
msgid "Fallback Server"
-msgstr "后备服务器"
+msgstr "备用服务器"
#: pve-manager/www/manager6/dc/Backup.js:809
msgid "Fallback from storage config"
@@ -5776,7 +5646,7 @@ msgstr "系列"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:541
#: proxmox-yew-comp/src/apt_repositories.rs:294
msgid "Fatal parsing error for at least one repository"
-msgstr "至少一个存储库的致命解析错误"
+msgstr "至少一个软件源存在致命解析错误"
#: pve-manager/www/manager6/lxc/FeaturesEdit.js:125
#: pve-manager/www/manager6/lxc/Options.js:148
@@ -5802,9 +5672,8 @@ msgstr "字段名称"
#: proxmox-yew-widget-toolkit/src/widget/form/field.rs:333
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:449
#: proxmox-yew-widget-toolkit/src/widget/form/textarea.rs:142
-#, fuzzy
msgid "Field may not be empty."
-msgstr "标签不能为空。"
+msgstr "字段不能为空。"
#: proxmox-widget-toolkit/src/node/Tasks.js:194
msgid "Fields"
@@ -5846,7 +5715,7 @@ msgstr "文件名"
msgid ""
"File of type {0} cannot be downloaded directly, download a parent directory "
"instead."
-msgstr "{0} 类型的文件无法直接下载,请下载父目录。"
+msgstr "无法直接下载 {0} 类型的文件,请下载其父目录。"
#: pve-manager/www/manager6/window/DownloadUrlToStorage.js:174
#: pve-manager/www/manager6/window/UploadToStorage.js:226
@@ -5878,7 +5747,7 @@ msgstr "文件类型"
#: proxmox-datacenter-manager/ui/src/pbs/tree.rs:254
#: proxmox-datacenter-manager/ui/src/pve/tree.rs:502
msgid "Filter"
-msgstr "筛选器"
+msgstr "过滤器"
#: proxmox-backup/www/form/GroupFilter.js:460
msgid "Filter Type"
@@ -5945,14 +5814,12 @@ msgid "Finish Edit"
msgstr "完成编辑"
#: proxmox-datacenter-manager/ui/src/dashboard/status_row.rs:215
-#, fuzzy
msgid "Finish Editing"
msgstr "完成编辑"
#: pve-yew-mobile-gui/src/widgets/task_list_button.rs:148
-#, fuzzy
msgid "Finished"
-msgstr "完成"
+msgstr "已完成"
#: pve-manager/www/manager6/dc/Config.js:330
#: pve-manager/www/manager6/grid/FirewallOptions.js:66
@@ -5981,7 +5848,7 @@ msgstr "固件"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:549
msgid "First Ceph monitor"
-msgstr "第一个 Ceph 监视器"
+msgstr "第一个 Ceph monitor"
#: pmg-gui/js/UserEdit.js:150 pve-manager/www/manager6/dc/UserEdit.js:83
#: proxmox-backup/www/window/UserEdit.js:146
@@ -5991,7 +5858,7 @@ msgstr "名字"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:333
#: proxmox-yew-comp/src/auth_edit_ldap.rs:211
msgid "First Name attribute"
-msgstr "姓氏属性"
+msgstr "名字属性"
#: pve-manager/www/manager6/form/CalendarEvent.js:39
msgid "First Saturday each month"
@@ -6005,9 +5872,8 @@ msgstr "每年的第一天"
#: proxmox-yew-comp/src/user_panel.rs:538
#: proxmox-yew-comp/src/user_panel.rs:557
-#, fuzzy
msgid "First name"
-msgstr "名字"
+msgstr "名"
#: proxmox-backup/www/tape/DriveStatus.js:338
msgid "Fixed"
@@ -6023,7 +5889,7 @@ msgstr "所有自动创建的用户的固定角色"
#: proxmox-widget-toolkit/src/window/DiskSmart.js:66
msgid "Flags"
-msgstr "标记"
+msgstr "标志位"
#: pve-manager/www/manager6/panel/BackupAdvancedOptions.js:210
msgid "Fleecing"
@@ -6035,7 +5901,7 @@ msgstr "急速存储"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_element.rs:88
msgid "Flex"
-msgstr ""
+msgstr "弹性"
#: pve-manager/www/manager6/qemu/Options.js:137
msgid "Floppy"
@@ -6051,9 +5917,8 @@ msgstr "刷新队列"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_spice_enhancement_property.rs:49
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_spice_enhancement_property.rs:82
-#, fuzzy
msgid "Folder Sharing"
-msgstr "文件夹视图"
+msgstr "文件夹共享"
#: pve-manager/www/manager6/form/ViewSelector.js:26
msgid "Folder View"
@@ -6070,18 +5935,16 @@ msgid "Font-Size"
msgstr "字体大小"
#: proxmox-yew-comp/src/configuration/network_edit.rs:209
-#, fuzzy
msgid "For example, bond0, bond0.100, bond1, ..."
-msgstr "例如:vmbr0.100, vmbr0, vlan0.100, vlan0"
+msgstr "例如:bond0、bond0.100、bond1 等"
#: proxmox-yew-comp/src/configuration/network_edit.rs:134
-#, fuzzy
msgid "For example, vmbr0, vmbr0.100, vmbr1, ..."
-msgstr "例如:vmbr0.100, vmbr0, vlan0.100, vlan0"
+msgstr "例如:vmbr0、vmbr0.100、vmbr1 等"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:334
msgid "For example, vmbr0.100, vmbr0, vlan0.100, vlan0"
-msgstr "例如:vmbr0.100, vmbr0, vlan0.100, vlan0"
+msgstr "例如:vmbr0.100、vmbr0、vlan0.100、vlan0"
#: proxmox-widget-toolkit/src/window/AddTotp.js:163
#: proxmox-widget-toolkit/src/window/AddWebauthn.js:197
@@ -6089,7 +5952,7 @@ msgstr "例如:vmbr0.100, vmbr0, vlan0.100, vlan0"
#: proxmox-yew-comp/src/tfa/tfa_add_totp.rs:102
#: proxmox-yew-comp/src/tfa/tfa_add_webauthn.rs:73
msgid "For example: TFA device ID, required to identify multiple factors."
-msgstr "例如:TFA设备ID,用于识别多个因素。"
+msgstr "例如:双因素认证设备 ID,用于识别多个验证因子。"
#: pve-manager/www/manager6/dc/UserView.js:74
msgid "For the PAM realm, this applies only to the connected node."
@@ -6166,19 +6029,18 @@ msgid "Forward Policy"
msgstr "转发策略"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:130
-#, fuzzy
msgid "Forward log level"
-msgstr "转发策略"
+msgstr "转发日志级别"
#: pve-manager/www/manager6/grid/FirewallRules.js:247
msgid ""
"Forward rules only take effect when the nftables firewall is activated in "
"the host options"
-msgstr "转发规则仅在主机选项中激活nftables防火墙时生效"
+msgstr "转发规则仅在主机选项中激活 nftables 防火墙时生效"
#: proxmox-widget-toolkit/src/Utils.js:733
msgid "Forwarded mails to the local root user"
-msgstr "将邮件转发给本地 root 用户"
+msgstr "转发给本地 root 用户的邮件"
#: pve-manager/www/manager6/node/ZFS.js:250 proxmox-backup/www/ZFSList.js:86
msgid "Fragmentation"
@@ -6196,7 +6058,6 @@ msgid "Freeze CPU at startup"
msgstr "启动时冻结 CPU"
#: proxmox-yew-comp/src/form/pve/qemu_property/mod.rs:144
-#, fuzzy
msgid "Freeze CPU on startup"
msgstr "启动时冻结 CPU"
@@ -6205,12 +6066,12 @@ msgstr "启动时冻结 CPU"
msgid ""
"Freeze/thaw for guest filesystems disabled. This can lead to inconsistent "
"disk backups."
-msgstr "已禁用来宾文件系统的冻结/解冻。这可能导致磁盘备份不一致。"
+msgstr "已禁用客户机文件系统的冻结/解冻。这可能导致磁盘备份不一致。"
#: pve-manager/www/manager6/form/AgentFeatureSelector.js:26
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_agent_property.rs:92
msgid "Freeze/thaw guest filesystems on backup for consistency"
-msgstr "在备份时冻结/解冻来宾文件系统以实现一致性"
+msgstr "在备份时冻结/解冻客户机文件系统以实现一致性"
#: proxmox-widget-toolkit/src/Utils.js:76 proxmox-yew-comp/src/lib.rs:307
msgid "French"
@@ -6229,7 +6090,7 @@ msgstr "从"
#: proxmox-widget-toolkit/src/panel/SendmailEditPanel.js:68
#: proxmox-widget-toolkit/src/panel/SmtpEditPanel.js:141
msgid "From Address"
-msgstr "发件人地址"
+msgstr "发件地址"
#: pve-manager/www/manager6/window/Restore.js:279
msgid "From Backup"
@@ -6254,7 +6115,7 @@ msgstr "从设备"
#: proxmox-yew-comp/src/acme/certificate_list.rs:255
#: proxmox-yew-comp/src/acme/certificate_list.rs:281
msgid "From File"
-msgstr "从文件"
+msgstr "从文件导入"
#: proxmox-backup/www/tape/ChangerStatus.js:83
#: proxmox-backup/www/tape/ChangerStatus.js:122
@@ -6266,9 +6127,8 @@ msgid "From backup configuration"
msgstr "从备份配置"
#: pmg-yew-quarantine-gui/src/page_spam_list.rs:86
-#, fuzzy
msgid "From:"
-msgstr "从"
+msgstr "发件人:"
#: pve-manager/www/manager6/ceph/OSDDetails.js:186
msgid "Front Address"
@@ -6299,11 +6159,11 @@ msgstr "GC访问时间截止(分钟)"
#: proxmox-backup/www/Utils.js:902
#: proxmox-backup/www/datastore/OptionView.js:281
msgid "GC Access-Time Support Check"
-msgstr "GC访问时间支持检查"
+msgstr "GC 访问时间支持检查"
#: proxmox-backup/www/datastore/OptionView.js:305
msgid "GC Cache Capacity (# chunks)"
-msgstr "GC缓存容量(块数)"
+msgstr "GC 缓存容量(块数)"
#: proxmox-backup/www/window/DataStoreEdit.js:148
#: proxmox-backup/www/window/GCJobEdit.js:25
@@ -6312,7 +6172,7 @@ msgstr "GC 时间表"
#: proxmox-backup/www/Utils.js:915
msgid "GC cache capacity"
-msgstr "GC缓存容量"
+msgstr "GC 缓存容量"
#: proxmox-backup/www/Utils.js:438
msgid "Garbage Collect"
@@ -6416,14 +6276,14 @@ msgstr "限制Ceph自我修复的全局标志已启用。"
#: proxmox-yew-widget-toolkit/src/widget/form/tristate_boolean.rs:117
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:444
msgid "Got wrong data type!"
-msgstr ""
+msgstr "获得了错误的数据类型!"
#: proxmox-widget-toolkit/src/panel/PermissionView.js:152
#: pve-manager/www/manager6/dc/PermissionView.js:148
#: proxmox-yew-comp/src/user_panel.rs:318
#: proxmox-yew-comp/src/token_panel.rs:317
msgid "Granted Permissions"
-msgstr "授予的权限"
+msgstr "已授予权限"
#: pve-manager/www/manager6/qemu/DisplayEdit.js:50
#: pve-manager/www/manager6/qemu/SystemEdit.js:81
@@ -6454,7 +6314,7 @@ msgstr "群组"
#: proxmox-backup/www/tape/window/TapeBackupJob.js:213
#: proxmox-backup/www/window/SyncJobEdit.js:555
msgid "Group Filter"
-msgstr "群组筛选器"
+msgstr "组筛选条件"
#: pve-manager/www/manager6/window/TreeSettingsEdit.js:48
msgid "Group Guest Types"
@@ -6502,7 +6362,7 @@ msgstr "群组声明"
#: pmg-gui/js/LDAPConfig.js:449
msgid "Groups of '{0}'"
-msgstr "'{0}' 的组"
+msgstr "'{0}'的组"
#: pve-manager/www/manager6/form/IPRefSelector.js:72
#: pve-manager/www/manager6/grid/Replication.js:298
@@ -6516,21 +6376,19 @@ msgstr "Guest Agent 未运行"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/ui_helpers.rs:102
msgid "Guest Firewall - {0}/{1}/{2} {3}"
-msgstr ""
+msgstr "虚拟机防火墙 - {0}/{1}/{2} {3}"
#: pve-manager/www/manager6/dc/BackupJobDetail.js:29
msgid "Guest Image"
msgstr "客户机镜像"
#: proxmox-datacenter-manager/ui/src/tasks.rs:168
-#, fuzzy
msgid "Guest Migrations"
-msgstr "迁移"
+msgstr "客户机迁移"
#: pve-manager/www/manager6/sdn/ZoneBridgesPanel.js:79
-#, fuzzy
msgid "Guest Network Device"
-msgstr "网络设备"
+msgstr "客户机网络设备"
#: pve-manager/www/manager6/window/Settings.js:283
msgid "Guest Notes"
@@ -6541,13 +6399,12 @@ msgid "Guest OS"
msgstr "客户机操作系统"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:567
-#, fuzzy
msgid "Guest Panels"
-msgstr "客户机镜像"
+msgstr "客户机面板"
#: pve-manager/www/manager6/storage/CIFSEdit.js:163
msgid "Guest user"
-msgstr "访客用户"
+msgstr "客户机用户"
#: pve-manager/www/manager6/dc/Guests.js:5
#: proxmox-datacenter-manager/ui/src/dashboard/guest_panel.rs:226
@@ -6557,7 +6414,7 @@ msgstr "客户"
#: proxmox-datacenter-manager/ui/src/dashboard/top_entities.rs:343
msgid "Guests With the Highest CPU Usage"
-msgstr ""
+msgstr "CPU 使用率最高的虚拟机"
#: pve-manager/www/manager6/dc/Backup.js:665
#: pve-manager/www/manager6/dc/Backup.js:677
@@ -6566,39 +6423,37 @@ msgstr "没有备份工作的客户机"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:601
msgid "Guests with Highest CPU Usage"
-msgstr ""
+msgstr "CPU 使用率最高的虚拟机"
#: pve-manager/www/manager6/ha/rules/NodeAffinityRules.js:6
-#, fuzzy
msgid "HA Node Affinity"
-msgstr "CPU 绑定"
+msgstr "高可用节点亲和性"
#: pve-manager/www/manager6/ha/Rules.js:208
msgid "HA Node Affinity Rules"
-msgstr ""
+msgstr "HA 节点亲和性规则"
#: pve-manager/www/manager6/ha/rules/ResourceAffinityRules.js:6
msgid "HA Resource Affinity"
-msgstr ""
+msgstr "HA 资源亲和性"
#: pve-manager/www/manager6/ha/Rules.js:219
msgid "HA Resource Affinity Rules"
-msgstr ""
+msgstr "HA 资源亲和性规则"
#: pve-manager/www/manager6/ha/RuleEdit.js:81
#: pve-manager/www/manager6/ha/rules/NodeAffinityRules.js:20
#: pve-manager/www/manager6/ha/rules/ResourceAffinityRules.js:20
-#, fuzzy
msgid "HA Resources"
-msgstr "资源"
+msgstr "高可用资源"
#: pve-manager/www/manager6/ha/Rules.js:146
msgid "HA Rule has conflicts and/or errors."
-msgstr ""
+msgstr "HA 规则存在冲突或错误。"
#: pve-manager/www/manager6/ha/Rules.js:147
msgid "HA Rule is OK."
-msgstr ""
+msgstr "HA 规则正常。"
#: pve-manager/www/manager6/dc/OptionView.js:193
msgid "HA Scheduling"
@@ -6619,41 +6474,36 @@ msgid "HA State: {0}"
msgstr "高可用状态: {0}"
#: proxmox-datacenter-manager/ui/src/tasks.rs:172
-#, fuzzy
msgid "HA related Tasks"
-msgstr "相对路径"
+msgstr "高可用相关任务"
#: pve-manager/www/manager6/window/Migrate.js:431
-#, fuzzy
msgid "HA resource {0} with negative affinity to VM on selected target node"
-msgstr "所选目标上的映射资源 ({0}) 不可用。"
+msgstr "高可用资源 {0} 对选定目标节点上的虚拟机具有负亲和性"
#: pve-manager/www/manager6/window/Migrate.js:521
-#, fuzzy
msgid ""
"HA resource {0} with negative affinity to container on selected target node"
-msgstr "所选目标上的映射资源 ({0}) 不可用。"
+msgstr "HA 资源 {0} 与所选目标节点上的容器具有负亲和性"
#: pve-manager/www/manager6/window/Migrate.js:457
msgid ""
"HA resource {0} with positive affinity to VM is also migrated to selected "
"target node."
-msgstr ""
+msgstr "与虚拟机具有正亲和性的 HA 资源 {0} 也将迁移到所选目标节点。"
#: pve-manager/www/manager6/window/Migrate.js:547
msgid ""
"HA resource {0} with positive affinity to container is also migrated to "
"selected target node."
-msgstr ""
+msgstr "与容器具有正亲和性的 HA 资源 {0} 也将迁移到所选目标节点。"
#: pve-manager/www/manager6/ha/RuleErrorsModal.js:10
-#, fuzzy
msgid "HA rule errors"
-msgstr "任意规则匹配"
+msgstr "高可用规则错误"
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:286
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:295
-#, fuzzy
msgid "HA state"
msgstr "高可用状态"
@@ -6668,13 +6518,12 @@ msgid "HD space"
msgstr "硬盘空间"
#: proxmox-yew-comp/src/node_info.rs:200
-#, fuzzy
msgid "HD space (root)"
-msgstr "硬盘空间"
+msgstr "硬盘空间(根目录)"
#: pve-manager/www/manager6/dc/MetricServerView.js:682
msgid "HTTP Headers (JSON)"
-msgstr ""
+msgstr "HTTP 头部 (JSON)"
#: pmg-gui/js/SystemOptions.js:94 pve-manager/www/manager6/dc/OptionView.js:82
#: proxmox-backup/www/config/NodeOptionView.js:42
@@ -6693,7 +6542,7 @@ msgstr "硬盘"
#: proxmox-widget-toolkit/src/Schema.js:94
msgid "Hardlink"
-msgstr "硬连接"
+msgstr "硬链接"
#: pve-manager/www/manager6/qemu/Config.js:319
#: proxmox-datacenter-manager/ui/src/pve/qemu/mod.rs:125
@@ -6703,7 +6552,7 @@ msgstr "硬件"
#: proxmox-widget-toolkit/src/node/NetworkView.js:360
msgid "Hash Policy"
-msgstr "Hash 策略"
+msgstr "哈希策略"
#: pve-manager/www/manager6/window/DownloadUrlToStorage.js:194
#: pve-manager/www/manager6/window/UploadToStorage.js:242
@@ -6714,7 +6563,7 @@ msgstr "哈希算法"
#: proxmox-yew-comp/src/configuration/network_view.rs:485
#: proxmox-yew-comp/src/configuration/network_edit.rs:244
msgid "Hash policy"
-msgstr "Hash 策略"
+msgstr "哈希策略"
#: pmg-gui/js/DKIMSettings.js:125 pmg-gui/js/ViewMailHeaders.js:100
#: pve-manager/www/manager6/Workspace.js:333
@@ -6728,7 +6577,7 @@ msgstr "标题属性"
#: proxmox-widget-toolkit/src/panel/WebhookEditPanel.js:70
#: pmg-gui/js/PostfixMailQueue.js:140
msgid "Headers"
-msgstr "标题"
+msgstr "头部信息"
#: proxmox-widget-toolkit/src/window/ZFSDetail.js:82
#: proxmox-widget-toolkit/src/window/ZFSDetail.js:136
@@ -6736,7 +6585,7 @@ msgstr "标题"
#: pve-manager/www/manager6/dc/Health.js:5
#: pve-manager/www/manager6/node/ZFS.js:257 proxmox-backup/www/ZFSList.js:93
msgid "Health"
-msgstr "健康"
+msgstr "健康状态"
#: pve-manager/www/manager6/ceph/OSDDetails.js:204
msgid "Heartbeat Back Address"
@@ -6753,11 +6602,11 @@ msgstr "希伯来语"
#. TRANSLATORS: See https://en.wikipedia.org/wiki/IS-IS#Packet_types
#: pve-manager/www/manager6/sdn/fabrics/openfabric/FabricEdit.js:47
msgid "Hello Interval"
-msgstr ""
+msgstr "Hello 间隔"
#: pve-manager/www/manager6/sdn/fabrics/openfabric/InterfacePanel.js:19
msgid "Hello Multiplier"
-msgstr ""
+msgstr "Hello 乘数"
#: proxmox-widget-toolkit/src/button/HelpButton.js:8
#: proxmox-widget-toolkit/src/button/HelpButton.js:73
@@ -6792,18 +6641,16 @@ msgid "Hide Internal Hosts"
msgstr "隐藏内部主机"
#: proxmox-yew-widget-toolkit/src/widget/form/field.rs:488
-#, fuzzy
msgid "Hide Password"
-msgstr "绑定密码"
+msgstr "隐藏密码"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/tree.rs:301
msgid "Hide tree panel"
-msgstr ""
+msgstr "隐藏树面板"
#: proxmox-datacenter-manager/ui/src/dashboard/pbs_datastores_panel.rs:113
-#, fuzzy
msgid "High usage"
-msgstr "磁盘使用率"
+msgstr "高使用率"
#: proxmox-widget-toolkit/src/window/ACMEPluginEdit.js:218
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:255
@@ -6842,12 +6689,10 @@ msgid "Host CPU usage"
msgstr "主机 CPU 利用率"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:209
-#, fuzzy
msgid "Host CPU usage (avg.)"
-msgstr "主机 CPU 利用率"
+msgstr "主机 CPU 使用率(平均)"
#: pve-manager/www/manager6/panel/GuestSummary.js:45
-#, fuzzy
msgid "Host Memory Usage"
msgstr "主机内存使用率"
@@ -6857,33 +6702,29 @@ msgid "Host Memory usage"
msgstr "主机内存使用率"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:217
-#, fuzzy
msgid "Host Memory used"
-msgstr "主机内存使用率"
+msgstr "主机内存已用"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:233
-#, fuzzy
msgid "Host Storage used"
-msgstr "存储使用"
+msgstr "主机存储已用"
#: pve-manager/www/manager6/storage/ZFSEdit.js:118
msgid "Host group"
msgstr "主机组"
#: pve-manager/www/manager6/panel/GuestStatusView.js:122
-#, fuzzy
msgid "Host memory usage"
msgstr "主机内存使用率"
#: pve-manager/www/manager6/lxc/Network.js:306
#: proxmox-yew-comp/src/form/pve/lxc_property/lxc_network_property.rs:105
-#, fuzzy
msgid "Host-Managed"
-msgstr "主机名"
+msgstr "主机管理"
#: proxmox-widget-toolkit/src/Toolkit.js:179
msgid "Host/IP address or optional port is invalid"
-msgstr "主机/IP地址或可选端口无效"
+msgstr "主机/IP 地址或可选端口无效"
#: proxmox-widget-toolkit/src/Utils.js:719
#: pve-manager/www/manager6/ceph/OSDDetails.js:148
@@ -6899,9 +6740,8 @@ msgid "Hostname"
msgstr "主机名"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_summary.rs:156
-#, fuzzy
msgid "Hostname/Address"
-msgstr "主机名/IP"
+msgstr "主机名/地址"
#: proxmox-backup/www/window/DatastoreRepoInfo.js:49
#: proxmox-datacenter-manager/ui/src/remotes/node_url_list.rs:248
@@ -6938,12 +6778,12 @@ msgstr "要显示的时间"
#: pve-manager/www/manager6/panel/BackupAdvancedOptions.js:201
msgid "I/O workers in the QEMU process (VMs only)."
-msgstr "QEMU 进程中的 I/O 工作程序(仅限虚拟机)。"
+msgstr "QEMU 进程中的 I/O 工作线程(仅限虚拟机)。"
#: pve-manager/www/manager6/grid/FirewallRules.js:415
#: pve-manager/www/manager6/grid/FirewallRules.js:427
msgid "ICMP type"
-msgstr "ICMP类型"
+msgstr "ICMP 类型"
#: pmg-gui/js/ClusterAdministration.js:250 pmg-gui/js/PBSRemoteEdit.js:31
#: pve-manager/www/manager6/dc/Backup.js:762
@@ -6996,7 +6836,7 @@ msgstr "IO 延迟(毫秒)"
#: pve-manager/www/manager6/node/Summary.js:278
#: pve-manager/www/manager6/panel/GuestSummary.js:147
msgid "IO Pressure Stall"
-msgstr ""
+msgstr "IO 压力停滞"
#: pmg-gui/js/ServerStatus.js:124 pmg-gui/js/dashboard/NodeInfo.js:32
#: pve-manager/www/manager6/node/StatusView.js:35
@@ -7008,7 +6848,7 @@ msgstr "IO 延迟"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_disk_property.rs:255
msgid "IO thread"
-msgstr ""
+msgstr "IO 线程"
#: proxmox-backup/www/ServerStatus.js:217
msgid "IO wait"
@@ -7068,7 +6908,7 @@ msgstr "IP 筛选"
#: proxmox-backup/www/window/S3ClientEdit.js:52
msgid "IP or FQDN S3 endpoint (allows {{bucket}} or {{region}} templating)"
-msgstr ""
+msgstr "IP 或 FQDN S3 端点(允许 {{bucket}} 或 {{region}} 模板)"
#: pve-manager/www/manager6/dc/ClusterEdit.js:261
msgid "IP resolved by node's hostname"
@@ -7079,11 +6919,11 @@ msgstr "IP 由节点的主机名解析"
#: pve-manager/www/manager6/sdn/NetworkBrowser.js:130
#: pve-manager/www/manager6/sdn/ZoneBridgesPanel.js:59
msgid "IP-VRF"
-msgstr ""
+msgstr "IP-VRF"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/evpn_panel.rs:251
msgid "IP-VRFs"
-msgstr ""
+msgstr "IP-VRF"
#: pve-manager/www/manager6/grid/FirewallAliases.js:35
#: pve-manager/www/manager6/grid/FirewallAliases.js:183
@@ -7113,7 +6953,7 @@ msgstr "IPv4"
#: pve-manager/www/manager6/sdn/fabrics/FabricEdit.js:29
msgid "IPv4 Prefix"
-msgstr "IPv4前缀"
+msgstr "IPv4 前缀"
#: pve-manager/www/manager6/qemu/IPConfigEdit.js:111
#: proxmox-yew-comp/src/configuration/network_edit.rs:145
@@ -7158,9 +6998,8 @@ msgstr "ISO 镜像"
#: proxmox-yew-comp/src/form/pve/pve_guest_selector.rs:214
#: proxmox-yew-comp/src/form/pve/pve_guest_selector.rs:244
-#, fuzzy
msgid "Id"
-msgstr "空闲"
+msgstr "ID"
#: proxmox-backup/www/Utils.js:770
msgid "Idle"
@@ -7170,7 +7009,7 @@ msgstr "空闲"
msgid ""
"If a response from a remote is older than 'Max Age', it will be updated on "
"the next refresh."
-msgstr ""
+msgstr "如果来自远程的响应早于\"最大期限\",则将在下次刷新时更新。"
#: pve-manager/www/manager6/qemu/DisplayEdit.js:127
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_display_property.rs:131
@@ -7200,11 +7039,11 @@ msgstr "导入"
#: pve-manager/www/manager6/window/GuestImport.js:5
msgid "Import Guest"
-msgstr "导入访客"
+msgstr "导入客户机"
#: pve-manager/www/manager6/window/GuestImport.js:996
msgid "Import Guest - {0}"
-msgstr "导入访客 - {0}"
+msgstr "导入客户机 - {0}"
#: pve-manager/www/manager6/qemu/HDEdit.js:587
#: pve-manager/www/manager6/qemu/HardwareView.js:740
@@ -7233,37 +7072,37 @@ msgid "Important: Save your Encryption Key"
msgstr "重要提示:保存加密密钥"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:403
-#, fuzzy
msgid "Imported"
-msgstr "导入"
+msgstr "已导入"
#: pve-manager/www/manager6/window/GuestImport.js:1027
msgid ""
"Importing an OVA temporarily requires extra space on the working storage "
"while extracting the contained disks for further processing."
msgstr ""
-"导入 OVA 临时需要工作存储上的额外空间,同时提取包含的磁盘以进行进一步处理。"
+"导入 OVA 文件时,需在工作存储上准备额外空间,用于临时解压内含的虚拟磁盘以供后"
+"续处理。"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:104
msgid ""
"Improve performance for nested virtualization. Only supported on Intel CPUs."
-msgstr ""
+msgstr "提高嵌套虚拟化的性能。仅在 Intel CPU 上支持。"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:103
msgid ""
"Improve performance in overcommitted Windows guests. May lead to guest "
"bluescreens on old CPUs."
-msgstr ""
+msgstr "提高过度分配的 Windows 客户机的性能。可能导致旧 CPU 上的客户机蓝屏。"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:100
msgid ""
"Improves Spectre mitigation performance with AMD CPUs, best used with \"virt-"
"ssbd\""
-msgstr ""
+msgstr "改进 AMD CPU 的 Spectre 缓解性能,最好与\"virt-ssbd\"一起使用"
#: pmg-gui/js/Utils.js:113 pve-manager/www/manager6/ceph/StatusDetail.js:39
msgid "In"
-msgstr "进入"
+msgstr "已加入"
#: pmg-gui/js/Utils.js:115
msgid "In & Out"
@@ -7275,9 +7114,8 @@ msgid "Include"
msgstr "包括"
#: proxmox-datacenter-manager/ui/src/configuration/views.rs:360
-#, fuzzy
msgid "Include All"
-msgstr "包括内存"
+msgstr "包含全部"
#: pmg-gui/js/MailTracker.js:145
msgid "Include Empty Senders"
@@ -7305,7 +7143,7 @@ msgstr "包括所有组"
#: proxmox-datacenter-manager/ui/src/configuration/views.rs:363
msgid "Include all remotes and their resources."
-msgstr ""
+msgstr "包括所有远程及其资源。"
#: pmg-gui/js/PBSRemoteEdit.js:109
msgid "Include in Backup"
@@ -7363,9 +7201,8 @@ msgstr "信息"
#: proxmox-datacenter-manager/ui/src/configuration/subscription_panel.rs:194
#: proxmox-yew-comp/src/subscription_panel.rs:221
-#, fuzzy
msgid "Info URL"
-msgstr "信息"
+msgstr "信息 URL"
#: pmg-gui/js/ClusterAdministration.js:84
#: pve-manager/www/manager6/dc/ClusterEdit.js:328
@@ -7398,16 +7235,15 @@ msgstr "输入策略"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:457
msgid "Input invalid: {}"
-msgstr ""
+msgstr "输入无效: {}"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:122
-#, fuzzy
msgid "Input log level"
-msgstr "日志级别"
+msgstr "输入日志级别"
#: proxmox-backup/www/datastore/Summary.js:351
msgid "Input/Output Operations per Second (IOPS)"
-msgstr "每秒输入/输出操作数(IOPS)"
+msgstr "每秒 I/O 操作数(IOPS)"
#: pve-manager/www/manager6/grid/FirewallRules.js:828
msgid "Insert"
@@ -7429,32 +7265,31 @@ msgstr "Intel(AMD兼容)"
#: pve-manager/www/manager6/qemu/Options.js:390
msgid "Intel TDX"
-msgstr ""
+msgstr "Intel TDX"
#: pve-manager/www/manager6/qemu/TdxEdit.js:35
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_intel_tdx_property.rs:31
-#, fuzzy
msgid "Intel TDX Type"
-msgstr "内容类型"
+msgstr "Intel TDX 类型"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_intel_tdx_property.rs:102
msgid "Intel Trust Domain Extension (TDX)"
-msgstr ""
+msgstr "Intel 信任域扩展 (TDX)"
#: proxmox-widget-toolkit/src/form/NetworkSelector.js:109
#: pve-manager/www/manager6/grid/FirewallRules.js:284
#: pve-manager/www/manager6/grid/FirewallRules.js:571
#: pve-manager/www/manager6/grid/FirewallRules.js:947
msgid "Interface"
-msgstr "接口"
+msgstr "网络接口"
#: pve-manager/www/manager6/sdn/fabrics/InterfacePanel.js:32
msgid "Interface already has an address configured in /etc/network/interfaces"
-msgstr "接口已在/etc/network/Interface中配置了地址"
+msgstr "接口已在 /etc/network/Interface 中配置了地址"
#: pve-manager/www/manager6/sdn/fabrics/InterfacePanel.js:26
msgid "Interface does not exist on node"
-msgstr "节点上不存在接口"
+msgstr "节点上不存在该接口"
#: pmg-gui/js/SystemConfiguration.js:40
#: pve-manager/www/manager6/sdn/FabricsView.js:80
@@ -7474,11 +7309,11 @@ msgstr "间隔"
#: pve-manager/www/manager6/dc/MetricServerView.js:697
#: pve-manager/www/manager6/dc/MetricServerView.js:719
msgid "Invalid JSON format"
-msgstr ""
+msgstr "无效的 JSON 格式"
#: pve-manager/www/manager6/storage/TemplateView.js:290
msgid "Invalid OCI Registry Reference"
-msgstr ""
+msgstr "无效的 OCI 注册表引用"
#: proxmox-widget-toolkit/src/form/ComboGrid.js:397
#: proxmox-widget-toolkit/src/form/ComboGrid.js:476
@@ -7488,7 +7323,7 @@ msgstr "无效值"
#: pve-manager/www/manager6/node/ZFS.js:56
msgid "Invalid characters in pool name"
-msgstr "池名称中的字符无效"
+msgstr "存储池名称包含无效字符"
#: pve-manager/www/manager6/Utils.js:1613
msgid "Invalid file size"
@@ -7497,7 +7332,7 @@ msgstr "无效的文件大小"
#: proxmox-widget-toolkit/src/Utils.js:1176
#: pve-manager/www/manager6/Utils.js:1625
msgid "Invalid file size: "
-msgstr "无效的文件大小: "
+msgstr "无效的文件大小:"
#: proxmox-backup/www/form/PermissionPathSelector.js:136
msgid "Invalid permission path."
@@ -7522,7 +7357,7 @@ msgstr "Ipam"
#: proxmox-widget-toolkit/src/window/AddWebauthn.js:104
msgid "Is this token already registered?"
-msgstr "这个令牌已经注册了吗?"
+msgstr "此令牌是否已注册?"
#: pve-manager/www/manager6/sdn/VnetEdit.js:81
msgid "Isolate Ports"
@@ -7537,31 +7372,31 @@ msgstr "隔离端口"
#: proxmox-yew-comp/src/acme/certificate_list.rs:354
#: proxmox-yew-comp/src/acme/certificate_list.rs:384
msgid "Issuer"
-msgstr "发行者"
+msgstr "签发者"
#: proxmox-widget-toolkit/src/window/AddTotp.js:222
#: proxmox-yew-comp/src/tfa/tfa_add_totp.rs:106
msgid "Issuer Name"
-msgstr "发行者名称"
+msgstr "签发者名称"
#: proxmox-widget-toolkit/src/window/AuthEditOpenId.js:24
#: pmg-gui/js/AuthEditOIDC.js:72
#: pve-manager/www/manager6/dc/AuthEditOpenId.js:23
#: proxmox-yew-comp/src/auth_edit_openid.rs:98
msgid "Issuer URL"
-msgstr "发行人URL"
+msgstr "签发者 URL"
#: proxmox-yew-comp/src/acme/acme_domains.rs:338
msgid "It is not possible to configure more that 5 ACME domain."
-msgstr ""
+msgstr "无法配置超过 5 个 ACME 域。"
#: pve-manager/www/manager6/window/Snapshot.js:103
msgid ""
"It is recommended to either include the RAM or use the QEMU Guest Agent when "
"taking a snapshot of a running VM to avoid inconsistencies."
msgstr ""
-"建议在为运行中的虚拟机拍摄快照时包括 RAM 或使用 QEMU Guest Agent,以避免不一"
-"致。"
+"为避免数据不一致,建议对运行中的虚拟机创建快照时,选择包含内存状态或使用 "
+"QEMU Guest Agent。"
#: pve-manager/www/manager6/panel/BackupJobPrune.js:108
msgid ""
@@ -7639,7 +7474,7 @@ msgstr "加入任务已完成"
#: pve-manager/www/manager6/dc/ClusterEdit.js:165
msgid "Join {0}"
-msgstr "加入{0}"
+msgstr "加入 {0}"
#: pmg-gui/js/GeneralMailStatistics.js:30
#: pmg-gui/js/GeneralMailStatistics.js:181
@@ -7675,7 +7510,7 @@ msgstr "保留全部"
#: pve-manager/www/manager6/window/Backup.js:93
#: proxmox-backup/www/panel/PrunePanel.js:49
msgid "Keep Daily"
-msgstr "保留每天"
+msgstr "保留每日"
#: proxmox-widget-toolkit/src/panel/PruneKeepPanel.js:47
#: pmg-gui/js/PBSRemoteEdit.js:158
@@ -7691,7 +7526,7 @@ msgstr "保留每小时"
#: pve-manager/www/manager6/window/Backup.js:91
#: proxmox-backup/www/panel/PrunePanel.js:41
msgid "Keep Last"
-msgstr "保留上次"
+msgstr "保留最近"
#: proxmox-widget-toolkit/src/panel/PruneKeepPanel.js:38
#: pmg-gui/js/PBSRemoteEdit.js:150
@@ -7702,19 +7537,16 @@ msgid "Keep Monthly"
msgstr "保留每月"
#: pve-manager/www/manager6/ha/rules/ResourceAffinityRuleEdit.js:17
-#, fuzzy
msgid "Keep Separate"
-msgstr "保留每年"
+msgstr "保持分离"
#: pve-manager/www/manager6/storage/Base.js:99
-#, fuzzy
msgid "Keep Snapshots as Volume-Chain enabled if qcow2 images exist!"
-msgstr "存储管理快照是一种技术预览。"
+msgstr "如果存在 qcow2 镜像,请保持 Snapshots as Volume-Chain 启用!"
#: pve-manager/www/manager6/ha/rules/ResourceAffinityRuleEdit.js:16
-#, fuzzy
msgid "Keep Together"
-msgstr "保留每月"
+msgstr "保持在一起"
#: proxmox-widget-toolkit/src/panel/PruneKeepPanel.js:56
#: pmg-gui/js/PBSRemoteEdit.js:164
@@ -7761,9 +7593,8 @@ msgid "Kernel Version"
msgstr "内核版本"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_processor_property.rs:314
-#, fuzzy
msgid "Kernel scheduler settings"
-msgstr "内核版本"
+msgstr "内核调度器设置"
#: proxmox-widget-toolkit/src/panel/WebhookEditPanel.js:364
#: pve-manager/www/manager6/storage/PBSEdit.js:33
@@ -7773,7 +7604,7 @@ msgstr "内核版本"
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/desktop.rs:797
#: proxmox-yew-comp/src/property_view/property_grid.rs:245
msgid "Key"
-msgstr "公钥"
+msgstr "密钥"
#: pmg-gui/js/UserEdit.js:187 pve-manager/www/manager6/dc/UserEdit.js:133
msgid "Key IDs"
@@ -7799,15 +7630,15 @@ msgstr "韩语"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:390
msgid "L2VNI"
-msgstr ""
+msgstr "L2VNI"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:385
msgid "L3VNI"
-msgstr ""
+msgstr "L3VNI"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:139
msgid "LDAP DN syntax can be used as well, e.g. cn=user,dc=company,dc=net"
-msgstr "也可以使用 LDAP DN 语法,例如 cn=user,dc=company,dc=net"
+msgstr "也可以使用 LDAP DN 语法,例如:cn=user,dc=company,dc=net"
#: pmg-gui/js/Utils.js:192
msgid "LDAP Group"
@@ -7918,7 +7749,7 @@ msgstr "姓氏"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:342
#: proxmox-yew-comp/src/auth_edit_ldap.rs:218
msgid "Last Name attribute"
-msgstr "名称属性"
+msgstr "姓氏属性"
#: proxmox-backup/www/config/PruneView.js:257
msgid "Last Prune"
@@ -7950,21 +7781,20 @@ msgstr "上次校验"
#: proxmox-yew-comp/src/user_panel.rs:539
#: proxmox-yew-comp/src/user_panel.rs:564
-#, fuzzy
msgid "Last name"
-msgstr "姓氏"
+msgstr "姓"
#: proxmox-datacenter-manager/ui/src/dashboard/status_row.rs:175
msgid "Last refresh: {0}"
-msgstr ""
+msgstr "上次刷新:{0}"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:451
msgid "Last verify task over 30 days ago: {0}"
-msgstr ""
+msgstr "上次验证任务超过 30 天前:{0}"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:456
msgid "Last verify task started on {0}"
-msgstr ""
+msgstr "上次验证任务开始于 {0}"
#: pve-manager/www/manager6/qemu/MachineEdit.js:117
#: pve-manager/www/manager6/qemu/MachineEdit.js:136
@@ -7986,18 +7816,17 @@ msgid "Layout"
msgstr "布局"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:598
-#, fuzzy
msgid "Leaderboards"
-msgstr "标题"
+msgstr "排行榜"
#: proxmox-yew-comp/src/node_info.rs:256
msgid "Legacy BIOS"
-msgstr ""
+msgstr "传统 BIOS"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:434
msgid ""
"Less than {0} recovery keys available. Please generate a new set after login!"
-msgstr "少于 {0} 个可用的还原密钥。 登录后请生成一个新的集合!"
+msgstr "可用恢复密钥少于 {0} 个。请在登录后生成新的一组!"
#: pmg-gui/js/Settings.js:258 pve-manager/www/manager6/window/Settings.js:354
#: proxmox-backup/www/window/Settings.js:258
@@ -8028,6 +7857,8 @@ msgid ""
"it'll only apply if the users request comes from one of the specified "
"networks."
msgstr ""
+"该限制仅对通过身份验证的用户请求生效。若同时匹配IP规则,本规则将优先于纯IP限"
+"制。若本规则还指定了网络范围,则仅当用户请求来自指定网络之一时方可生效。"
#: pmg-gui/js/Settings.js:266 pve-manager/www/manager6/window/Settings.js:362
#: proxmox-backup/www/window/Settings.js:266
@@ -8052,41 +7883,38 @@ msgstr "链接克隆"
#: proxmox-yew-comp/src/configuration/network_view.rs:212
#: proxmox-yew-comp/src/configuration/mod.rs:32
msgid "Linux Bond"
-msgstr ""
+msgstr "Linux 绑定"
#: proxmox-yew-comp/src/configuration/network_view.rs:206
#: proxmox-yew-comp/src/configuration/mod.rs:31
-#, fuzzy
msgid "Linux Bridge"
-msgstr "桥接"
+msgstr "Linux 网桥"
#: proxmox-datacenter-manager/ui/src/dashboard/guest_panel.rs:225
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:581
-#, fuzzy
msgid "Linux Container"
-msgstr "LXC 容器"
+msgstr "Linux 容器"
#: proxmox-yew-comp/src/configuration/mod.rs:33
-#, fuzzy
msgid "Linux VLAN"
-msgstr "无 VLAN"
+msgstr "Linux VLAN"
#: proxmox-yew-widget-toolkit/src/widget/form/selector.rs:410
msgid "List does not contain any items."
-msgstr ""
+msgstr "列表不包含任何项。"
#: pve-yew-mobile-gui/src/widgets/tasks_panel.rs:146
#: pve-yew-mobile-gui/src/widgets/storage_content_panel.rs:283
#: pve-yew-mobile-gui/src/pages/page_node_status/updates_panel.rs:122
msgid "List is empty."
-msgstr ""
+msgstr "列表为空。"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:76
msgid ""
"List of VLAN IDs and ranges, useful for NICs with restricted VLAN offloading "
"support. For example: '2 4 100-200'"
msgstr ""
-"VLAN ID 和范围列表,适用于具有受限VLAN卸载支持的 NIC。例如:“2 4 100-200”"
+"VLAN ID 和范围列表,适用于支持有限 VLAN 卸载功能的网卡。例如:'2 4 100-200'"
#: pve-manager/www/manager6/window/GuestImport.js:616
msgid "Live Import"
@@ -8108,16 +7936,15 @@ msgstr "实时还原"
#: pve-manager/www/manager6/window/Migrate.js:356
msgid "Live-migrating running VM with mapped resources (Experimental): {0}"
-msgstr "使用映射资源实时迁移正在运行的虚拟机(实验): {0}"
+msgstr "正在实时迁移带有映射资源的虚拟机(实验性功能):{0}"
#: proxmox-backup/www/tape/ChangerStatus.js:779
msgid "Load"
msgstr "加载"
#: proxmox-yew-comp/src/node_info.rs:193
-#, fuzzy
msgid "Load Average"
-msgstr "平均负荷"
+msgstr "平均负载"
#: proxmox-backup/www/Utils.js:443
msgid "Load Media"
@@ -8130,7 +7957,7 @@ msgstr "将媒体加载到驱动器"
#: pve-manager/www/manager6/lxc/CreateWizard.js:174
#: pve-manager/www/manager6/qemu/SSHKey.js:33
msgid "Load SSH Key File"
-msgstr "加载SSH密钥文件"
+msgstr "加载 SSH 密钥文件"
#: pmg-gui/js/ClusterAdministration.js:295 pmg-gui/js/ServerStatus.js:131
#: pmg-gui/js/dashboard/NodeInfo.js:51
@@ -8143,25 +7970,22 @@ msgstr "平均负荷"
#: proxmox-datacenter-manager/ui/src/pve/mod.rs:186
#: proxmox-yew-comp/src/loadable_component.rs:483
-#, fuzzy
msgid "Load failed"
-msgstr "登录失败:"
+msgstr "加载失败"
#: proxmox-widget-toolkit/src/window/ACMEAccount.js:79
#: pve-manager/www/manager6/node/ACME.js:143 proxmox-backup/www/Utils.js:742
#: proxmox-yew-comp/src/acme/acme_register_account.rs:158
msgid "Loading"
-msgstr "载入中"
+msgstr "正在加载"
#: proxmox-yew-comp/src/acme/acme_register_account.rs:145
-#, fuzzy
msgid "Loading TOS failed: {0}"
-msgstr "登录失败:"
+msgstr "加载服务条款失败:{0}"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/columns.rs:40
-#, fuzzy
msgid "Loading {}..."
-msgstr "载入中..."
+msgstr "正在加载 {}..."
#: proxmox-widget-toolkit/src/Utils.js:403
#: pve-manager/www/manager6/ceph/OSD.js:502
@@ -8170,7 +7994,7 @@ msgstr "载入中..."
#: proxmox-yew-comp/src/syslog.rs:93
#: proxmox-yew-widget-toolkit/src/state/loader.rs:154
msgid "Loading..."
-msgstr "载入中..."
+msgstr "正在加载..."
#: pmg-gui/js/UserManagement.js:13 proxmox-backup/www/Utils.js:868
#: proxmox-backup/www/window/DataStoreEdit.js:62
@@ -8182,9 +8006,8 @@ msgid "Local Backup/Restore"
msgstr "本地备份/还原"
#: proxmox-backup/www/window/DataStoreEdit.js:107
-#, fuzzy
msgid "Local Cache"
-msgstr "本地命名空间"
+msgstr "本地缓存"
#: proxmox-backup/www/tape/window/TapeBackupJob.js:87
#: proxmox-backup/www/window/SyncJobEdit.js:141
@@ -8231,7 +8054,7 @@ msgstr "锁定"
#: proxmox-backup/www/config/UserView.js:260
#: proxmox-yew-comp/src/tfa/tfa_view.rs:379
msgid "Locked"
-msgstr "锁定"
+msgstr "已锁定"
#: pmg-gui/js/UserView.js:106 pve-manager/www/manager6/dc/UserView.js:122
#: proxmox-backup/www/config/UserView.js:125
@@ -8249,24 +8072,20 @@ msgid "Log"
msgstr "日志"
#: proxmox-yew-comp/src/firewall/options_edit.rs:461
-#, fuzzy
msgid "Log Level Forward"
-msgstr "日志级别"
+msgstr "日志级别转发"
#: proxmox-yew-comp/src/firewall/options_edit.rs:362
#: proxmox-yew-comp/src/firewall/options_edit.rs:441
-#, fuzzy
msgid "Log Level In"
-msgstr "日志级别"
+msgstr "日志级别入站"
#: proxmox-yew-comp/src/firewall/options_edit.rs:372
#: proxmox-yew-comp/src/firewall/options_edit.rs:451
-#, fuzzy
msgid "Log Level Out"
-msgstr "日志级别"
+msgstr "日志级别出站"
#: proxmox-yew-comp/src/firewall/options_edit.rs:316
-#, fuzzy
msgid "Log Rate Limiting"
msgstr "日志速率限制"
@@ -8295,7 +8114,6 @@ msgid "Log rate limit"
msgstr "日志速率限制"
#: proxmox-yew-comp/src/form/pve/firewall_property/log_ratelimit_property.rs:56
-#, fuzzy
msgid "Log rate limiting"
msgstr "日志速率限制"
@@ -8317,7 +8135,7 @@ msgstr "登录(OpenID 重定向)"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_info.rs:309
msgid "Login and create Token"
-msgstr ""
+msgstr "登录并创建令牌"
#: pmg-gui/js/LoginView.js:137
#: pve-manager/www/manager6/window/LoginWindow.js:159
@@ -8327,13 +8145,12 @@ msgstr "登录失败,请重试"
#: proxmox-yew-comp/src/login_panel.rs:359
#: proxmox-yew-comp/src/login_panel.rs:488
-#, fuzzy
msgid "Login failed. Please try again ({0})"
-msgstr "登录失败,请重试"
+msgstr "登录失败。请重试({0})"
#: pve-manager/www/manager6/window/LoginWindow.js:163
msgid "Login failed:"
-msgstr "登录失败:"
+msgstr "登录失败:"
#: pmg-gui/js/MainView.js:237 pmg-gui/js/QuarantineView.js:317
#: pve-manager/www/manager6/Workspace.js:449 proxmox-backup/www/MainView.js:291
@@ -8353,9 +8170,8 @@ msgid "Longest Tasks"
msgstr "最长的任务"
#: proxmox-yew-comp/src/configuration/mod.rs:29
-#, fuzzy
msgid "Loopback"
-msgstr "回滚"
+msgstr "回环"
#: pve-manager/www/manager6/sdn/controllers/BgpEdit.js:59
#: pve-manager/www/manager6/sdn/controllers/IsisEdit.js:55
@@ -8367,7 +8183,6 @@ msgid "Lower"
msgstr "起始值"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vnet_status.rs:91
-#, fuzzy
msgid "MAC Address"
msgstr "MAC 地址"
@@ -8384,7 +8199,7 @@ msgstr "MAC 地址"
#: pve-manager/www/manager6/node/NodeOptionsView.js:66
msgid "MAC address for Wake on LAN"
-msgstr "局域网唤醒的 MAC 地址"
+msgstr "用于网络唤醒的 MAC 地址"
#: pve-manager/www/manager6/dc/OptionView.js:99
msgid "MAC address prefix"
@@ -8397,18 +8212,17 @@ msgid "MAC filter"
msgstr "MAC 筛选"
#: pve-manager/www/manager6/sdn/EvpnZoneMacVrfPanel.js:69
-#, fuzzy
msgid "MAC-Address"
-msgstr "MAC地址"
+msgstr "MAC 地址"
#: pve-manager/www/manager6/sdn/EvpnZoneMacVrfPanel.js:56
msgid "MAC-VRF"
-msgstr ""
+msgstr "MAC-VRF"
#: pve-manager/www/manager6/sdn/Browser.js:65
#: pve-manager/www/manager6/sdn/NetworkBrowser.js:139
msgid "MAC-VRFs"
-msgstr ""
+msgstr "MAC-VRF"
#: proxmox-widget-toolkit/src/Utils.js:790
msgid "MB"
@@ -8483,7 +8297,6 @@ msgid "Mails / min"
msgstr "邮件数/分钟"
#: proxmox-datacenter-manager/ui/src/pbs/datastore/overview.rs:209
-#, fuzzy
msgid "Maintenance Mode"
msgstr "维护模式"
@@ -8501,7 +8314,7 @@ msgstr "维护模式"
msgid ""
"Make sure that the correct tape is inserted in the selected drive and type "
"in the label written on the tape."
-msgstr "确保在所选驱动器中插入了正确的磁带,并键入写在磁带上的标签。"
+msgstr "确保在所选驱动器中插入了正确的磁带,并输入写在磁带上的标签。"
#: pve-manager/www/manager6/form/AgentFeatureSelector.js:49
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_agent_property.rs:65
@@ -8523,7 +8336,7 @@ msgstr "管理全局标志"
#: pve-manager/www/manager6/ceph/OSD.js:241
msgid "Manage Global OSD Flags"
-msgstr "管理全局OSD标志"
+msgstr "管理全局 OSD 标志"
#: pve-manager/www/manager6/lxc/Config.js:153
#: pve-manager/www/manager6/qemu/Config.js:120
@@ -8532,19 +8345,19 @@ msgstr "管理 HA"
#: pve-manager/www/manager6/ceph/Monitor.js:43
msgid "Manager"
-msgstr "管理员"
+msgstr "Manager"
#: pve-manager/www/manager6/node/StatusView.js:137
msgid "Manager Version"
-msgstr "管理器版本"
+msgstr "Manager 版本"
#: pve-manager/www/manager6/ceph/Services.js:29
msgid "Managers"
-msgstr "管理员"
+msgstr "Managers"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:354
msgid "Manual"
-msgstr ""
+msgstr "手动"
#: pve-manager/www/manager6/form/USBSelector.js:86
#: pve-manager/www/manager6/qemu/Smbios1Edit.js:36
@@ -8582,8 +8395,8 @@ msgid ""
"Maps SCSI disks to SATA and changes the SCSI Controller. Useful for a "
"quicker switch to VirtIO-SCSI attached disks"
msgstr ""
-"将 SCSI 磁盘映射到 SATA 并更改 SCSI 控制器。有助于更快地切换到 VirtIO-SCSI 连"
-"接磁盘"
+"此操作将SCSI磁盘映射为SATA并更换控制器,可帮助您更快地切换至使用VirtIO-SCSI连"
+"接的磁盘"
#: pmg-gui/js/LDAPGroupEditor.js:74
msgid "Match"
@@ -8620,7 +8433,7 @@ msgstr "匹配类型"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:494
msgid "Match calendar: {0}"
-msgstr "匹配日历: {0}"
+msgstr "匹配日历:{0}"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:484
msgid "Match field: {0}={1}"
@@ -8629,7 +8442,7 @@ msgstr "匹配字段:{0}={1}"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:893
#: pmg-gui/js/ObjectGroup.js:256 pmg-gui/js/RuleInfo.js:351
msgid "Match if"
-msgstr "如果匹配"
+msgstr "匹配条件"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:473
msgid "Match severity: {0}"
@@ -8642,12 +8455,11 @@ msgstr "匹配器名称"
#: proxmox-datacenter-manager/ui/src/dashboard/refresh_config_edit.rs:86
msgid "Max Age (seconds)"
-msgstr ""
+msgstr "最大期限(秒)"
#: pve-manager/www/manager6/dc/MetricServerView.js:654
-#, fuzzy
msgid "Max Body Size (bytes)"
-msgstr "最大垃圾邮件大小(字节)"
+msgstr "最大主体大小(字节)"
#: proxmox-backup/www/tape/window/TapeBackup.js:50
msgid "Max Depth"
@@ -8704,9 +8516,8 @@ msgstr "最大工作数/批量动作"
#: proxmox-widget-toolkit/src/form/RRDTypeSelector.js:83
#: proxmox-yew-comp/src/rrd_timeframe_selector.rs:223
-#, fuzzy
msgid "Maximum"
-msgstr "最大"
+msgstr "最大值"
#: pve-manager/www/manager6/panel/BackupJobPrune.js:114
msgid "Maximum Protected"
@@ -8754,7 +8565,7 @@ msgstr "中介设备"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:95
msgid ""
"Meltdown fix cost reduction on Westmere, Sandy-, and IvyBridge Intel CPUs"
-msgstr ""
+msgstr "在 Westmere、Sandy- 和 IvyBridge Intel CPU 上降低 Meltdown 修复成本"
#: pve-manager/www/manager6/pool/Config.js:26
msgid "Members"
@@ -8791,20 +8602,18 @@ msgstr "内存"
#: pve-manager/www/manager6/node/Summary.js:287
#: pve-manager/www/manager6/panel/GuestSummary.js:157
msgid "Memory Pressure Stall"
-msgstr ""
+msgstr "内存压力停滞"
#: pve-manager/www/manager6/panel/GuestSummary.js:104
#: proxmox-datacenter-manager/ui/src/widget/pve_node_selector.rs:157
#: proxmox-datacenter-manager/ui/src/pbs/node/overview.rs:258
#: proxmox-datacenter-manager/ui/src/pve/node/overview.rs:262
-#, fuzzy
msgid "Memory Usage"
msgstr "内存使用率"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:273
-#, fuzzy
msgid "Memory assigned"
-msgstr "内存大小"
+msgstr "已分配内存"
#: pve-manager/www/manager6/data/ResourceStore.js:206
msgid "Memory size"
@@ -8846,7 +8655,7 @@ msgstr "元数据池"
#: pve-manager/www/manager6/ceph/FS.js:182
#: pve-manager/www/manager6/ceph/Services.js:35
msgid "Metadata Servers"
-msgstr "元数据服务器"
+msgstr "MDS"
#: pve-manager/www/manager6/node/LVMThin.js:152
msgid "Metadata Size"
@@ -8862,13 +8671,12 @@ msgstr "已使用的元数据"
#: proxmox-widget-toolkit/src/panel/WebhookEditPanel.js:38
msgid "Method/URL"
-msgstr "Method/URL"
+msgstr "方法/URL"
#: pve-manager/www/manager6/sdn/EvpnZoneIpVrfPanel.js:41
#: proxmox-datacenter-manager/ui/src/sdn/evpn/zone_status.rs:102
-#, fuzzy
msgid "Metric"
-msgstr "受限制的"
+msgstr "指标"
#: pve-manager/www/manager6/dc/Config.js:374
#: proxmox-backup/www/SystemConfiguration.js:51
@@ -8909,7 +8717,7 @@ msgid ""
"Migrating VM with local resources: {0}. This might fail if the resources are "
"not available on the target node."
msgstr ""
-"正在使用本地资源迁移虚拟机: {0}。如果目标节点上的资源不可用,则此操作可能会失"
+"正在迁移使用了本地资源的虚拟机:{0}。若目标节点上无相应资源,此操作可能会失"
"败。"
#: pve-manager/www/manager6/dc/OptionView.js:360
@@ -8922,9 +8730,8 @@ msgid "Migration Settings"
msgstr "迁移设置"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:329
-#, fuzzy
msgid "Migration with local disk might take long: {0} ({1})"
-msgstr "使用本地磁盘迁移可能需要很长时间: {0} {1}"
+msgstr "使用本地磁盘的迁移可能需要较长时间:{0}({1})"
#: pve-manager/www/manager6/window/Migrate.js:380
msgid "Migration with local disk might take long: {0} {1}"
@@ -8932,7 +8739,7 @@ msgstr "使用本地磁盘迁移可能需要很长时间: {0} {1}"
#: pve-manager/www/manager6/ceph/Pool.js:362
msgid "Min. # of PGs"
-msgstr "最小值# PG"
+msgstr "最少 PG 个数"
#: pve-manager/www/manager6/ceph/Pool.js:42
#: pve-manager/www/manager6/ceph/Pool.js:44
@@ -8982,8 +8789,8 @@ msgid ""
"Mode to detect file changes and switch archive encoding format for container "
"backups to Proxmox Backup Server. Not available for VM backups."
msgstr ""
-"检测文件更改并将容器备份的存档编码格式切换到Proxmox Backup Server的模式。不适"
-"用于虚拟机备份。"
+"此模式用于检测文件更改,并将容器备份的存档编码格式切换为适用于 Proxmox "
+"Backup Server 的格式。注意:此功能不适用于虚拟机备份。"
#: pve-manager/www/manager6/panel/BackupAdvancedOptions.js:294
msgid ""
@@ -9011,21 +8818,21 @@ msgstr "模式:{0}"
#: proxmox-backup/www/tape/form/TapeDevicePathSelector.js:29
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_network_property.rs:73
msgid "Model"
-msgstr "模型"
+msgstr "型号"
#: proxmox-widget-toolkit/src/window/FileBrowser.js:293
msgid "Modified"
-msgstr "调整"
+msgstr "修改时间"
#: proxmox-widget-toolkit/src/panel/NotificationConfigView.js:240
#: proxmox-widget-toolkit/src/panel/NotificationConfigView.js:397
msgid "Modify"
-msgstr "调整"
+msgstr "修改"
#: proxmox-widget-toolkit/src/window/TfaEdit.js:10
#: proxmox-yew-comp/src/tfa/tfa_edit.rs:97
msgid "Modify a TFA entry's description"
-msgstr "修改TFA条目的描述"
+msgstr "修改双因素认证条目的描述"
#: proxmox-backup/www/window/TrafficControlEdit.js:366
msgid "Mon"
@@ -9049,11 +8856,11 @@ msgstr "监视器"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:553
msgid "Monitor node"
-msgstr "监控节点"
+msgstr "Monitor 节点"
#: pve-manager/www/manager6/ceph/Services.js:23
msgid "Monitors"
-msgstr "监视器"
+msgstr "Monitors"
#: proxmox-widget-toolkit/src/form/RRDTypeSelector.js:64
#: proxmox-yew-comp/src/rrd_timeframe_selector.rs:158
@@ -9111,9 +8918,8 @@ msgstr "挂载选项"
#: proxmox-yew-comp/src/form/pve/lxc_property/lxc_mount_point_property.rs:92
#: proxmox-yew-comp/src/configuration/pve/lxc_resources_panel/reassign_volume_dialog.rs:118
-#, fuzzy
msgid "Mount point is already in use."
-msgstr "挂载点卷也被删除。"
+msgstr "挂载点已被使用。"
#: pve-manager/www/manager6/window/Restore.js:101
msgid "Mount point volumes are also erased."
@@ -9125,12 +8931,11 @@ msgstr "已挂载"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:497
msgid "Move Row down"
-msgstr ""
+msgstr "向下移动行"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:507
-#, fuzzy
msgid "Move Row up"
-msgstr "移动卷"
+msgstr "向上移动行"
#: pve-manager/www/manager6/lxc/Resources.js:275
#: pve-manager/www/manager6/qemu/HardwareView.js:446
@@ -9179,7 +8984,7 @@ msgstr "多个收件人必须用空格、逗号或分号分隔"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_network_property.rs:49
msgid "Multiqueue"
-msgstr ""
+msgstr "多队列"
#: proxmox-widget-toolkit/src/panel/WebhookEditPanel.js:62
msgid "Must be a valid URL"
@@ -9187,7 +8992,7 @@ msgstr "必须是有效的 URL"
#: proxmox-yew-comp/src/tfa/tfa_add_totp.rs:190
msgid "Must be base32 [A-Z2-7=]"
-msgstr ""
+msgstr "必须是 base32 [A-Z2-7=]"
#: pve-manager/www/manager6/form/MultiPCISelector.js:42
msgid "Must choose at least one device"
@@ -9201,7 +9006,7 @@ msgstr "必须以……结尾"
#: proxmox-widget-toolkit/src/Toolkit.js:120
#: proxmox-widget-toolkit/src/Toolkit.js:133
msgid "Must start with"
-msgstr "必须以……开始"
+msgstr "必须以……开头"
#: pmg-gui/js/MainView.js:216 pmg-gui/js/Settings.js:5
#: pve-manager/www/manager6/Workspace.js:400
@@ -9215,7 +9020,7 @@ msgstr "我的设置"
#: proxmox-backup/www/Utils.js:322 proxmox-yew-comp/src/node_info.rs:71
#: proxmox-yew-comp/src/node_info.rs:222
msgid "N/A"
-msgstr "N/A"
+msgstr "不适用"
#: pve-manager/www/manager6/storage/NFSEdit.js:148
msgid "NFS Version"
@@ -9239,7 +9044,7 @@ msgstr "现在"
#: pve-manager/www/manager6/window/GuestImport.js:1009
msgid "NVMe disks are currently not supported, '{0}' will get attached as SCSI"
-msgstr "NVMe 磁盘目前不受支持,'{0}' 将作为 SCSI 连接"
+msgstr "NVMe 磁盘目前不受支持,'{0}'将作为 SCSI 连接"
#: proxmox-widget-toolkit/src/form/UserSelector.js:33
#: proxmox-widget-toolkit/src/grid/ObjectGrid.js:391
@@ -9395,9 +9200,8 @@ msgid "Name, Format, Notes"
msgstr "命名,格式,备注"
#: pve-manager/www/manager6/grid/PoolMembers.js:72
-#, fuzzy
msgid "Name, Node, VMID"
-msgstr "名称/VMID"
+msgstr "名称、节点、VMID"
#: proxmox-widget-toolkit/src/panel/WebhookEditPanel.js:256
msgid "Name/value must not be empty."
@@ -9423,16 +9227,15 @@ msgstr "命名空间"
#: proxmox-backup/www/datastore/Content.js:360
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:109
msgid "Namespace '{0}'"
-msgstr "命名空间 '{0}'"
+msgstr "命名空间'{0}'"
#: proxmox-backup/www/window/NamespaceEdit.js:44
msgid "Namespace Name"
msgstr "命名空间名称"
#: pmg-gui/js/QuarantineView.js:240
-#, fuzzy
msgid "Narrow viewport detected"
-msgstr "未选择端点"
+msgstr "检测到窄屏显示"
#: proxmox-backup/www/tape/window/TapeRestore.js:630
msgid "Need at least one mapping"
@@ -9444,11 +9247,11 @@ msgstr "至少需要一个快照"
#: pve-manager/www/manager6/sdn/FabricsContentView.js:33
msgid "Neighbor"
-msgstr ""
+msgstr "邻居"
#: pve-manager/www/manager6/sdn/NetworkBrowser.js:56
msgid "Neighbors"
-msgstr ""
+msgstr "邻居"
#: pve-manager/www/manager6/lxc/CreateWizard.js:83
#: pve-manager/www/manager6/lxc/FeaturesEdit.js:38
@@ -9460,14 +9263,13 @@ msgstr "嵌套"
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:180
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:177
msgid "Net In"
-msgstr ""
+msgstr "网络入站"
#. TRANSLATORS: As in amount of outgoing network traffic
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:181
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:179
-#, fuzzy
msgid "Net Out"
-msgstr "出口速率"
+msgstr "网络出站"
#: pmg-gui/js/MailProxyOptions.js:44
msgid "Netmask for Greylisting IPv4"
@@ -9497,9 +9299,8 @@ msgid "Network"
msgstr "网络"
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:315
-#, fuzzy
msgid "Network (Proxmox VE)"
-msgstr "Proxmox VE"
+msgstr "网络(Proxmox VE)"
#: pve-manager/www/manager6/qemu/IPConfigEdit.js:222
msgid "Network Config"
@@ -9518,9 +9319,8 @@ msgid "Network Device"
msgstr "网络设备"
#: pve-manager/www/manager6/panel/IPView.js:4
-#, fuzzy
msgid "Network Information"
-msgstr "无网络信息"
+msgstr "网络信息"
#: pve-manager/www/manager6/window/GuestImport.js:856
#: proxmox-backup/www/SystemConfiguration.js:40
@@ -9532,14 +9332,12 @@ msgstr "网络接口"
#: pve-manager/www/manager6/panel/GuestSummary.js:121
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:365
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:374
-#, fuzzy
msgid "Network Traffic"
msgstr "网络流量"
#: proxmox-yew-comp/src/configuration/pve/qemu_hardware_panel/desktop.rs:342
-#, fuzzy
msgid "Network card"
-msgstr "IP 网络"
+msgstr "网卡"
#: pmg-gui/js/ServerStatus.js:152 proxmox-backup/www/ServerStatus.js:247
msgid "Network traffic"
@@ -9582,11 +9380,11 @@ msgstr "新密码"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:118
msgid "Newest ceph version in cluster is {0}"
-msgstr "群集中最新的Ceph版本是 {0}"
+msgstr "集群中最新的Ceph版本是 {0}"
#: proxmox-yew-comp/src/subscription_info.rs:19
msgid "Newly set subscription, not yet checked"
-msgstr ""
+msgstr "新设置的订阅,尚未检查"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:383
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:500
@@ -9628,14 +9426,12 @@ msgstr "下一个到期日期"
#: pve-manager/www/manager6/sdn/EvpnZoneIpVrfPanel.js:24
#: pve-manager/www/manager6/sdn/EvpnZoneMacVrfPanel.js:75
-#, fuzzy
msgid "Nexthop"
-msgstr "下一步"
+msgstr "下一跳"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/zone_status.rs:88
-#, fuzzy
msgid "Nexthops"
-msgstr "下一步"
+msgstr "下一跳"
#: proxmox-widget-toolkit/src/Utils.js:45
#: proxmox-widget-toolkit/src/window/ConfirmRemoveDialog.js:24
@@ -9669,11 +9465,11 @@ msgstr "否"
#: proxmox-widget-toolkit/src/panel/ACMEDomains.js:313
#: pve-manager/www/manager6/node/ACME.js:682
msgid "No Account available."
-msgstr "没有可用的帐户。"
+msgstr "没有可用的账户。"
#: proxmox-widget-toolkit/src/panel/ACMEAccount.js:60
msgid "No Accounts configured"
-msgstr "未配置帐户"
+msgstr "未配置账户"
#: proxmox-backup/www/Utils.js:740
msgid "No Activity"
@@ -9696,7 +9492,7 @@ msgstr "未找到 CloudInit 驱动器"
#: pve-manager/www/manager6/node/Summary.js:218
#: proxmox-backup/www/dashboard/DataStoreStatistics.js:59
msgid "No Data"
-msgstr "没有数据"
+msgstr "暂无数据"
#: proxmox-backup/www/datastore/DataStoreList.js:130
msgid "No Datastores configured"
@@ -9712,7 +9508,7 @@ msgstr "未找到设备"
#: proxmox-widget-toolkit/src/form/MultiDiskSelector.js:69
msgid "No Disk selected"
-msgstr "没有选中磁盘"
+msgstr "未选择磁盘"
#: pve-manager/www/manager6/panel/MultiDiskEdit.js:239
msgid "No Disks"
@@ -9731,7 +9527,7 @@ msgstr "没有未使用的磁盘"
#: proxmox-widget-toolkit/src/panel/ACMEDomains.js:15
#: pve-manager/www/manager6/node/ACME.js:405
msgid "No Domains configured"
-msgstr "未配置域"
+msgstr "未配置域名"
#: pmg-gui/js/QuarantineList.js:5
msgid "No E-Mail address selected"
@@ -9747,13 +9543,13 @@ msgstr "未配置 Guest Agent"
#: proxmox-widget-toolkit/src/button/HelpButton.js:73
msgid "No Help available"
-msgstr "没有可用的帮助"
+msgstr "无可用帮助"
#: pve-manager/www/manager6/window/PCIMapEdit.js:179
msgid ""
"No IOMMU detected, please activate it. See Documentation for further "
"information."
-msgstr "未检测到 IOMMU,请将其激活。有关详细信息,请参阅文档。"
+msgstr "未检测到 IOMMU 功能,请先启用。更多信息请查阅文档。"
#: pve-manager/www/manager6/dc/RealmSyncJob.js:296
msgid "No LDAP/AD Realm found"
@@ -9794,12 +9590,11 @@ msgstr "没有报告"
#: proxmox-widget-toolkit/src/window/DiskSmart.js:24
msgid "No S.M.A.R.T. Values"
-msgstr "没有 S.M.A.R.T. 值"
+msgstr "无 S.M.A.R.T. 值"
#: pmg-gui/js/DNSBLSitesField.js:17
-#, fuzzy
msgid "No Sites defined"
-msgstr "未定义标记"
+msgstr "未定义站点"
#: proxmox-backup/www/tape/window/TapeRestore.js:837
msgid "No Snapshots"
@@ -9845,16 +9640,15 @@ msgstr "没有警告/错误"
#: proxmox-backup/www/datastore/Content.js:394
msgid "No accessible snapshots found in namespace {0}"
-msgstr "在命名空间{0}中找不到可访问的快照"
+msgstr "在命名空间 {0} 中找不到可访问的快照"
#: pmg-gui/js/PBSSnapshotView.js:197
msgid "No backups on remote"
msgstr "远程没有备份"
#: proxmox-yew-comp/src/form/pve/qemu_property/mod.rs:252
-#, fuzzy
msgid "No boot device selected"
-msgstr "(没有选中启动设备)"
+msgstr "未选择启动设备"
#: pve-manager/www/manager6/form/CacheTypeSelector.js:5
#: pve-manager/www/manager6/form/CacheTypeSelector.js:10
@@ -9876,9 +9670,8 @@ msgstr "无更改"
#: proxmox-datacenter-manager/ui/src/dashboard/top_entities.rs:264
#: proxmox-datacenter-manager/ui/src/widget/resource_tree.rs:346
-#, fuzzy
msgid "No data"
-msgstr "复制数据"
+msgstr "无数据"
#: pmg-gui/js/AttachmentQuarantine.js:52 pmg-gui/js/ContactStatistics.js:115
#: pmg-gui/js/Dashboard.js:468 pmg-gui/js/DomainStatistics.js:75
@@ -9898,23 +9691,20 @@ msgid "No default available"
msgstr "没有默认可用"
#: proxmox-yew-comp/src/apt_repositories.rs:714
-#, fuzzy
msgid "No description available"
-msgstr "没有可用的帮助"
+msgstr "无可用描述"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/ui_helpers.rs:114
-#, fuzzy
msgid "No entry selected"
-msgstr "未选择目标"
+msgstr "未选择条目"
#: pve-manager/www/manager6/grid/FirewallRules.js:623
msgid "No firewall rule configured here."
msgstr "此处未配置防火墙规则。"
#: proxmox-yew-comp/src/firewall/rules.rs:258
-#, fuzzy
msgid "No firewall rules configured"
-msgstr "此处未配置防火墙规则。"
+msgstr "未配置防火墙规则"
#: pmg-gui/js/QuarantineList.js:264
msgid "No match found"
@@ -9922,7 +9712,7 @@ msgstr "找不到匹配项"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:421
msgid "No more recovery keys left! Please generate a new set!"
-msgstr "没有剩余的恢复密钥了!请生成一个新集合!"
+msgstr "没有剩余的恢复密钥了!请生成新的一组!"
#: proxmox-backup/www/form/NamespaceSelector.js:38
msgid "No namespaces accessible."
@@ -9939,9 +9729,8 @@ msgid "No network information"
msgstr "无网络信息"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:599
-#, fuzzy
msgid "No node selected"
-msgstr "没有选中虚拟机"
+msgstr "未选择节点"
#: proxmox-widget-toolkit/src/panel/NotificationConfigView.js:327
msgid "No notification matchers configured"
@@ -9952,9 +9741,8 @@ msgid "No notification targets configured"
msgstr "未配置通知目标"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:713
-#, fuzzy
msgid "No product repository configured"
-msgstr "未配置 VNet。"
+msgstr "未配置产品仓库"
#: pve-manager/www/manager6/dc/BackupJobDetail.js:237
msgid "No recipients configured"
@@ -9962,12 +9750,11 @@ msgstr "未配置收件人"
#: proxmox-datacenter-manager/ui/src/dashboard/subscription_info.rs:78
msgid "No remotes configured or could not fetch status."
-msgstr ""
+msgstr "未配置远程或无法获取状态。"
#: proxmox-datacenter-manager/ui/src/dashboard/remote_panel.rs:77
-#, fuzzy
msgid "No remotes configured."
-msgstr "未配置 VNet。"
+msgstr "未配置远程。"
#: pve-manager/www/manager6/sdn/zones/Base.js:45
#: pve-manager/www/manager6/storage/Base.js:42
@@ -9977,7 +9764,7 @@ msgstr "无限制"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:510
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:903
msgid "No rule matches"
-msgstr "没有规则匹配"
+msgstr "无规则匹配"
#: proxmox-backup/www/dashboard/RunningTasks.js:6
#: proxmox-yew-comp/src/running_tasks.rs:164
@@ -9990,7 +9777,7 @@ msgstr "没有计划设置。"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:408
msgid "No second factor left! Please contact an administrator!"
-msgstr "没有第二个因素了!请联系管理员!"
+msgstr "没有可用的二次验证因子!请联系管理员!"
#: pve-manager/www/manager6/window/ScheduleSimulator.js:12
msgid "No simulation done"
@@ -10006,7 +9793,7 @@ msgstr "未选择目标"
#: proxmox-widget-toolkit/src/node/APT.js:199
msgid "No updates available."
-msgstr "没有可用的更新。"
+msgstr "没有可用更新。"
#: proxmox-widget-toolkit/src/Utils.js:616 proxmox-backup/www/Dashboard.js:348
#: proxmox-datacenter-manager/ui/src/dashboard/subscription_info.rs:58
@@ -10017,7 +9804,6 @@ msgid "No valid subscription"
msgstr "无有效订阅"
#: proxmox-datacenter-manager/ui/src/lib.rs:289
-#, fuzzy
msgid "No valid subscriptions"
msgstr "无有效订阅"
@@ -10039,17 +9825,16 @@ msgstr "未找到 {0}"
#: proxmox-widget-toolkit/src/Utils.js:1377
msgid "No {0} repository enabled!"
-msgstr "未启用 {0} 存储库!"
+msgstr "未启用 {0} 软件源!"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:475
#: proxmox-yew-comp/src/apt_repositories.rs:167
msgid "No {0} repository is enabled, you do not get any updates!"
-msgstr "没有启用 {0} 存储库,没有得到任何更新!"
+msgstr "未启用任何 {0} 软件源,您将无法获取更新!"
#: pve-manager/www/manager6/ha/Rules.js:92
-#, fuzzy
msgid "No {0} rules configured."
-msgstr "未配置 {0}"
+msgstr "未配置 {0} 规则。"
#: pve-manager/www/manager6/node/Directory.js:174
#: pve-manager/www/manager6/node/LVM.js:174
@@ -10109,25 +9894,21 @@ msgstr "节点"
#: proxmox-datacenter-manager/ui/src/pve/node/mod.rs:66
#: pve-yew-mobile-gui/src/pages/page_node_tasks.rs:32
-#, fuzzy
msgid "Node '{0}'"
-msgstr "移除 '{0}'"
+msgstr "节点 '{0}'"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/ui_helpers.rs:78
-#, fuzzy
msgid "Node Firewall - {0}/{1}"
-msgstr "VNet 防火墙"
+msgstr "节点防火墙 - {0}/{1}"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:548
-#, fuzzy
msgid "Node Panels"
-msgstr "设定状态"
+msgstr "节点面板"
#: proxmox-datacenter-manager/ui/src/administration/mod.rs:77
#: proxmox-yew-comp/src/node_status_panel.rs:219
-#, fuzzy
msgid "Node Status"
-msgstr "设定状态"
+msgstr "节点状态"
#: pve-manager/www/manager6/Utils.js:2186
msgid "Node fencing notifications"
@@ -10168,29 +9949,27 @@ msgstr "节点"
#: proxmox-datacenter-manager/ui/src/dashboard/top_entities.rs:350
msgid "Nodes With the Highest CPU Usage"
-msgstr ""
+msgstr "CPU 使用率最高的节点"
#: proxmox-datacenter-manager/ui/src/dashboard/top_entities.rs:357
msgid "Nodes With the Highest Memory Usage"
-msgstr ""
+msgstr "内存使用率最高的节点"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:608
msgid "Nodes with Highest CPU Usage"
-msgstr ""
+msgstr "CPU 使用率最高的节点"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:615
-#, fuzzy
msgid "Nodes with Highest Memory Usage"
-msgstr "主机内存使用率"
+msgstr "内存使用率最高的节点"
#: proxmox-widget-toolkit/src/Utils.js:1405
msgid "Non production-ready repository enabled!"
-msgstr "非生产就绪存储库已启用!"
+msgstr "已启用非生产环境适用的软件源!"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:722
-#, fuzzy
msgid "Non-production-ready repositories enabled"
-msgstr "非生产就绪存储库已启用!"
+msgstr "已启用非生产就绪仓库"
#: proxmox-widget-toolkit/src/Utils.js:49 pmg-gui/js/PBSSnapshotView.js:179
#: pve-manager/www/manager6/Utils.js:292
@@ -10216,9 +9995,8 @@ msgid "None"
msgstr "无"
#: proxmox-backup/www/window/S3ClientEdit.js:145
-#, fuzzy
msgid "None (default)"
-msgstr "默认"
+msgstr "无(默认)"
#: proxmox-widget-toolkit/src/panel/SmtpEditPanel.js:79
msgid "None (insecure)"
@@ -10230,7 +10008,7 @@ msgstr "无匹配"
#: proxmox-widget-toolkit/src/window/DiskSmart.js:48
msgid "Normalized"
-msgstr "标准化"
+msgstr "标准化值"
#: proxmox-widget-toolkit/src/Utils.js:83 proxmox-yew-comp/src/lib.rs:314
msgid "Norwegian (Bokmal)"
@@ -10238,7 +10016,7 @@ msgstr "挪威语(博克马尔语)"
#: proxmox-widget-toolkit/src/Utils.js:85 proxmox-yew-comp/src/lib.rs:316
msgid "Norwegian (Nynorsk)"
-msgstr "挪威语(尼诺尔斯克语)"
+msgstr "挪威语(尼诺斯克语)"
#: proxmox-backup/www/tape/ChangerStatus.js:646
msgid "Not Labeled"
@@ -10246,7 +10024,7 @@ msgstr "未标记"
#: proxmox-widget-toolkit/src/Toolkit.js:170
msgid "Not a valid DNS name or IP address."
-msgstr "不是有效的DNS名称或IP地址。"
+msgstr "不是有效的 DNS 名称或 IP 地址。"
#: pve-manager/www/manager6/form/TagColorGrid.js:168
msgid "Not a valid color."
@@ -10264,7 +10042,9 @@ msgstr "不是一个卷"
msgid ""
"Not all nodes have an active subscription, which is required for cluster-"
"wide enterprise repo access"
-msgstr "并非所有节点都有活动订阅,这是集群范围的企业源库访问所必需的"
+msgstr ""
+"集群范围内启用企业软件源访问需要所有节点均具备有效订阅,但当前部分节点不符合"
+"条件"
#: proxmox-backup/www/config/WebauthnView.js:13
#: proxmox-backup/www/config/WebauthnView.js:19
@@ -10280,9 +10060,8 @@ msgid "Not enough data"
msgstr "数据不足"
#: pmg-yew-quarantine-gui/src/page_not_found.rs:8
-#, fuzzy
msgid "Not found"
-msgstr "未找到任何内容"
+msgstr "未找到"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:44
#: proxmox-yew-comp/src/apt_repositories.rs:709
@@ -10306,7 +10085,7 @@ msgstr "备注模板"
#: pve-manager/www/manager6/dc/OptionView.js:322
#: proxmox-backup/www/config/WebauthnView.js:129
msgid "Note:"
-msgstr "备注:"
+msgstr "备注:"
#: pve-manager/www/manager6/window/GuestImport.js:334
#: pve-manager/www/manager6/window/GuestImport.js:628
@@ -10323,16 +10102,16 @@ msgstr "注意:如果实时恢复期间出现任何问题,虚拟机写入的
#: pve-manager/www/manager6/qemu/TdxEdit.js:62
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_intel_tdx_property.rs:65
-#, fuzzy
msgid ""
"Note: Intel TDX is only supported by specific recent CPU models and requires "
"host kernel version 6.16 or higher."
-msgstr "注意:SEV-SNP需要主机内核版本6.11或更高版本。"
+msgstr ""
+"注意:Intel TDX 仅支持特定的新款 CPU 型号,且需要主机内核 6.16 或更高版本。"
#: pve-manager/www/manager6/qemu/SevEdit.js:82
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_amd_sev_property.rs:84
msgid "Note: SEV-SNP requires host kernel version 6.11 or higher."
-msgstr "注意:SEV-SNP需要主机内核版本6.11或更高版本。"
+msgstr "注意:SEV-SNP 需要主机内核的版本为6.11或更高。"
#: proxmox-widget-toolkit/src/panel/NotesView.js:6
#: proxmox-widget-toolkit/src/window/NotesEdit.js:4
@@ -10359,7 +10138,7 @@ msgstr "未找到任何内容"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:1083
msgid "Notice"
-msgstr "通知"
+msgstr "注意"
#: pmg-gui/js/Utils.js:530 pve-manager/www/manager6/dc/BackupJobDetail.js:211
#: pve-manager/www/manager6/window/Backup.js:47
@@ -10406,7 +10185,7 @@ msgstr "通知"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:101
msgid "Notifies guest OS that host is not vulnerable for Spectre on AMD CPUs"
-msgstr ""
+msgstr "通知客户操作系统主机在 AMD CPU 上不易受 Spectre 攻击"
#: pmg-gui/js/PBSRemoteEdit.js:85
msgid "Notify"
@@ -10418,9 +10197,8 @@ msgid "Notify User"
msgstr "通知用户"
#: proxmox-datacenter-manager/ui/src/dashboard/status_row.rs:177
-#, fuzzy
msgid "Now refreshing"
-msgstr "刷新"
+msgstr "现正刷新"
#: pve-manager/www/manager6/form/IPProtocolSelector.js:16
msgid "Number"
@@ -10451,7 +10229,7 @@ msgstr "节点数"
#: pmg-yew-quarantine-gui/src/page_spam_list.rs:232
#: proxmox-yew-comp/src/node_status_panel.rs:132
msgid "OK"
-msgstr "OK"
+msgstr "确定"
#: pve-manager/www/manager6/qemu/CreateWizard.js:192
msgid "OS"
@@ -10479,7 +10257,7 @@ msgstr "没有元数据的 OSD,可能是移除后遗留下来的"
#: pve-manager/www/manager6/window/GuestImport.js:1012
msgid "OVMF is built without LSI drivers, scsi hardware was set to '{1}'"
-msgstr "OVMF 构建时未使用 LSI 驱动程序,scsi 硬件设置为 '{1}'"
+msgstr "OVMF 构建时未使用 LSI 驱动程序,scsi 硬件设置为'{1}'"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:161
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:181
@@ -10489,12 +10267,11 @@ msgstr "OVS 选项"
#: pve-manager/www/manager6/ceph/OSD.js:197
msgid "Objects are degraded. Consider waiting until the cluster is healthy."
-msgstr "对象已降级。请考虑等待群集恢复正常。"
+msgstr "对象已降级。请考虑等待集群恢复正常。"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:172
-#, fuzzy
msgid "Off"
-msgstr "离线"
+msgstr "关闭"
#: pve-manager/www/manager6/dc/Health.js:114
#: pve-manager/www/manager6/window/Migrate.js:45
@@ -10546,30 +10323,26 @@ msgstr "站内"
#: proxmox-yew-comp/src/apt_package_manager.rs:481
msgid "One item"
msgid_plural "{} items"
-msgstr[0] ""
-msgstr[1] ""
+msgstr[0] "{}个项目"
#: proxmox-datacenter-manager/ui/src/dashboard/node_status_panel.rs:146
-#, fuzzy
msgid "One of {0} nodes online"
msgid_plural "{n} of {0} nodes online"
-msgstr[0] "节点已下线"
+msgstr[0] "{0} 个节点中有 {n} 个在线"
#: pve-yew-mobile-gui/src/pages/page_node_status/services_panel.rs:78
msgid "One or more required services is not running"
-msgstr ""
+msgstr "一个或多个必需的服务未运行"
#: proxmox-yew-comp/src/apt_repositories.rs:867
-#, fuzzy
msgid "One repository"
msgid_plural "{n} repositories"
-msgstr[0] "存储库"
-msgstr[1] "存储库"
+msgstr[0] "{n}个仓库"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:676
msgid "One update pending"
msgid_plural "{n} updates pending"
-msgstr[0] ""
+msgstr[0] "{n} 个待处理更新"
#: pve-manager/www/manager6/data/ResourceStore.js:105
#: pve-manager/www/manager6/dc/Health.js:108
@@ -10584,11 +10357,11 @@ msgstr "在线"
#: proxmox-widget-toolkit/src/window/ACMEDomains.js:122
#: pve-manager/www/manager6/node/ACME.js:325
msgid "Only 5 Domains with type DNS can be configured"
-msgstr "只能配置5个DNS类型的域"
+msgstr "最多只能配置 5 个 DNS 类型的域名"
#: proxmox-backup/www/window/NamespaceEdit.js:49
msgid "Only alpha numerical, '_' and '-' (if not at start) allowed"
-msgstr "只允许使用字母数字、“_”和“-”(如果不是在开始时)"
+msgstr "名称只能包含字母、数字、下划线,以及非首位的连字符(-)"
#: pmg-gui/js/Utils.js:389
msgid "Only top level headers"
@@ -10596,12 +10369,11 @@ msgstr "仅顶层标题"
#: proxmox-widget-toolkit/src/panel/NodeInfoRepoStatus.js:50
msgid "Open Repositories Panel"
-msgstr "打开存储库面板"
+msgstr "打开软件源面板"
#: proxmox-datacenter-manager/ui/src/pbs/mod.rs:160
-#, fuzzy
msgid "Open Shell"
-msgstr "Shell"
+msgstr "打开 Shell"
#: proxmox-datacenter-manager/ui/src/dashboard/filtered_tasks.rs:286
#: proxmox-yew-comp/src/running_tasks.rs:122
@@ -10614,7 +10386,7 @@ msgstr "打开任务"
#: proxmox-datacenter-manager/ui/src/pve/qemu/mod.rs:74
#: proxmox-datacenter-manager/ui/src/pve/mod.rs:257
msgid "Open Web UI"
-msgstr ""
+msgstr "打开 Web UI"
#: pve-manager/www/manager6/window/Settings.js:297
msgid "Open editor on double-click"
@@ -10622,11 +10394,11 @@ msgstr "双击打开编辑器"
#: proxmox-datacenter-manager/ui/src/pbs/tree.rs:319
msgid "Open in PBS UI"
-msgstr ""
+msgstr "在 PBS UI 中打开"
#: proxmox-datacenter-manager/ui/src/pve/tree.rs:734
msgid "Open in PVE UI"
-msgstr ""
+msgstr "在 PVE UI 中打开"
#: proxmox-backup/www/tape/BackupOverview.js:365
msgid "Open restore wizard for {0}"
@@ -10634,23 +10406,23 @@ msgstr "打开 {0} 的还原向导"
#: proxmox-datacenter-manager/ui/src/top_nav_bar.rs:197
msgid "Open the Beta documentation in a new tab."
-msgstr ""
+msgstr "在新标签页中打开 Beta 文档。"
#: proxmox-datacenter-manager/ui/src/pve/qemu/mod.rs:76
#: proxmox-datacenter-manager/ui/src/pve/qemu/mod.rs:92
msgid "Open the web UI of VM {0}."
-msgstr ""
+msgstr "打开虚拟机 {0} 的 Web UI。"
#: proxmox-datacenter-manager/ui/src/pve/lxc/mod.rs:77
#: proxmox-datacenter-manager/ui/src/pve/lxc/mod.rs:93
msgid "Open the web UI of container {0}."
-msgstr ""
+msgstr "打开容器 {0} 的 Web UI。"
#: proxmox-widget-toolkit/src/Schema.js:17
#: pve-manager/www/manager6/Utils.js:742
#: proxmox-yew-comp/src/auth_edit_openid.rs:173
msgid "OpenID Connect Server"
-msgstr "OpenID Connect服务器"
+msgstr "OpenID Connect 服务器"
#: pmg-gui/js/LoginView.js:248
msgid "OpenID Connect login - please wait..."
@@ -10683,18 +10455,16 @@ msgid "OpenID redirect failed."
msgstr "OpenID 重定向失败。"
#: proxmox-yew-comp/src/auth_view.rs:315
-#, fuzzy
msgid "OpenId Connect Server"
-msgstr "OpenID Connect服务器"
+msgstr "OpenId Connect 服务器"
#: pve-manager/www/manager6/dc/MetricServerView.js:529
-#, fuzzy
msgid "OpenTelemetry Server"
-msgstr "OpenID Connect服务器"
+msgstr "OpenTelemetry 服务器"
#: pve-manager/www/manager6/ceph/Pool.js:348
msgid "Optimal # of PGs"
-msgstr "最优置放值"
+msgstr "最优 PG 个数"
#: pve-manager/www/manager6/dc/OptionView.js:490
msgid "Option"
@@ -10729,24 +10499,23 @@ msgstr "选项"
#: proxmox-widget-toolkit/src/form/MultiDiskSelector.js:118
#: proxmox-yew-comp/src/form/pve/qemu_property/mod.rs:210
msgid "Order"
-msgstr "预定"
+msgstr "顺序"
#: pve-manager/www/manager6/Utils.js:2079 proxmox-backup/www/Utils.js:424
#: proxmox-datacenter-manager/ui/src/tasks.rs:10
#: proxmox-yew-comp/src/utils/mod.rs:355
msgid "Order Certificate"
-msgstr "预定凭证"
+msgstr "预定证书"
#: proxmox-yew-comp/src/acme/acme_domains.rs:251
-#, fuzzy
msgid "Order Certificate Now"
-msgstr "立即预定凭证"
+msgstr "立即订购证书"
#: proxmox-widget-toolkit/src/panel/ACMEDomains.js:474
#: proxmox-widget-toolkit/src/panel/ACMEDomains.js:484
#: pve-manager/www/manager6/node/ACME.js:638
msgid "Order Certificates Now"
-msgstr "立即预定凭证"
+msgstr "立即订购证书"
#: pve-manager/www/manager6/dc/OptionView.js:522
msgid "Ordering"
@@ -10772,7 +10541,7 @@ msgstr "组织"
#: proxmox-yew-comp/src/apt_package_manager.rs:477
#: proxmox-yew-comp/src/apt_repositories.rs:830
msgid "Origin"
-msgstr "源"
+msgstr "来源"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:347
#: proxmox-backup/www/SystemConfiguration.js:58
@@ -10799,11 +10568,11 @@ msgstr "其它集群成员使用此服务的较新版本,请升级并重启"
#: pmg-gui/js/Utils.js:114 pve-manager/www/manager6/ceph/StatusDetail.js:42
msgid "Out"
-msgstr "输出"
+msgstr "已移出"
#: pve-manager/www/manager6/ceph/StatusDetail.js:65
msgid "Outdated OSDs"
-msgstr "过时的 OSDs"
+msgstr "旧版的 OSDs"
#: pmg-gui/js/ContactStatistics.js:109 pmg-gui/js/DomainStatistics.js:114
#: pmg-gui/js/SenderStatistics.js:102
@@ -10840,9 +10609,8 @@ msgid "Output Policy"
msgstr "输出策略"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:126
-#, fuzzy
msgid "Output log level"
-msgstr "日志级别"
+msgstr "输出日志级别"
#: pve-manager/www/manager6/window/Restore.js:326
msgid "Override Settings"
@@ -10857,9 +10625,8 @@ msgstr "停止执行关闭任务"
#: proxmox-datacenter-manager/ui/src/pve/lxc/mod.rs:98
#: proxmox-datacenter-manager/ui/src/pve/node/mod.rs:77
#: proxmox-datacenter-manager/ui/src/pve/qemu/mod.rs:97
-#, fuzzy
msgid "Overview"
-msgstr "覆写"
+msgstr "概览"
#: pve-manager/www/manager6/window/Restore.js:389
#: proxmox-backup/www/tape/form/RetentionSelector.js:7
@@ -10875,9 +10642,8 @@ msgid "Overwrite existing file"
msgstr "改写现有文件"
#: proxmox-backup/www/window/DataStoreEdit.js:215
-#, fuzzy
msgid "Overwrite in-use marker"
-msgstr "改写组"
+msgstr "覆盖使用中标记"
#: pve-manager/www/manager6/window/Migrate.js:632
msgid "Overwrite local resources unavailable check"
@@ -10893,14 +10659,12 @@ msgid "PB"
msgstr "PB"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:594
-#, fuzzy
msgid "PBS Datastores"
-msgstr "数据存储"
+msgstr "PBS 数据存储"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:554
-#, fuzzy
msgid "PBS Nodes"
-msgstr "节点"
+msgstr "PBS 节点"
#: pve-manager/www/manager6/panel/BackupAdvancedOptions.js:280
#: pve-manager/www/manager6/window/Backup.js:72
@@ -10935,9 +10699,8 @@ msgid "POSIX ACLs"
msgstr "POSIX ACLs"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:559
-#, fuzzy
msgid "PVE Nodes"
-msgstr "退出节点"
+msgstr "PVE 节点"
#: proxmox-widget-toolkit/src/node/APT.js:26
#: pve-manager/www/manager6/storage/TemplateView.js:76
@@ -10947,7 +10710,6 @@ msgstr "软件包"
#: proxmox-datacenter-manager/ui/src/administration/node_status.rs:92
#: proxmox-datacenter-manager/ui/src/administration/node_status.rs:200
-#, fuzzy
msgid "Package Versions"
msgstr "软件包版本"
@@ -11020,9 +10782,8 @@ msgid "Password"
msgstr "密码"
#: proxmox-datacenter-manager/ui/src/remotes/edit_remote.rs:110
-#, fuzzy
msgid "Password/Secret"
-msgstr "密码"
+msgstr "密码/密钥"
#: proxmox-widget-toolkit/src/Toolkit.js:210
#: pve-manager/www/manager6/dc/UserEdit.js:22
@@ -11030,13 +10791,12 @@ msgid "Passwords do not match"
msgstr "密码不匹配"
#: proxmox-yew-comp/src/user_panel.rs:268
-#, fuzzy
msgid "Passwords do not match!"
-msgstr "密码不匹配"
+msgstr "密码不匹配!"
#: pve-manager/www/manager6/dc/ClusterEdit.js:329
msgid "Paste encoded Cluster Information here"
-msgstr "在此处粘贴编码了的群集信息"
+msgstr "在此处粘贴编码了的集群信息"
#: proxmox-widget-toolkit/src/panel/PermissionView.js:29
#: pve-manager/www/manager6/dc/ACLView.js:21
@@ -11072,7 +10832,7 @@ msgstr "路径"
#: proxmox-backup/www/window/S3ClientEdit.js:68
msgid "Path Style"
-msgstr ""
+msgstr "路径样式"
#: pve-manager/www/manager6/lxc/DeviceEdit.js:59
msgid "Path has to start with /dev/"
@@ -11115,23 +10875,22 @@ msgstr "对端"
#: pve-manager/www/manager6/Utils.js:217
msgid "Pending Changes"
-msgstr "待更改"
+msgstr "待应用的更改"
#: proxmox-backup/www/config/GCView.js:225
msgid "Pending Data"
-msgstr "待处理数据"
+msgstr "待处理的数据"
#: proxmox-widget-toolkit/src/node/NetworkView.js:431
#: pmg-gui/js/SpamDetectorCustom.js:310
msgid "Pending changes"
-msgstr "待更改"
+msgstr "待应用的更改"
#: proxmox-yew-comp/src/configuration/network_view.rs:276
-#, fuzzy
msgid ""
"Pending changes (Either reboot or use 'Apply Configuration' (needs "
"ifupdown2) to activate)"
-msgstr "重新启动或使用“应用配置”(需要 ifupdown2 )激活"
+msgstr "待应用的更改(重启或使用“应用配置”来激活,后者需要 ifupdown2)"
#: pmg-gui/js/SpamScoreDistribution.js:44
msgid "Percentage"
@@ -11147,11 +10906,11 @@ msgstr "周期"
#: proxmox-backup/www/datastore/Content.js:1092
msgid "Permanently forget group '{0}'"
-msgstr "永久删除组 '{0}'"
+msgstr "永久删除组'{0}'"
#: proxmox-backup/www/datastore/Content.js:1090
msgid "Permanently forget snapshot '{0}'"
-msgstr "永久删除快照 {0}"
+msgstr "永久删除快照'{0}'"
#: proxmox-widget-toolkit/src/panel/PermissionView.js:29
#: pve-manager/www/manager6/dc/PermissionView.js:28
@@ -11191,29 +10950,27 @@ msgstr "PiB"
#: proxmox-widget-toolkit/src/Schema.js:96
msgid "Pipe/Fifo"
-msgstr "管道/命名管道"
+msgstr "管道/FIFO"
#: pve-manager/www/manager6/window/DownloadUrlToStorage.js:167
msgid "Please (re-)query URL to get meta information"
msgstr "请(重新)查询 URL 以获取元信息"
#: proxmox-yew-comp/src/acme/certificate_list.rs:316
-#, fuzzy
msgid "Please Reload"
-msgstr "磁带读取"
+msgstr "请重新加载"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:447
msgid "Please enter one of your single-use recovery keys"
-msgstr "请输入您的一次性还原密钥"
+msgstr "请输入您的一个一次性恢复密钥"
#: proxmox-widget-toolkit/src/window/ConfirmRemoveDialog.js:164
msgid "Please enter the ID to confirm"
msgstr "请输入 ID 以确认"
#: proxmox-yew-comp/src/safe_confirm_dialog.rs:133
-#, fuzzy
msgid "Please enter the ID to confirm ({0})"
-msgstr "请输入 ID 以确认"
+msgstr "请输入 ID 以确认({0})"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:379
msgid "Please enter your TOTP verification code"
@@ -11230,7 +10987,7 @@ msgstr "请输入搜索参数,然后按“搜索”。"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:346
#: proxmox-widget-toolkit/src/window/TfaWindow.js:477
msgid "Please insert your authentication device and press its button"
-msgstr "请插入您的身份验证设备,然后按其按钮"
+msgstr "请插入您的身份验证设备并按设备上的按钮"
#: pve-manager/www/manager6/window/LoginWindow.js:205
msgid "Please press the button on your U2F Device"
@@ -11238,12 +10995,12 @@ msgstr "请按 U2F 设备上的按钮"
#: proxmox-widget-toolkit/src/window/AddWebauthn.js:94
msgid "Please press the button on your Webauthn Device"
-msgstr "请按你的 WebAuthn 设备上的按钮"
+msgstr "请按您的 WebAuthn 设备上的按钮"
#: proxmox-widget-toolkit/src/window/AddTfaRecovery.js:167
#: proxmox-yew-comp/src/tfa/tfa_add_recovery.rs:138
msgid "Please record recovery keys - they will only be displayed now"
-msgstr "请记录还原密钥-它们仅在现在显示"
+msgstr "请记录恢复密钥 - 它们现在只显示一次"
#: pve-manager/www/manager6/dc/TokenEdit.js:154
#: proxmox-backup/www/window/TokenEdit.js:204
@@ -11251,9 +11008,8 @@ msgid "Please record the API token secret - it will only be displayed now"
msgstr "请记录 API 令牌密钥-仅在现在显示"
#: proxmox-yew-comp/src/token_panel.rs:379
-#, fuzzy
msgid "Please record the API token secret - it will only be displayed now."
-msgstr "请记录 API 令牌密钥-仅在现在显示"
+msgstr "请记录 API 令牌密钥 - 它只会显示一次。"
#: pve-manager/www/manager6/storage/PBSEdit.js:138
msgid ""
@@ -11279,9 +11035,8 @@ msgid "Please select a sender."
msgstr "请选择一个发件人。"
#: pve-yew-mobile-gui/src/widgets/guest_backup_panel.rs:186
-#, fuzzy
msgid "Please select a target storage."
-msgstr "请选择一个规则。"
+msgstr "请选择目标存储。"
#: pmg-gui/js/ObjectGroup.js:15
msgid "Please select an object."
@@ -11355,11 +11110,11 @@ msgstr "资源池"
#: pve-manager/www/manager6/ceph/Pool.js:302
msgid "Pool #"
-msgstr "资源池 #"
+msgstr "存储池序号"
#: pve-manager/www/manager6/form/ViewSelector.js:30
msgid "Pool View"
-msgstr "资源池视图"
+msgstr "池视图"
#: pve-manager/www/manager6/dc/Backup.js:261
#: pve-manager/www/manager6/dc/BackupJobDetail.js:414
@@ -11411,7 +11166,7 @@ msgstr "端口"
#: proxmox-widget-toolkit/src/node/NetworkView.js:339
#: proxmox-yew-comp/src/configuration/network_view.rs:477
msgid "Ports/Slaves"
-msgstr "端口/从属"
+msgstr "端口/从属设备"
#: proxmox-widget-toolkit/src/Utils.js:87 proxmox-yew-comp/src/lib.rs:321
msgid "Portuguese (Brazil)"
@@ -11451,7 +11206,9 @@ msgstr "预定义标记"
msgid ""
"Prefer a fast and local storage, ideally with support for discard and thin-"
"provisioning or sparse files."
-msgstr "更喜欢快速和本地存储,最好支持丢弃和精简配置或稀疏文件。"
+msgstr ""
+"建议选择快速的本地存储,最好支持 discard、精简配置(thin-provisioning)或稀疏"
+"文件。"
#: pve-manager/www/manager6/Utils.js:32
msgid "Premium"
@@ -11469,9 +11226,8 @@ msgid "Preview"
msgstr "预览"
#: proxmox-yew-comp/src/auth_view.rs:432
-#, fuzzy
msgid "Preview Only"
-msgstr "预览"
+msgstr "仅预览"
#: pmg-gui/js/LDAPConfig.js:263
msgid "Primary E-Mail"
@@ -11486,9 +11242,8 @@ msgid "Primary GPU"
msgstr "主 GPU"
#: pve-manager/www/manager6/sdn/ZoneBridgesPanel.js:85
-#, fuzzy
msgid "Primary VLAN"
-msgstr "主 GPU"
+msgstr "主 VLAN"
#: pve-manager/www/manager6/storage/PBSEdit.js:119
msgid "Print Key"
@@ -11497,7 +11252,7 @@ msgstr "打印密钥"
#: proxmox-widget-toolkit/src/window/AddTfaRecovery.js:187
#: proxmox-yew-comp/src/tfa/tfa_add_recovery.rs:152
msgid "Print Recovery Keys"
-msgstr "打印还原密钥"
+msgstr "打印恢复密钥"
#: pve-manager/www/manager6/storage/PBSEdit.js:114
msgid "Print as paperkey, laminated and placed in secure vault."
@@ -11532,13 +11287,12 @@ msgstr "特权"
#: pve-manager/www/manager6/dc/RoleView.js:65
#: proxmox-yew-comp/src/role_selector.rs:29
msgid "Privileges"
-msgstr "特权"
+msgstr "权限"
#. TRANSLATORS: Probe is a verb here
#: proxmox-datacenter-manager/ui/src/remotes/add_wizard.rs:100
-#, fuzzy
msgid "Probe Remote"
-msgstr "源远程"
+msgstr "探测远程"
#: proxmox-widget-toolkit/src/window/TaskViewer.js:152
#: pve-manager/www/manager6/ceph/OSDDetails.js:169
@@ -11551,7 +11305,6 @@ msgid "Processing..."
msgstr "处理中..."
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_processor_property.rs:178
-#, fuzzy
msgid "Processor"
msgstr "处理器"
@@ -11570,12 +11323,11 @@ msgstr "产品"
#: proxmox-widget-toolkit/src/Utils.js:1384
#: proxmox-widget-toolkit/src/Utils.js:1391
msgid "Production-ready Enterprise repository enabled"
-msgstr "已启用生产就绪的企业存储库"
+msgstr "已启用适用于生产环境的企业版软件源"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:709
-#, fuzzy
msgid "Production-ready enterprise repository enabled"
-msgstr "已启用生产就绪的企业存储库"
+msgstr "已启用生产就绪企业仓库"
#: pmg-gui/js/LDAPGroupEditor.js:80 pmg-gui/js/LDAPProfileSelector.js:28
#: pmg-gui/js/LDAPUserEditor.js:36
@@ -11640,7 +11392,7 @@ msgstr "保护"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:97
msgid "Protection for \"Speculative Store Bypass\" for Intel models"
-msgstr ""
+msgstr "为 Intel 型号提供\"推测性存储绕过\"保护"
#: pmg-gui/js/FetchmailEdit.js:41 pmg-gui/js/FetchmailView.js:113
#: pmg-gui/js/LDAPConfig.js:70 pmg-gui/js/LDAPConfig.js:591
@@ -11659,12 +11411,11 @@ msgstr "协议"
#: proxmox-backup/www/window/S3ClientEdit.js:141
msgid "Provider Quirks"
-msgstr ""
+msgstr "提供商特性"
#: proxmox-yew-comp/src/proxmox_product.rs:60
-#, fuzzy
msgid "Proxmox Backup Server"
-msgstr "Proxmox Backup Server 登录"
+msgstr "Proxmox 备份服务器"
#: proxmox-backup/www/LoginView.js:274
msgid "Proxmox Backup Server Login"
@@ -11672,12 +11423,11 @@ msgstr "Proxmox Backup Server 登录"
#: proxmox-yew-comp/src/proxmox_product.rs:62
msgid "Proxmox Datacenter Manager"
-msgstr ""
+msgstr "Proxmox 数据中心管理器"
#: proxmox-yew-comp/src/proxmox_product.rs:59
-#, fuzzy
msgid "Proxmox Mail Gateway"
-msgstr "Proxmox Mail Gateway 登录"
+msgstr "Proxmox 邮件网关"
#: pmg-gui/js/LoginView.js:332
msgid "Proxmox Mail Gateway Login"
@@ -11689,7 +11439,7 @@ msgstr "Proxmox Mail Gateway 隔离帮助"
#: proxmox-yew-comp/src/proxmox_product.rs:61
msgid "Proxmox Offline Mirror"
-msgstr ""
+msgstr "Proxmox 离线镜像"
#: pve-manager/www/manager6/window/LoginWindow.js:351
msgid "Proxmox VE Login"
@@ -11697,7 +11447,7 @@ msgstr "Proxmox VE 登录"
#: proxmox-yew-comp/src/proxmox_product.rs:58
msgid "Proxmox Virtual Environment"
-msgstr ""
+msgstr "Proxmox 虚拟环境"
#: pve-manager/www/manager6/window/Backup.js:112
#: pve-manager/www/manager6/window/Prune.js:212 proxmox-backup/www/Utils.js:450
@@ -11711,7 +11461,7 @@ msgstr "精简 & GC 作业"
#: proxmox-backup/www/datastore/Content.js:1065
msgid "Prune '{0}'"
-msgstr "精简 '{0}'"
+msgstr "精简'{0}'"
#: proxmox-backup/www/datastore/Content.js:1348
msgid "Prune All"
@@ -11719,7 +11469,7 @@ msgstr "全部精简"
#: pve-manager/www/manager6/window/Prune.js:238
msgid "Prune Backups for '{0}' on Storage '{1}'"
-msgstr "删除存储 '{1}' 上 '{0}' 的备份"
+msgstr "删除存储'{1}'上'{0}'的备份"
#: proxmox-backup/www/Utils.js:451 proxmox-backup/www/window/PruneJobEdit.js:12
msgid "Prune Job"
@@ -11794,11 +11544,11 @@ msgstr "拉取文件"
#: pve-manager/www/manager6/storage/TemplateView.js:188
#: pve-manager/www/manager6/storage/TemplateView.js:375
msgid "Pull from OCI Registry"
-msgstr ""
+msgstr "从 OCI 注册表拉取"
#: proxmox-backup/www/config/SyncView.js:367
msgid "Pull: The local owner."
-msgstr "拉取: 本地所有者。"
+msgstr "拉取: 本地所有者。"
#: pve-manager/www/manager6/window/SafeDestroyGuest.js:13
msgid "Purge from job configurations"
@@ -11806,7 +11556,7 @@ msgstr "从作业配置中清除"
#: pve-manager/www/manager6/window/ConfirmRemoveResource.js:13
msgid "Purge resource from referenced HA rules"
-msgstr ""
+msgstr "从引用的 HA 规则中清除资源"
#: proxmox-backup/www/config/SyncView.js:316
msgid "Push"
@@ -11820,16 +11570,15 @@ msgstr "推送文件"
#: proxmox-backup/www/config/SyncView.js:368
msgid "Push: The local user used for access control."
-msgstr "推送:用于访问控制的本地用户。"
+msgstr "推送: 用于访问控制的本地用户。"
#: pve-manager/www/manager6/qemu/PCIEdit.js:43
msgid "Q35 only"
msgstr "仅 Q35"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_agent_property.rs:112
-#, fuzzy
msgid "QEMU Guest Agent"
-msgstr "Qemu 代理"
+msgstr "QEMU 客户机代理"
#: pve-manager/www/manager6/form/DiskFormatSelector.js:6
#: proxmox-yew-comp/src/form/pve/qemu_disk_format_selector.rs:80
@@ -11860,9 +11609,8 @@ msgid "Quarantine port"
msgstr "隔离端口"
#: pve-manager/www/manager6/storage/TemplateView.js:296
-#, fuzzy
msgid "Query Tags"
-msgstr "排除标记"
+msgstr "查询标签"
#: pve-manager/www/manager6/node/ACME.js:127
#: pve-manager/www/manager6/window/DownloadUrlToStorage.js:151
@@ -11876,7 +11624,7 @@ msgstr "查询用户信息端点"
#: proxmox-datacenter-manager/ui/src/pbs/tree.rs:287
#: proxmox-datacenter-manager/ui/src/pve/tree.rs:598
msgid "Querying Remote..."
-msgstr ""
+msgstr "正在查询远程..."
#: pmg-gui/js/QueueAdministration.js:5
msgid "Queue Administration"
@@ -11892,7 +11640,7 @@ msgstr "具有法定数目的"
#: pve-manager/www/manager6/ceph/Monitor.js:27
msgid "Quorum"
-msgstr "法定数目"
+msgstr "仲裁有效"
#: pve-manager/www/manager6/node/ZFS.js:71
#: proxmox-backup/www/window/ZFSCreate.js:40
@@ -11904,9 +11652,8 @@ msgid "RAM"
msgstr "内存"
#: proxmox-yew-comp/src/node_info.rs:179
-#, fuzzy
msgid "RAM Usage"
-msgstr "内存使用率"
+msgstr "RAM 使用率"
#: pmg-gui/js/ClusterAdministration.js:313 pmg-gui/js/dashboard/NodeInfo.js:43
#: pve-manager/www/manager6/node/StatusView.js:54
@@ -11919,11 +11666,11 @@ msgstr "内存使用率"
#: pve-manager/www/manager6/node/NodeOptionsView.js:75
msgid "RAM usage target for ballooning"
-msgstr ""
+msgstr "内存气球的 RAM 使用目标"
#: pve-manager/www/manager6/storage/RBDEdit.js:250
msgid "RBD namespaces must be created manually!"
-msgstr "必须手动创建RBD命名空间!"
+msgstr "必须手动创建 RBD 命名空间!"
#: pve-manager/www/manager6/qemu/Options.js:271
#: pve-manager/www/manager6/qemu/Options.js:276
@@ -11942,9 +11689,8 @@ msgid "Randomize"
msgstr "随机化"
#: proxmox-yew-comp/src/firewall/log_ratelimit_field.rs:179
-#, fuzzy
msgid "Rate"
-msgstr "入口速率"
+msgstr "速率"
#: proxmox-backup/www/config/TrafficControlView.js:134
#: proxmox-backup/www/window/S3ClientEdit.js:127
@@ -11983,7 +11729,7 @@ msgstr "速率限制"
#: pve-manager/www/manager6/node/Certificates.js:99
msgid "Raw Certificate"
-msgstr "原始凭证"
+msgstr "原始证书"
#: pve-manager/www/manager6/qemu/PCIEdit.js:214
msgid "Raw Device"
@@ -12170,9 +11916,8 @@ msgid "Reboot"
msgstr "重启"
#: proxmox-datacenter-manager/ui/src/administration/node_status.rs:215
-#, fuzzy
msgid "Reboot Datacenter Manager"
-msgstr "Proxmox Backup Server 登录"
+msgstr "重启数据中心管理器"
#: proxmox-backup/www/ServerStatus.js:146
msgid "Reboot backup server?"
@@ -12181,7 +11926,7 @@ msgstr "重新启动备份服务器?"
#: pve-manager/www/manager6/node/Config.js:105
#: pve-yew-mobile-gui/src/pages/page_node_status/dashboard_panel.rs:136
msgid "Reboot node '{0}'?"
-msgstr "重启节点 '{0}'?"
+msgstr "重启节点'{0}'?"
#: pve-manager/www/manager6/lxc/CmdMenu.js:84
#: pve-manager/www/manager6/lxc/Config.js:76
@@ -12201,9 +11946,8 @@ msgid "Receiver"
msgstr "接收者"
#: pve-yew-mobile-gui/src/widgets/guest_backup_panel.rs:215
-#, fuzzy
msgid "Recent backups"
-msgstr "保留所有备份"
+msgstr "最近的备份"
#: proxmox-backup/www/tape/window/TapeBackupJob.js:275
#: proxmox-backup/www/window/NotifyOptions.js:107
@@ -12234,9 +11978,8 @@ msgid "Recovery Keys"
msgstr "还原密钥"
#: proxmox-yew-comp/src/tfa/tfa_add_recovery.rs:119
-#, fuzzy
msgid "Recovery Keys for user '{}'"
-msgstr "还原密钥"
+msgstr "用户 '{}' 的恢复密钥"
#: proxmox-backup/www/panel/PrunePanel.js:100
msgid "Recursive"
@@ -12244,7 +11987,7 @@ msgstr "递归的"
#: pve-manager/www/manager6/storage/TemplateView.js:273
msgid "Reference"
-msgstr ""
+msgstr "引用"
#: pve-manager/www/manager6/window/SafeDestroyGuest.js:35
msgid "Referenced disks will always be destroyed."
@@ -12259,32 +12002,29 @@ msgid "Refresh"
msgstr "刷新"
#: proxmox-datacenter-manager/ui/src/dashboard/refresh_config_edit.rs:55
-#, fuzzy
msgid "Refresh Configuration"
-msgstr "保留配置"
+msgstr "刷新配置"
#: proxmox-datacenter-manager/ui/src/dashboard/refresh_config_edit.rs:78
msgid "Refresh Interval (seconds)"
-msgstr ""
+msgstr "刷新间隔(秒)"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:464
-#, fuzzy
msgid "Refresh all"
-msgstr "刷新"
+msgstr "全部刷新"
#: proxmox-backup/www/datastore/Content.js:1332
msgid "Refresh contents from S3 bucket"
-msgstr ""
+msgstr "从 S3 存储桶刷新内容"
#: proxmox-datacenter-manager/ui/src/dashboard/status_row.rs:170
-#, fuzzy
msgid "Refresh now"
-msgstr "刷新"
+msgstr "立即刷新"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:484
msgid ""
"Refresh the status of the repository and pending updates for all remotes"
-msgstr ""
+msgstr "刷新所有远程的仓库状态和待处理更新"
#: pve-manager/www/manager6/qemu/CloudInit.js:79
msgid "Regenerate Image"
@@ -12300,7 +12040,7 @@ msgid ""
"Regenerate the secret of the API token '{0}'? All users of the previous "
"token secret will lose access!"
msgstr ""
-"是否重新生成API令牌'{0}'的机密?之前令牌密钥的所有用户都将失去访问权限!"
+"是否重新生成 API 令牌'{0}'的密钥?之前令牌密钥的所有用户都将失去访问权限!"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:1304
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:1374
@@ -12312,7 +12052,7 @@ msgstr "正则表达式"
#: proxmox-backup/www/config/S3ClientView.js:128
#: proxmox-backup/www/window/S3ClientEdit.js:82
msgid "Region"
-msgstr ""
+msgstr "区域"
#: proxmox-widget-toolkit/src/window/ACMEAccount.js:12
#: pve-manager/www/manager6/Utils.js:2081
@@ -12347,7 +12087,6 @@ msgid "Regular Expression"
msgstr "正则表达式"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:21
-#, fuzzy
msgid "Reject"
msgstr "拒绝"
@@ -12410,13 +12149,12 @@ msgid "Reload"
msgstr "重载"
#: proxmox-datacenter-manager/ui/src/tasks.rs:77
-#, fuzzy
msgid "Reload network configuration"
-msgstr "重新加载所有节点上的网络配置"
+msgstr "重新加载网络配置"
#: pve-manager/www/manager6/Utils.js:2145
msgid "Reload network configuration on all nodes"
-msgstr "重新加载所有节点上的网络配置"
+msgstr "重新读取所有节点上的网络配置"
#: pmg-gui/js/TFAView.js:27 proxmox-backup/www/config/WebauthnView.js:11
#: proxmox-backup/www/config/WebauthnView.js:82
@@ -12443,9 +12181,8 @@ msgstr "远程"
#: proxmox-datacenter-manager/ui/src/pbs/mod.rs:128
#: proxmox-datacenter-manager/ui/src/pve/remote/mod.rs:48
#: proxmox-datacenter-manager/ui/src/pve/mod.rs:242
-#, fuzzy
msgid "Remote '{0}'"
-msgstr "移除 '{0}'"
+msgstr "远程 '{0}'"
#: proxmox-backup/www/config/RemoteView.js:129
#: proxmox-backup/www/config/SyncView.js:340
@@ -12459,41 +12196,36 @@ msgid "Remote ID"
msgstr "远程 ID"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:424
-#, fuzzy
msgid "Remote Migration Settings"
-msgstr "迁移设置"
+msgstr "远程迁移设置"
#: proxmox-backup/www/config/SyncView.js:353
msgid "Remote Namespace"
msgstr "远程命名空间"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:544
-#, fuzzy
msgid "Remote Panel"
-msgstr "远程同步"
+msgstr "远程面板"
#: proxmox-backup/www/config/SyncView.js:347
msgid "Remote Store"
msgstr "远程存储"
#: proxmox-datacenter-manager/ui/src/dashboard/subscription_info.rs:163
-#, fuzzy
msgid "Remote Subscription Status"
-msgstr "订阅"
+msgstr "远程订阅状态"
#: proxmox-backup/www/Utils.js:455 proxmox-backup/www/Utils.js:456
msgid "Remote Sync"
msgstr "远程同步"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:477
-#, fuzzy
msgid "Remote System Updates"
-msgstr "远程存储"
+msgstr "远程系统更新"
#: proxmox-datacenter-manager/ui/src/pve/remote/mod.rs:58
-#, fuzzy
msgid "Remote Tasks"
-msgstr "显示所有任务"
+msgstr "远程任务"
#: proxmox-backup/www/NavigationTree.js:54
#: proxmox-backup/www/config/RemoteView.js:39
@@ -12504,9 +12236,8 @@ msgid "Remotes"
msgstr "远程"
#: proxmox-backup/www/window/DataStoreEdit.js:63
-#, fuzzy
msgid "Removable"
-msgstr "移除"
+msgstr "可移除"
#: proxmox-backup/www/window/CreateDirectory.js:59
msgid "Removable datastore"
@@ -12519,7 +12250,7 @@ msgstr "未挂载可移动数据存储"
#: pve-manager/www/manager6/grid/Replication.js:343
#: pve-manager/www/manager6/grid/Replication.js:346
msgid "Removal Scheduled"
-msgstr "移除已安排"
+msgstr "已计划移除"
#: proxmox-widget-toolkit/src/button/Button.js:103
#: proxmox-widget-toolkit/src/panel/NotificationConfigView.js:11
@@ -12578,12 +12309,11 @@ msgstr "移除"
#: pve-manager/www/manager6/tree/ResourceMapTree.js:372
msgid "Remove '{0}'"
-msgstr "移除 '{0}'"
+msgstr "移除'{0}'"
#: proxmox-yew-comp/src/acl/acl_view.rs:214
-#, fuzzy
msgid "Remove ACL Entry"
-msgstr "移除条目?"
+msgstr "删除 ACL 条目"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:424
msgid "Remove ACLs of vanished users"
@@ -12598,9 +12328,8 @@ msgstr "移除消失的用户和组的 ACL。"
#: proxmox-yew-comp/src/auth_view.rs:450
#: proxmox-yew-comp/src/auth_edit_ldap.rs:244
-#, fuzzy
msgid "Remove ACLs of vanished users."
-msgstr "删除已消失用户的 ACL"
+msgstr "删除已消失用户的 ACL。"
#: pmg-gui/js/Utils.js:652
msgid "Remove Attachments"
@@ -12624,9 +12353,8 @@ msgid "Remove Namespace"
msgstr "移除命名空间"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:481
-#, fuzzy
msgid "Remove Row"
-msgstr "移除"
+msgstr "删除行"
#: pmg-gui/js/PBSSnapshotView.js:146
msgid "Remove Schedule"
@@ -12659,7 +12387,7 @@ msgstr "移除所有的附件"
#: proxmox-backup/www/datastore/OptionView.js:23
msgid "Remove data from S3 bucket and local cache (dangerous!)"
-msgstr ""
+msgstr "从 S3 存储桶和本地缓存中删除数据(危险!)"
#: proxmox-backup/www/config/PruneView.js:177
#: proxmox-backup/www/config/SyncView.js:248
@@ -12674,20 +12402,19 @@ msgstr "从复制和备份作业中移除"
#: pve-manager/www/manager6/tree/ResourceMapTree.js:375
msgid "Remove mapping '{0}'"
-msgstr "移除映射 '{0}'"
+msgstr "移除映射'{0}'"
#: pve-manager/www/manager6/tree/ResourceMapTree.js:374
msgid "Remove mapping for '{0}'"
-msgstr "删除 '{0}' 的映射"
+msgstr "删除'{0}'的映射"
#: proxmox-backup/www/datastore/Content.js:1088
msgid "Remove namespace '{0}'"
-msgstr "移除命名空间 '{0}'"
+msgstr "移除命名空间'{0}'"
#: proxmox-yew-comp/src/configuration/pve/lxc_network_panel.rs:193
-#, fuzzy
msgid "Remove network failed"
-msgstr "无网络设备"
+msgstr "删除网络失败"
#: proxmox-backup/www/window/SyncJobEdit.js:406
msgid ""
@@ -12697,9 +12424,8 @@ msgstr "如果快照从源数据存储中消失,是否从同步目标数据存
#: proxmox-yew-comp/src/auth_view.rs:462
#: proxmox-yew-comp/src/auth_edit_ldap.rs:256
-#, fuzzy
msgid "Remove vanished properties"
-msgstr "删除消失的用户"
+msgstr "删除已消失的属性"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:436
#: proxmox-widget-toolkit/src/window/SyncWindow.js:125
@@ -12713,14 +12439,14 @@ msgstr "从同步用户中移除已消失的属性。"
#: proxmox-yew-comp/src/auth_view.rs:456
#: proxmox-yew-comp/src/auth_edit_ldap.rs:250
msgid "Remove vanished user"
-msgstr "删除消失的用户"
+msgstr "移除已消失的用户"
#: proxmox-widget-toolkit/src/window/SyncWindow.js:118
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:342
#: pve-manager/www/manager6/dc/RealmSyncJob.js:377
#: pve-manager/www/manager6/dc/SyncWindow.js:140
msgid "Remove vanished user and group entries."
-msgstr "移除消失的用户和组条目。"
+msgstr "移除已消失的用户和组条目。"
#: proxmox-backup/www/config/GCView.js:217
msgid "Removed Data"
@@ -12730,7 +12456,7 @@ msgstr "已删除的数据"
#: proxmox-datacenter-manager/ui/src/tasks.rs:13
#: proxmox-yew-comp/src/utils/mod.rs:358
msgid "Renew Certificate"
-msgstr "更新凭证"
+msgstr "更新证书"
#: pve-manager/www/manager6/panel/BackupAdvancedOptions.js:260
msgid "Repeat missed"
@@ -12752,9 +12478,8 @@ msgid "Replication Log"
msgstr "复制日志"
#: pve-manager/www/manager6/dc/OptionView.js:132
-#, fuzzy
msgid "Replication Settings"
-msgstr "迁移设置"
+msgstr "复制设置"
#: pve-manager/www/manager6/Utils.js:2185
msgid "Replication job notifications"
@@ -12769,7 +12494,7 @@ msgstr "复制至少需要两个节点"
#: proxmox-backup/www/ServerAdministration.js:58
#: proxmox-datacenter-manager/ui/src/administration/mod.rs:102
msgid "Repositories"
-msgstr "存储库"
+msgstr "软件源"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:25
#: proxmox-widget-toolkit/src/node/APTRepositories.js:58
@@ -12778,12 +12503,12 @@ msgstr "存储库"
#: proxmox-yew-comp/src/apt_repositories.rs:747
#: proxmox-yew-comp/src/apt_repositories.rs:777
msgid "Repository"
-msgstr "存储库"
+msgstr "软件源"
#: proxmox-widget-toolkit/src/panel/NodeInfoRepoStatus.js:5
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:196
msgid "Repository Status"
-msgstr "存储库状态"
+msgstr "软件源状态"
#: proxmox-backup/www/window/DatastoreRepoInfo.js:65
msgid "Repository for CLI and API"
@@ -12804,12 +12529,12 @@ msgstr "需要 TFA"
#: proxmox-yew-comp/src/form/pve/qemu_cpu_flags_list.rs:94
msgid "Required to let the guest OS know if MDS is mitigated correctly"
-msgstr ""
+msgstr "用于告知客户机操作系统 MDS 缓解措施是否已正确启用"
#: pve-manager/www/manager6/panel/IPView.js:233
#: pve-manager/www/manager6/panel/IPView.js:296
msgid "Requires '{0}' Privileges"
-msgstr "需要 '{0}' 权限"
+msgstr "需要'{0}'权限"
#: proxmox-widget-toolkit/src/panel/NotificationConfigView.js:11
#: pmg-gui/js/Settings.js:160 pmg-gui/js/Settings.js:181
@@ -12843,9 +12568,8 @@ msgid "Reset rule database to factory defaults?"
msgstr "将规则数据库重置为出厂默认值?"
#: pve-manager/www/manager6/qemu/CmdMenu.js:118
-#, fuzzy
msgid "Reset {0}"
-msgstr "使用 {0}"
+msgstr "重置 {0}"
#: pve-manager/www/manager6/qemu/Config.js:219
msgid "Reset {0} immediately"
@@ -12864,7 +12588,6 @@ msgid "Resize"
msgstr "调整大小"
#: proxmox-yew-comp/src/configuration/pve/resize_disk_dialog.rs:16
-#, fuzzy
msgid "Resize Disk"
msgstr "调整磁盘大小"
@@ -12880,14 +12603,12 @@ msgid "Resource"
msgstr "资源"
#: pve-manager/www/manager6/dc/MetricServerView.js:704
-#, fuzzy
msgid "Resource Attributes (JSON)"
-msgstr "用户属性名称"
+msgstr "资源属性(JSON)"
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:271
-#, fuzzy
msgid "Resource ID"
-msgstr "资源"
+msgstr "资源 ID"
#: pve-manager/www/manager6/dc/Config.js:391
msgid "Resource Mappings"
@@ -12903,14 +12624,12 @@ msgid "Resource Pool"
msgstr "资源池"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:642
-#, fuzzy
msgid "Resource Tree"
-msgstr "资源"
+msgstr "资源树"
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:269
-#, fuzzy
msgid "Resource Type"
-msgstr "资源"
+msgstr "资源类型"
#: pve-manager/www/manager6/dc/Summary.js:26
#: pve-manager/www/manager6/ha/Status.js:38
@@ -12941,7 +12660,7 @@ msgstr "重启模式"
#: pmg-gui/js/SpamDetectorCustom.js:96
msgid "Restart pmg-smtp-filter to activate changes."
-msgstr "重新启动 pmg-smtp-filter 以激活更改。"
+msgstr "重新启动 pmg-smtp-filter 以启用更改。"
#: pmg-gui/js/BackupRestore.js:21 pmg-gui/js/BackupRestore.js:24
#: pmg-gui/js/BackupRestore.js:100 pmg-gui/js/BackupRestore.js:140
@@ -13040,7 +12759,7 @@ msgstr "还原"
#: proxmox-datacenter-manager/ui/src/tasks.rs:14
#: proxmox-yew-comp/src/utils/mod.rs:359
msgid "Revoke Certificate"
-msgstr "撤销凭证"
+msgstr "撤销证书"
#: proxmox-backup/www/Utils.js:453
msgid "Rewind Media"
@@ -13103,7 +12822,7 @@ msgstr "根磁盘IO延迟(毫秒)"
#: proxmox-backup/www/ServerStatus.js:267
msgid "Root Disk Input/Output Operations per Second (IOPS)"
-msgstr "每秒根磁盘输入/输出操作(IOPS)"
+msgstr "根磁盘每秒 I/O 操作数(IOPS)"
#: proxmox-backup/www/ServerStatus.js:260
msgid "Root Disk Transfer Rate (bytes/second)"
@@ -13114,9 +12833,8 @@ msgid "Root Disk usage"
msgstr "根磁盘使用率"
#: pve-yew-mobile-gui/src/pages/page_node_status/dashboard_panel.rs:110
-#, fuzzy
msgid "Root Filesystem"
-msgstr "文件系统"
+msgstr "根文件系统"
#: proxmox-backup/www/datastore/Content.js:359
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:107
@@ -13125,7 +12843,7 @@ msgstr "根命名空间"
#: pve-manager/www/manager6/sdn/FabricsContentView.js:7
msgid "Route"
-msgstr ""
+msgstr "路由"
#: pve-manager/www/manager6/sdn/zones/EvpnEdit.js:87
msgid "Route Target Import"
@@ -13139,7 +12857,7 @@ msgstr "路由器广播"
#: pve-manager/www/manager6/sdn/NetworkBrowser.js:34
msgid "Routes"
-msgstr ""
+msgstr "路由"
#: pve-manager/www/manager6/grid/FirewallRules.js:498
#: pve-manager/www/manager6/grid/FirewallRules.js:598
@@ -13185,14 +12903,12 @@ msgid "Run now"
msgstr "现在运行"
#: proxmox-backup/www/window/SyncJobEdit.js:496
-#, fuzzy
msgid "Run on Mount"
-msgstr "现在运行"
+msgstr "挂载时运行"
#: proxmox-backup/www/window/SyncJobEdit.js:500
-#, fuzzy
msgid "Run this job when a relevant removable datastore gets mounted."
-msgstr "未挂载可移动数据存储"
+msgstr "在相关的可移除数据存储挂载时运行此作业。"
#: pve-manager/www/manager6/dc/Guests.js:42
#: pve-manager/www/manager6/dc/Guests.js:87
@@ -13217,39 +12933,33 @@ msgid "S.Port"
msgstr "来源端口"
#: proxmox-backup/www/window/DataStoreEdit.js:64
-#, fuzzy
msgid "S3 (tech preview)"
-msgstr "nftables(技术预览)"
+msgstr "S3(技术预览)"
#: proxmox-backup/www/window/S3ClientEdit.js:10
-#, fuzzy
msgid "S3 Endpoint"
-msgstr "端点名称"
+msgstr "S3 端点"
#: proxmox-backup/www/config/S3ClientView.js:108
#: proxmox-backup/www/form/S3ClientSelector.js:19
#: proxmox-backup/www/window/DataStoreEdit.js:130
#: proxmox-backup/www/window/S3ClientEdit.js:35
-#, fuzzy
msgid "S3 Endpoint ID"
-msgstr "端点名称"
+msgstr "S3 端点 ID"
#: proxmox-backup/www/NavigationTree.js:60
#: proxmox-backup/www/config/S3ClientView.js:15
-#, fuzzy
msgid "S3 Endpoints"
-msgstr "端点名称"
+msgstr "S3 端点"
#: proxmox-backup/www/Utils.js:454
#: proxmox-backup/www/window/MaintenanceOptions.js:99
-#, fuzzy
msgid "S3 Refresh"
-msgstr "刷新"
+msgstr "S3 刷新"
#: proxmox-backup/www/Utils.js:853
-#, fuzzy
msgid "S3 refresh"
-msgstr "刷新"
+msgstr "S3 刷新"
#: pve-manager/www/manager6/qemu/HDEdit.js:204
#: pve-manager/www/manager6/qemu/HardwareView.js:200
@@ -13272,14 +12982,12 @@ msgid "SDN"
msgstr "SDN"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:640
-#, fuzzy
msgid "SDN Panel"
-msgstr "DNS 域"
+msgstr "SDN 面板"
#: proxmox-datacenter-manager/ui/src/dashboard/sdn_zone_panel.rs:179
-#, fuzzy
msgid "SDN Zones"
-msgstr "DNS 域"
+msgstr "SDN 区域"
#: pve-manager/www/manager6/qemu/IPConfigEdit.js:163
msgid "SLAAC"
@@ -13301,9 +13009,8 @@ msgstr "SMTPD 横幅"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:138
#: proxmox-yew-comp/src/firewall/options_edit.rs:481
-#, fuzzy
msgid "SMURF Log Level"
-msgstr "日志级别"
+msgstr "SMURF 日志级别"
#: pve-manager/www/manager6/grid/FirewallOptions.js:73
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:87
@@ -13398,7 +13105,7 @@ msgstr "扫描"
#: proxmox-widget-toolkit/src/window/AddTotp.js:254
#: proxmox-yew-comp/src/tfa/tfa_add_totp.rs:136
msgid "Scan QR code in a TOTP app and enter an auth. code here"
-msgstr "在 TOTP 应用中扫描 QR 码,然后输入验证码。 在这里输验证码"
+msgstr "在 TOTP 应用中扫描二维码,并在此处输入验证码"
#: pve-manager/www/manager6/window/SafeDestroyGuest.js:29
msgid "Scan all enabled storages for unreferenced disks and delete them."
@@ -13448,7 +13155,7 @@ msgstr "立即安排"
#: pmg-gui/js/PBSSnapshotView.js:171
msgid "Schedule on '{0}'"
-msgstr "'{0}' 上的计划"
+msgstr "'{0}'上的计划"
#: proxmox-backup/www/Utils.js:464
msgid "Scheduled Verification"
@@ -13472,7 +13179,7 @@ msgstr "范围"
#: pve-manager/www/manager6/dc/AuthEditOpenId.js:46
#: proxmox-yew-comp/src/auth_edit_openid.rs:126
msgid "Scopes"
-msgstr "范围"
+msgstr "作用域"
#: pmg-gui/js/ReceiverStatistics.js:93 pmg-gui/js/SpamDetectorCustom.js:131
#: pmg-gui/js/SpamDetectorCustom.js:177 pmg-gui/js/SpamDetectorCustom.js:261
@@ -13482,9 +13189,8 @@ msgid "Score"
msgstr "得分"
#: pmg-yew-quarantine-gui/src/spam_list.rs:243
-#, fuzzy
msgid "Score: {0}"
-msgstr "模式:{0}"
+msgstr "得分:{0}"
#: pve-manager/www/manager6/ceph/OSD.js:967
msgid "Scrub"
@@ -13511,7 +13217,7 @@ msgstr "搜索"
#: proxmox-datacenter-manager/ui/src/widget/search_box.rs:151
msgid "Search (Ctrl+Space / Ctrl+Shift+F)"
-msgstr ""
+msgstr "搜索 (Ctrl+Space / Ctrl+Shift+F)"
#: proxmox-widget-toolkit/src/node/DNSEdit.js:19
#: proxmox-widget-toolkit/src/node/DNSView.js:30
@@ -13526,11 +13232,11 @@ msgstr "二次验证"
#: proxmox-widget-toolkit/src/panel/TfaView.js:22
msgid "Second Factors"
-msgstr "二次验证"
+msgstr "二次验证因子"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:6
msgid "Second login factor required"
-msgstr "需要二次登录验证"
+msgstr "需要二次登录验证因子"
#: pve-manager/www/manager6/node/NodeOptionsView.js:59
msgid "Seconds"
@@ -13572,14 +13278,12 @@ msgid "Security Group"
msgstr "安全群组"
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:229
-#, fuzzy
msgid "Select"
-msgstr "选择器"
+msgstr "选择"
#: pmg-yew-quarantine-gui/src/page_spam_list.rs:219
-#, fuzzy
msgid "Select Date"
-msgstr "选择镜像"
+msgstr "选择日期"
#: pve-manager/www/manager6/window/UploadToStorage.js:200
msgid "Select File"
@@ -13590,9 +13294,8 @@ msgid "Select Image"
msgstr "选择镜像"
#: pmg-yew-quarantine-gui/src/page_spam_list.rs:240
-#, fuzzy
msgid "Select Language"
-msgstr "默认语言"
+msgstr "选择语言"
#: proxmox-backup/www/tape/window/TapeRestore.js:316
msgid "Select Media-Set to restore"
@@ -13605,21 +13308,20 @@ msgid "Select Timespan"
msgstr "选择时间范围"
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:403
-#, fuzzy
msgid "Select Type first"
-msgstr "选择时间范围"
+msgstr "请先选择类型"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/evpn_panel.rs:342
msgid "Select a Zone or VNet for more details."
-msgstr ""
+msgstr "选择区域或 VNet 以获取更多详细信息。"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/ui_helpers.rs:115
msgid "Select a firewall entry to show its rules."
-msgstr ""
+msgstr "选择防火墙条目以显示其规则。"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:600
msgid "Select a node to show available updates."
-msgstr ""
+msgstr "选择一个节点以显示可用更新。"
#: pve-manager/www/manager6/dc/ClusterEdit.js:316
msgid ""
@@ -13643,7 +13345,7 @@ msgstr "已选的邮件"
#: pve-manager/www/manager6/grid/PoolMembers.js:160
msgid ""
"Selected guests who are already part of a pool will be removed from it first."
-msgstr "已成为池中一部分的选定客人将首先从池中移除。"
+msgstr "已成为池中一部分的选定客户机将首先从池中移除。"
#: pve-manager/www/manager6/dc/Backup.js:813
#: pve-yew-mobile-gui/src/widgets/volume_action_dialog.rs:74
@@ -13695,7 +13397,7 @@ msgstr "发件人/主题"
#: proxmox-widget-toolkit/src/panel/NotificationConfigView.js:136
msgid "Sent test notification to '{0}'."
-msgstr "已向 '{0}' 发送测试通知。"
+msgstr "已向'{0}'发送测试通知。"
#: proxmox-backup/www/tape/BackupOverview.js:378
msgid "Seq. Nr."
@@ -13715,7 +13417,7 @@ msgstr "序号."
#: proxmox-backup/www/tape/form/TapeDevicePathSelector.js:36
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_smbios1_property.rs:61
msgid "Serial"
-msgstr "串行"
+msgstr "序列号"
#: pve-manager/www/manager6/qemu/HardwareView.js:327
#: pve-manager/www/manager6/qemu/HardwareView.js:783
@@ -13726,11 +13428,11 @@ msgstr "串行端口"
#: pve-manager/www/manager6/qemu/DisplayEdit.js:56
msgid "Serial interface '{0}' is not correctly configured."
-msgstr "串行接口 '{0}' 未正确配置。"
+msgstr "串行接口'{0}'未正确配置。"
#: pve-manager/www/manager6/window/GuestImport.js:1015
msgid "Serial socket '{0}' will be mapped to a socket"
-msgstr "串行 socket '{0}' 将映射到 socket"
+msgstr "串行 socket'{0}'将映射到 socket"
#: pve-manager/www/manager6/Utils.js:610 pve-manager/www/manager6/Utils.js:611
#: pve-manager/www/manager6/Utils.js:612 pve-manager/www/manager6/Utils.js:613
@@ -13783,7 +13485,6 @@ msgstr "服务器 ID"
#: proxmox-datacenter-manager/ui/src/pbs/node/overview.rs:246
#: proxmox-datacenter-manager/ui/src/pve/node/overview.rs:152
#: proxmox-datacenter-manager/ui/src/pve/node/overview.rs:250
-#, fuzzy
msgid "Server Load"
msgstr "服务器负载"
@@ -13804,7 +13505,7 @@ msgstr "服务器视图"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_connect.rs:251
msgid ""
"Server certificate SHA-256 fingerprint, required for self-signed certificates"
-msgstr "服务器凭证 SHA-256 指纹,对于自签名凭证是必需的"
+msgstr "服务器证书 SHA-256 指纹,自签名证书必须提供"
#: proxmox-backup/www/window/RemoteEdit.js:116
#: proxmox-backup/www/window/S3ClientEdit.js:115
@@ -13876,7 +13577,7 @@ msgstr "设定状态"
#: proxmox-widget-toolkit/src/window/AuthEditSimple.js:25
#: pmg-gui/js/AuthEditOIDC.js:98
msgid "Set realm as default for login"
-msgstr "将域设置为登录的默认值"
+msgstr "设置此领域为登录默认值"
#: pmg-gui/js/MailProxyDKIMPanel.js:30 pmg-gui/js/MailProxyTLSPanel.js:21
#: pve-manager/www/manager6/window/Snapshot.js:110
@@ -13892,11 +13593,11 @@ msgstr "设置保存在浏览器的本地存储中"
#: proxmox-widget-toolkit/src/window/AddWebauthn.js:93
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:196
msgid "Setup"
-msgstr "设定"
+msgstr "设置"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:1068
msgid "Severities to match"
-msgstr "匹配的严重性"
+msgstr "匹配的严重性级别"
#: pve-manager/www/manager6/ceph/Status.js:138
#: pve-manager/www/manager6/dc/Log.js:73
@@ -13932,14 +13633,12 @@ msgid "Shell"
msgstr "Shell"
#: proxmox-yew-comp/src/utils/mod.rs:241
-#, fuzzy
msgid "Shell (Spice)"
-msgstr "Shell(JS)"
+msgstr "Shell (Spice)"
#: proxmox-yew-comp/src/utils/mod.rs:242
-#, fuzzy
msgid "Shell (VNC)"
-msgstr "Shell(JS)"
+msgstr "Shell(VNC)"
#: pmg-gui/js/SpamQuarantineOptions.js:15
msgid "Short"
@@ -13978,9 +13677,8 @@ msgid "Show Fingerprint"
msgstr "显示指纹"
#: proxmox-datacenter-manager/ui/src/top_nav_bar.rs:208
-#, fuzzy
msgid "Show Local Tasks"
-msgstr "显示所有任务"
+msgstr "显示本地任务"
#: proxmox-backup/www/config/GCView.js:156
#: proxmox-backup/www/config/PruneView.js:183
@@ -13991,9 +13689,8 @@ msgid "Show Log"
msgstr "显示日志"
#: proxmox-yew-widget-toolkit/src/widget/form/field.rs:486
-#, fuzzy
msgid "Show Password"
-msgstr "新密码"
+msgstr "显示密码"
#: pve-manager/www/manager6/dc/TokenView.js:109
#: proxmox-backup/www/config/TokenView.js:225
@@ -14004,9 +13701,8 @@ msgid "Show Permissions"
msgstr "显示权限"
#: proxmox-datacenter-manager/ui/src/top_nav_bar.rs:213
-#, fuzzy
msgid "Show Remote Tasks"
-msgstr "显示所有任务"
+msgstr "显示远程任务"
#: proxmox-widget-toolkit/src/panel/DiskList.js:393
msgid "Show S.M.A.R.T. values"
@@ -14018,7 +13714,7 @@ msgstr "显示用户"
#: proxmox-widget-toolkit/src/node/APT.js:176
msgid "Show details"
-msgstr "显示详细信息"
+msgstr "显示详情"
#: pve-manager/www/manager6/dc/Backup.js:658
msgid ""
@@ -14031,12 +13727,11 @@ msgstr "仅显示已安装的服务"
#: proxmox-datacenter-manager/ui/src/remotes/firewall/tree.rs:343
msgid "Show tree panel"
-msgstr ""
+msgstr "显示树面板"
#: proxmox-datacenter-manager/ui/src/dashboard/tasks.rs:158
-#, fuzzy
msgid "Show: {0} - {1}"
-msgstr "{0} 的 {1}"
+msgstr "显示:{0} - {1}"
#: pmg-gui/js/ServerStatus.js:74 pmg-gui/js/ServerStatus.js:76
#: pve-manager/www/manager6/Utils.js:2111
@@ -14068,9 +13763,8 @@ msgid "Shutdown"
msgstr "关机"
#: proxmox-datacenter-manager/ui/src/administration/node_status.rs:226
-#, fuzzy
msgid "Shutdown Datacenter Manager"
-msgstr "Proxmox Backup Server 登录"
+msgstr "关闭数据中心管理器"
#: pve-manager/www/manager6/dc/OptionView.js:169
msgid "Shutdown Policy"
@@ -14083,7 +13777,7 @@ msgstr "关闭备份服务器?"
#: pve-manager/www/manager6/node/Config.js:116
#: pve-yew-mobile-gui/src/pages/page_node_status/dashboard_panel.rs:141
msgid "Shutdown node '{0}'?"
-msgstr "关闭节点 '{0}' ?"
+msgstr "关闭节点'{0}' ?"
#: pve-manager/www/manager6/qemu/CreateWizard.js:149
#: pve-manager/www/manager6/window/StartupEdit.js:49
@@ -14093,7 +13787,7 @@ msgstr "关机超时"
#: pve-manager/www/manager6/qemu/Config.js:167
msgid "Shutdown, apply pending changes and reboot {0}"
-msgstr "关闭,应用挂起的更改并重新启动{0}"
+msgstr "关闭,应用挂起的更改并重新启动 {0}"
#: pmg-gui/js/MailProxyDKIMPanel.js:6
msgid "Sign Domain"
@@ -14138,7 +13832,7 @@ msgstr "模拟"
#: proxmox-widget-toolkit/src/panel/LogView.js:324
#: pmg-gui/js/QuarantineList.js:320 proxmox-yew-comp/src/tasks.rs:417
msgid "Since"
-msgstr "有效期自"
+msgstr "自"
#: pve-manager/www/manager6/node/ZFS.js:75
#: proxmox-backup/www/window/ZFSCreate.js:44
@@ -14147,12 +13841,11 @@ msgstr "单磁盘"
#: pmg-gui/js/DNSBLSitesField.js:149
msgid "Site"
-msgstr ""
+msgstr "站点"
#: pmg-gui/js/DNSBLSitesField.js:72
-#, fuzzy
msgid "Site must not be empty."
-msgstr "标签不能为空。"
+msgstr "站点不能为空。"
#: proxmox-widget-toolkit/src/form/DiskSelector.js:30
#: proxmox-widget-toolkit/src/form/MultiDiskSelector.js:112
@@ -14195,7 +13888,7 @@ msgstr "跳过证书验证"
#: proxmox-backup/www/window/S3ClientEdit.js:146
msgid "Skip If-None-Match header"
-msgstr ""
+msgstr "跳过 If-None-Match 头部"
#: proxmox-backup/www/config/VerifyView.js:233
#: proxmox-backup/www/window/VerifyAll.js:80
@@ -14214,7 +13907,7 @@ msgstr "跳过复制"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:389
#: proxmox-yew-comp/src/configuration/network_edit.rs:223
msgid "Slaves"
-msgstr "从属"
+msgstr "从属设备"
#: pve-manager/www/manager6/window/GuestImport.js:819
msgid "Slot"
@@ -14260,20 +13953,19 @@ msgid "Snapshots"
msgstr "快照"
#: pve-manager/www/manager6/storage/Base.js:106
-#, fuzzy
msgid "Snapshots as Volume-Chain are a technology preview."
-msgstr "存储管理快照是一种技术预览。"
+msgstr "Snapshots as Volume-Chain 是技术预览功能。"
#: pve-manager/www/manager6/Utils.js:698
#: pve-manager/www/manager6/storage/Browser.js:125
#: proxmox-datacenter-manager/ui/src/pve/utils.rs:295
msgid "Snippets"
-msgstr "片段"
+msgstr "配置片段"
#: proxmox-widget-toolkit/src/Schema.js:97
#: proxmox-widget-toolkit/src/Utils.js:1160
msgid "Socket"
-msgstr "插槽"
+msgstr "套接字"
#: proxmox-widget-toolkit/src/Utils.js:1160 pmg-gui/js/Subscription.js:138
#: pve-manager/www/manager6/node/Subscription.js:136
@@ -14283,7 +13975,7 @@ msgstr "插槽"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_processor_property.rs:82
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_processor_property.rs:179
msgid "Sockets"
-msgstr "插槽"
+msgstr "CPU 插槽数"
#: proxmox-widget-toolkit/src/Schema.js:95
msgid "Softlink"
@@ -14300,11 +13992,11 @@ msgstr "部分套件配置错误"
#: proxmox-yew-widget-toolkit/src/widget/data_table/header_widget.rs:630
msgid "Sort Ascending"
-msgstr ""
+msgstr "升序排序"
#: proxmox-yew-widget-toolkit/src/widget/data_table/header_widget.rs:638
msgid "Sort Descending"
-msgstr ""
+msgstr "降序排序"
#: pve-manager/www/manager6/window/TreeSettingsEdit.js:22
msgid "Sort Key"
@@ -14359,7 +14051,7 @@ msgstr "源端口"
#: proxmox-yew-comp/src/configuration/network_edit.rs:156
#: proxmox-yew-comp/src/configuration/network_edit.rs:225
msgid "Space-separated list of interfaces, for example: enp0s0 enp1s0"
-msgstr "以空格分隔的接口列表,例如:enp0s0 enp1s0"
+msgstr "以空格分隔的网络接口列表,例如:enp0s0 enp1s0"
#: pmg-gui/js/DomainStatistics.js:105 pmg-gui/js/ReceiverStatistics.js:179
msgid "Spam"
@@ -14509,14 +14201,12 @@ msgid "Start at boot"
msgstr "开机自启动"
#: pve-yew-mobile-gui/src/widgets/guest_backup_panel.rs:101
-#, fuzzy
msgid "Start backup now"
-msgstr "立即备份"
+msgstr "立即开始备份"
#: proxmox-yew-comp/src/form/pve/qemu_property/mod.rs:128
-#, fuzzy
msgid "Start on boot"
-msgstr "开机自启动"
+msgstr "开机启动"
#: pve-manager/www/manager6/node/NodeOptionsView.js:48
msgid "Start on boot delay"
@@ -14730,7 +14420,7 @@ msgstr "停止 OSD"
#: pve-manager/www/manager6/qemu/CmdMenu.js:98
#: pve-manager/www/manager6/qemu/Config.js:206
msgid "Stop {0} immediately"
-msgstr "立即停止{0}"
+msgstr "立即停止 {0}"
#: pve-manager/www/manager6/ceph/Services.js:178
#: pve-manager/www/manager6/dc/Guests.js:58
@@ -14770,14 +14460,12 @@ msgid "Storage"
msgstr "存储"
#: proxmox-datacenter-manager/ui/src/pve/storage.rs:234
-#, fuzzy
msgid "Storage '{0}'"
-msgstr "存储"
+msgstr "存储 '{0}'"
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:314
-#, fuzzy
msgid "Storage (Proxmox VE)"
-msgstr "Proxmox VE"
+msgstr "存储 (Proxmox VE)"
#: proxmox-backup/www/NavigationTree.js:105
#: proxmox-backup/www/panel/StorageAndDisks.js:6
@@ -14790,9 +14478,8 @@ msgstr "存储保留配置"
#: pve-yew-mobile-gui/src/widgets/mod.rs:53
#: proxmox-yew-comp/src/form/pve/pve_storage_selector.rs:244
-#, fuzzy
msgid "Storage size/usage unknown"
-msgstr "存储使用"
+msgstr "存储大小/使用情况未知"
#: proxmox-backup/www/datastore/Summary.js:341
msgid "Storage usage"
@@ -14811,22 +14498,21 @@ msgid ""
"Storage(s) ({0}) not available on selected target. Start VM to use live "
"storage migration or select other target node."
msgstr ""
-"所选目标上的存储({0}) 不可用。启动虚拟机以使用实时存储迁移或选择其他目标节"
+"所选目标上的存储 ({0}) 不可用。启动虚拟机以使用实时存储迁移或选择其他目标节"
"点。"
#: pve-manager/www/manager6/ha/rules/NodeAffinityRuleEdit.js:129
#: pve-manager/www/manager6/ha/rules/NodeAffinityRules.js:15
-#, fuzzy
msgid "Strict"
-msgstr "受限制的"
+msgstr "严格"
#: pve-manager/www/manager6/qemu/PCIEdit.js:332
msgid "Sub-Device ID"
-msgstr "设备"
+msgstr "子设备 SD"
#: pve-manager/www/manager6/qemu/PCIEdit.js:323
msgid "Sub-Vendor ID"
-msgstr "子供应商"
+msgstr "子供应商 ID"
#: pve-manager/www/manager6/storage/CIFSEdit.js:226
msgid "Subdirectory"
@@ -14854,7 +14540,7 @@ msgstr "主题"
#: proxmox-yew-comp/src/acme/certificate_list.rs:360
#: proxmox-yew-comp/src/acme/certificate_list.rs:417
msgid "Subject Alternative Names"
-msgstr "主题替代名称"
+msgstr "主题备用名称"
#: pmg-gui/js/QuarantineList.js:378
msgid "Subject, Sender"
@@ -14862,7 +14548,7 @@ msgstr "主题,发送者"
#: proxmox-yew-widget-toolkit/src/widget/form/submit_button.rs:162
msgid "Submit"
-msgstr ""
+msgstr "提交"
#: pve-manager/www/manager6/sdn/SubnetEdit.js:26
#: pve-manager/www/manager6/sdn/SubnetEdit.js:241
@@ -14900,30 +14586,28 @@ msgid "Subscription Key"
msgstr "订阅密钥"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:590
-#, fuzzy
msgid "Subscription Panel"
-msgstr "订阅密钥"
+msgstr "订阅面板"
#: proxmox-datacenter-manager/ui/src/configuration/subscription_panel.rs:184
msgid "Subscription Ratio (Basic or Higher): {0} ({1} {2})"
-msgstr ""
+msgstr "订阅比率(基础或更高):{0} ({1} {2})"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:176
-#, fuzzy
msgid "Subscription Status"
-msgstr "订阅"
+msgstr "订阅状态"
#: proxmox-yew-comp/src/subscription_info.rs:24
msgid "Subscription got (recently) suspended"
-msgstr ""
+msgstr "订阅(最近)被暂停"
#: proxmox-yew-comp/src/subscription_info.rs:23
msgid "Subscription set but expired for this server."
-msgstr ""
+msgstr "订阅已设置但对此服务器已过期。"
#: proxmox-yew-comp/src/subscription_info.rs:22
msgid "Subscription set but invalid for this server."
-msgstr ""
+msgstr "订阅已设置但对此服务器无效。"
#: pve-manager/www/manager6/dc/Summary.js:58
msgid "Subscriptions"
@@ -14989,7 +14673,7 @@ msgstr "支持"
#: proxmox-widget-toolkit/src/panel/EOLNotice.js:41
msgid "Support for {0} {1} ends on {2}"
-msgstr "对 {0} {1} 的支持将于 {2} 结束"
+msgstr "对 {0} {1} 的支持将于 {2} 终止"
#: pve-manager/www/manager6/Utils.js:2171
#: pve-manager/www/manager6/dc/BackupJobDetail.js:256
@@ -15033,15 +14717,15 @@ msgstr "瑞典语"
#: pmg-yew-quarantine-gui/src/page_spam_list.rs:301
msgid "Switch to Desktop View"
-msgstr ""
+msgstr "切换到桌面视图"
#: pmg-gui/js/QuarantineView.js:310
msgid "Switch to Mobile View"
-msgstr ""
+msgstr "切换到移动视图"
#: pmg-gui/js/QuarantineView.js:245
msgid "Switch to mobile view"
-msgstr ""
+msgstr "切换到移动视图"
#: proxmox-widget-toolkit/src/panel/AuthView.js:160
#: proxmox-widget-toolkit/src/window/SyncWindow.js:150
@@ -15054,9 +14738,8 @@ msgid "Sync"
msgstr "同步"
#: proxmox-yew-comp/src/auth_view.rs:132
-#, fuzzy
msgid "Sync Failed"
-msgstr "失败"
+msgstr "同步失败"
#: proxmox-backup/www/Utils.js:456
msgid "Sync Job"
@@ -15158,7 +14841,7 @@ msgstr "TB"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:134
#: proxmox-yew-comp/src/firewall/options_edit.rs:471
msgid "TCP Flags Log Level"
-msgstr ""
+msgstr "TCP 标志日志级别"
#: pve-manager/www/manager6/dc/MetricServerView.js:512
msgid "TCP Timeout"
@@ -15166,9 +14849,8 @@ msgstr "TCP 超时"
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:208
#: proxmox-yew-comp/src/firewall/options_edit.rs:432
-#, fuzzy
msgid "TCP Timeout Established"
-msgstr "TCP 超时"
+msgstr "TCP 超时已建立"
#: pve-manager/www/manager6/grid/FirewallOptions.js:74
#: proxmox-yew-comp/src/form/pve/firewall_property/mod.rs:83
@@ -15185,19 +14867,18 @@ msgid "TFA Lock"
msgstr "TFA 锁定"
#: proxmox-yew-comp/src/tfa/tfa_confirm_remove.rs:97
-#, fuzzy
msgid "TFA Removal"
-msgstr "确认移除 TFA"
+msgstr "删除双因素认证"
#: proxmox-widget-toolkit/src/panel/TfaView.js:232
#: proxmox-yew-comp/src/tfa/tfa_view.rs:395
msgid "TFA Type"
-msgstr "TFA 类型"
+msgstr "双因素认证类型"
#: proxmox-widget-toolkit/src/window/AddTfaRecovery.js:9
#: proxmox-yew-comp/src/tfa/tfa_add_recovery.rs:223
msgid "TFA recovery keys"
-msgstr "TFA 还原密钥"
+msgstr "双因素认证恢复密钥"
#: pmg-gui/js/MailProxyConfiguration.js:43
msgid "TLS"
@@ -15226,7 +14907,7 @@ msgstr "TOTP"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:370
msgid "TOTP App"
-msgstr "TOTP App"
+msgstr "TOTP 应用"
#: pmg-gui/js/UserView.js:226 pve-manager/www/manager6/dc/UserView.js:231
#: proxmox-backup/www/config/UserView.js:265
@@ -15235,11 +14916,11 @@ msgstr "TOTP 锁定"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:522
msgid "TOTP codes consist of six decimal digits"
-msgstr "TOTP 码由六位十进制数字组成"
+msgstr "TOTP 验证码由六位数字组成"
#: proxmox-widget-toolkit/src/window/TfaWindow.js:386
msgid "TOTP codes usually consist of six decimal digits"
-msgstr "TOTP 代码通常由六位十进制数字组成"
+msgstr "TOTP 验证码通常为六位数字"
#: pve-manager/www/manager6/qemu/HDTPM.js:81
#: pve-manager/www/manager6/qemu/HardwareView.js:289
@@ -15387,9 +15068,8 @@ msgid "Target Datastore"
msgstr "目标数据存储"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:390
-#, fuzzy
msgid "Target Endpoint"
-msgstr "端点名称"
+msgstr "目标端点"
#: pve-manager/www/manager6/qemu/HDEdit.js:645
#: pve-manager/www/manager6/window/GuestDiskReassign.js:138
@@ -15410,12 +15090,10 @@ msgid "Target Namespace"
msgstr "目标命名空间"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:478
-#, fuzzy
msgid "Target Network"
-msgstr "信任网络"
+msgstr "目标网络"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:379
-#, fuzzy
msgid "Target Node"
msgstr "目标节点"
@@ -15447,9 +15125,8 @@ msgid "Target Storage"
msgstr "目标存储"
#: proxmox-datacenter-manager/ui/src/widget/migrate_window.rs:442
-#, fuzzy
msgid "Target VMID"
-msgstr "目标"
+msgstr "目标 VMID"
#: pve-manager/www/manager6/storage/ZFSEdit.js:82
msgid "Target group"
@@ -15471,7 +15148,7 @@ msgstr "目标存储"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:128
msgid "Targets to notify"
-msgstr "要通知的目标"
+msgstr "待通知目标"
#: proxmox-widget-toolkit/src/window/TaskViewer.js:61
#: proxmox-backup/www/dashboard/LongestTasks.js:80
@@ -15494,16 +15171,14 @@ msgid "Task ID"
msgstr "任务 ID"
#: pve-yew-mobile-gui/src/widgets/task_list_button.rs:173
-#, fuzzy
msgid "Task List"
-msgstr "任务历史"
+msgstr "任务列表"
#: proxmox-widget-toolkit/src/node/Tasks.js:352
msgid "Task Result"
msgstr "任务结果"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:624
-#, fuzzy
msgid "Task Summaries"
msgstr "任务摘要"
@@ -15514,29 +15189,24 @@ msgid "Task Summary"
msgstr "任务摘要"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:632
-#, fuzzy
msgid "Task Summary Sorted by Failed Tasks"
-msgstr "任务摘要(上个月)"
+msgstr "按照失败任务排序的任务摘要"
#: proxmox-datacenter-manager/ui/src/dashboard/tasks.rs:315
-#, fuzzy
msgid "Task Summary Sorted by Failed Tasks (Last {0}h)"
-msgstr "任务摘要(上个月)"
+msgstr "按照失败任务(最近{0}小时)排序的任务摘要"
#: proxmox-datacenter-manager/ui/src/dashboard/refresh_config_edit.rs:99
-#, fuzzy
msgid "Task Summary Time Range (last hours)"
-msgstr "任务摘要(上个月)"
+msgstr "任务摘要的时间区间(最近小时数)"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:626
-#, fuzzy
msgid "Task Summary by Category"
-msgstr "任务摘要(上个月)"
+msgstr "按类别显示的任务摘要"
#: proxmox-datacenter-manager/ui/src/dashboard/tasks.rs:316
-#, fuzzy
msgid "Task Summary by Category (Last {0}h)"
-msgstr "任务摘要(上个月)"
+msgstr "按照类型陈列的任务摘要(最近{0}小时)"
#: proxmox-widget-toolkit/src/node/Tasks.js:344
#: proxmox-yew-comp/src/tasks.rs:423
@@ -15544,9 +15214,8 @@ msgid "Task Type"
msgstr "任务类型"
#: proxmox-yew-comp/src/task_viewer.rs:162
-#, fuzzy
msgid "Task Viewer"
-msgstr "标签视图"
+msgstr "任务查看器"
#: proxmox-widget-toolkit/src/window/TaskViewer.js:125
#: pve-yew-mobile-gui/src/pages/page_task_status.rs:142
@@ -15579,7 +15248,6 @@ msgid "Templates"
msgstr "模板"
#: proxmox-yew-comp/src/acme/acme_register_account.rs:128
-#, fuzzy
msgid "Terms Of Service"
msgstr "服务条款"
@@ -15612,46 +15280,46 @@ msgstr "文本替换"
#: pve-manager/www/manager6/ha/RuleErrorsModal.js:17
msgid "The HA rule has no errors."
-msgstr ""
+msgstr "该 HA 规则没有错误。"
#: pve-manager/www/manager6/ha/RuleErrorsModal.js:29
msgid "The HA rule has the following errors:"
-msgstr ""
+msgstr "该 HA 规则存在以下错误:"
#: pve-manager/www/manager6/ceph/Pool.js:215
msgid ""
"The amount of data eventually stored in this pool. Used for auto-scaling."
-msgstr "最终存储在该池中的数据量。用于自动缩放。"
+msgstr "最终存储在该池中的数据规模。用于规划自动缩放。"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_connect.rs:93
-#, fuzzy
msgid "The certificate of the remote server is not trusted."
-msgstr "验证服务器的TLS证书"
+msgstr "远程服务器的证书不受信任。"
#: pve-manager/www/manager6/tree/SnapshotTree.js:312
msgid "The current guest configuration does not support taking new snapshots"
-msgstr "当前的来宾配置不支持拍摄新快照"
+msgstr "当前客户机配置不支持创建新快照"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:164
msgid ""
"The enterprise repository is enabled, but there is no active subscription!"
-msgstr "企业仓库已启用,但没有激活订阅!"
+msgstr "已启用企业版软件源,但没有有效的订阅!"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_nodes.rs:65
msgid "The following certificates of remote servers are not trusted."
-msgstr ""
+msgstr "以下远程服务器的证书不受信任。"
#: proxmox-datacenter-manager/ui/src/dashboard/view/row_view.rs:342
msgid ""
"The layout is empty. To add widgets, enable editing by clicking the {0} icon "
"above."
-msgstr ""
+msgstr "布局为空。要添加小部件,请单击上方的 {0} 图标启用编辑。"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:182
msgid ""
"The manual repository option expects that the repository is already "
"configured. For example, in combination with the Proxmox Offline Mirror."
msgstr ""
+"手动软件源选项要求软件源已经配置完成。例如,可与 Proxmox 离线镜像结合使用。"
#: proxmox-backup/www/window/SyncJobEdit.js:444
msgid "The maximum amount of snapshots to be transferred (per group)"
@@ -15659,24 +15327,25 @@ msgstr "要传输的快照的最大数量(每组)"
#: pve-manager/www/manager6/ceph/Status.js:66
msgid "The newest version installed in the Cluster."
-msgstr "群集中安装的是最新版本。"
+msgstr "集群中已安装最新版本。"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:305
#: proxmox-yew-comp/src/apt_repositories.rs:937
msgid "The no-subscription repository is NOT production-ready"
-msgstr "无订阅存储库未做好为生产准备"
+msgstr "无订阅软件源不适合生产环境"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:178
msgid ""
"The no-subscription repository is not the best choice for production setups."
-msgstr "无订阅存储库不是生产设置的最佳选择。"
+msgstr "无订阅的软件源并非生产环境的上选。"
#: pve-manager/www/manager6/panel/BackupAdvancedOptions.js:302
msgid ""
"The node-specific 'vzdump.conf' or, if this is not set, the default from the "
"config schema is used to determine fallback values."
msgstr ""
-"如果未设置,则使用节点特定的 'vzdump.conf' 或配置模式的默认值来确定后备值。"
+"如果未设置,则使用节点特定的 'vzdump.conf' 或配置模式的默认值来确定后备值。如"
+"果未设置,则使用节点特定的 'vzdump.conf' 或配置模式的默认值来确定后备值。"
#: pve-manager/www/manager6/dc/Backup.js:405
msgid "The notes are added to each backup created by this job."
@@ -15684,13 +15353,13 @@ msgstr "注释将添加到此作业创建的每个备份中。"
#: proxmox-widget-toolkit/src/panel/EmailRecipientPanel.js:43
msgid "The notification will be sent to the user's configured mail address"
-msgstr "通知将发送到用户配置的邮件地址"
+msgstr "通知将发送至用户配置的邮箱"
#: pve-manager/www/manager6/ceph/Pool.js:198
msgid ""
"The ratio of storage amount this pool will consume compared to other pools "
"with ratios. Used for auto-scaling."
-msgstr "与其他具有比率的池相比,该池将消耗的存储量的比率。 用于自动缩放。"
+msgstr "存储池预期占用集群总容量的比例,用于规划自动扩展。"
#: pve-manager/www/manager6/qemu/HardwareView.js:211
msgid "The saved VM state will be permanently lost."
@@ -15703,32 +15372,32 @@ msgid ""
"Enterprise Repository is not yet available."
msgstr ""
"所选版本目前被视为技术预览版。虽然我们没有发现任何重大问题,但可能存在一些错"
-"误,企业存储库尚未可用。"
+"误,对应的企业版软件源尚不可用。"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:306
#: proxmox-yew-comp/src/apt_repositories.rs:941
msgid "The test repository may contain unstable updates"
-msgstr "测试存储库可能包含不稳定的更新"
+msgstr "测试软件源可能包含不稳定的更新"
#: pve-manager/www/manager6/ceph/CephInstallWizard.js:186
msgid ""
"The test repository should only be used for test setups or after consulting "
"the official Proxmox support!"
-msgstr "测试存储库只能用于测试设置或在咨询官方Proxmox支持后使用!"
+msgstr "测试软件源只能用于测试环境或在咨询官方Proxmox支持后使用!"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:505
#: proxmox-yew-comp/src/apt_repositories.rs:249
#: proxmox-yew-comp/src/apt_repositories.rs:272
msgid ""
"The {0}enterprise repository is enabled, but there is no active subscription!"
-msgstr "{0}企业存储库已启用,但没有活动订阅!"
+msgstr "已启用 {0}企业版软件源,但无有效订阅!"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:516
#: proxmox-yew-comp/src/apt_repositories.rs:256
#: proxmox-yew-comp/src/apt_repositories.rs:279
msgid ""
"The {0}no-subscription{1} repository is not recommended for production use!"
-msgstr "不建议将无订阅存储库 {0}no-subscription{1} 用于生产!"
+msgstr "不建议在生产环境中使用 {0}无订阅{1} 软件源!"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:528
#: proxmox-yew-comp/src/apt_repositories.rs:264
@@ -15736,7 +15405,7 @@ msgstr "不建议将无订阅存储库 {0}no-subscription{1} 用于生产!"
msgid ""
"The {0}test repository may pull in unstable updates and is not recommended "
"for production use!"
-msgstr "{0} 测试存储库可能会引入不稳定的更新,不建议用于生产!"
+msgstr "{0}测试软件源可能引入不稳定的更新,不建议用于生产!"
#: proxmox-datacenter-manager/ui/src/top_nav_bar.rs:166
#: pve-yew-mobile-gui/src/pages/page_settings.rs:40
@@ -15745,14 +15414,12 @@ msgid "Theme"
msgstr "主题"
#: proxmox-yew-comp/src/theme_dialog.rs:57
-#, fuzzy
msgid "Theme mode"
-msgstr "NAT模式"
+msgstr "主题模式"
#: proxmox-yew-comp/src/theme_dialog.rs:53
-#, fuzzy
msgid "Theme name"
-msgstr "令牌名称"
+msgstr "主题名称"
#: pve-manager/www/manager6/storage/LvmThinEdit.js:167
msgid "Thin Pool"
@@ -15761,16 +15428,16 @@ msgstr "精简池"
#: pve-manager/www/manager6/storage/ZFSEdit.js:101
#: pve-manager/www/manager6/storage/ZFSPoolEdit.js:101
msgid "Thin provision"
-msgstr "精简配置"
+msgstr "精简制备"
#: proxmox-widget-toolkit/src/Toolkit.js:145
msgid "This is not a valid CpuSet"
-msgstr "这不是有效的CpuSet"
+msgstr "无效的 CpuSet"
#: proxmox-widget-toolkit/src/Toolkit.js:150
#: proxmox-widget-toolkit/src/Toolkit.js:155
msgid "This is not a valid hostname"
-msgstr "这不是有效的主机名"
+msgstr "该主机名无效"
#: pve-manager/www/manager6/qemu/DisplayEdit.js:124
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_display_property.rs:128
@@ -15785,14 +15452,12 @@ msgid "This will permanently erase all data."
msgstr "这将永久删除所有数据。"
#: pve-manager/www/manager6/window/Restore.js:100
-#, fuzzy
msgid "This will permanently erase current CT data."
-msgstr "这将永久删除当前的{0}数据。"
+msgstr "这将永久删除当前容器数据。"
#: pve-manager/www/manager6/window/Restore.js:103
-#, fuzzy
msgid "This will permanently erase current VM data."
-msgstr "这将永久删除当前的{0}数据。"
+msgstr "这将永久删除当前虚拟机数据。"
#: proxmox-backup/www/window/NamespaceEdit.js:92
msgid ""
@@ -15852,7 +15517,7 @@ msgstr "时间步长"
#: proxmox-widget-toolkit/src/window/AddTotp.js:201
msgid "Time period"
-msgstr "时区段"
+msgstr "时间周期"
#: proxmox-widget-toolkit/src/node/TimeEdit.js:5
#: proxmox-widget-toolkit/src/node/TimeEdit.js:17
@@ -15883,7 +15548,7 @@ msgstr "超时(秒)"
#: proxmox-widget-toolkit/src/window/NotificationMatcherEdit.js:995
msgid "Timespan to match"
-msgstr "要匹配的时间跨度"
+msgstr "要匹配的时间范围"
#: pve-manager/www/manager6/window/Snapshot.js:77
msgid "Timestamp"
@@ -15891,7 +15556,7 @@ msgstr "时间戳"
#: proxmox-widget-toolkit/src/window/AddYubico.js:131
msgid "Tip:"
-msgstr "提示:"
+msgstr "提示:"
#: pmg-gui/js/MailTracker.js:379 pmg-gui/js/ObjectGroupSelector.js:26
#: pmg-gui/js/RuleInfo.js:456 pmg-gui/js/Utils.js:59
@@ -15912,9 +15577,8 @@ msgid ""
msgstr "要使用这些功能,请在虚拟机的硬件设置中将显示设置为SPICE。"
#: pmg-yew-quarantine-gui/src/page_spam_list.rs:93
-#, fuzzy
msgid "To:"
-msgstr "到"
+msgstr "收件人:"
#: pmg-gui/js/AttachmentQuarantine.js:116 pmg-gui/js/SpamQuarantine.js:226
#: pmg-gui/js/VirusQuarantine.js:129
@@ -15951,9 +15615,8 @@ msgid "Token Name"
msgstr "令牌名称"
#: proxmox-datacenter-manager/ui/src/configuration/mod.rs:123
-#, fuzzy
msgid "Token Permission"
-msgstr "API 令牌权限"
+msgstr "令牌权限"
#: pve-manager/www/manager6/dc/TokenEdit.js:116
#: proxmox-backup/www/window/TokenEdit.js:166
@@ -15969,7 +15632,7 @@ msgstr "令牌名称"
#: pve-manager/www/manager6/grid/FirewallRules.js:309
#: pve-manager/www/manager6/grid/FirewallRules.js:319
msgid "Too long, consider using IP sets."
-msgstr "太长了,请考虑使用IP集。"
+msgstr "长度超长,请考虑使用IP集。"
#: pve-manager/www/manager6/window/GuestImport.js:179
msgid "Too many disks, could not map to SATA."
@@ -15979,14 +15642,14 @@ msgstr "磁盘太多,无法映射到 SATA。"
msgid ""
"Too many remote nodes without active basic or higher subscription. Please "
"visit {0} for more details."
-msgstr ""
+msgstr "太多远程节点没有激活的基础版或更高级别订阅。请访问 {0} 了解更多详情。"
#. only get here if there are remotes and PDM-subscription failed.
#: proxmox-datacenter-manager/ui/src/dashboard/status_row.rs:262
msgid ""
"Too many remote nodes without basic or higher subscriptions! No access to "
"Enterprise-Repository or Enterprise Support."
-msgstr ""
+msgstr "太多远程节点没有基础版或更高级别的订阅!无法访问企业软件源或企业支持。"
#: pmg-gui/js/Dashboard.js:454
msgid "Top Receivers"
@@ -16009,15 +15672,15 @@ msgstr "最受好评"
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:175
#: proxmox-datacenter-manager/ui/src/pve/storage.rs:191
msgid "Total"
-msgstr "总额"
+msgstr "总计"
#: pve-manager/www/manager6/data/ResourceStore.js:228
msgid "Total Disk Read"
-msgstr "磁盘读取总额"
+msgstr "磁盘读取总数据量"
#: pve-manager/www/manager6/data/ResourceStore.js:236
msgid "Total Disk Write"
-msgstr "磁盘写入总额"
+msgstr "磁盘写入总数据量"
#: pmg-gui/js/GeneralMailStatistics.js:159
#: pmg-gui/js/GeneralMailStatistics.js:163
@@ -16030,17 +15693,16 @@ msgstr "邮件总额"
#: proxmox-datacenter-manager/ui/src/pbs/node/overview.rs:149
#: proxmox-datacenter-manager/ui/src/pve/node/overview.rs:154
-#, fuzzy
msgid "Total Memory"
-msgstr "核心总数"
+msgstr "总内存"
#: pve-manager/www/manager6/data/ResourceStore.js:244
msgid "Total NetIn"
-msgstr "流入总额"
+msgstr "流入总数据量"
#: pve-manager/www/manager6/data/ResourceStore.js:252
msgid "Total NetOut"
-msgstr "流出总额"
+msgstr "流出总数据量"
#: pve-manager/www/manager6/qemu/ProcessorEdit.js:147
#: pve-manager/www/manager6/window/GuestImport.js:551
@@ -16081,9 +15743,8 @@ msgid "Transfer Rate (bytes/second)"
msgstr "传输速率(字节/秒)"
#: proxmox-yew-widget-toolkit/src/widget/language_selector.rs:204
-#, fuzzy
msgid "Translated"
-msgstr "转移"
+msgstr "已翻译"
#: pmg-gui/js/Transport.js:154
msgid "Transport"
@@ -16203,17 +15864,16 @@ msgstr "二次验证"
#: proxmox-yew-comp/src/subscription_panel.rs:196
#: proxmox-yew-comp/src/tfa/tfa_confirm_remove.rs:52
msgid "Type"
-msgstr "类别"
+msgstr "类型"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:285
-#, fuzzy
msgid "Type / Name"
-msgstr "测试名"
+msgstr "类型 / 名称"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:249
#: proxmox-yew-comp/src/apt_repositories.rs:814
msgid "Types"
-msgstr "类别"
+msgstr "类型"
#: pve-manager/www/manager6/dc/OptionView.js:224
msgid "U2F AppID URL"
@@ -16233,16 +15893,16 @@ msgstr "U2F已弃用,请使用WebAuthn"
#: proxmox-yew-comp/src/node_info.rs:258
msgid "UEFI"
-msgstr ""
+msgstr "UEFI"
#: proxmox-yew-comp/src/node_info.rs:257
msgid "UEFI (Secure Boot Enabled)"
-msgstr ""
+msgstr "UEFI(已启用安全启动)"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:257
#: proxmox-yew-comp/src/apt_repositories.rs:818
msgid "URIs"
-msgstr "URIs"
+msgstr "URI"
#: proxmox-widget-toolkit/src/window/ACMEAccount.js:59
#: pve-manager/www/manager6/node/ACME.js:75
@@ -16275,24 +15935,22 @@ msgstr "乌克兰语"
#: proxmox-yew-comp/src/configuration/network_view.rs:184
msgid "Unable to apply changes"
-msgstr ""
+msgstr "无法应用更改"
#: proxmox-datacenter-manager/ui/src/remotes/config.rs:164
#: proxmox-yew-comp/src/auth_view.rs:234
#: proxmox-yew-comp/src/configuration/network_view.rs:158
#: proxmox-yew-comp/src/tfa/tfa_view.rs:233
msgid "Unable to delete item"
-msgstr ""
+msgstr "无法删除项目"
#: proxmox-yew-comp/src/user_panel.rs:167
-#, fuzzy
msgid "Unable to delete user"
-msgstr "启用新用户"
+msgstr "无法删除用户"
#: proxmox-yew-comp/src/subscription_info.rs:27
-#, fuzzy
msgid "Unable to get the subscription status (API problems)."
-msgstr "无法加载订阅状态"
+msgstr "无法获取订阅状态(API 问题)。"
#: pve-manager/www/manager6/dc/Support.js:67
msgid "Unable to load subscription status"
@@ -16303,9 +15961,8 @@ msgid "Unable to parse network configuration"
msgstr "无法解析网络配置"
#: proxmox-yew-comp/src/configuration/network_view.rs:173
-#, fuzzy
msgid "Unable to revert changes"
-msgstr "无法解析驱动器选项"
+msgstr "无法恢复更改"
#: proxmox-widget-toolkit/src/panel/GotifyEditPanel.js:39
#: proxmox-widget-toolkit/src/panel/SmtpEditPanel.js:40
@@ -16320,16 +15977,15 @@ msgstr "无法解析驱动器选项"
#: proxmox-datacenter-manager/ui/src/remotes/edit_remote.rs:113
#: proxmox-yew-comp/src/auth_edit_ldap.rs:367
msgid "Unchanged"
-msgstr "未更改"
+msgstr "保持不变"
#: proxmox-datacenter-manager/ui/src/dashboard/pbs_datastores_panel.rs:119
-#, fuzzy
msgid "Under Maintenance"
-msgstr "维护模式"
+msgstr "维护中"
#: proxmox-widget-toolkit/src/panel/RRDChart.js:288
msgid "Undo Zoom"
-msgstr "撤消缩放"
+msgstr "撤销缩放"
#: pve-manager/www/manager6/window/Restore.js:226
msgid "Unique"
@@ -16372,9 +16028,8 @@ msgid "Unknown"
msgstr "未知"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:442
-#, fuzzy
msgid "Unknown ({0})"
-msgstr "未知"
+msgstr "未知({0})"
#: pmg-gui/js/LDAPGroupEditor.js:71 pmg-gui/js/LDAPGroupEditor.js:72
msgid "Unknown LDAP address"
@@ -16391,9 +16046,8 @@ msgstr "未知错误"
#: proxmox-datacenter-manager/ui/src/dashboard/subscription_info.rs:64
#: proxmox-datacenter-manager/ui/src/dashboard/subscription_info.rs:77
-#, fuzzy
msgid "Unknown subscriptions"
-msgstr "没有订阅"
+msgstr "未知订阅"
#: pve-manager/www/manager6/window/GuestImport.js:1032
msgid "Unknown warning"
@@ -16442,14 +16096,12 @@ msgid "Unmount Device"
msgstr "卸载设备"
#: proxmox-backup/www/window/SyncJobEdit.js:524
-#, fuzzy
msgid "Unmount relevant removable datastore once sync job finishes."
-msgstr "未挂载可移动数据存储"
+msgstr "一旦同步完成即卸载相关的可移除数据存储。"
#: proxmox-backup/www/window/SyncJobEdit.js:520
-#, fuzzy
msgid "Unmount when done"
-msgstr "卸载设备"
+msgstr "完成后卸载"
#: proxmox-backup/www/Utils.js:850
#: proxmox-backup/www/window/MaintenanceOptions.js:96
@@ -16476,13 +16128,12 @@ msgstr "无特权的容器"
#: proxmox-widget-toolkit/src/panel/LogView.js:343
#: pmg-gui/js/QuarantineList.js:327
msgid "Until"
-msgstr "至"
+msgstr "截止时间"
#. second row
#: proxmox-yew-comp/src/tasks.rs:431
-#, fuzzy
msgid "Until:"
-msgstr "至"
+msgstr "直到:"
#: pve-manager/www/manager6/window/GuestDiskReassign.js:205
msgid "Unused"
@@ -16497,18 +16148,16 @@ msgid "Unused Disk"
msgstr "未使用的磁盘"
#: proxmox-yew-comp/src/form/pve/lxc_property/lxc_mount_point_property.rs:530
-#, fuzzy
msgid "Unused Volume"
-msgstr "移动卷"
+msgstr "未使用卷"
#: pve-manager/www/manager6/ceph/StatusDetail.js:47
msgid "Up"
msgstr "在线"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:679
-#, fuzzy
msgid "Up-to-date"
-msgstr "更新"
+msgstr "最新"
#: pmg-gui/js/DKIMSettings.js:154 pve-manager/www/manager6/Utils.js:2084
#: proxmox-datacenter-manager/ui/src/tasks.rs:15
@@ -16523,25 +16172,22 @@ msgid "Update Available"
msgstr "有可用的更新"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:596
-#, fuzzy
msgid "Update List"
-msgstr "更新"
+msgstr "更新列表"
#. TRANSLATORS: The first parameter is the name of the remote, the second one
#. the name of the node.
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:523
-#, fuzzy
msgid "Update List - {0} ({1})"
-msgstr "更新"
+msgstr "更新列表 - {0}({1})"
#: pmg-gui/js/SpamDetectorStatus.js:65
msgid "Update Now"
msgstr "现在更新"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:188
-#, fuzzy
msgid "Update Status"
-msgstr "设定状态"
+msgstr "更新状态"
#: pmg-gui/js/ClamAVDatabase.js:170
msgid "Update now"
@@ -16604,7 +16250,7 @@ msgstr "上传"
#: proxmox-yew-comp/src/acme/certificate_list.rs:120
#: proxmox-yew-comp/src/acme/certificate_list.rs:238
msgid "Upload Custom Certificate"
-msgstr "上传自定义凭证"
+msgstr "上传自定义证书"
#: pmg-gui/js/Subscription.js:4 pmg-gui/js/Subscription.js:154
#: pve-manager/www/manager6/node/Subscription.js:4
@@ -16723,9 +16369,8 @@ msgid "Use Proxmox VE managed hyper-converged cephFS"
msgstr "使用 Proxmox VE 管理超融合 cephFS"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_agent_property.rs:77
-#, fuzzy
msgid "Use QEMU Guest Agent"
-msgstr "Qemu 代理"
+msgstr "使用 QEMU Guest Agent"
#: pmg-gui/js/SpamDetectorOptions.js:18
msgid "Use RBL checks"
@@ -16762,18 +16407,16 @@ msgid "Use advanced statistic filters"
msgstr "使用高级统计过滤器"
#: pmg-gui/js/SpamDetectorOptions.js:10
-#, fuzzy
msgid "Use auto-welcomelists"
-msgstr "使用自动白名单"
+msgstr "使用 auto-welcomelists"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_info.rs:356
-#, fuzzy
msgid "Use existing Token"
-msgstr "复用现有数据存储"
+msgstr "使用现有令牌"
#: proxmox-datacenter-manager/ui/src/remotes/edit_remote.rs:121
msgid "Use first endpoint."
-msgstr ""
+msgstr "使用第一个端点。"
#: pve-manager/www/manager6/dc/BackupJobDetail.js:219
#: pve-manager/www/manager6/panel/BackupNotificationOptions.js:64
@@ -16801,7 +16444,7 @@ msgstr "中介设备"
#: proxmox-backup/www/window/S3ClientEdit.js:71
msgid "Use path style over vhost style bucket addressing."
-msgstr ""
+msgstr "使用路径样式而非虚拟主机样式的存储桶寻址。"
#: pve-manager/www/manager6/qemu/CDEdit.js:108
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_disk_property.rs:596
@@ -16834,9 +16477,8 @@ msgstr "使用特殊值 '1' 从基础网桥继承 MTU 值"
#: proxmox-datacenter-manager/ui/src/remotes/wizard_page_summary.rs:173
#: proxmox-datacenter-manager/ui/src/remotes/node_url_list.rs:276
-#, fuzzy
msgid "Use trusted certificate"
-msgstr "验证凭证"
+msgstr "使用受信任的证书"
#: pve-manager/www/manager6/ha/Fencing.js:23
msgid "Use watchdog based fencing."
@@ -16870,9 +16512,8 @@ msgstr "已用"
#: proxmox-datacenter-manager/ui/src/pbs/node/overview.rs:148
#: proxmox-datacenter-manager/ui/src/pve/node/overview.rs:153
-#, fuzzy
msgid "Used Memory"
-msgstr "内存"
+msgstr "已用内存"
#: pmg-gui/js/RuleInfo.js:313
msgid "Used Objects"
@@ -16921,18 +16562,17 @@ msgstr "用户"
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:24
#: proxmox-yew-comp/src/auth_edit_ldap.rs:310
msgid "User Attribute Name"
-msgstr "用户属性名称"
+msgstr "用户属性名"
#: pmg-gui/js/NavigationTree.js:134
-#, fuzzy
msgid "User Blocklist"
-msgstr "用户黑名单"
+msgstr "用户阻止列表"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:408
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:292
#: proxmox-yew-comp/src/auth_edit_ldap.rs:219
msgid "User Filter"
-msgstr "用户筛选"
+msgstr "用户过滤器"
#: pmg-gui/js/PBSConfig.js:162
msgid "User ID"
@@ -16969,19 +16609,18 @@ msgid "User Tag Access"
msgstr "用户标记访问"
#: pmg-gui/js/NavigationTree.js:128
-#, fuzzy
msgid "User Welcomelist"
-msgstr "用户白名单"
+msgstr "用户 welcomelist"
#: proxmox-widget-toolkit/src/window/AddTfaRecovery.js:108
msgid "User already has recovery keys."
-msgstr "用户已经具有还原密钥。"
+msgstr "用户已拥有恢复密钥。"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:393
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:278
#: proxmox-yew-comp/src/auth_edit_ldap.rs:213
msgid "User classes"
-msgstr "用户类别"
+msgstr "用户类"
#: proxmox-widget-toolkit/src/node/Tasks.js:430
#: proxmox-widget-toolkit/src/node/Tasks.js:515
@@ -17020,9 +16659,8 @@ msgid "User/Group/API Token"
msgstr "用户/组/API 令牌"
#: proxmox-datacenter-manager/ui/src/remotes/edit_remote.rs:103
-#, fuzzy
msgid "User/Token"
-msgstr "用户/组/API 令牌"
+msgstr "用户/令牌"
#: proxmox-widget-toolkit/src/panel/SmtpEditPanel.js:114
#: pmg-gui/js/FetchmailEdit.js:64 pmg-gui/js/PBSRemoteEdit.js:61
@@ -17060,7 +16698,7 @@ msgstr "用户和组"
#: pmg-gui/js/LDAPConfig.js:289 pmg-gui/js/LDAPConfig.js:472
msgid "Users of '{0}'"
-msgstr "'{0}' 的用户"
+msgstr "'{0}'的用户"
#: proxmox-widget-toolkit/src/panel/ACMEDomains.js:274
#: pve-manager/www/manager6/node/ACME.js:647
@@ -17079,15 +16717,15 @@ msgstr "VG 名称"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:101
msgid "VID range includes not-a-number: {0}"
-msgstr "VID 范围包括非数字:{0}"
+msgstr "VID 范围包含非数字:{0}"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:106
msgid "VID range must go from lower to higher tag: {0}"
-msgstr "VID 范围必须从较低标签到较高标签:{0}"
+msgstr "VID 范围必须从低到高排列:{0}"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:112
msgid "VID range outside of allowed 2 and 4094 limit: {0}"
-msgstr "VID 范围超出允许的 2 到 4094 限制:{0}"
+msgstr "VID 范围超出允许的 2 至 4094 限制:{0}"
#: pve-manager/www/manager6/sdn/VnetACLView.js:173
msgid "VLAN"
@@ -17104,7 +16742,7 @@ msgstr "VLAN ID"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:69
msgid "VLAN IDs"
-msgstr "VLAN IDs"
+msgstr "VLAN ID"
#: proxmox-widget-toolkit/src/form/VlanField.js:9
#: pve-manager/www/manager6/form/VLanField.js:9
@@ -17128,12 +16766,10 @@ msgid "VLAN raw device"
msgstr "VLAN 原始设备"
#: pve-manager/www/manager6/sdn/ZoneBridgeView.js:27
-#, fuzzy
msgid "VLAN-aware"
msgstr "VLAN 感知"
#: pve-manager/www/manager6/sdn/ZoneBridgesPanel.js:91
-#, fuzzy
msgid "VLANs"
msgstr "VLAN"
@@ -17144,9 +16780,8 @@ msgid "VM"
msgstr "VM"
#: proxmox-datacenter-manager/ui/src/pve/qemu/mod.rs:65
-#, fuzzy
msgid "VM '{0}'"
-msgstr "验证 '{0}'"
+msgstr "虚拟机 '{0}'"
#: pve-manager/www/manager6/storage/Browser.js:80
msgid "VM Disks"
@@ -17179,9 +16814,8 @@ msgid "VNC clipboard requires spice-tools installed in the Guest-VM."
msgstr "VNC 剪贴板需要在 Guest-VM 中安装 spice-tools。"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:312
-#, fuzzy
msgid "VNI"
-msgstr "VLAN ID"
+msgstr "VNI"
#: pve-manager/www/manager6/form/SDNVnetSelector.js:28
#: pve-manager/www/manager6/sdn/VnetEdit.js:123
@@ -17195,9 +16829,8 @@ msgid "VNet Firewall"
msgstr "VNet 防火墙"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_vnet.rs:75
-#, fuzzy
msgid "VNet ID"
-msgstr "VNet"
+msgstr "虚拟网络 ID"
#: pve-manager/www/manager6/sdn/zones/EvpnEdit.js:38
msgid "VNet MAC Address"
@@ -17205,7 +16838,7 @@ msgstr "VNet MAC 地址"
#: pve-manager/www/manager6/sdn/EvpnZoneMacVrfPanel.js:13
msgid "VNet MAC-VRF"
-msgstr ""
+msgstr "VNet MAC-VRF"
#: pve-manager/www/manager6/sdn/ZoneContentPanel.js:13
msgid "VNet Permissions"
@@ -17214,38 +16847,35 @@ msgstr "VNet 权限"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:287
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:226
msgid "VNet {} has no VNI"
-msgstr ""
+msgstr "VNet {} 没有 VNI"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/remote_tree.rs:238
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:177
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vrf_tree.rs:256
msgid "VNet {} has no zone defined!"
-msgstr ""
+msgstr "VNet {} 未定义区域!"
#: pve-manager/www/manager6/sdn/EvpnZoneMacVrfPanel.js:19
#: pve-manager/www/manager6/sdn/ZoneBridgesPanel.js:22
-#, fuzzy
msgid "VNets"
-msgstr "VNet"
+msgstr "虚拟网络"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_vnet.rs:300
msgid "VRF VNI"
-msgstr ""
+msgstr "VRF VNI"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_zone.rs:82
-#, fuzzy
msgid "VRF VXLAN VNI"
-msgstr "VLAN ID"
+msgstr "VRF VXLAN VNI"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_vnet.rs:82
-#, fuzzy
msgid "VXLAN VNI"
-msgstr "VLAN ID"
+msgstr "VXLAN VNI"
#: proxmox-widget-toolkit/src/Toolkit.js:21
#: proxmox-widget-toolkit/src/Toolkit.js:37
msgid "Valid CIDR Range"
-msgstr "有效的 CIDR 范围"
+msgstr "有效 CIDR 范围"
#: proxmox-widget-toolkit/src/panel/Certificates.js:40
#: proxmox-widget-toolkit/src/window/Certificates.js:46
@@ -17255,7 +16885,7 @@ msgstr "有效的 CIDR 范围"
#: proxmox-yew-comp/src/acme/certificate_list.rs:358
#: proxmox-yew-comp/src/acme/certificate_list.rs:403
msgid "Valid Since"
-msgstr "有效期自"
+msgstr "生效时间"
#: proxmox-widget-toolkit/src/window/ACMEPluginEdit.js:188
#: proxmox-yew-comp/src/acme/acme_plugins.rs:411
@@ -17282,9 +16912,8 @@ msgid "Value"
msgstr "值"
#: proxmox-yew-comp/src/safe_confirm_dialog.rs:101
-#, fuzzy
msgid "Value does not match!"
-msgstr "至少有一个不匹配"
+msgstr "值不匹配!"
#: pve-manager/www/manager6/ceph/OSDDetails.js:133
msgid "Various information about the OSD"
@@ -17353,7 +16982,7 @@ msgstr "验证"
#: proxmox-backup/www/datastore/Content.js:1049
msgid "Verify '{0}'"
-msgstr "验证 '{0}'"
+msgstr "验证'{0}'"
#: proxmox-backup/www/datastore/Content.js:1342
msgid "Verify All"
@@ -17365,7 +16994,7 @@ msgstr "全部验证"
#: pve-manager/www/manager6/dc/MetricServerView.js:361
#: proxmox-yew-comp/src/auth_edit_ldap.rs:337
msgid "Verify Certificate"
-msgstr "验证凭证"
+msgstr "验证证书"
#: proxmox-widget-toolkit/src/window/AddTotp.js:246
#: proxmox-yew-comp/src/tfa/tfa_add_totp.rs:134
@@ -17400,9 +17029,8 @@ msgid "Verify Receivers"
msgstr "验证收件者"
#: pve-manager/www/manager6/dc/MetricServerView.js:641
-#, fuzzy
msgid "Verify SSL"
-msgstr "验证"
+msgstr "验证 SSL"
#. TRANSLATORS: The state of the verification task
#: pve-manager/www/manager6/grid/BackupView.js:380
@@ -17416,11 +17044,11 @@ msgstr "验证状态"
#: pve-manager/www/manager6/dc/AuthEditAD.js:85
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:85
msgid "Verify TLS certificate of the server"
-msgstr "验证服务器的TLS证书"
+msgstr "验证服务器的 TLS 证书"
#: pve-manager/www/manager6/window/DownloadUrlToStorage.js:216
msgid "Verify certificates"
-msgstr "验证凭证"
+msgstr "验证证书"
#: pve-manager/www/manager6/dc/AuthEditAD.js:100
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:100
@@ -17453,15 +17081,13 @@ msgid "Version"
msgstr "版本"
#: pve-manager/www/manager6/sdn/FabricsContentView.js:13
-#, fuzzy
msgid "Via"
-msgstr "虚拟"
+msgstr "经由"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_spice_enhancement_property.rs:53
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_spice_enhancement_property.rs:85
-#, fuzzy
msgid "Video Streaming"
-msgstr "测试字符串"
+msgstr "视频流"
#: proxmox-widget-toolkit/src/panel/ACMEAccount.js:105
#: pve-manager/www/manager6/tree/SnapshotTree.js:27
@@ -17476,7 +17102,7 @@ msgstr "查看"
#: pve-manager/www/manager6/node/Certificates.js:303
#: proxmox-yew-comp/src/acme/certificate_list.rs:152
msgid "View Certificate"
-msgstr "查看凭证"
+msgstr "查看证书"
#: pmg-gui/js/DKIMSettings.js:212
msgid "View DNS Record"
@@ -17497,15 +17123,13 @@ msgid "View images"
msgstr "查看映像"
#: proxmox-datacenter-manager/ui/src/main_menu.rs:210
-#, fuzzy
msgid "Views"
-msgstr "查看"
+msgstr "视图"
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_machine_property.rs:142
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_machine_property.rs:156
-#, fuzzy
msgid "VirtIO"
-msgstr "VirtIO RNG"
+msgstr "VirtIO"
#: pve-manager/www/manager6/qemu/HardwareView.js:356
#: pve-manager/www/manager6/qemu/HardwareView.js:806
@@ -17520,7 +17144,7 @@ msgstr "Virtiofs"
#: pve-manager/www/manager6/qemu/VirtiofsEdit.js:97
msgid "Virtiofs Filesystem Passthrough"
-msgstr "Virtiofs文件系统直通"
+msgstr "Virtiofs 文件系统直通"
#: proxmox-widget-toolkit/src/Schema.js:98
msgid "Virtual"
@@ -17528,7 +17152,7 @@ msgstr "虚拟"
#: proxmox-datacenter-manager/ui/src/dashboard/node_status_panel.rs:165
msgid "Virtual Environment Nodes"
-msgstr ""
+msgstr "虚拟环境节点"
#: pve-manager/www/manager6/storage/Browser.js:160
msgid "Virtual Guests"
@@ -17549,13 +17173,12 @@ msgid "Virtual Machine"
msgstr "虚拟机"
#: proxmox-datacenter-manager/ui/src/tasks.rs:169
-#, fuzzy
msgid "Virtual Machine related Tasks"
-msgstr "虚拟机"
+msgstr "虚拟机相关任务"
#: pve-manager/www/manager6/qemu/Config.js:277
msgid "Virtual Machine {0} on node '{1}'"
-msgstr "虚拟机 {0} 在节点 '{1}' 上"
+msgstr "虚拟机 {0} 在节点'{1}'上"
#: pve-manager/www/manager6/dc/Guests.js:38
#: proxmox-datacenter-manager/ui/src/dashboard/guest_panel.rs:224
@@ -17601,7 +17224,7 @@ msgstr "病毒爆发"
#: pmg-gui/js/NavigationTree.js:116 pmg-gui/js/VirusQuarantine.js:52
msgid "Virus Quarantine"
-msgstr "病毒爆发"
+msgstr "病毒隔离"
#: pmg-gui/js/ReceiverStatistics.js:89
msgid "Virus info"
@@ -17648,14 +17271,13 @@ msgstr "WAL 大小"
#: pve-manager/www/manager6/qemu/TdxEdit.js:53
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_intel_tdx_property.rs:60
-#, fuzzy
msgid "WARNING: When using Intel TDX no EFI disk is loaded as pflash."
-msgstr "警告:使用SEV-SNP时,没有EFI磁盘作为pflash加载。"
+msgstr "警告:使用 Intel TDX 时,不会将 EFI 磁盘作为 pflash 加载。"
#: pve-manager/www/manager6/qemu/SevEdit.js:74
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_amd_sev_property.rs:79
msgid "WARNING: When using SEV-SNP no EFI disk is loaded as pflash."
-msgstr "警告:使用SEV-SNP时,没有EFI磁盘作为pflash加载。"
+msgstr "警告:使用 SEV-SNP 时,没有 EFI 磁盘作为 pflash 加载。"
#: pve-manager/www/manager6/qemu/ProcessorEdit.js:161
msgid ""
@@ -17666,11 +17288,11 @@ msgstr "警告:您无权配置自定义 CPU 类型,如果更改类型,将
#: proxmox-widget-toolkit/src/window/TfaWindow.js:352
#: proxmox-widget-toolkit/src/window/TfaWindow.js:483
msgid "Waiting for second factor."
-msgstr "等待二次验证。"
+msgstr "等待第二验证因素。"
#: pve-manager/www/manager6/node/CmdMenu.js:114
msgid "Wake on LAN packet send for '{0}': '{1}'"
-msgstr "为 '{0}' 发送的唤醒局域网数据包:'{1}'"
+msgstr "为'{0}'发送的唤醒局域网数据包:'{1}'"
#: pve-manager/www/manager6/node/CmdMenu.js:99
msgid "Wake-on-LAN"
@@ -17689,11 +17311,9 @@ msgstr "网络唤醒"
#: proxmox-datacenter-manager/ui/src/dashboard/filtered_tasks.rs:193
#: proxmox-datacenter-manager/ui/src/dashboard/tasks.rs:154
#: proxmox-yew-comp/src/apt_repositories.rs:922
-#, fuzzy
msgid "Warning"
msgid_plural "Warnings"
msgstr[0] "警告"
-msgstr[1] "警告"
#: pve-manager/www/manager6/window/FirewallEnableEdit.js:28
msgid "Warning: Firewall still disabled at datacenter level!"
@@ -17735,7 +17355,7 @@ msgstr "磨损"
#: proxmox-datacenter-manager/ui/src/remotes/edit_remote.rs:118
msgid "Web UI URL"
-msgstr ""
+msgstr "Web UI URL"
#: proxmox-widget-toolkit/src/panel/TfaView.js:268 pmg-gui/js/TFAView.js:97
#: proxmox-yew-comp/src/tfa/tfa_view.rs:259
@@ -17754,16 +17374,15 @@ msgstr "Webauthn TFA"
#: pmg-gui/js/TFAView.js:75 pve-manager/www/manager6/dc/OptionView.js:323
#: proxmox-backup/www/config/WebauthnView.js:130
msgid "WebAuthn requires using a trusted certificate."
-msgstr "WebAuthn 需要使用受信任的凭证。"
+msgstr "WebAuthn 需要使用受信任的证书。"
#: pmg-gui/js/TFAView.js:6 proxmox-backup/www/config/WebauthnView.js:61
msgid "Webauthn"
msgstr "WebAuthn"
#: proxmox-yew-comp/src/tfa/tfa_add_webauthn.rs:109
-#, fuzzy
msgid "Webauthn Device"
-msgstr "注册 Webauthn 设备"
+msgstr "Webauthn 设备"
#: pmg-gui/js/Settings.js:133 pve-manager/www/manager6/window/Settings.js:166
#: proxmox-backup/www/window/Settings.js:133
@@ -17785,16 +17404,15 @@ msgstr "每周"
#: pmg-gui/js/DNSBLSitesField.js:178
msgid "Weight"
-msgstr ""
+msgstr "权重"
#: pmg-gui/js/MailProxyConfiguration.js:53 pmg-gui/js/QuarantineView.js:22
#: pmg-gui/js/SpamContextMenu.js:19 pmg-gui/js/SpamQuarantine.js:265
#: pmg-gui/js/UserBlockWelcomeList.js:57 pmg-gui/js/UserBlockWelcomeList.js:247
#: pmg-yew-quarantine-gui/src/spam_list.rs:278
#: pmg-yew-quarantine-gui/src/page_mail_view.rs:135
-#, fuzzy
msgid "Welcomelist"
-msgstr "白名单"
+msgstr "欢迎列表"
#: pmg-gui/js/ObjectGroupSelector.js:32 pmg-gui/js/RuleInfo.js:464
msgid "What"
@@ -17821,7 +17439,7 @@ msgstr "当选择了多个设备时,将在客户端启动时选择第一个自
#: pmg-gui/js/NavigationTree.js:28 pmg-gui/js/Utils.js:54
msgid "Who Objects"
-msgstr "操作对象"
+msgstr "身份对象"
#: pmg-gui/js/StatTimeSelector.js:158
msgid "Whole month"
@@ -17868,14 +17486,14 @@ msgstr "使用此功能,可以手动将来自某些域或地址的电子邮件
#: pve-manager/www/manager6/node/Summary.js:227
msgid "Without ZFS ARC"
-msgstr ""
+msgstr "不含 ZFS ARC"
#: pve-manager/www/manager6/storage/Base.js:163
msgid ""
"Without any keep option, the node's vzdump.conf or `keep-all` is used as "
"fallback for backup jobs"
msgstr ""
-"如果没有任何保留选项,节点的 vzdump.conf 或 “keep all” 将用作备份作业的回退"
+"如果没有任何保留选项,节点的 vzdump.conf 或 `keep-all` 将用作备份作业的回退"
#: pve-manager/www/manager6/dc/Backup.js:366
msgid ""
@@ -17884,9 +17502,8 @@ msgid ""
msgstr "没有任何保留选项,存储的配置或节点的 vzdump.conf 用作回退"
#: pve-yew-mobile-gui/src/pages/page_task_status.rs:144
-#, fuzzy
msgid "Worker ID"
-msgstr "服务器 ID"
+msgstr "工作器 ID"
#: proxmox-widget-toolkit/src/window/DiskSmart.js:60
msgid "Worst"
@@ -18004,12 +17621,12 @@ msgstr "您可以在此处拖放密钥文件。"
#: proxmox-widget-toolkit/src/form/TextAreaField.js:13
#: proxmox-widget-toolkit/src/window/NotesEdit.js:32
msgid "You can use Markdown for rich text formatting."
-msgstr "您可以使用 Markdown 进行富文本格式设置。"
+msgstr "您可以使用 Markdown 进行富文本格式化。"
#: pve-manager/www/manager6/qemu/DisplayEdit.js:114
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_display_property.rs:123
msgid "You cannot live-migrate while using the VNC clipboard."
-msgstr "使用VNC剪贴板时无法实时迁移。"
+msgstr "使用 VNC 剪贴板时无法实时迁移。"
#: pve-manager/www/manager6/qemu/DisplayEdit.js:102
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_display_property.rs:116
@@ -18022,17 +17639,17 @@ msgstr "如果选择了 VNC 剪贴板,则不能使用默认的 SPICE 剪贴板
msgid ""
"You do not have a valid subscription for this server. Please visit {0} to "
"get a list of available options."
-msgstr "您没有此服务器的有效订阅。请访问 {0} 获取可用选项列表。"
+msgstr "此服务器无有效订阅。请访问 {0} 获取可用选项列表。"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:484
#: proxmox-yew-comp/src/apt_repositories.rs:179
msgid "You get supported updates for {0}"
-msgstr "您获得 {0} 的受支持更新"
+msgstr "您将获得 {0} 的受支持更新"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:489
#: proxmox-yew-comp/src/apt_repositories.rs:174
msgid "You get updates for {0}"
-msgstr "您会收到 {0} 的更新"
+msgstr "您将获得 {0} 的更新"
#: pmg-gui/js/dashboard/SubscriptionInfo.js:29
#: pve-manager/www/manager6/dc/Summary.js:273
@@ -18059,7 +17676,7 @@ msgstr "您需要创建一次初始配置。"
msgid ""
"You won't get any security fixes after the End-Of-Life date. Please consider "
"upgrading."
-msgstr "在生命周期结束日期之后,将不会获得任何安全修复程序。请考虑升级。"
+msgstr "生命周期结束后,您将不会收到任何安全修复。请考虑升级。"
#: proxmox-widget-toolkit/src/window/PasswordEdit.js:28
msgid "Your Current Password"
@@ -18070,9 +17687,8 @@ msgid "Your E-Mail"
msgstr "您的 E-Mail"
#: proxmox-datacenter-manager/ui/src/dashboard/subscription_info.rs:144
-#, fuzzy
msgid "Your Subscriptions"
-msgstr "没有订阅"
+msgstr "您的订阅"
#: pmg-gui/js/dashboard/SubscriptionInfo.js:21
#: pve-manager/www/manager6/dc/Summary.js:287
@@ -18084,7 +17700,7 @@ msgstr "您的订阅状态有效。"
#: proxmox-widget-toolkit/src/window/AddYubico.js:133
msgid "YubiKeys also support WebAuthn, which is often a better alternative."
-msgstr "YubiKeys 还支持 WebAuthn,这通常是更好的选择。"
+msgstr "YubiKey 也支持 WebAuthn,这通常是更好的选择。"
#: proxmox-widget-toolkit/src/panel/TfaView.js:280
#: proxmox-widget-toolkit/src/window/TfaWindow.js:501
@@ -18101,7 +17717,7 @@ msgstr "ZB"
#: pve-manager/www/manager6/node/Summary.js:252
msgid "ZFS ARC"
-msgstr ""
+msgstr "ZFS ARC"
#: pve-manager/www/manager6/storage/ZFSPoolEdit.js:17
#: pve-manager/www/manager6/storage/ZFSPoolEdit.js:71
@@ -18129,13 +17745,12 @@ msgid "Zone"
msgstr "区"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_zone.rs:75
-#, fuzzy
msgid "Zone ID"
-msgstr "区"
+msgstr "区域 ID"
#: pve-manager/www/manager6/sdn/Browser.js:23
msgid "Zone {0} on node {1}"
-msgstr "区域{0}在节点{1}上"
+msgstr "区域 {0} 在节点 {1} 上"
#: pve-manager/www/manager6/dc/Config.js:270
msgid "Zones"
@@ -18143,7 +17758,7 @@ msgstr "区域"
#: pve-manager/www/manager6/panel/BackupAdvancedOptions.js:166
msgid "Zstd Threads"
-msgstr "Zstd线程"
+msgstr "Zstd 线程"
#: pve-manager/www/manager6/ceph/Pool.js:159
msgid "a min_size of 1 is not recommended and can lead to data loss"
@@ -18154,9 +17769,8 @@ msgid "all"
msgstr "全部"
#: proxmox-yew-comp/src/form/pve/qemu_property/mod.rs:209
-#, fuzzy
msgid "any"
-msgstr "天"
+msgstr "任意"
#: pve-manager/www/manager6/qemu/Options.js:139
#: proxmox-yew-comp/src/form/pve/qemu_property/mod.rs:246
@@ -18175,11 +17789,11 @@ msgstr "ashift"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_zone.rs:192
msgid "at least one EVPN controller needs to be selected"
-msgstr ""
+msgstr "至少需要选择一个 EVPN 控制器"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_zone.rs:189
msgid "at least one remote needs to have an EVPN controller configured"
-msgstr ""
+msgstr "至少需要一个远程配置 EVPN 控制器"
#: pve-manager/www/manager6/ceph/OSD.js:117
msgid "auto detect"
@@ -18192,25 +17806,25 @@ msgstr "自动 DHCP"
#: pve-manager/www/manager6/window/Migrate.js:437
#: pve-manager/www/manager6/window/Migrate.js:527
msgid "blocking HA resource {0} on selected target node"
-msgstr ""
+msgstr "在所选目标节点上阻止 HA 资源 {0}"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/add_zone.rs:202
msgid "can only create the zone once per remote!"
-msgstr ""
+msgstr "每个远程只能创建一次区域!"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:53
msgid "cannot represent number as f64"
-msgstr ""
+msgstr "无法将数字表示为 f64"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:110
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:119
msgid "cannot represent number as signed integer"
-msgstr ""
+msgstr "无法将数字表示为有符号整数"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:189
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:198
msgid "cannot represent number as unsigned integer"
-msgstr ""
+msgstr "无法将数字表示为无符号整数"
#: proxmox-widget-toolkit/src/node/APT.js:35
#: proxmox-yew-comp/src/apt_package_manager.rs:428
@@ -18249,19 +17863,16 @@ msgid "default"
msgstr "默认"
#: proxmox-backup/www/window/S3ClientEdit.js:60
-#, fuzzy
msgid "default (443)"
-msgstr "默认"
+msgstr "默认(443)"
#: proxmox-backup/www/window/S3ClientEdit.js:83
-#, fuzzy
msgid "default (us-west-1)"
-msgstr "默认(总是)"
+msgstr "默认(us-west-1)"
#: proxmox-yew-comp/src/form/pve/qemu_controller_selector.rs:49
-#, fuzzy
msgid "device '{0}' name is already in use."
-msgstr "该 {0} ID 已被使用"
+msgstr "设备 '{0}' 名称已被使用。"
#: pve-manager/www/manager6/node/Directory.js:174
#: proxmox-backup/www/DirectoryList.js:96
@@ -18280,26 +17891,24 @@ msgstr "dns"
#: proxmox-backup/www/window/S3ClientEdit.js:48
msgid "e.g. {{bucket}}.s3.{{region}}.amazonaws.com"
-msgstr ""
+msgstr "例如 {{bucket}}.s3.{{region}}.amazonaws.com"
#: proxmox-yew-comp/src/auth_edit_openid.rs:129
-#, fuzzy
msgid "email profile"
-msgstr "失败时发送电子邮件"
+msgstr "邮件配置文件"
#: proxmox-widget-toolkit/src/node/APTRepositories.js:49
#: proxmox-yew-comp/src/apt_repositories.rs:703
msgid "enabled"
-msgstr "启用"
+msgstr "已启用"
#: proxmox-yew-comp/src/form/pve/lxc_property/lxc_features_property.rs:123
-#, fuzzy
msgid "experimental"
msgstr "实验性"
#: proxmox-yew-comp/src/tfa/tfa_add_webauthn.rs:147
msgid "failed to parse webauthn registration challenge"
-msgstr ""
+msgstr "无法解析 webauthn 注册质询"
#: pve-manager/www/manager6/form/BackupCompressionSelector.js:6
#: pve-yew-mobile-gui/src/widgets/guest_backup_panel.rs:72
@@ -18312,9 +17921,8 @@ msgid "fast and good"
msgstr "又快又好"
#: proxmox-yew-comp/src/form/pve/qemu_property/mod.rs:245
-#, fuzzy
msgid "first Disk"
-msgstr "首个磁盘"
+msgstr "第一块磁盘"
#: pve-manager/www/manager6/qemu/Options.js:132
msgid "first disk"
@@ -18322,7 +17930,7 @@ msgstr "首个磁盘"
#: pve-manager/www/manager6/storage/TemplateView.js:308
msgid "for example 'latest'"
-msgstr ""
+msgstr "例如 'latest'"
#: pve-manager/www/manager6/form/BackupCompressionSelector.js:7
#: pve-yew-mobile-gui/src/widgets/guest_backup_panel.rs:71
@@ -18331,21 +17939,20 @@ msgid "good"
msgstr "很好"
#: proxmox-yew-widget-toolkit/src/widget/form/checkbox.rs:174
-#, fuzzy
msgid "got invalid value."
-msgstr "无效值"
+msgstr "获得无效值。"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:61
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:131
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:210
msgid "got wrong data type"
-msgstr ""
+msgstr "获得了错误的数据类型"
#: proxmox-yew-widget-toolkit/src/widget/form/radio_button.rs:149
#: proxmox-yew-widget-toolkit/src/widget/form/field.rs:328
#: proxmox-yew-widget-toolkit/src/widget/form/selector.rs:214
msgid "got wrong data type."
-msgstr ""
+msgstr "获得了错误的数据类型。"
#: proxmox-backup/www/datastore/Content.js:1378
msgid "group, date or owner"
@@ -18370,35 +17977,31 @@ msgid "in {0}"
msgstr "在 {0}"
#: proxmox-yew-comp/src/form/pve/lxc_property/lxc_network_property.rs:67
-#, fuzzy
msgid "interface name already in use"
-msgstr "该 {0} ID 已被使用"
+msgstr "接口名称已经被占用"
#: proxmox-datacenter-manager/ui/src/configuration/subscription_panel.rs:160
-#, fuzzy
msgid "invalid data"
-msgstr "无效的文件大小"
+msgstr "无效数据"
#. do not allow "inf", "nan", ...
#: proxmox-yew-widget-toolkit/src/dom/number_format.rs:112
#: proxmox-yew-widget-toolkit/src/dom/number_format.rs:117
-#, fuzzy
msgid "invalid float literal"
-msgstr "无效的文件大小"
+msgstr "无效的浮点数字面量"
#: proxmox-yew-widget-toolkit/src/dom/number_format.rs:101
msgid "invalid float literal (wrong decimal separator)"
-msgstr ""
+msgstr "无效的浮点数字面量(错误的小数分隔符)"
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:274
#: proxmox-datacenter-manager/ui/src/widget/view_filter_selector.rs:319
msgid "invalid type: {0}"
-msgstr ""
+msgstr "无效类型:{0}"
#: proxmox-yew-comp/src/login_panel.rs:300
-#, fuzzy
msgid "invalid username"
-msgstr "无效值"
+msgstr "无效的用户名"
#: pve-manager/www/manager6/window/Prune.js:135
#: proxmox-backup/www/datastore/Prune.js:167
@@ -18437,7 +18040,7 @@ msgstr "按键"
#: proxmox-widget-toolkit/src/Toolkit.js:135
msgid "letter"
-msgstr "信件"
+msgstr "字母"
#: proxmox-widget-toolkit/src/panel/SmtpEditPanel.js:71
msgid "mail.example.com"
@@ -18445,7 +18048,7 @@ msgstr "mail.example.com"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:741
msgid "major difference"
-msgstr ""
+msgstr "主要差异"
#: pve-manager/www/manager6/data/ResourceStore.js:221
msgid "maxcpu"
@@ -18454,7 +18057,7 @@ msgstr "最大 CPU"
#: pve-manager/www/manager6/ceph/Pool.js:149
msgid ""
"min_size < size/2 can lead to data loss, incomplete PGs or unfound objects."
-msgstr "最小大小<大小/2可能导致数据丢失、PGs不完整或找不到对象。"
+msgstr "min_size < size/2 可能导致数据丢失、PGs不完整或对象丢失。"
#: proxmox-backup/www/Utils.js:8
msgid "missing"
@@ -18466,7 +18069,7 @@ msgstr "丢失"
#: proxmox-yew-comp/src/token_panel.rs:457
#: proxmox-yew-comp/src/token_panel.rs:514
msgid "never"
-msgstr "永不过期"
+msgstr "从不"
#: proxmox-widget-toolkit/src/node/APT.js:41
#: proxmox-yew-comp/src/apt_package_manager.rs:438
@@ -18487,11 +18090,11 @@ msgstr "无 VLAN"
#: pve-yew-mobile-gui/src/pages/page_task_status.rs:186
msgid "no data loaded"
-msgstr ""
+msgstr "未加载数据"
#: proxmox-yew-widget-toolkit/src/widget/form/combobox.rs:227
msgid "no such item"
-msgstr ""
+msgstr "没有此项"
#: pve-manager/www/manager6/window/Settings.js:394
msgid "noVNC Settings"
@@ -18523,7 +18126,7 @@ msgstr "无(禁用)"
#: proxmox-widget-toolkit/src/node/NetworkEdit.js:92
msgid "not a valid bridge VLAN ID entry: {0}"
-msgstr "无效的网桥 VLAN ID条目:{0}"
+msgstr "无效的网桥 VLAN ID 条目:{0}"
#: proxmox-widget-toolkit/src/node/ServiceView.js:213
msgid "not installed"
@@ -18534,14 +18137,14 @@ msgstr "未安装"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:175
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:203
msgid "number too large (n > {})"
-msgstr ""
+msgstr "数字太大 (n > {})"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:102
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:127
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:181
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:206
msgid "number too small (n < {})"
-msgstr ""
+msgstr "数字太小 (n < {})"
#: pve-manager/www/manager6/dc/Summary.js:212
msgid "of {0} CPU(s)"
@@ -18549,11 +18152,11 @@ msgstr "的 {0} 个CPU"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:394
msgid "old"
-msgstr ""
+msgstr "旧"
#: proxmox-widget-toolkit/src/Toolkit.js:79
msgid "only unicast addresses are allowed"
-msgstr "只允许单播地址"
+msgstr "仅允许单播地址"
#: pve-manager/www/manager6/node/ACME.js:23
msgid "optional"
@@ -18561,13 +18164,12 @@ msgstr "可选"
#. TRANSLATORS: otel-collector is an OpenTelemetry endpoint.
#: pve-manager/www/manager6/dc/MetricServerView.js:589
-#, fuzzy
msgid "otel-collector.example.com"
-msgstr "mail.example.com"
+msgstr "otel-collector.example.com"
#: pmg-yew-quarantine-gui/src/page_not_found.rs:9
msgid "page not found"
-msgstr ""
+msgstr "页面未找到"
#: pve-manager/www/manager6/form/NetworkCardSelector.js:7
#: proxmox-yew-comp/src/form/pve/qemu_property/qemu_network_property.rs:79
@@ -18598,9 +18200,8 @@ msgid "protected"
msgstr "受保护"
#: proxmox-datacenter-manager/ui/src/pve/node/mod.rs:161
-#, fuzzy
msgid "pve-manager version too old"
-msgstr "管理器版本"
+msgstr "pve-manager 版本过旧"
#: pve-manager/www/manager6/node/ACME.js:588
msgid ""
@@ -18626,7 +18227,7 @@ msgstr "运行中..."
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:745
msgid "small difference"
-msgstr ""
+msgstr "小差异"
#: proxmox-widget-toolkit/src/Utils.js:57
#: proxmox-datacenter-manager/ui/src/dashboard/guest_panel.rs:130
@@ -18641,31 +18242,28 @@ msgstr "子(主题)"
#: proxmox-datacenter-manager/ui/src/remotes/updates.rs:743
msgid "substantial difference"
-msgstr ""
+msgstr "重大差异"
#: proxmox-backup/www/Utils.js:448
msgid "sync jobs handler triggered by mount"
-msgstr ""
+msgstr "挂载触发的同步作业处理程序"
#: pve-manager/www/manager6/grid/Replication.js:373
msgid "syncing"
msgstr "同步中"
#: proxmox-yew-comp/src/bandwidth_selector.rs:98
-#, fuzzy
msgid "unable to parse number"
-msgstr "无法解析驱动器选项"
+msgstr "无法解析数字"
#: proxmox-yew-widget-toolkit/src/widget/form/field.rs:342
-#, fuzzy
msgid "unable to parse number: {}"
-msgstr "无法解析驱动器选项"
+msgstr "无法解析数字:{}"
#: proxmox-yew-comp/src/bandwidth_selector.rs:104
#: proxmox-yew-comp/src/bandwidth_selector.rs:113
-#, fuzzy
msgid "unable to parse value: {}"
-msgstr "无法解析驱动器选项"
+msgstr "无法解析: {}"
#: pve-manager/www/manager6/dc/MetricServerView.js:207
#: proxmox-backup/www/window/InfluxDbEdit.js:12
@@ -18675,17 +18273,16 @@ msgstr "未更改"
#: pve-yew-mobile-gui/src/pages/page_task_status.rs:130
#: pve-yew-mobile-gui/src/pages/page_task_status.rs:136
#: proxmox-yew-comp/src/subscription_panel.rs:192
-#, fuzzy
msgid "unknown"
msgstr "未知"
#: proxmox-datacenter-manager/ui/src/pve/utils.rs:298
msgid "unknown content type ({0})"
-msgstr ""
+msgstr "未知内容类型 ({0})"
#: pve-yew-mobile-gui/src/pages/page_task_status.rs:135
msgid "unknown status '{0}'"
-msgstr ""
+msgstr "未知状态'{0}'"
#: pve-manager/www/manager6/grid/Replication.js:45
#: pve-manager/www/manager6/grid/Replication.js:415
@@ -18719,7 +18316,7 @@ msgstr "不安全"
#: pve-manager/www/manager6/ceph/OSD.js:78
msgid "use OSD disk"
-msgstr "使用OSD磁盘"
+msgstr "使用 OSD 磁盘"
#: pve-manager/www/manager6/ceph/OSD.js:132
msgid "use OSD/DB disk"
@@ -18753,28 +18350,27 @@ msgstr "vIOMMU"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:463
msgid "value must be greater than or equal to '{0}'"
-msgstr ""
+msgstr "值必须大于或等于'{0}'"
#: proxmox-yew-widget-toolkit/src/widget/form/field.rs:347
msgid "value must be greater than or equal to '{}'"
-msgstr ""
+msgstr "值必须大于或等于'{}'"
#: proxmox-yew-widget-toolkit/src/widget/form/number.rs:471
msgid "value must be less than or equal to '{0}'"
-msgstr ""
+msgstr "值必须小于或等于'{0}'"
#: proxmox-yew-widget-toolkit/src/widget/form/field.rs:355
msgid "value must be less than or equal to '{}'"
-msgstr ""
+msgstr "值必须小于或等于'{}'"
#: proxmox-widget-toolkit/src/window/TfaEdit.js:80
msgid "verify current password"
msgstr "验证当前密码"
#: proxmox-datacenter-manager/ui/src/sdn/evpn/vnet_status.rs:94
-#, fuzzy
msgid "via"
-msgstr "虚拟"
+msgstr "通过"
#: pve-manager/www/manager6/qemu/CloudInit.js:253
msgid "with options"
@@ -18782,12 +18378,12 @@ msgstr "选项"
#: pve-manager/www/manager6/qemu/VirtiofsEdit.js:65
msgid "xattr Support"
-msgstr "xattr支持"
+msgstr "xattr 支持"
#: pmg-gui/js/Settings.js:223 pve-manager/www/manager6/window/Settings.js:319
#: proxmox-backup/www/window/Settings.js:223
msgid "xterm.js Settings"
-msgstr "xterm.js设置"
+msgstr "xterm.js 设置"
#: pve-manager/www/manager6/dc/MetricServerView.js:686
msgid ""
@@ -18796,6 +18392,10 @@ msgid ""
" \"X-Custom-Header\": \"value\"\n"
"}"
msgstr ""
+"{\n"
+" \"Authorization\": \"Bearer token\",\n"
+" \"X-Custom-Header\": \"value\"\n"
+"}"
#: pve-manager/www/manager6/dc/MetricServerView.js:708
msgid ""
@@ -18805,6 +18405,11 @@ msgid ""
" \"region\": \"us-east-1\"\n"
"}"
msgstr ""
+"{\n"
+" \"environment\": \"production\",\n"
+" \"datacenter\": \"dc1\",\n"
+" \"region\": \"us-east-1\"\n"
+"}"
#: proxmox-widget-toolkit/src/window/AuthEditLDAP.js:376
#: pve-manager/www/manager6/dc/AuthEditLDAP.js:314
@@ -18817,7 +18422,7 @@ msgstr "{0} ({1}/{2}) 成功"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:193
msgid "{0} / {1} (running / total)"
-msgstr ""
+msgstr "{0} / {1} (运行中 / 总计)"
#: pmg-gui/js/AttachmentGrid.js:75
msgid "{0} Attachments"
@@ -18834,9 +18439,8 @@ msgstr "{0} 项"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:409
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:414
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:417
-#, fuzzy
msgid "{0} OK"
-msgstr "{0} ID"
+msgstr "{0} OK"
#: proxmox-backup/www/Utils.js:829
msgid "{0} conflicting tasks still active."
@@ -18850,9 +18454,8 @@ msgstr "{0} 天"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:419
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:427
-#, fuzzy
msgid "{0} failed"
-msgstr "全部失败"
+msgstr "{0} 失败"
#: pmg-gui/js/Dashboard.js:339
#: proxmox-backup/www/tape/form/RetentionSelector.js:10
@@ -18878,12 +18481,11 @@ msgstr "{0} 月"
#: proxmox-datacenter-manager/ui/src/dashboard/node_status_panel.rs:135
msgid "{0} nodes have an unknown status"
-msgstr ""
+msgstr "{0} 个节点状态未知"
#: proxmox-datacenter-manager/ui/src/dashboard/node_status_panel.rs:151
-#, fuzzy
msgid "{0} nodes online"
-msgstr "节点已下线"
+msgstr "{0} 个节点在线"
#: pve-manager/www/manager6/Utils.js:1831
msgid "{0} not installed."
@@ -18893,11 +18495,11 @@ msgstr "{0} 没有安装。"
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:411
#: proxmox-datacenter-manager/ui/src/pbs/snapshot_list.rs:421
msgid "{0} not verified yet"
-msgstr ""
+msgstr "{0} 尚未验证"
#: proxmox-datacenter-manager/ui/src/dashboard/node_status_panel.rs:141
msgid "{0} of an unknown number of nodes online"
-msgstr ""
+msgstr "未知数量的节点中有 {0} 个在线"
#: proxmox-widget-toolkit/src/Utils.js:1134
#: pve-manager/www/manager6/ceph/Status.js:362
@@ -18906,17 +18508,16 @@ msgstr ""
#: proxmox-backup/www/datastore/DataStoreListSummary.js:77
#: proxmox-backup/www/datastore/DataStoreListSummary.js:82
msgid "{0} of {1}"
-msgstr "{0} 的 {1}"
+msgstr "{1} 中的 {0}"
#: proxmox-datacenter-manager/ui/src/dashboard/node_status_panel.rs:125
msgid "{0} of {1} nodes are offline"
-msgstr ""
+msgstr "{1} 个节点中有 {0} 个离线"
#. TRANSLATORS: For example "resource on Remote 'HAL 9000'"
#: proxmox-datacenter-manager/ui/src/dashboard/top_entities.rs:249
-#, fuzzy
msgid "{0} on Remote '{1}'"
-msgstr "区域{0}在节点{1}上"
+msgstr "{0} 在远程 '{1}' 上"
#: pmg-gui/js/Utils.js:866
msgid "{0} on behalf of {1}"
@@ -18925,7 +18526,7 @@ msgstr "{0} 代表 {1}"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:263
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:279
msgid "{0} running / {1} physical ({2} total configured)"
-msgstr ""
+msgstr "{0} 运行中 / {1} 物理 ({2} 总配置)"
#: pmg-gui/js/GeneralMailStatistics.js:120
msgid "{0} seconds"
@@ -18945,7 +18546,7 @@ msgstr "{0} 到 {1}"
#: proxmox-widget-toolkit/src/Utils.js:1376
msgid "{0} updates"
-msgstr "{0} 更新"
+msgstr "{0} 个更新"
#: proxmox-backup/www/tape/form/RetentionSelector.js:12
msgid "{0} weeks"
@@ -18956,34 +18557,30 @@ msgid "{0} years"
msgstr "{0} 年"
#: pve-manager/www/manager6/sdn/NetworkBrowser.js:157
-#, fuzzy
msgid "{0} {1} on node {2}"
-msgstr "{0}%的{1}"
+msgstr "{0} {1} 在节点 {2} 上"
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:220
#: proxmox-datacenter-manager/ui/src/pve/remote_overview.rs:236
#: proxmox-datacenter-manager/ui/src/pve/storage.rs:288
#: proxmox-datacenter-manager/ui/src/renderer.rs:76
-#, fuzzy
msgid "{0}% ({1} of {2})"
-msgstr "{0}%的{1}"
+msgstr "{0}%({1} / {2})"
#: proxmox-widget-toolkit/src/Utils.js:1121
-#, fuzzy, javascript-format
+#, javascript-format
msgid "{0}% of {1}"
-msgstr "{0}%的{1}"
+msgstr "{0}% of {1}"
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:296
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:305
-#, fuzzy
msgid "{0}% of {1} CPU(s)"
-msgstr "的 {0} 个CPU"
+msgstr "{0}%/{1}个 CPU"
#: proxmox-datacenter-manager/ui/src/pve/lxc/overview.rs:281
#: proxmox-datacenter-manager/ui/src/pve/qemu/overview.rs:290
-#, fuzzy
msgid "{0}, Group: {1}"
-msgstr "{0} 的 {1}"
+msgstr "{0},组:{1}"
#~ msgid " Network/Time"
#~ msgstr "网络/时间"
@@ -19015,12 +18612,8 @@ msgstr "{0} 的 {1}"
#~ msgid "Are you sure you want to navigate away from this page?"
#~ msgstr "确定要离开此页?"
-#, fuzzy
-#~ msgid "Are you sure you want to remove entry {0}."
-#~ msgstr "确定要删除该项 {0} 吗?"
-
#~ msgid "Are you sure you want to remove {item.type} {item.id}?"
-#~ msgstr "确定要删除该项{item.type} {item.id}吗?"
+#~ msgstr "确定要删除该项 {item.type} {item.id}吗?"
#~ msgid ""
#~ "Are you sure you want to remove {item.type} {item.id}? This will "
@@ -19051,16 +18644,9 @@ msgstr "{0} 的 {1}"
#~ msgid "Barrier"
#~ msgstr "Barrier"
-#~ msgid "Blacklist"
-#~ msgstr "黑名单"
-
#~ msgid "Blocksize"
#~ msgstr "块尺寸"
-#, fuzzy
-#~ msgid "Boot Device"
-#~ msgstr "引导设备"
-
#~ msgid "Bootdisk Size"
#~ msgstr "引导磁盘大小"
@@ -19073,10 +18659,6 @@ msgstr "{0} 的 {1}"
#~ msgid "CD/DVD"
#~ msgstr "CD/DVD"
-#, fuzzy
-#~ msgid "CPU Model"
-#~ msgstr "模型"
-
#~ msgid "CPU usage %"
#~ msgstr "CPU使用率%"
@@ -19095,21 +18677,9 @@ msgstr "{0} 的 {1}"
#~ msgid "Clear User name"
#~ msgstr "清除用户名"
-#, fuzzy
-#~ msgid "Connection OK"
-#~ msgstr "连接错误"
-
#~ msgid ""
#~ "Custom 2nd factor configuration is not supported on realms with '{0}' TFA."
-#~ msgstr "具有'{0}' TFA的域不支持自定义二次验证配置。"
-
-#, fuzzy
-#~ msgid "DNS Domain"
-#~ msgstr "DNS 域"
-
-#, fuzzy
-#~ msgid "Dashboard Configuration"
-#~ msgstr "显示配置"
+#~ msgstr "具有 '{0}' TFA的域不支持自定义二次验证配置。"
#~ msgid "Datacenter Health"
#~ msgstr "数据中心健康"
@@ -19117,33 +18687,9 @@ msgstr "{0} 的 {1}"
#~ msgid "Day of week"
#~ msgstr "星期几"
-#, fuzzy
-#~ msgid "Default (any)"
-#~ msgstr "默认(总是)"
-
-#, fuzzy
-#~ msgid "Default (disabled)"
-#~ msgstr "无(禁用)"
-
-#, fuzzy
-#~ msgid "Default)"
-#~ msgstr "默认"
-
-#, fuzzy
-#~ msgid "Delete Device"
-#~ msgstr "删除源"
-
-#, fuzzy
-#~ msgid "Detach disk"
-#~ msgstr "分离"
-
#~ msgid "Disabling notifications is not recommended for production systems!"
#~ msgstr "不建议对生产系统禁用通知!"
-#, fuzzy
-#~ msgid "Disk Actions"
-#~ msgstr "磁盘操作"
-
#~ msgid "Disk Throttle"
#~ msgstr "磁盘节流"
@@ -19216,10 +18762,6 @@ msgstr "{0} 的 {1}"
#~ msgid "Download Files"
#~ msgstr "下载文件"
-#, fuzzy
-#~ msgid "Edit Options"
-#~ msgstr "选项"
-
#~ msgid "Eject media"
#~ msgstr "擦除数据"
@@ -19246,10 +18788,6 @@ msgstr "{0} 的 {1}"
#~ msgid "Failover Domain"
#~ msgstr "故障转移域"
-#, fuzzy
-#~ msgid "Firewall Rules"
-#~ msgstr "防火墙"
-
#~ msgid "Gateway Nodes"
#~ msgstr "网关节点"
@@ -19277,10 +18815,6 @@ msgstr "{0} 的 {1}"
#~ msgid "Host ifname"
#~ msgstr "主机ifname"
-#, fuzzy
-#~ msgid "Hostame"
-#~ msgstr "主机名"
-
#~ msgid "ID may only consist of alphanumeric characters"
#~ msgstr "ID只能由字母数字字符组成"
@@ -19314,10 +18848,6 @@ msgstr "{0} 的 {1}"
#~ msgid "MAC"
#~ msgstr "MAC"
-#, fuzzy
-#~ msgid "Machine Type"
-#~ msgstr "匹配类型"
-
#~ msgid "Manage {0}"
#~ msgstr "管理 {0}"
@@ -19342,26 +18872,6 @@ msgstr "{0} 的 {1}"
#~ msgid "Minimum replicas"
#~ msgstr "最小副本数"
-#, fuzzy
-#~ msgid "Mixed subscriptions"
-#~ msgstr "混合订阅"
-
-#, fuzzy
-#~ msgid "Move Disk"
-#~ msgstr "移动磁盘"
-
-#, fuzzy
-#~ msgid "Nameserver"
-#~ msgstr "DNS 服务器"
-
-#, fuzzy
-#~ msgid "Network Device Index"
-#~ msgstr "网络设备"
-
-#, fuzzy
-#~ msgid "Next due data"
-#~ msgstr "下一个到期日期"
-
#~ msgid "No Data in Database"
#~ msgstr "数据库中没有数据"
@@ -19371,31 +18881,15 @@ msgstr "{0} 的 {1}"
#~ msgid "No data in database."
#~ msgstr "数据库中没有数据。"
-#, fuzzy
-#~ msgid "No enhancements"
-#~ msgstr "Spice 增强"
-
-#, fuzzy
-#~ msgid "No remotes configured"
-#~ msgstr "未配置 VNet。"
-
#~ msgid "No target configured"
#~ msgstr "未配置目标"
-#, fuzzy
-#~ msgid "No valid Subscription"
-#~ msgstr "无有效订阅"
-
#~ msgid "Node Fencing"
#~ msgstr "节点围栏"
#~ msgid "Node Resources"
#~ msgstr "节点资源"
-#, fuzzy
-#~ msgid "Node/Error"
-#~ msgstr "错误"
-
#~ msgid "Note: Rollback stops CT"
#~ msgstr "注意:回滚会停止CT"
@@ -19503,10 +18997,6 @@ msgstr "{0} 的 {1}"
#~ msgid "Removed Bytes"
#~ msgstr "删除的字节"
-#, fuzzy
-#~ msgid "Respository"
-#~ msgstr "存储库"
-
#~ msgid "Restart pmg-smtp-filter"
#~ msgstr "重启pmg-smtp-filter"
@@ -19519,17 +19009,9 @@ msgstr "{0} 的 {1}"
#~ msgid "Ring 0 Address"
#~ msgstr "Ring 0地址"
-#, fuzzy
-#~ msgid "Root filesystem usage"
-#~ msgstr "根磁盘使用率"
-
#~ msgid "SMTP"
#~ msgstr "SMTP"
-#, fuzzy
-#~ msgid "Scan OK"
-#~ msgstr "扫描"
-
#~ msgid "Scan QR code and enter TOTP auth. code to verify"
#~ msgstr "扫描二维码,并输入TOTP验证码以用于验证"
@@ -19545,21 +19027,9 @@ msgstr "{0} 的 {1}"
#~ msgid "Service vlan"
#~ msgstr "服务vlan"
-#, fuzzy
-#~ msgid "Setrvice"
-#~ msgstr "服务"
-
-#, fuzzy
-#~ msgid "Size IncrementX"
-#~ msgstr "增量大小"
-
#~ msgid "Skip verified snapshots"
#~ msgstr "跳过已验证的快照"
-#, fuzzy
-#~ msgid "Some nodes unavailable"
-#~ msgstr "没有可用的更新。"
-
#~ msgid "Start All VMs"
#~ msgstr "启动所有虚拟机"
@@ -19593,7 +19063,7 @@ msgstr "{0} 的 {1}"
#~ msgid ""
#~ "To register a U2F device, connect the device, then click the button and "
#~ "follow the instructions."
-#~ msgstr "要注册U2F设备,请连接设备,然后单击按钮并按照说明进行操作。"
+#~ msgstr "要注册 U2F 设备,请连接设备,然后单击按钮并按照说明进行操作。"
#~ msgid "Toggle Theme"
#~ msgstr "切换主题"
@@ -19607,17 +19077,9 @@ msgstr "{0} 的 {1}"
#~ msgid "Unkown"
#~ msgstr "未知"
-#, fuzzy
-#~ msgid "Unpriviledged"
-#~ msgstr "无特权"
-
#~ msgid "Unused Mount Point"
#~ msgstr "未使用的挂载点"
-#, fuzzy
-#~ msgid "Update status unknown"
-#~ msgstr "现在更新"
-
#~ msgid "Uploading file..."
#~ msgstr "上传文件中..."
@@ -19627,10 +19089,6 @@ msgstr "{0} 的 {1}"
#~ msgid "Use fixed size memory"
#~ msgstr "使用固定大小的内存"
-#, fuzzy
-#~ msgid "Use host settings"
-#~ msgstr "使用主机设置"
-
#~ msgid "User quotas disabled."
#~ msgstr "用户配额已禁用。"
@@ -19646,11 +19104,7 @@ msgstr "{0} 的 {1}"
#~ "a decrease in security in practice."
#~ msgstr ""
#~ "不建议使用 /dev/random 作为熵源,因为它会导致主机熵不足。/dev/urandom 是首"
-#~ "选,并且在实践中不会导致安全性降低。"
-
-#, fuzzy
-#~ msgid "VM State Storage"
-#~ msgstr "VM 状态存储"
+#~ "选,并且在实践中不会降低安全性。"
#~ msgid "VM protection"
#~ msgstr "VM保护"
@@ -19658,10 +19112,6 @@ msgstr "{0} 的 {1}"
#~ msgid "VZDump backup file"
#~ msgstr "VZDump 备份文件"
-#, fuzzy
-#~ msgid "Valid subscriptions"
-#~ msgstr "无有效订阅"
-
#~ msgid "Verify SSL certificate of the server"
#~ msgstr "验证服务器的SSL凭证"
@@ -19683,9 +19133,6 @@ msgstr "{0} 的 {1}"
#~ msgid "WebAuthn "
#~ msgstr "WebAuthn"
-#~ msgid "Whitelist"
-#~ msgstr "白名单"
-
#~ msgid "Working"
#~ msgstr "工作中"
@@ -19695,25 +19142,9 @@ msgstr "{0} 的 {1}"
#~ msgid "You are logged in as '{0}'"
#~ msgstr "您的登录名是'{0}'"
-#, fuzzy
-#~ msgid "You have one new {}"
-#~ msgid_plural "You have {n} new {}s"
-#~ msgstr[0] "您的登录名是{0} "
-#~ msgstr[1] "您的登录名是{0} "
-
-#, fuzzy
-#~ msgctxt "context"
-#~ msgid "You have one new {}"
-#~ msgid_plural "You have {n} new {}s"
-#~ msgstr[0] "您的登录名是{0} "
-#~ msgstr[1] "您的登录名是{0} "
-
#~ msgid "api key"
#~ msgstr "api key"
-#~ msgid "average"
-#~ msgstr "平均"
-
#~ msgid "bond-primary"
#~ msgstr "主bond"
@@ -19723,29 +19154,9 @@ msgstr "{0} 的 {1}"
#~ msgid "gateway-external-peers"
#~ msgstr "网关外部对等"
-#~ msgid "maximum"
-#~ msgstr "最大"
-
#~ msgid "nofailback"
#~ msgstr "无故障回复"
-#, fuzzy
-#~ msgid "one"
-#~ msgid_plural "plural"
-#~ msgstr[0] "完成"
-#~ msgstr[1] "完成"
-
-#, fuzzy
-#~ msgctxt "context"
-#~ msgid "one"
-#~ msgid_plural "plural"
-#~ msgstr[0] "完成"
-#~ msgstr[1] "完成"
-
-#, fuzzy
-#~ msgid "paused"
-#~ msgstr "已暂停"
-
#~ msgid "peers address list"
#~ msgstr "对端地址列表"
@@ -19776,26 +19187,8 @@ msgstr "{0} 的 {1}"
#~ msgid "{0} (Auto)"
#~ msgstr "{0} (自动)"
-#, fuzzy
-#~ msgid "{0} ({1} sockets)"
-#~ msgstr "{0} ({1})"
-
-#, fuzzy
-#~ msgctxt "context"
-#~ msgid "{0} bar"
-#~ msgstr "{0} 年"
-
-#, fuzzy
-#~ msgid "{0} remotes failed"
-#~ msgstr "全部失败"
-
-#, fuzzy
-#~ msgid "{0} {1}"
-#~ msgstr "{0} ({1})"
-
#~ msgid "{1} ({2}), notify via target \\'{0}\\'"
#~ msgstr "{1} ({2}),通过目标\\'{0}\\'通知"
-#, fuzzy
-#~ msgid "{1} {0}"
-#~ msgstr "ID {0}"
+#~ msgid "以逗号分隔的网络列表,用于应用共享限制。"
+#~ msgstr "要应用(共享)限制的以逗号分隔的网络列表。"
--
2.47.3
^ permalink raw reply related [relevance 3%]
* Re: [RFC] Native ZFS over NVMe/TCP storage backend for Proxmox VE
@ 2026-07-21 11:45 9% ` Max R. Carrara
2026-08-02 3:20 15% ` Joaquin Varela
0 siblings, 1 reply; 43+ results
From: Max R. Carrara @ 2026-07-21 11:45 UTC (permalink / raw)
To: Joaquin Varela, pve-devel
On Wed Jul 15, 2026 at 6:23 PM CEST, Joaquin Varela wrote:
> Hello,
>
> I have implemented an in-tree Proxmox VE storage backend named `zfsnvme`.
> It follows the remote ZFS lifecycle model used by ZFS over iSCSI, but uses
> Linux nvmet, NVMe/TCP and native kernel multipath.
Hello!
This sounds like a great contribution! Using the existing flow of the
ZFS-over-iSCSI plugin is also a good idea.
>
> The ZFS dataset is the durable source of truth. Each owned zvol stores its
> subsystem NQN, NSID and namespace UUID as ZFS user properties. Configfs is
> reconciled from those properties, and the namespace UUID provides the stable
> by-id path used by QEMU.
>
> The implementation includes:
>
> - one NVMe/TCP connection per configured portal and host interface;
> - native multipath and ANA state handling;
> - DH-HMAC-CHAP without exposing the key in process arguments;
> - thin provisioning, discard, snapshots, rollback and linked clones;
> - safe teardown and foreign-zvol identity checks;
> - an explicit queue-versus-fast-fail policy for complete path loss;
> - pve-manager and pve-docs integration.
>
> Validation covered the complete pve-storage test suite (593 assertions),
> two-node live migration under guest I/O, migration to a degraded
> destination,
> real ANA transitions, simultaneous allocations from both cluster nodes,
> single and dual path loss, configfs reconstruction, watchdog HA and a live
> Corosync/QDevice partition. No source/destination QEMU overlap was observed
> in
> the live partition test.
>
> The implementation and detailed validation report are available here:
>
> https://github.com/joaquinv98/pve-storage/tree/feature/zfs-nvme-tcp
> https://github.com/joaquinv98/pve-manager/tree/feature/zfs-nvme-tcp
> https://github.com/joaquinv98/pve-docs/tree/feature/zfs-nvme-tcp
>
> The lab results are not presented as hardware certification. TLS, online
> resize and target control-plane HA remain explicit limitations.
>
> I have prepared signed patch series for pve-storage, pve-manager and
> pve-docs.
> Before posting the full series, I would appreciate feedback on whether this
> in-tree backend and its architecture are acceptable for upstream review.
I have skimmed through the respective branches on your repositories
above, and from what I can tell, the commits look pretty decent.
I do have some remarks up front that you may want to consider before
sending this in as a patch series -- mostly to save you some time:
- If you haven't already, please sign our CLA. You can find the
respective section here: https://proxmox.com/en/about/open-source/developers
- From what I can tell, you're already adhering quite well to our style
guide, which is great! A few remarks:
* I suggest using `use v5.36;` for new Perl modules instead of
`use strict; use warnings;`, as that enables subroutine signatures
by default. Helps modernizing the code base overall.
See our style guide for more details: https://pve.proxmox.com/wiki/Perl_Style_Guide
* While not in the style guide, I can personally recommend using the
`n` and `x`/`xx` modifiers for your regexes, and declaring any
inline regexes as constants (=> `my $RE_NVME_FOO = qr/.../nxx`)
in a little section at the top of your module. These flags help
future readers to understand your regexes a little easier, and since
`n` forces the use of named capture groups, they'll also more likely
to be "self-documenting" in a sense.
* For subroutines that are not part of the storage plugin API, i.e.
helpers, utilts, etc. specific to your module, prefer declaring them
using `my sub` instead of a plain `sub`, as that keeps them visible
inside the module only (=> "private" in other languages). That
prevents other places from using these helpers.
You can then also drop the `_` prefix in that case (if you prefer).
* I also suggest using postfix dereferencing instead of the
"traditional" dereferencing syntax, that is, `$hashref->%*` instead
of `%$hashref`, for example. It's a little more legible and makes
nested hash access a little easier to follow as well. Note that this
isn't explicitly stated in our style guide either (we only have it
there for subref calls, hash and array accessing), so no hard
feelings.
- When you submit your series, please do not any entries in
`debian/changelog` -- though it's nice to see that you've been
thorough there!
That's all I can think of / find at the moment without giving it a
proper in-depth review. I'll happily review your series once you send it
in.
I'd also be interested in what kind of storage backend you were using
for your tests, so that I can replicate your setup myself. I have
skimmed through your docs and validation reports, but haven't found
anything specific -- maybe I just missed it.
>
> Kind regards,
Thanks a lot for your interest in contributing and your work already,
it's much appreciated!
Kind regards,
Max
^ permalink raw reply [relevance 9%]
* Re: [RFC] Native ZFS over NVMe/TCP storage backend for Proxmox VE
2026-07-21 11:45 9% ` Max R. Carrara
@ 2026-08-02 3:20 15% ` Joaquin Varela
2026-08-07 9:46 6% ` Max R. Carrara
0 siblings, 1 reply; 43+ results
From: Joaquin Varela @ 2026-08-02 3:20 UTC (permalink / raw)
To: Max R. Carrara; +Cc: pve-devel
Hi Max,
sorry for the delayed reply. Gmail had grouped your response into the
original RFC conversation and I missed it at the time.
Thank you very much for taking the time to review the repositories and
for the encouraging feedback.
I signed and submitted the Proxmox Individual CLA on July 15.
I have now applied the style changes you suggested:
- the new Perl modules use `use v5.36`;
- the relevant regular expressions are declared as constants and use
the `n` and `x`/`xx` modifiers with named capture groups;
- internal helpers use lexical `my sub` declarations where appropriate;
- the new code uses postfix dereferencing;
- the submission branches do not contain debian/changelog entries.
Regarding the storage backend used for validation, the target was a
dedicated Ubuntu 24.04 virtual machine running:
- kernel 6.8.0-136-generic;
- ZFS 2.2.2;
- Linux nvmet;
- nvme-cli 2.8;
- a ZFS pool named `tank`;
- two independent NVMe/TCP portals.
The initiators were a two-node nested Proxmox VE 9.2 cluster running
kernel 7.0.14-8-pve and nvme-cli 2.13. Each node had two independent
NVMe/TCP paths and native kernel multipath enabled.
The tests covered thin provisioning and discard, snapshots, clones,
concurrent namespace allocation, path failures, all-path loss policies,
target reboot reconstruction, bidirectional live migration under guest
I/O, migration to a degraded destination, HA fencing, a live corosync
partition and explicit dual-writer detection.
The target-reboot testing also uncovered an ACL publication race. The
backend now restores every configured Host NQN, DH-HMAC-CHAP key and
namespace before linking the subsystem to its NVMe/TCP ports.
The complete test report, machine-readable results and raw logs are
available here:
https://github.com/joaquinv98/pve-storage/tree/feature/zfs-nvme-tcp
The clean branches corresponding to the patch series are:
https://github.com/joaquinv98/pve-storage/tree/submission/zfs-nvme-tcp-rfc-v2
https://github.com/joaquinv98/pve-manager/tree/submission/zfs-nvme-tcp-rfc-v2
https://github.com/joaquinv98/pve-docs/tree/submission/zfs-nvme-tcp-rfc-v2
I have prepared the formal pve-storage, pve-manager and pve-docs patch
series and will send them to pve-devel as separate threads shortly.
Thank you again for your review.
Kind regards,
Joaquin Varela
On Tue, Jul 21, 2026 at 8:46 AM Max R. Carrara <m.carrara@proxmox.com>
wrote:
> On Wed Jul 15, 2026 at 6:23 PM CEST, Joaquin Varela wrote:
> > Hello,
> >
> > I have implemented an in-tree Proxmox VE storage backend named `zfsnvme`.
> > It follows the remote ZFS lifecycle model used by ZFS over iSCSI, but
> uses
> > Linux nvmet, NVMe/TCP and native kernel multipath.
>
> Hello!
>
> This sounds like a great contribution! Using the existing flow of the
> ZFS-over-iSCSI plugin is also a good idea.
>
> >
> > The ZFS dataset is the durable source of truth. Each owned zvol stores
> its
> > subsystem NQN, NSID and namespace UUID as ZFS user properties. Configfs
> is
> > reconciled from those properties, and the namespace UUID provides the
> stable
> > by-id path used by QEMU.
> >
> > The implementation includes:
> >
> > - one NVMe/TCP connection per configured portal and host interface;
> > - native multipath and ANA state handling;
> > - DH-HMAC-CHAP without exposing the key in process arguments;
> > - thin provisioning, discard, snapshots, rollback and linked clones;
> > - safe teardown and foreign-zvol identity checks;
> > - an explicit queue-versus-fast-fail policy for complete path loss;
> > - pve-manager and pve-docs integration.
> >
> > Validation covered the complete pve-storage test suite (593 assertions),
> > two-node live migration under guest I/O, migration to a degraded
> > destination,
> > real ANA transitions, simultaneous allocations from both cluster nodes,
> > single and dual path loss, configfs reconstruction, watchdog HA and a
> live
> > Corosync/QDevice partition. No source/destination QEMU overlap was
> observed
> > in
> > the live partition test.
> >
> > The implementation and detailed validation report are available here:
> >
> > https://github.com/joaquinv98/pve-storage/tree/feature/zfs-nvme-tcp
> > https://github.com/joaquinv98/pve-manager/tree/feature/zfs-nvme-tcp
> > https://github.com/joaquinv98/pve-docs/tree/feature/zfs-nvme-tcp
> >
> > The lab results are not presented as hardware certification. TLS, online
> > resize and target control-plane HA remain explicit limitations.
> >
> > I have prepared signed patch series for pve-storage, pve-manager and
> > pve-docs.
> > Before posting the full series, I would appreciate feedback on whether
> this
> > in-tree backend and its architecture are acceptable for upstream review.
>
> I have skimmed through the respective branches on your repositories
> above, and from what I can tell, the commits look pretty decent.
>
> I do have some remarks up front that you may want to consider before
> sending this in as a patch series -- mostly to save you some time:
>
> - If you haven't already, please sign our CLA. You can find the
> respective section here:
> https://proxmox.com/en/about/open-source/developers
>
> - From what I can tell, you're already adhering quite well to our style
> guide, which is great! A few remarks:
>
> * I suggest using `use v5.36;` for new Perl modules instead of
> `use strict; use warnings;`, as that enables subroutine signatures
> by default. Helps modernizing the code base overall.
> See our style guide for more details:
> https://pve.proxmox.com/wiki/Perl_Style_Guide
>
> * While not in the style guide, I can personally recommend using the
> `n` and `x`/`xx` modifiers for your regexes, and declaring any
> inline regexes as constants (=> `my $RE_NVME_FOO = qr/.../nxx`)
> in a little section at the top of your module. These flags help
> future readers to understand your regexes a little easier, and since
> `n` forces the use of named capture groups, they'll also more likely
> to be "self-documenting" in a sense.
>
> * For subroutines that are not part of the storage plugin API, i.e.
> helpers, utilts, etc. specific to your module, prefer declaring them
> using `my sub` instead of a plain `sub`, as that keeps them visible
> inside the module only (=> "private" in other languages). That
> prevents other places from using these helpers.
>
> You can then also drop the `_` prefix in that case (if you prefer).
>
> * I also suggest using postfix dereferencing instead of the
> "traditional" dereferencing syntax, that is, `$hashref->%*` instead
> of `%$hashref`, for example. It's a little more legible and makes
> nested hash access a little easier to follow as well. Note that this
> isn't explicitly stated in our style guide either (we only have it
> there for subref calls, hash and array accessing), so no hard
> feelings.
>
> - When you submit your series, please do not any entries in
> `debian/changelog` -- though it's nice to see that you've been
> thorough there!
>
> That's all I can think of / find at the moment without giving it a
> proper in-depth review. I'll happily review your series once you send it
> in.
>
> I'd also be interested in what kind of storage backend you were using
> for your tests, so that I can replicate your setup myself. I have
> skimmed through your docs and validation reports, but haven't found
> anything specific -- maybe I just missed it.
>
> >
> > Kind regards,
>
> Thanks a lot for your interest in contributing and your work already,
> it's much appreciated!
>
> Kind regards,
> Max
>
>
>
--
Joaquin Varela
^ permalink raw reply [relevance 15%]
* [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend
@ 2026-08-02 3:31 15% Joaquin Varela
2026-08-02 3:31 16% ` [PATCH storage v2 2/7] zfs: add native NVMe/TCP storage backend Joaquin Varela
2026-09-28 11:53 10% ` [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend Max R. Carrara
0 siblings, 2 replies; 43+ results
From: Joaquin Varela @ 2026-08-02 3:31 UTC (permalink / raw)
To: pve-devel; +Cc: Joaquin Varela
Hi,
this series adds an in-tree `zfsnvme` shared storage backend. It reuses the
remote ZFS lifecycle model of ZFS over iSCSI, publishes zvols through Linux
nvmet, and uses native NVMe multipath on PVE initiators.
The ZFS dataset remains the source of truth for namespace identity. The
backend stores NQN, NSID and UUID as ZFS user properties and reconstructs
derived configfs state after a target restart. Target publication is atomic:
all namespaces, Host NQN ACLs and authentication keys are restored before
the subsystem is linked to its NVMe/TCP ports.
This revision follows the feedback on the RFC:
* new Perl modules use v5.36;
* regular expressions are named constants using n/x and named captures;
* module-private helpers use lexical subroutines where appropriate;
* postfix dereferencing is used throughout;
* no debian/changelog entries are included.
It also makes the all-path-loss policy explicit, checks active users before
teardown, and handles both the current activation-hints API and the short
activation form used by cloud-init.
Test target:
* Ubuntu 24.04, kernel 6.8.0-136-generic;
* ZFS 2.2.2, Linux nvmet, nvme-cli 2.8;
* one ZFS pool with two independent 100 Mbit/s NVMe/TCP paths.
Initiators were a two-node nested PVE 9.2 cluster running kernel
7.0.14-8-pve and nvme-cli 2.13. The test matrix covered thin provisioning
and discard, snapshots and clones, concurrent allocation, ANA multipath,
single/all-path faults, bidirectional live migration under guest I/O,
watchdog fencing, live split-brain isolation, target reboot reconstruction,
package upgrade protection, and a verified 45.7 GB mixed-I/O soak. No
dual-writer interval was observed.
The complete report, machine-readable results and raw logs are available at:
https://github.com/joaquinv98/pve-storage/tree/feature/zfs-nvme-tcp
The branch corresponding exactly to this series is:
https://github.com/joaquinv98/pve-storage/tree/submission/zfs-nvme-tcp-rfc-v2
This remains a lab-qualified release candidate; hardware qualification and a
long-duration production-hardware soak are intentionally not claimed.
Joaquin Varela (7):
zfs: make LUN provider dispatch overridable
zfs: add native NVMe/TCP storage backend
zfsnvme: harden node preflight and storage teardown
zfsnvme: make all-path loss policy explicit
zfsnvme: accept activation hints from storage API
zfsnvme: accept short volume activation calls
zfsnvme: restore ACLs before publishing target
debian/control | 1 +
src/PVE/Storage.pm | 2 +
src/PVE/Storage/LunCmd/Makefile | 2 +-
src/PVE/Storage/LunCmd/NVMET.pm | 722 +++++++++++++++++++++++++
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/ZFSNVMePlugin.pm | 893 +++++++++++++++++++++++++++++++
src/PVE/Storage/ZFSPlugin.pm | 45 +-
src/test/run_plugin_tests.pl | 1 +
src/test/zfsnvme_test.pm | 513 ++++++++++++++++++
10 files changed, 2158 insertions(+), 24 deletions(-)
create mode 100644 src/PVE/Storage/LunCmd/NVMET.pm
create mode 100644 src/PVE/Storage/ZFSNVMePlugin.pm
create mode 100644 src/test/zfsnvme_test.pm
--
2.54.0.windows.1
^ permalink raw reply [relevance 15%]
* [PATCH storage v2 2/7] zfs: add native NVMe/TCP storage backend
2026-08-02 3:31 15% [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend Joaquin Varela
@ 2026-08-02 3:31 16% ` Joaquin Varela
2026-09-28 11:53 10% ` [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend Max R. Carrara
1 sibling, 0 replies; 43+ results
From: Joaquin Varela @ 2026-08-02 3:31 UTC (permalink / raw)
To: pve-devel; +Cc: Joaquin Varela
Add the zfsnvme shared-storage type and an NVMET LUN provider.
ZFS continues to own volume lifecycle. Linux nvmet publishes
each zvol as a namespace, and native NVMe multipath combines
the configured paths.
Persist subsystem NQN, NSID and UUID as ZFS user properties.
Configfs is derived state and reconcile can rebuild it after a
target restart. Use the namespace UUID for the stable device
path exposed to QEMU.
Bind each connection to its configured host interface, require
native multipath, and support DH-HMAC-CHAP without exposing
secrets in argv. Add tests for parsing, identity, lifecycle and
connect behavior.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
debian/control | 1 +
src/PVE/Storage.pm | 2 +
src/PVE/Storage/LunCmd/Makefile | 2 +-
src/PVE/Storage/LunCmd/NVMET.pm | 693 ++++++++++++++++++++++++++++++
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/ZFSNVMePlugin.pm | 716 +++++++++++++++++++++++++++++++
src/test/run_plugin_tests.pl | 1 +
src/test/zfsnvme_test.pm | 350 +++++++++++++++
9 files changed, 1766 insertions(+), 2 deletions(-)
create mode 100644 src/PVE/Storage/LunCmd/NVMET.pm
create mode 100644 src/PVE/Storage/ZFSNVMePlugin.pm
create mode 100644 src/test/zfsnvme_test.pm
diff --git a/debian/control b/debian/control
index 3ad25e7..ac770a4 100644
--- a/debian/control
+++ b/debian/control
@@ -43,6 +43,7 @@ Depends: bzip2,
lvm2,
lzop,
nfs-common,
+ nvme-cli,
proxmox-backup-client (>= 2.1.10~),
proxmox-backup-file-restore,
pve-cluster (>= 5.0-32),
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index 64ea9da..4356d83 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -36,6 +36,7 @@ use PVE::Storage::CephFSPlugin;
use PVE::Storage::ISCSIDirectPlugin;
use PVE::Storage::ZFSPoolPlugin;
use PVE::Storage::ZFSPlugin;
+use PVE::Storage::ZFSNVMePlugin;
use PVE::Storage::PBSPlugin;
use PVE::Storage::BTRFSPlugin;
use PVE::Storage::ESXiPlugin;
@@ -61,6 +62,7 @@ PVE::Storage::CephFSPlugin->register();
PVE::Storage::ISCSIDirectPlugin->register();
PVE::Storage::ZFSPoolPlugin->register();
PVE::Storage::ZFSPlugin->register();
+PVE::Storage::ZFSNVMePlugin->register();
PVE::Storage::PBSPlugin->register();
PVE::Storage::BTRFSPlugin->register();
PVE::Storage::ESXiPlugin->register();
diff --git a/src/PVE/Storage/LunCmd/Makefile b/src/PVE/Storage/LunCmd/Makefile
index a7209d1..2d30cad 100644
--- a/src/PVE/Storage/LunCmd/Makefile
+++ b/src/PVE/Storage/LunCmd/Makefile
@@ -1,4 +1,4 @@
-SOURCES=Comstar.pm Istgt.pm Iet.pm LIO.pm
+SOURCES=Comstar.pm Istgt.pm Iet.pm LIO.pm NVMET.pm
.PHONY: install
install:
diff --git a/src/PVE/Storage/LunCmd/NVMET.pm b/src/PVE/Storage/LunCmd/NVMET.pm
new file mode 100644
index 0000000..7a902da
--- /dev/null
+++ b/src/PVE/Storage/LunCmd/NVMET.pm
@@ -0,0 +1,693 @@
+package PVE::Storage::LunCmd::NVMET;
+
+use v5.36;
+
+use PVE::Tools qw(run_command trim);
+
+my @ssh_opts = ('-o', 'BatchMode=yes');
+my @ssh_cmd = ('/usr/bin/ssh', @ssh_opts);
+my $id_rsa_path = '/etc/pve/priv/zfs';
+
+my $REMOTE_HELPER = <<'REMOTE_HELPER';
+set -euo pipefail
+
+ROOT=/sys/kernel/config/nvmet
+MODEL='Proxmox ZFS NVMe'
+PROP_SUBSYS='proxmox:nvme-subsys'
+PROP_NSID='proxmox:nvme-nsid'
+PROP_UUID='proxmox:nvme-uuid'
+
+die() {
+ echo "$*" >&2
+ exit 1
+}
+
+validate_nqn() {
+ local value="$1"
+ [[ "$value" =~ ^nqn\.[A-Za-z0-9][A-Za-z0-9.-]*:[A-Za-z0-9][A-Za-z0-9._:-]*$ ]] ||
+ die "invalid NQN"
+ ((${#value} <= 223)) || die "NQN is too long"
+}
+
+validate_pool() {
+ [[ "$1" =~ ^[A-Za-z0-9][A-Za-z0-9_.:/-]*$ ]] || die "invalid ZFS pool name"
+}
+
+validate_device() {
+ [[ "$1" =~ ^/dev/zvol/[A-Za-z0-9][A-Za-z0-9_.:/-]*$ ]] ||
+ die "invalid zvol device path"
+}
+
+validate_uuid() {
+ [[ "$1" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]] ||
+ die "invalid namespace UUID"
+}
+
+prepare_configfs() {
+ modprobe nvmet_tcp
+ if ! mountpoint -q /sys/kernel/config; then
+ mount -t configfs none /sys/kernel/config
+ fi
+ [[ -d "$ROOT/subsystems" && -d "$ROOT/ports" && -d "$ROOT/hosts" ]] ||
+ die "NVMe target configfs is unavailable"
+
+ install -d -m 0755 /run/lock
+ exec 9>/run/lock/pve-nvmet.lock
+ flock -w 30 9 || die "timed out waiting for NVMe target configuration lock"
+}
+
+ensure_subsystem() {
+ local nqn="$1"
+ local subsystem="$ROOT/subsystems/$nqn"
+ local serial
+
+ validate_nqn "$nqn"
+ serial="PVEZFS$(printf '%s' "$nqn" | sha256sum | cut -c1-14)"
+
+ if [[ ! -d "$subsystem" ]]; then
+ mkdir "$subsystem"
+ printf '%s\n' "$MODEL" >"$subsystem/attr_model"
+ printf '%s\n' "$serial" >"$subsystem/attr_serial"
+ else
+ local current_model current_serial
+ current_model="$(<"$subsystem/attr_model")"
+ current_serial="$(<"$subsystem/attr_serial")"
+ if [[ "$current_model" != "$MODEL" || "$current_serial" != "$serial" ]]; then
+ if find "$subsystem/namespaces" -mindepth 1 -maxdepth 1 -type d -print -quit |
+ grep -q .; then
+ die "refusing to take over existing NVMe subsystem '$nqn'"
+ fi
+ printf '%s\n' "$MODEL" >"$subsystem/attr_model"
+ printf '%s\n' "$serial" >"$subsystem/attr_serial"
+ fi
+ fi
+
+ printf '0\n' >"$subsystem/attr_allow_any_host"
+}
+
+find_port() {
+ local family="$1"
+ local address="$2"
+ local service="$3"
+ local port
+
+ for port in "$ROOT"/ports/*; do
+ [[ -d "$port" ]] || continue
+ [[ "$(<"$port/addr_trtype")" == tcp ]] || continue
+ [[ "$(<"$port/addr_adrfam")" == "$family" ]] || continue
+ [[ "$(<"$port/addr_traddr")" == "$address" ]] || continue
+ [[ "$(<"$port/addr_trsvcid")" == "$service" ]] || continue
+ basename "$port"
+ return 0
+ done
+ return 1
+}
+
+allocate_port_id() {
+ local id=1
+ while [[ -e "$ROOT/ports/$id" ]]; do
+ ((id++))
+ done
+ printf '%s\n' "$id"
+}
+
+ensure_port() {
+ local nqn="$1"
+ local spec="$2"
+ local family address service id port
+
+ IFS=, read -r family address service <<<"$spec"
+ [[ "$family" == ipv4 || "$family" == ipv6 ]] || die "invalid address family"
+ [[ "$service" =~ ^[0-9]{1,5}$ ]] || die "invalid NVMe/TCP service"
+ ((service >= 1 && service <= 65535)) || die "invalid NVMe/TCP service"
+ if [[ "$family" == ipv4 ]]; then
+ [[ "$address" =~ ^[0-9.]+$ ]] || die "invalid IPv4 target address"
+ else
+ [[ "$address" =~ ^[0-9a-fA-F:]+$ ]] || die "invalid IPv6 target address"
+ fi
+
+ id="$(find_port "$family" "$address" "$service" || true)"
+ if [[ -z "$id" ]]; then
+ id="$(allocate_port_id)"
+ port="$ROOT/ports/$id"
+ mkdir "$port"
+ printf 'tcp\n' >"$port/addr_trtype"
+ printf '%s\n' "$family" >"$port/addr_adrfam"
+ printf '%s\n' "$address" >"$port/addr_traddr"
+ printf '%s\n' "$service" >"$port/addr_trsvcid"
+ fi
+
+ port="$ROOT/ports/$id"
+ if [[ ! -e "$port/subsystems/$nqn" ]]; then
+ ln -s "$ROOT/subsystems/$nqn" "$port/subsystems/$nqn"
+ fi
+ printf '%s\n' "$id"
+}
+
+ensure_target() {
+ local nqn="$1"
+ local pool="$2"
+ shift 2
+ local spec id port desired_ports=''
+
+ validate_nqn "$nqn"
+ validate_pool "$pool"
+ (($# >= 1)) || die "at least one NVMe/TCP portal is required"
+ ensure_subsystem "$nqn"
+
+ for spec in "$@"; do
+ id="$(ensure_port "$nqn" "$spec")"
+ desired_ports="$desired_ports $id"
+ done
+
+ for port in "$ROOT"/ports/*; do
+ [[ -d "$port" && -L "$port/subsystems/$nqn" ]] || continue
+ id="$(basename "$port")"
+ case " $desired_ports " in
+ *" $id "*) ;;
+ *) rm "$port/subsystems/$nqn" ;;
+ esac
+ done
+}
+
+ensure_host() {
+ local nqn="$1"
+ local hostnqn="$2"
+ validate_nqn "$nqn"
+ validate_nqn "$hostnqn"
+ [[ -d "$ROOT/subsystems/$nqn" ]] || die "NVMe subsystem does not exist"
+ [[ -d "$ROOT/hosts/$hostnqn" ]] || mkdir "$ROOT/hosts/$hostnqn"
+}
+
+allow_host() {
+ local nqn="$1"
+ local hostnqn="$2"
+ validate_nqn "$nqn"
+ validate_nqn "$hostnqn"
+ [[ -d "$ROOT/hosts/$hostnqn" ]] || die "NVMe host does not exist"
+ if [[ ! -e "$ROOT/subsystems/$nqn/allowed_hosts/$hostnqn" ]]; then
+ ln -s "$ROOT/hosts/$hostnqn" "$ROOT/subsystems/$nqn/allowed_hosts/$hostnqn"
+ fi
+}
+
+list_volumes() {
+ local pool="$1"
+ local dataset property value source
+ declare -A datasets=()
+ declare -A subsystems=()
+ declare -A nsids=()
+ declare -A uuids=()
+
+ while IFS=$'\t' read -r dataset property value source; do
+ datasets["$dataset"]=1
+ if [[ "$source" != local && "$source" != received ]]; then
+ value='-'
+ fi
+ case "$property" in
+ "$PROP_SUBSYS") subsystems["$dataset"]="$value" ;;
+ "$PROP_NSID") nsids["$dataset"]="$value" ;;
+ "$PROP_UUID") uuids["$dataset"]="$value" ;;
+ esac
+ done < <(
+ zfs get -H -r -t volume -o name,property,value,source \
+ "$PROP_SUBSYS,$PROP_NSID,$PROP_UUID" "$pool"
+ )
+
+ for dataset in "${!datasets[@]}"; do
+ printf '%s\t%s\t%s\t%s\n' \
+ "$dataset" \
+ "${subsystems[$dataset]:--}" \
+ "${nsids[$dataset]:--}" \
+ "${uuids[$dataset]:--}"
+ done
+}
+
+property_value() {
+ local property="$1"
+ local dataset="$2"
+ local output value source
+ output="$(zfs get -H -o value,source "$property" "$dataset" 2>/dev/null || true)"
+ IFS=$'\t' read -r value source <<<"$output"
+ if [[ -z "$value" || ("$source" != local && "$source" != received) ]]; then
+ value='-'
+ fi
+ printf '%s\n' "$value"
+}
+
+identity_is_duplicate() {
+ local pool="$1"
+ local dataset="$2"
+ local nqn="$3"
+ local nsid="$4"
+ local uuid="$5"
+ local other other_nqn other_nsid other_uuid
+
+ while IFS=$'\t' read -r other other_nqn other_nsid other_uuid; do
+ [[ "$other" != "$dataset" && "$other_nqn" == "$nqn" ]] || continue
+ [[ "$other_nsid" == "$nsid" || "$other_uuid" == "$uuid" ]] && return 0
+ done < <(list_volumes "$pool")
+ return 1
+}
+
+allocate_nsid() {
+ local pool="$1"
+ local nqn="$2"
+ local dataset other_nqn other_nsid other_uuid namespace nsid=1
+ declare -A used=()
+
+ while IFS=$'\t' read -r dataset other_nqn other_nsid other_uuid; do
+ if [[ "$other_nqn" == "$nqn" && "$other_nsid" =~ ^[1-9][0-9]*$ ]]; then
+ used["$other_nsid"]=1
+ fi
+ done < <(list_volumes "$pool")
+
+ for namespace in "$ROOT/subsystems/$nqn"/namespaces/*; do
+ [[ -d "$namespace" ]] || continue
+ used["$(basename "$namespace")"]=1
+ done
+
+ while [[ -n "${used[$nsid]:-}" ]]; do
+ ((nsid++))
+ done
+ printf '%s\n' "$nsid"
+}
+
+ensure_identity() {
+ local nqn="$1"
+ local pool="$2"
+ local dataset="$3"
+ local current_nqn nsid uuid
+
+ current_nqn="$(property_value "$PROP_SUBSYS" "$dataset")"
+ nsid="$(property_value "$PROP_NSID" "$dataset")"
+ uuid="$(property_value "$PROP_UUID" "$dataset")"
+
+ if [[ "$current_nqn" != '-' && "$current_nqn" != "$nqn" ]]; then
+ die "ZFS volume '$dataset' belongs to NVMe subsystem '$current_nqn'"
+ fi
+
+ if [[ ! "$nsid" =~ ^[1-9][0-9]*$ ]] ||
+ [[ ! "$uuid" =~ ^[0-9a-fA-F-]{36}$ ]] ||
+ identity_is_duplicate "$pool" "$dataset" "$nqn" "$nsid" "$uuid"; then
+ nsid="$(allocate_nsid "$pool" "$nqn")"
+ uuid="$(< /proc/sys/kernel/random/uuid)"
+ fi
+
+ validate_uuid "$uuid"
+ zfs set "$PROP_SUBSYS=$nqn" "$PROP_NSID=$nsid" "$PROP_UUID=$uuid" "$dataset"
+ IDENTITY_NSID="$nsid"
+ IDENTITY_UUID="$uuid"
+}
+
+remove_namespace() {
+ local namespace="$1"
+ if [[ "$(<"$namespace/enable")" == 1 ]]; then
+ printf '0\n' >"$namespace/enable"
+ fi
+ rmdir "$namespace"
+}
+
+ensure_namespace() {
+ local nqn="$1"
+ local nsid="$2"
+ local uuid="$3"
+ local device="$4"
+ local namespace="$ROOT/subsystems/$nqn/namespaces/$nsid"
+ local other
+
+ validate_uuid "$uuid"
+ validate_device "$device"
+ [[ -b "$device" ]] || die "zvol '$device' is not a block device"
+ [[ -d "$ROOT/subsystems/$nqn" ]] || die "NVMe subsystem does not exist"
+
+ for other in "$ROOT/subsystems/$nqn"/namespaces/*; do
+ [[ -d "$other" && "$other" != "$namespace" ]] || continue
+ if [[ "$(<"$other/device_uuid")" == "$uuid" ]]; then
+ die "namespace UUID '$uuid' is already in use"
+ fi
+ done
+
+ if [[ -d "$namespace" ]]; then
+ if [[ "$(<"$namespace/device_uuid")" == "$uuid" ]] &&
+ [[ "$(<"$namespace/device_path")" == "$device" ]]; then
+ [[ "$(<"$namespace/enable")" == 1 ]] || printf '1\n' >"$namespace/enable"
+ return
+ fi
+ remove_namespace "$namespace"
+ fi
+
+ mkdir "$namespace"
+ if ! {
+ printf '%s\n' "$device" >"$namespace/device_path"
+ printf '%s\n' "$uuid" >"$namespace/device_uuid"
+ printf '0\n' >"$namespace/buffered_io"
+ printf '1\n' >"$namespace/enable"
+ }; then
+ printf '0\n' >"$namespace/enable" 2>/dev/null || true
+ rmdir "$namespace" 2>/dev/null || true
+ die "failed to create namespace '$nsid'"
+ fi
+}
+
+create_volume() {
+ local nqn="$1"
+ local pool="$2"
+ local device="$3"
+ local dataset
+
+ validate_nqn "$nqn"
+ validate_pool "$pool"
+ validate_device "$device"
+ dataset="${device#/dev/zvol/}"
+ [[ "$dataset" == "$pool/"* ]] || die "zvol is outside configured pool"
+ [[ "$(zfs get -H -o value type "$dataset")" == volume ]] ||
+ die "'$dataset' is not a ZFS volume"
+
+ ensure_identity "$nqn" "$pool" "$dataset"
+ ensure_namespace "$nqn" "$IDENTITY_NSID" "$IDENTITY_UUID" "$device"
+ printf '%s\n' "$IDENTITY_UUID"
+}
+
+delete_volume() {
+ local nqn="$1"
+ local uuid="$2"
+ local namespace found=0
+
+ validate_nqn "$nqn"
+ validate_uuid "$uuid"
+ [[ -d "$ROOT/subsystems/$nqn" ]] || return 0
+ for namespace in "$ROOT/subsystems/$nqn"/namespaces/*; do
+ [[ -d "$namespace" ]] || continue
+ [[ "$(<"$namespace/device_uuid")" == "$uuid" ]] || continue
+ ((found == 0)) || die "duplicate namespace UUID '$uuid'"
+ remove_namespace "$namespace"
+ found=1
+ done
+}
+
+lookup_volume() {
+ local nqn="$1"
+ local pool="$2"
+ local device="$3"
+ local dataset current_nqn nsid uuid
+
+ validate_nqn "$nqn"
+ validate_pool "$pool"
+ validate_device "$device"
+ dataset="${device#/dev/zvol/}"
+ [[ "$dataset" == "$pool/"* ]] || die "zvol is outside configured pool"
+ [[ "$(zfs get -H -o value type "$dataset")" == volume ]] ||
+ die "'$dataset' is not a ZFS volume"
+
+ current_nqn="$(property_value "$PROP_SUBSYS" "$dataset")"
+ nsid="$(property_value "$PROP_NSID" "$dataset")"
+ uuid="$(property_value "$PROP_UUID" "$dataset")"
+ [[ "$current_nqn" == "$nqn" ]] ||
+ die "ZFS volume '$dataset' is not owned by NVMe subsystem '$nqn'"
+ [[ "$nsid" =~ ^[1-9][0-9]*$ ]] || die "invalid NSID on '$dataset'"
+ validate_uuid "$uuid"
+ identity_is_duplicate "$pool" "$dataset" "$nqn" "$nsid" "$uuid" &&
+ die "duplicate NVMe identity on '$dataset'"
+
+ ensure_namespace "$nqn" "$nsid" "$uuid" "$device"
+ printf '%s\n' "$uuid"
+}
+
+lookup_view() {
+ local nqn="$1"
+ local pool="$2"
+ local uuid="$3"
+ local dataset other_nqn nsid other_uuid found=''
+
+ validate_nqn "$nqn"
+ validate_pool "$pool"
+ validate_uuid "$uuid"
+ while IFS=$'\t' read -r dataset other_nqn nsid other_uuid; do
+ [[ "$other_nqn" == "$nqn" && "$other_uuid" == "$uuid" ]] || continue
+ [[ -z "$found" ]] || die "duplicate namespace UUID '$uuid'"
+ found="$nsid"
+ done < <(list_volumes "$pool")
+ [[ "$found" =~ ^[1-9][0-9]*$ ]] || die "namespace UUID '$uuid' was not found"
+ printf '%s\n' "$found"
+}
+
+resize_volume() {
+ local nqn="$1"
+ local uuid="$2"
+ local namespace
+
+ validate_nqn "$nqn"
+ validate_uuid "$uuid"
+ for namespace in "$ROOT/subsystems/$nqn"/namespaces/*; do
+ [[ -d "$namespace" ]] || continue
+ if [[ "$(<"$namespace/device_uuid")" == "$uuid" ]]; then
+ printf '1\n' >"$namespace/revalidate_size"
+ return
+ fi
+ done
+ die "namespace UUID '$uuid' was not found"
+}
+
+reconcile() {
+ local nqn="$1"
+ local pool="$2"
+ local dataset other_nqn nsid uuid device namespace
+ declare -A desired=()
+ declare -A seen_uuid=()
+
+ validate_nqn "$nqn"
+ validate_pool "$pool"
+ [[ -d "$ROOT/subsystems/$nqn" ]] || die "NVMe subsystem does not exist"
+
+ while IFS=$'\t' read -r dataset other_nqn nsid uuid; do
+ [[ "$other_nqn" == "$nqn" ]] || continue
+ [[ "$nsid" =~ ^[1-9][0-9]*$ ]] || die "invalid NSID on '$dataset'"
+ validate_uuid "$uuid"
+ [[ -z "${desired[$nsid]:-}" ]] || die "duplicate NSID '$nsid'"
+ [[ -z "${seen_uuid[$uuid]:-}" ]] || die "duplicate namespace UUID '$uuid'"
+ desired["$nsid"]=1
+ seen_uuid["$uuid"]=1
+ device="/dev/zvol/$dataset"
+ ensure_namespace "$nqn" "$nsid" "$uuid" "$device"
+ done < <(list_volumes "$pool")
+
+ for namespace in "$ROOT/subsystems/$nqn"/namespaces/*; do
+ [[ -d "$namespace" ]] || continue
+ nsid="$(basename "$namespace")"
+ [[ -n "${desired[$nsid]:-}" ]] || remove_namespace "$namespace"
+ done
+}
+
+delete_target() {
+ local nqn="$1"
+ local subsystem="$ROOT/subsystems/$nqn"
+ local namespace port link hostnqn referenced
+ local -a hosts=()
+
+ validate_nqn "$nqn"
+ [[ -d "$subsystem" ]] || return 0
+
+ for namespace in "$subsystem"/namespaces/*; do
+ [[ -d "$namespace" ]] || continue
+ remove_namespace "$namespace"
+ done
+ for port in "$ROOT"/ports/*; do
+ [[ -d "$port" ]] || continue
+ link="$port/subsystems/$nqn"
+ [[ -L "$link" ]] && rm "$link"
+ done
+ for link in "$subsystem"/allowed_hosts/*; do
+ [[ -L "$link" ]] || continue
+ hosts+=("$(basename "$link")")
+ rm "$link"
+ done
+ rmdir "$subsystem"
+
+ # Host objects (and their DHCHAP keys) are global in nvmet. Remove an
+ # orphan only after proving that no other subsystem still authorizes it.
+ for hostnqn in "${hosts[@]}"; do
+ referenced=0
+ for link in "$ROOT"/subsystems/*/allowed_hosts/"$hostnqn"; do
+ if [[ -L "$link" ]]; then
+ referenced=1
+ break
+ fi
+ done
+ ((referenced == 1)) || rmdir "$ROOT/hosts/$hostnqn"
+ done
+}
+
+prepare_configfs
+mode="${1:-}"
+shift || true
+
+case "$mode" in
+ ensure-target) ensure_target "$@" ;;
+ ensure-host) ensure_host "$@" ;;
+ allow-host) allow_host "$@" ;;
+ create) create_volume "$@" ;;
+ delete) delete_volume "$@" ;;
+ lookup) lookup_volume "$@" ;;
+ view) lookup_view "$@" ;;
+ resize) resize_volume "$@" ;;
+ reconcile) reconcile "$@" ;;
+ delete-target) delete_target "$@" ;;
+ *) die "unknown NVMe target operation" ;;
+esac
+REMOTE_HELPER
+
+my $REMOTE_SET_HOST_KEY = <<'REMOTE_SET_HOST_KEY';
+set -euo pipefail
+
+ROOT=/sys/kernel/config/nvmet
+hostnqn="$1"
+host="$ROOT/hosts/$hostnqn"
+
+[[ "$hostnqn" =~ ^nqn\.[A-Za-z0-9][A-Za-z0-9.-]*:[A-Za-z0-9][A-Za-z0-9._:-]*$ ]] || {
+ echo "invalid host NQN '$hostnqn'" >&2
+ exit 1
+}
+((${#hostnqn} <= 223)) || {
+ echo 'host NQN is too long' >&2
+ exit 1
+}
+[[ -d "$host" ]] || {
+ echo 'NVMe host does not exist' >&2
+ exit 1
+}
+
+IFS= read -r key
+[[ "$key" =~ ^DHHC-1:[0-9A-Fa-f]{2}:[A-Za-z0-9+/=]+:$ ]] || {
+ echo 'invalid DH-HMAC-CHAP key representation' >&2
+ exit 1
+}
+current="$(<"$host/dhchap_key")"
+if [[ -n "$current" && "$current" != "$key" ]]; then
+ for link in "$ROOT"/subsystems/*/allowed_hosts/"$hostnqn"; do
+ if [[ -L "$link" ]]; then
+ echo "refusing to replace an in-use DH-HMAC-CHAP key for '$hostnqn'" >&2
+ exit 1
+ fi
+ done
+fi
+printf '%s\n' "$key" >"$host/dhchap_key"
+REMOTE_SET_HOST_KEY
+
+my sub server($scfg) {
+ return $scfg->{server} // $scfg->{portal};
+}
+
+my sub ssh_key($scfg) {
+ my $server = server($scfg);
+ return "$id_rsa_path/${server}_id_rsa";
+}
+
+my sub remote_call($scfg, $timeout, $operation, @params) {
+ my $server = server($scfg);
+ my $target = 'root@' . $server;
+ my $msg = '';
+ my $err = '';
+ my $cmd = [
+ @ssh_cmd,
+ '-i',
+ ssh_key($scfg),
+ $target,
+ '--',
+ '/bin/bash',
+ '-s',
+ '--',
+ $operation,
+ @params,
+ ];
+
+ run_command(
+ $cmd,
+ input => $REMOTE_HELPER,
+ timeout => $timeout // 10,
+ outfunc => sub($line) { $msg .= "$line\n" },
+ errfunc => sub($line) { $err .= "$line\n" },
+ errmsg => "NVMe target operation '$operation' failed",
+ );
+
+ return trim($msg);
+}
+
+sub get_base($scfg) {
+ return '/dev/zvol';
+}
+
+sub ensure_target($scfg, $hostnqn, $portals) {
+ my $nqn = $scfg->{subsysnqn};
+
+ remote_call($scfg, 15, 'ensure-target', $nqn, $scfg->{pool}, $portals->@*);
+ remote_call($scfg, 10, 'ensure-host', $nqn, $hostnqn);
+}
+
+sub set_host_key($scfg, $hostnqn, $key) {
+ my $server = server($scfg);
+ my $target = 'root@' . $server;
+ my $remote_cmd = join(
+ ' ',
+ map { PVE::Tools::shellquote($_) }
+ ('/bin/bash', '-c', $REMOTE_SET_HOST_KEY, '--', $hostnqn),
+ );
+ my $cmd = [
+ @ssh_cmd,
+ '-i',
+ ssh_key($scfg),
+ $target,
+ '--',
+ $remote_cmd,
+ ];
+
+ run_command(
+ $cmd,
+ input => "$key\n",
+ timeout => 10,
+ quiet => 1,
+ errmsg => "failed to configure NVMe DH-HMAC-CHAP key",
+ );
+}
+
+sub allow_host($scfg, $hostnqn) {
+ remote_call($scfg, 10, 'allow-host', $scfg->{subsysnqn}, $hostnqn);
+}
+
+sub reconcile($scfg) {
+ remote_call($scfg, 30, 'reconcile', $scfg->{subsysnqn}, $scfg->{pool});
+}
+
+sub delete_target($scfg) {
+ remote_call($scfg, 15, 'delete-target', $scfg->{subsysnqn});
+}
+
+my %lun_cmd_map = (
+ create_lu => sub($scfg, $timeout, $method, $device) {
+ return remote_call($scfg, $timeout, 'create', $scfg->{subsysnqn}, $scfg->{pool}, $device);
+ },
+ delete_lu => sub($scfg, $timeout, $method, $uuid) {
+ return remote_call($scfg, $timeout, 'delete', $scfg->{subsysnqn}, $uuid);
+ },
+ import_lu => sub($scfg, $timeout, $method, $device) {
+ return remote_call($scfg, $timeout, 'create', $scfg->{subsysnqn}, $scfg->{pool}, $device);
+ },
+ modify_lu => sub($scfg, $timeout, $method, $size, $uuid) {
+ return remote_call($scfg, $timeout, 'resize', $scfg->{subsysnqn}, $uuid);
+ },
+ add_view => sub($scfg, $timeout, $method, @params) {
+ return '';
+ },
+ list_view => sub($scfg, $timeout, $method, $uuid) {
+ return remote_call($scfg, $timeout, 'view', $scfg->{subsysnqn}, $scfg->{pool}, $uuid);
+ },
+ list_lu => sub($scfg, $timeout, $method, $device) {
+ return remote_call($scfg, $timeout, 'lookup', $scfg->{subsysnqn}, $scfg->{pool}, $device);
+ },
+);
+
+sub run_lun_command($scfg, $timeout, $method, @params) {
+ die "unknown command '$method'\n" if !exists($lun_cmd_map{$method});
+ return $lun_cmd_map{$method}->($scfg, $timeout, $method, @params);
+}
+
+1;
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index a67dc25..d1cbfe2 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -11,6 +11,7 @@ SOURCES= \
ISCSIDirectPlugin.pm \
ZFSPoolPlugin.pm \
ZFSPlugin.pm \
+ ZFSNVMePlugin.pm \
PBSPlugin.pm \
BTRFSPlugin.pm \
LvmThinPlugin.pm \
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index 4f69f9b..3a45a73 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -35,7 +35,7 @@ our @COMMON_TAR_FLAGS = qw(
);
our @SHARED_STORAGE = (
- 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs',
+ 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'zfsnvme', 'drbd', 'pbs',
);
our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/ZFSNVMePlugin.pm b/src/PVE/Storage/ZFSNVMePlugin.pm
new file mode 100644
index 0000000..83d086c
--- /dev/null
+++ b/src/PVE/Storage/ZFSNVMePlugin.pm
@@ -0,0 +1,716 @@
+package PVE::Storage::ZFSNVMePlugin;
+
+use v5.36;
+
+use File::Path qw(make_path);
+use IO::Socket::IP;
+use IO::File;
+use JSON;
+
+use PVE::JSONSchema;
+use PVE::RESTEnvironment qw(log_warn);
+use PVE::Storage::LunCmd::NVMET;
+use PVE::Storage::ZFSPlugin;
+use PVE::Tools qw(file_read_firstline file_set_contents run_command trim);
+
+use base qw(PVE::Storage::ZFSPlugin);
+
+my $nvme = '/usr/sbin/nvme';
+my $secret_dir = '/etc/pve/priv/storage';
+my $runtime_dir = '/run/pve-storage';
+my $max_paths = 16;
+
+my $RE_NQN = qr{
+ \A
+ nqn \.
+ [A-Za-z0-9] [A-Za-z0-9.-]*
+ :
+ [A-Za-z0-9] [A-Za-z0-9._:-]*
+ \z
+}nxx;
+my $RE_IPV4_PORTAL = qr{
+ \A
+ (?<address> [^:]+)
+ (?: : (?<port> [0-9]+))?
+ \z
+}nxx;
+my $RE_IPV6_PORTAL = qr{
+ \A
+ \[ (?<address> [^\]]+) \]
+ (?: : (?<port> [0-9]+))?
+ \z
+}nxx;
+my $RE_HOST_IFACE = qr{\A [A-Za-z0-9_.-]+ \z}nxx;
+my $RE_DHCHAP_KEY = qr{
+ \A DHHC-1 : [0-9A-Fa-f]{2} : [A-Za-z0-9+/=]+ : \z
+}nxx;
+my $RE_NVME_CONTROLLER = qr{\A nvme [0-9]+ \z}nxx;
+my $RE_NVME_SUBSYSTEM = qr{\A nvme-subsys [0-9]+ \z}nxx;
+my $RE_TRADDR = qr{(?: \A | ,) traddr=(?<value>[^,]+)}nxx;
+my $RE_TRSVCID = qr{(?: \A | ,) trsvcid=(?<value>[^,]+)}nxx;
+my $RE_HOST_IFACE_ADDRESS = qr{(?: \A | ,) host_iface=(?<value>[^,]+)}nxx;
+
+sub verify_nvme_nqn($value, $noerr = undef) {
+
+ if (
+ length($value) > 223
+ || $value !~ $RE_NQN
+ ) {
+ return undef if $noerr;
+ die "value is not a valid NVMe qualified name\n";
+ }
+
+ return $value;
+}
+
+sub parse_nvme_portals($value, $noerr = undef) {
+ my $result = [];
+ my $seen = {};
+
+ for my $entry (split(/,/, $value // '')) {
+ $entry = trim($entry);
+ my ($address, $port, $family);
+ if ($entry =~ $RE_IPV6_PORTAL) {
+ ($address, $port, $family) = ($+{address}, $+{port} // 4420, 'ipv6');
+ } elsif ($entry =~ $RE_IPV4_PORTAL) {
+ ($address, $port, $family) = ($+{address}, $+{port} // 4420, 'ipv4');
+ } else {
+ return undef if $noerr;
+ die "invalid NVMe/TCP portal '$entry'\n";
+ }
+
+ if (
+ !PVE::JSONSchema::pve_verify_ip($address, 1)
+ || ($family eq 'ipv4' && index($address, ':') >= 0)
+ || ($family eq 'ipv6' && index($address, ':') < 0)
+ || $port < 1
+ || $port > 65535
+ ) {
+ return undef if $noerr;
+ die "invalid NVMe/TCP portal '$entry'\n";
+ }
+ my $id = join("\0", $family, $address, $port);
+ if ($seen->{$id}++) {
+ return undef if $noerr;
+ die "duplicate NVMe/TCP portal '$entry'\n";
+ }
+ push $result->@*, {
+ address => $address,
+ port => int($port),
+ family => $family,
+ };
+ if (scalar($result->@*) > $max_paths) {
+ return undef if $noerr;
+ die "at most $max_paths NVMe/TCP portals are supported\n";
+ }
+ }
+
+ if (!$result->@*) {
+ return undef if $noerr;
+ die "at least one NVMe/TCP portal is required\n";
+ }
+
+ return $result;
+}
+
+my sub verify_nvme_portals($value, $noerr = undef) {
+ return undef if !parse_nvme_portals($value, $noerr);
+ return $value;
+}
+
+sub parse_nvme_host_ifaces($value, $noerr = undef) {
+ my $result = [];
+
+ for my $iface (split(/,/, $value // '')) {
+ $iface = trim($iface);
+ if (length($iface) < 1 || length($iface) > 15 || $iface !~ $RE_HOST_IFACE) {
+ return undef if $noerr;
+ die "invalid NVMe/TCP host interface '$iface'\n";
+ }
+ push $result->@*, $iface;
+ }
+
+ if (!$result->@*) {
+ return undef if $noerr;
+ die "at least one NVMe/TCP host interface is required\n";
+ }
+
+ return $result;
+}
+
+my sub verify_nvme_host_ifaces($value, $noerr = undef) {
+ return undef if !parse_nvme_host_ifaces($value, $noerr);
+ return $value;
+}
+
+sub _configured_portals($scfg) {
+ my $portals = parse_nvme_portals($scfg->{'nvme-portals'});
+ my $ifaces = parse_nvme_host_ifaces($scfg->{'nvme-host-ifaces'});
+ die "nvme-host-ifaces must contain one interface for each nvme-portals entry\n"
+ if scalar($ifaces->@*) != scalar($portals->@*);
+
+ for (my $i = 0; $i < scalar($portals->@*); $i++) {
+ $portals->[$i]->{host_iface} = $ifaces->[$i];
+ }
+ return $portals;
+}
+
+PVE::JSONSchema::register_format('pve-storage-nvme-nqn', \&verify_nvme_nqn);
+PVE::JSONSchema::register_format('pve-storage-nvme-portals', \&verify_nvme_portals);
+PVE::JSONSchema::register_format('pve-storage-nvme-host-ifaces', \&verify_nvme_host_ifaces);
+
+sub type($class) {
+ return 'zfsnvme';
+}
+
+sub plugindata($class) {
+ return {
+ content => [{ images => 1 }, { images => 1 }],
+ 'sensitive-properties' => { 'dhchap-key' => 1 },
+ };
+}
+
+sub properties($class) {
+ return {
+ subsysnqn => {
+ description => "NVMe subsystem qualified name.",
+ type => 'string',
+ format => 'pve-storage-nvme-nqn',
+ },
+ 'nvme-portals' => {
+ description =>
+ "Comma-separated NVMe/TCP target addresses. The default TCP port is 4420.",
+ type => 'string',
+ format => 'pve-storage-nvme-portals',
+ maxLength => 2048,
+ },
+ 'nvme-host-ifaces' => {
+ description =>
+ "Comma-separated local interfaces, in portal order. Interface names must be identical on every cluster node.",
+ type => 'string',
+ format => 'pve-storage-nvme-host-ifaces',
+ maxLength => 512,
+ },
+ 'dhchap-key' => {
+ description => "NVMe DH-HMAC-CHAP key in secret representation format.",
+ type => 'string',
+ maxLength => 256,
+ },
+ 'nvme-iopolicy' => {
+ description => "Native NVMe multipath I/O policy.",
+ type => 'string',
+ enum => ['numa', 'round-robin', 'queue-depth'],
+ default => 'round-robin',
+ },
+ 'nvme-keep-alive-tmo' => {
+ description => "NVMe keep-alive timeout in seconds.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 120,
+ default => 5,
+ },
+ 'nvme-reconnect-delay' => {
+ description => "Delay between NVMe reconnect attempts in seconds.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 120,
+ default => 2,
+ },
+ 'nvme-ctrl-loss-tmo' => {
+ description => "Time to keep retrying a lost NVMe controller in seconds.",
+ type => 'integer',
+ minimum => -1,
+ maximum => 86400,
+ default => 600,
+ },
+ 'nvme-nr-io-queues' => {
+ description => "Number of NVMe/TCP I/O queues per controller.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 1024,
+ optional => 1,
+ },
+ };
+}
+
+sub options($class) {
+ return {
+ server => { fixed => 1 },
+ subsysnqn => { fixed => 1 },
+ 'nvme-portals' => { fixed => 1 },
+ 'nvme-host-ifaces' => { optional => 1 },
+ pool => { fixed => 1 },
+ blocksize => { fixed => 1 },
+ sparse => { optional => 1 },
+ 'dhchap-key' => { optional => 1 },
+ 'nvme-iopolicy' => { optional => 1 },
+ 'nvme-keep-alive-tmo' => { optional => 1 },
+ 'nvme-reconnect-delay' => { optional => 1 },
+ 'nvme-ctrl-loss-tmo' => { optional => 1 },
+ 'nvme-nr-io-queues' => { optional => 1 },
+ nodes => { optional => 1 },
+ disable => { optional => 1 },
+ content => { optional => 1 },
+ bwlimit => { optional => 1 },
+ };
+}
+
+sub check_config($class, $section_id, $config, $create, $skip_schema_check) {
+ if ($create) {
+ $config->{sparse} = 1 if !defined($config->{sparse});
+ $config->{'nvme-iopolicy'} //= 'round-robin';
+ $config->{'nvme-keep-alive-tmo'} //= 5;
+ $config->{'nvme-reconnect-delay'} //= 2;
+ $config->{'nvme-ctrl-loss-tmo'} //= 600;
+ }
+
+ verify_nvme_nqn($config->{subsysnqn}) if defined($config->{subsysnqn});
+ parse_nvme_portals($config->{'nvme-portals'}) if defined($config->{'nvme-portals'});
+ if (defined($config->{'nvme-host-ifaces'}) && defined($config->{'nvme-portals'})) {
+ _configured_portals($config);
+ } elsif (defined($config->{'nvme-host-ifaces'})) {
+ parse_nvme_host_ifaces($config->{'nvme-host-ifaces'});
+ }
+ return $class->SUPER::check_config($section_id, $config, $create, $skip_schema_check);
+}
+
+sub zfs_lun_provider($class, $scfg = undef) {
+ return 'PVE::Storage::LunCmd::NVMET';
+}
+
+sub zfs_request($class, $scfg, @params) {
+ local $scfg->{portal} = $scfg->{server};
+ return $class->SUPER::zfs_request($scfg, @params);
+}
+
+sub zfs_list_zvol($class, $scfg) {
+ my $list = $class->SUPER::zfs_list_zvol($scfg);
+ my $properties = $class->zfs_request(
+ $scfg,
+ 10,
+ 'get',
+ '-H',
+ '-d',
+ '1',
+ '-o',
+ 'name,value,source',
+ 'proxmox:nvme-subsys',
+ $scfg->{pool},
+ );
+ my $owned = {};
+ for my $line (split(/\n/, $properties)) {
+ my ($dataset, $nqn, $source) = split(/\t/, $line, 3);
+ next if !defined($source) || ($source ne 'local' && $source ne 'received');
+ next if !defined($nqn) || $nqn ne $scfg->{subsysnqn};
+ my $prefix = "$scfg->{pool}/";
+ next if index($dataset, $prefix) != 0;
+ $owned->{substr($dataset, length($prefix))} = 1;
+ }
+ for my $name (keys $list->%*) {
+ delete $list->{$name} if !$owned->{$name};
+ }
+ return $list;
+}
+
+my sub secret_path($storeid) {
+ return "$secret_dir/$storeid.nvme-dhchap";
+}
+
+sub _assert_unique_target($storeid, $scfg, $cfg = undef) {
+ $cfg //= PVE::Storage::config();
+ my $ids = $cfg->{ids} // {};
+ for my $other_id (keys $ids->%*) {
+ next if $other_id eq $storeid;
+ my $other = $cfg->{ids}->{$other_id};
+ next if ($other->{type} // '') ne 'zfsnvme';
+
+ die "NVMe subsystem NQN is already used by storage '$other_id'\n"
+ if ($other->{subsysnqn} // '') eq $scfg->{subsysnqn};
+ die "ZFS pool '$scfg->{pool}' on '$scfg->{server}' is already used by storage '$other_id'\n"
+ if ($other->{server} // '') eq $scfg->{server}
+ && ($other->{pool} // '') eq $scfg->{pool};
+ }
+}
+
+sub _validate_secret($key) {
+ die "missing NVMe DH-HMAC-CHAP key\n" if !defined($key) || $key eq '';
+ die "invalid NVMe DH-HMAC-CHAP key representation\n"
+ if $key !~ $RE_DHCHAP_KEY;
+ return $key;
+}
+
+my sub set_secret($storeid, $key) {
+ _validate_secret($key);
+ make_path($secret_dir, { mode => 0700 });
+ file_set_contents(secret_path($storeid), "$key\n", 0600);
+}
+
+my sub get_secret($storeid) {
+ my $key = file_read_firstline(secret_path($storeid));
+ return _validate_secret($key);
+}
+
+my sub delete_secret($storeid) {
+ unlink(secret_path($storeid));
+}
+
+sub on_add_hook($class, $storeid, $scfg, %sensitive) {
+ _configured_portals($scfg);
+ _assert_unique_target($storeid, $scfg);
+ set_secret($storeid, $sensitive{'dhchap-key'});
+ return;
+}
+
+sub on_update_hook_full($class, $storeid, $scfg, $update, $delete, $sensitive) {
+ my %prospective = ($scfg->%*, $update->%*);
+ delete @prospective{$delete->@*} if $delete;
+ verify_nvme_nqn($prospective{subsysnqn});
+ _configured_portals(\%prospective);
+ _assert_unique_target($storeid, \%prospective);
+
+ my $old_key = file_read_firstline(secret_path($storeid));
+ my $key = exists($sensitive->{'dhchap-key'}) ? $sensitive->{'dhchap-key'} : $old_key;
+ _validate_secret($key);
+
+ # nvmet stores authentication on the global Host NQN object, which can be
+ # shared by multiple subsystems. Replacing an active key in place can make
+ # unrelated storages unrecoverable on their next reconnect. Until PVE can
+ # coordinate a rolling rotation on every node, fail before mutating the
+ # cluster-wide secret.
+ die "online NVMe DH-HMAC-CHAP key rotation is not supported; create a new storage/NQN\n"
+ if defined($old_key) && $key ne $old_key;
+
+ set_secret($storeid, $key) if exists($sensitive->{'dhchap-key'});
+ return;
+}
+
+sub on_delete_hook($class, $storeid, $scfg) {
+ eval { $class->deactivate_storage($storeid, $scfg) };
+ log_warn("failed to disconnect NVMe storage '$storeid': $@") if $@;
+ eval { PVE::Storage::LunCmd::NVMET::delete_target($scfg) };
+ log_warn("failed to remove NVMe target for '$storeid': $@") if $@;
+ delete_secret($storeid);
+ return;
+}
+
+my sub runtime_config_path($storeid) {
+ return "$runtime_dir/nvme-$storeid.json";
+}
+
+my sub write_runtime_config($storeid, $scfg, $hostnqn, $hostid, $key, $portals) {
+ my $ports = [
+ map {
+ {
+ transport => 'tcp',
+ traddr => $_->{address},
+ host_iface => $_->{host_iface},
+ trsvcid => "$_->{port}",
+ keep_alive_tmo => $scfg->{'nvme-keep-alive-tmo'} // 5,
+ reconnect_delay => $scfg->{'nvme-reconnect-delay'} // 2,
+ ctrl_loss_tmo => $scfg->{'nvme-ctrl-loss-tmo'} // 600,
+ ($scfg->{'nvme-nr-io-queues'}
+ ? (nr_io_queues => $scfg->{'nvme-nr-io-queues'})
+ : ()),
+ }
+ } $portals->@*
+ ];
+ my $config = [
+ {
+ hostnqn => $hostnqn,
+ hostid => $hostid,
+ dhchap_key => $key,
+ subsystems => [
+ {
+ nqn => $scfg->{subsysnqn},
+ ports => $ports,
+ application => 'pve-storage',
+ },
+ ],
+ },
+ ];
+
+ make_path($runtime_dir, { mode => 0700 });
+ my $json = JSON->new->canonical->utf8->encode($config);
+ my $path = runtime_config_path($storeid);
+ file_set_contents($path, "$json\n", 0600);
+ return $path;
+}
+
+my sub controller_states($nqn) {
+ my $states = {};
+
+ opendir(my $dh, '/sys/class/nvme') or return $states;
+ while (defined(my $entry = readdir($dh))) {
+ next if $entry !~ $RE_NVME_CONTROLLER;
+ my $base = "/sys/class/nvme/$entry";
+ my $subsys = file_read_firstline("$base/subsysnqn");
+ next if !defined($subsys) || $subsys ne $nqn;
+ my $address = file_read_firstline("$base/address") // '';
+ my $state = file_read_firstline("$base/state") // 'unknown';
+ my $traddr = $address =~ $RE_TRADDR ? $+{value} : undef;
+ my $trsvcid = $address =~ $RE_TRSVCID ? $+{value} : undef;
+ my $host_iface = $address =~ $RE_HOST_IFACE_ADDRESS ? $+{value} : undef;
+ next if !defined($traddr) || !defined($trsvcid);
+ $states->{"$traddr:$trsvcid"} = {
+ device => "/dev/$entry",
+ host_iface => $host_iface,
+ state => $state,
+ };
+ }
+ closedir($dh);
+ return $states;
+}
+
+my sub portal_reachable($portal) {
+ my $socket = IO::Socket::IP->new(
+ PeerHost => $portal->{address},
+ PeerPort => $portal->{port},
+ Proto => 'tcp',
+ Timeout => 2,
+ );
+ return 0 if !$socket;
+ close($socket);
+ return 1;
+}
+
+sub _live_portal_count($states, $portals) {
+ my $live = 0;
+ for my $portal ($portals->@*) {
+ my $id = "$portal->{address}:$portal->{port}";
+ my $controller = $states->{$id};
+ $live++
+ if $controller
+ && $controller->{state} eq 'live'
+ && ($controller->{host_iface} // '') eq $portal->{host_iface};
+ }
+ return $live;
+}
+
+sub _connect_portal($config_path, $scfg, $portal) {
+ my $cmd = [
+ $nvme,
+ 'connect',
+ '--config',
+ $config_path,
+ '--transport',
+ 'tcp',
+ '--nqn',
+ $scfg->{subsysnqn},
+ '--traddr',
+ $portal->{address},
+ '--host-iface',
+ $portal->{host_iface},
+ '--trsvcid',
+ "$portal->{port}",
+ '--keep-alive-tmo',
+ $scfg->{'nvme-keep-alive-tmo'} // 5,
+ '--reconnect-delay',
+ $scfg->{'nvme-reconnect-delay'} // 2,
+ '--ctrl-loss-tmo',
+ $scfg->{'nvme-ctrl-loss-tmo'} // 600,
+ ];
+ if (my $queues = $scfg->{'nvme-nr-io-queues'}) {
+ push $cmd->@*, '--nr-io-queues', $queues;
+ }
+
+ run_command($cmd, timeout => 10, quiet => 1, errmsg => "NVMe/TCP connect failed");
+}
+
+my sub set_iopolicy($nqn, $policy) {
+ opendir(my $dh, '/sys/class/nvme-subsystem') or return;
+ while (defined(my $entry = readdir($dh))) {
+ next if $entry !~ $RE_NVME_SUBSYSTEM;
+ my $base = "/sys/class/nvme-subsystem/$entry";
+ my $subsys = file_read_firstline("$base/subsysnqn");
+ next if !defined($subsys) || $subsys ne $nqn;
+ my $fh = IO::File->new("$base/iopolicy", 'w')
+ or die "unable to set NVMe multipath policy: $!\n";
+ print $fh "$policy\n";
+ close($fh) or die "unable to set NVMe multipath policy: $!\n";
+ }
+ closedir($dh);
+}
+
+sub activate_storage($class, $storeid, $scfg, $cache = undef) {
+ $cache //= {};
+
+ die "nvme-cli is not installed\n" if !-x $nvme;
+ die "native NVMe multipath is disabled in the running kernel\n"
+ if (file_read_firstline('/sys/module/nvme_core/parameters/multipath') // 'N') ne 'Y';
+
+ _assert_unique_target($storeid, $scfg);
+ my $portals = _configured_portals($scfg);
+ my $states = controller_states($scfg->{subsysnqn});
+ my $force_reconcile =
+ delete($cache->{'zfsnvme-force-reconcile'}->{$storeid}) // 0;
+ my $live = _live_portal_count($states, $portals);
+
+ # This method is called by the periodic storage status loop. Once every
+ # configured controller is live, all lifecycle mutations are already
+ # reconciled by their individual operations, so avoid four SSH round-trips
+ # on every status poll. Missing namespaces explicitly force the slow path
+ # from activate_volume().
+ if (!$force_reconcile && $live == scalar($portals->@*)) {
+ die "missing NVMe DH-HMAC-CHAP key\n" if !-s secret_path($storeid);
+ set_iopolicy($scfg->{subsysnqn}, $scfg->{'nvme-iopolicy'} // 'round-robin');
+ return 1;
+ }
+
+ my $hostnqn = file_read_firstline('/etc/nvme/hostnqn')
+ // die "missing /etc/nvme/hostnqn\n";
+ my $hostid = file_read_firstline('/etc/nvme/hostid')
+ // die "missing /etc/nvme/hostid\n";
+ verify_nvme_nqn($hostnqn);
+ my $key = get_secret($storeid);
+ my $target_portals = [
+ map { "$_->{family},$_->{address},$_->{port}" } $portals->@*
+ ];
+
+ PVE::Storage::LunCmd::NVMET::ensure_target($scfg, $hostnqn, $target_portals);
+ PVE::Storage::LunCmd::NVMET::set_host_key($scfg, $hostnqn, $key);
+ PVE::Storage::LunCmd::NVMET::allow_host($scfg, $hostnqn);
+ PVE::Storage::LunCmd::NVMET::reconcile($scfg);
+
+ my $config_path =
+ write_runtime_config($storeid, $scfg, $hostnqn, $hostid, $key, $portals);
+ $states = controller_states($scfg->{subsysnqn});
+ for my $portal ($portals->@*) {
+ my $id = "$portal->{address}:$portal->{port}";
+ my $needs_rebind = 0;
+ if (my $controller = $states->{$id}) {
+ $needs_rebind = ($controller->{host_iface} // '') ne $portal->{host_iface};
+ next if !$needs_rebind && $controller->{state} ne 'dead';
+ run_command(
+ [$nvme, 'disconnect', '--device', $controller->{device}],
+ timeout => 5,
+ noerr => 1,
+ quiet => 1,
+ );
+ }
+ if (!portal_reachable($portal)) {
+ log_warn("NVMe/TCP portal '$id' is unreachable");
+ next;
+ }
+ eval { _connect_portal($config_path, $scfg, $portal) };
+ log_warn("$id: $@") if $@;
+
+ # Rebind controllers one at a time. Do not disconnect the next path
+ # until this one is live on its configured interface, so changing an
+ # interface mapping cannot cause an avoidable all-path outage.
+ if ($needs_rebind) {
+ my $rebound = 0;
+ for (my $attempt = 0; $attempt < 40; $attempt++) {
+ $states = controller_states($scfg->{subsysnqn});
+ my $controller = $states->{$id};
+ if (
+ $controller
+ && $controller->{state} eq 'live'
+ && ($controller->{host_iface} // '') eq $portal->{host_iface}
+ ) {
+ $rebound = 1;
+ last;
+ }
+ select(undef, undef, undef, 0.25);
+ }
+ if (!$rebound) {
+ log_warn("NVMe/TCP portal '$id' did not rebind to '$portal->{host_iface}'");
+ last;
+ }
+ }
+ }
+
+ # Existing controllers can be in the middle of their kernel reconnect delay
+ # after a target restart. Do not create duplicates, but give that recovery
+ # cycle enough time to complete before declaring the storage unavailable.
+ for (my $attempt = 0; $attempt < 60; $attempt++) {
+ $states = controller_states($scfg->{subsysnqn});
+ last if _live_portal_count($states, $portals);
+ select(undef, undef, undef, 0.25);
+ }
+ $live = _live_portal_count($states, $portals);
+ die "no live NVMe/TCP path for storage '$storeid'\n" if !$live;
+ log_warn("storage '$storeid' is degraded: $live/" . scalar($portals->@*) . " paths live")
+ if $live < scalar($portals->@*);
+
+ set_iopolicy($scfg->{subsysnqn}, $scfg->{'nvme-iopolicy'} // 'round-robin');
+ return 1;
+}
+
+sub deactivate_storage($class, $storeid, $scfg, $cache = undef) {
+
+ run_command(
+ [$nvme, 'disconnect', '--nqn', $scfg->{subsysnqn}],
+ timeout => 15,
+ noerr => 1,
+ quiet => 1,
+ ) if -x $nvme;
+ unlink(runtime_config_path($storeid));
+ return 1;
+}
+
+sub path($class, $scfg, $volname, $storeid, $snapname = undef) {
+ die "direct access to snapshots not implemented\n" if defined($snapname);
+ my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+ my $uuid = $class->zfs_get_lu_name($scfg, $name);
+ my $path = "/dev/disk/by-id/nvme-uuid.$uuid";
+ return ($path, $vmid, $vtype);
+}
+
+sub qemu_blockdev_options($class, $scfg, $storeid, $volname, $machine_version, $options) {
+ die "direct access to snapshots not implemented\n" if $options->{'snapshot-name'};
+ my ($path) = $class->path($scfg, $volname, $storeid);
+ return { driver => 'host_device', filename => $path };
+}
+
+sub activate_volume($class, $storeid, $scfg, $volname, $snapname, $cache = undef) {
+ die "unable to activate snapshot from remote zfs storage\n" if $snapname;
+ my ($path) = $class->path($scfg, $volname, $storeid);
+ if (!-b $path) {
+ $cache //= {};
+ $cache->{'zfsnvme-force-reconcile'}->{$storeid} = 1;
+ $class->activate_storage($storeid, $scfg, $cache);
+ for (my $attempt = 0; $attempt < 40 && !-b $path; $attempt++) {
+ select(undef, undef, undef, 0.25);
+ }
+ }
+ die "NVMe namespace for '$volname' did not appear\n" if !-b $path;
+ return 1;
+}
+
+sub deactivate_volume($class, $storeid, $scfg, $volname, $snapname, $cache = undef) {
+ die "unable to deactivate snapshot from remote zfs storage\n" if $snapname;
+ return 1;
+}
+
+sub volume_resize($class, $scfg, $storeid, $volname, $size, $running, $snapname) {
+ # QEMU's block_resize command explicitly cannot resize host block devices.
+ # Reject before changing the zvol/namespace, otherwise qemu-server would
+ # leave the backend larger while the running VM and its config keep the old
+ # size. A stopped VM is reopened with the new capacity on its next start.
+ die "online resize is not supported for NVMe/TCP block devices; stop the VM first\n"
+ if $running;
+ return $class->SUPER::volume_resize(
+ $scfg, $storeid, $volname, $size, $running, $snapname,
+ );
+}
+
+sub alloc_image($class, $storeid, $scfg, $vmid, $fmt, $name, $size) {
+ die "unsupported format '$fmt'" if $fmt ne 'raw';
+ die "illegal name '$name' - should be 'vm-$vmid-*'\n"
+ if $name && index($name, "vm-$vmid-") != 0;
+ my $volname = $name // $class->find_free_diskname($storeid, $scfg, $vmid, $fmt);
+
+ $class->zfs_create_zvol($scfg, $volname, $size);
+ eval {
+ my $uuid = $class->zfs_create_lu($scfg, $volname);
+ $class->zfs_add_lun_mapping_entry($scfg, $volname, $uuid);
+ };
+ if (my $err = $@) {
+ eval { $class->zfs_delete_zvol($scfg, $volname) };
+ warn "failed to clean up zvol '$volname': $@" if $@;
+ die $err;
+ }
+ return $volname;
+}
+
+1;
diff --git a/src/test/run_plugin_tests.pl b/src/test/run_plugin_tests.pl
index 8bce9d3..c341f4d 100755
--- a/src/test/run_plugin_tests.pl
+++ b/src/test/run_plugin_tests.pl
@@ -17,6 +17,7 @@ my $res = $harness->runtests(
"get_subdir_test.pm",
"filesystem_path_test.pm",
"prune_backups_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 0000000..3e9e04b
--- /dev/null
+++ b/src/test/zfsnvme_test.pm
@@ -0,0 +1,350 @@
+package PVE::Storage::TestZFSNVMe;
+
+use v5.36;
+
+use lib qw(..);
+
+use PVE::Storage::LunCmd::LIO;
+use PVE::Storage::LunCmd::NVMET;
+use PVE::Storage::ZFSNVMePlugin;
+use PVE::Storage::ZFSPlugin;
+use Test::MockModule;
+use Test::More;
+
+is(
+ PVE::Storage::ZFSNVMePlugin::verify_nvme_nqn(
+ 'nqn.2014-08.org.nvmexpress:uuid:12345678-1234-1234-1234-123456789abc',
+ ),
+ 'nqn.2014-08.org.nvmexpress:uuid:12345678-1234-1234-1234-123456789abc',
+ 'accepts a standards-based NQN',
+);
+
+ok(
+ !PVE::Storage::ZFSNVMePlugin::verify_nvme_nqn('not-an-nqn', 1),
+ 'rejects an invalid NQN',
+);
+
+is_deeply(
+ PVE::Storage::ZFSNVMePlugin::parse_nvme_portals(
+ '10.90.1.11:4420,[fd00::11]:4421,10.90.2.11',
+ ),
+ [
+ { address => '10.90.1.11', port => 4420, family => 'ipv4' },
+ { address => 'fd00::11', port => 4421, family => 'ipv6' },
+ { address => '10.90.2.11', port => 4420, family => 'ipv4' },
+ ],
+ 'parses and normalizes IPv4 and IPv6 portals',
+);
+
+eval {
+ PVE::Storage::ZFSNVMePlugin::parse_nvme_portals(
+ '10.90.1.11:4420,10.90.1.11:4420',
+ );
+};
+like($@, qr/duplicate NVMe\/TCP portal/, 'duplicate portal is rejected');
+
+ok(
+ !PVE::Storage::ZFSNVMePlugin::parse_nvme_portals('10.90.1.11:70000', 1),
+ 'rejects an invalid TCP port',
+);
+
+ok(
+ !PVE::Storage::ZFSNVMePlugin::parse_nvme_portals(
+ join(',', map { "10.90.1.$_:4420" } 1 .. 17),
+ 1,
+ ),
+ 'limits the number of configured paths',
+);
+
+is_deeply(
+ PVE::Storage::ZFSNVMePlugin::_configured_portals({
+ 'nvme-portals' => '10.90.1.11:4420,10.90.2.11:4421',
+ 'nvme-host-ifaces' => 'ens20,ens21',
+ }),
+ [
+ {
+ address => '10.90.1.11',
+ port => 4420,
+ family => 'ipv4',
+ host_iface => 'ens20',
+ },
+ {
+ address => '10.90.2.11',
+ port => 4421,
+ family => 'ipv4',
+ host_iface => 'ens21',
+ },
+ ],
+ 'binds each target portal to its configured local interface',
+);
+
+eval {
+ PVE::Storage::ZFSNVMePlugin::_configured_portals({
+ 'nvme-portals' => '10.90.1.11,10.90.2.11',
+ 'nvme-host-ifaces' => 'ens20',
+ });
+};
+like($@, qr/one interface for each/, 'portal and host-interface counts must match');
+
+eval {
+ PVE::Storage::ZFSNVMePlugin::_assert_unique_target(
+ 'new-storage',
+ {
+ server => '192.0.2.10',
+ pool => 'tank/new',
+ subsysnqn => 'nqn.2026-07.example:duplicate',
+ },
+ {
+ ids => {
+ existing => {
+ type => 'zfsnvme',
+ server => '192.0.2.11',
+ pool => 'tank/existing',
+ subsysnqn => 'nqn.2026-07.example:duplicate',
+ },
+ },
+ },
+ );
+};
+like($@, qr/NQN is already used/, 'a subsystem NQN cannot be shared by storage definitions');
+
+eval {
+ PVE::Storage::ZFSNVMePlugin::_assert_unique_target(
+ 'new-storage',
+ {
+ server => '192.0.2.10',
+ pool => 'tank/shared',
+ subsysnqn => 'nqn.2026-07.example:new',
+ },
+ {
+ ids => {
+ existing => {
+ type => 'zfsnvme',
+ server => '192.0.2.10',
+ pool => 'tank/shared',
+ subsysnqn => 'nqn.2026-07.example:existing',
+ },
+ },
+ },
+ );
+};
+like($@, qr/ZFS pool .* is already used/, 'a target pool cannot be shared by storage definitions');
+
+ok(
+ !PVE::Storage::ZFSNVMePlugin::parse_nvme_host_ifaces('ens20,not/an/interface', 1),
+ 'rejects an invalid host interface name',
+);
+
+is(
+ PVE::Storage::ZFSNVMePlugin::_live_portal_count(
+ {
+ '10.90.1.11:4420' => { state => 'live', host_iface => 'eth0' },
+ '10.90.2.11:4420' => { state => 'live', host_iface => 'ens21' },
+ },
+ [
+ { address => '10.90.1.11', port => 4420, host_iface => 'ens20' },
+ { address => '10.90.2.11', port => 4420, host_iface => 'ens21' },
+ ],
+ ),
+ 1,
+ 'a live controller on the wrong interface is not an eligible path',
+);
+
+is(
+ PVE::Storage::ZFSNVMePlugin::_validate_secret(
+ 'DHHC-1:01:YWJjZGVmZ2hpamtsbW5vcA==:',
+ ),
+ 'DHHC-1:01:YWJjZGVmZ2hpamtsbW5vcA==:',
+ 'accepts an NVMe DH-HMAC-CHAP secret representation',
+);
+
+eval { PVE::Storage::ZFSNVMePlugin::_validate_secret('plaintext') };
+like($@, qr/invalid NVMe DH-HMAC-CHAP/, 'rejects a plaintext secret');
+
+my $nvme_mock = Test::MockModule->new('PVE::Storage::ZFSNVMePlugin');
+$nvme_mock->redefine(zfs_get_lu_name => sub { return '12345678-1234-1234-1234-123456789abc' });
+
+my $scfg = {};
+my ($path, $vmid, $vtype) = PVE::Storage::ZFSNVMePlugin->path(
+ $scfg,
+ 'vm-100-disk-0',
+ 'nvmetest',
+);
+is(
+ $path,
+ '/dev/disk/by-id/nvme-uuid.12345678-1234-1234-1234-123456789abc',
+ 'uses the stable namespace UUID symlink',
+);
+is($vmid, 100, 'returns the VM owner');
+is($vtype, 'images', 'returns the volume type');
+is_deeply(
+ PVE::Storage::ZFSNVMePlugin->qemu_blockdev_options(
+ $scfg,
+ 'nvmetest',
+ 'vm-100-disk-0',
+ undef,
+ {},
+ ),
+ {
+ driver => 'host_device',
+ filename => '/dev/disk/by-id/nvme-uuid.12345678-1234-1234-1234-123456789abc',
+ },
+ 'uses the QEMU host_device driver',
+);
+
+my $lio_mock = Test::MockModule->new('PVE::Storage::LunCmd::LIO');
+my @provider_args;
+$lio_mock->redefine(
+ run_lun_command => sub {
+ @provider_args = @_;
+ return 'ok';
+ },
+);
+is(
+ PVE::Storage::ZFSPlugin->zfs_request(
+ { iscsiprovider => 'LIO' },
+ 10,
+ 'add_view',
+ 'guid',
+ ),
+ 'ok',
+ 'legacy LIO dispatch still works',
+);
+is(ref($provider_args[0]), 'HASH', 'provider dispatch does not inject a class argument');
+is($provider_args[1], 10, 'provider timeout argument is preserved');
+is($provider_args[2], 'add_view', 'provider method argument is preserved');
+is($provider_args[3], 'guid', 'provider parameters are preserved');
+
+my @connect_cmd;
+$nvme_mock->redefine(
+ run_command => sub {
+ @connect_cmd = $_[0]->@*;
+ return 0;
+ },
+);
+PVE::Storage::ZFSNVMePlugin::_connect_portal(
+ '/run/pve-storage/test.json',
+ { subsysnqn => 'nqn.2026-07.example:test' },
+ { address => '10.90.2.11', port => 4420, host_iface => 'ens21' },
+);
+is_deeply(
+ [@connect_cmd[10, 11]],
+ ['--host-iface', 'ens21'],
+ 'nvme connect is explicitly bound to the configured data interface',
+);
+
+$nvme_mock->redefine(
+ zfs_request => sub {
+ my ($class, $config, $timeout, $method, @params) = @_;
+ return join(
+ "\n",
+ "tank/vm-100-disk-0\t1048576\t-\tvolume\t-",
+ "tank/vm-200-disk-0\t1048576\t-\tvolume\t-",
+ "tank/vm-300-disk-0\t1048576\t-\tvolume\t-",
+ '',
+ ) if $method eq 'list';
+ return join(
+ "\n",
+ "tank/vm-100-disk-0\tnqn.2026-07.example:owned\tlocal",
+ "tank/vm-200-disk-0\t-\t-",
+ "tank/vm-300-disk-0\tnqn.2026-07.example:owned\tinherited from tank",
+ '',
+ ) if $method eq 'get';
+ die "unexpected mocked ZFS method '$method'\n";
+ },
+);
+my $owned_zvols = PVE::Storage::ZFSNVMePlugin->zfs_list_zvol(
+ { pool => 'tank', subsysnqn => 'nqn.2026-07.example:owned' },
+);
+is_deeply(
+ [sort keys $owned_zvols->%*],
+ ['vm-100-disk-0'],
+ 'volume listing requires a local or received ownership property',
+);
+
+eval {
+ PVE::Storage::ZFSNVMePlugin->volume_resize(
+ {}, 'nvmetest', 'vm-100-disk-0', 2 * 1024 * 1024 * 1024, 1, undef,
+ );
+};
+like(
+ $@,
+ qr/online resize is not supported.*stop the VM first/,
+ 'online resize is rejected before mutating the backend',
+);
+
+my $update_key = 'DHHC-1:01:dXBkYXRlLXRlc3Qta2V5:';
+$nvme_mock->redefine(file_read_firstline => sub { return $update_key });
+my $zfs_parent_mock = Test::MockModule->new('PVE::Storage::ZFSPlugin');
+$zfs_parent_mock->redefine(check_config => sub { return $_[2] });
+eval {
+ PVE::Storage::ZFSNVMePlugin->check_config(
+ 'nvmetest',
+ { 'nvme-host-ifaces' => 'ens20,ens21' },
+ 0,
+ 1,
+ );
+};
+is($@, '', 'check_config accepts a valid partial update');
+
+{
+ no warnings 'redefine';
+ local *PVE::Storage::config = sub { return { ids => {} } };
+ eval {
+ PVE::Storage::ZFSNVMePlugin->on_update_hook_full(
+ 'nvmetest',
+ {
+ subsysnqn => 'nqn.2026-07.example:test',
+ 'nvme-portals' => '10.90.1.11,10.90.2.11',
+ },
+ { 'nvme-host-ifaces' => 'ens20,ens21' },
+ undef,
+ {},
+ );
+ };
+ is($@, '', 'partial update with no delete list validates against the current config');
+}
+
+my $nvmet_mock = Test::MockModule->new('PVE::Storage::LunCmd::NVMET');
+my @helper_calls;
+$nvmet_mock->redefine(
+ run_command => sub {
+ my ($cmd, %opts) = @_;
+ push @helper_calls, { cmd => $cmd, %opts };
+ return 0;
+ },
+);
+PVE::Storage::LunCmd::NVMET::ensure_target(
+ {
+ server => '192.0.2.10',
+ subsysnqn => 'nqn.2026-07.example:test',
+ pool => 'tank/pve-nvme',
+ },
+ 'nqn.2014-08.org.nvmexpress:uuid:12345678-1234-1234-1234-123456789abc',
+ ['ipv4,10.90.1.11,4420'],
+);
+like(
+ $helper_calls[0]->{input},
+ qr/current_model.*current_serial.*refusing to take over existing NVMe subsystem/s,
+ 'target reconcile verifies model and deterministic serial before taking over a subsystem',
+);
+
+my ($key_cmd, %key_opts);
+$nvmet_mock->redefine(
+ run_command => sub {
+ ($key_cmd, %key_opts) = @_;
+ return 0;
+ },
+);
+my $test_key = 'DHHC-1:01:bm90LWEtcmVhbC1rZXk=:';
+PVE::Storage::LunCmd::NVMET::set_host_key(
+ { server => '192.0.2.10' },
+ 'nqn.2014-08.org.nvmexpress:uuid:12345678-1234-1234-1234-123456789abc',
+ $test_key,
+);
+unlike(join(' ', $key_cmd->@*), qr/\Q$test_key\E/, 'DHCHAP key is absent from the process argv');
+is($key_opts{input}, "$test_key\n", 'DHCHAP key is provided through standard input');
+
+done_testing();
+
+1;
--
2.54.0.windows.1
^ permalink raw reply related [relevance 16%]
* Re: [RFC] Native ZFS over NVMe/TCP storage backend for Proxmox VE
2026-08-02 3:20 15% ` Joaquin Varela
@ 2026-08-07 9:46 6% ` Max R. Carrara
0 siblings, 0 replies; 43+ results
From: Max R. Carrara @ 2026-08-07 9:46 UTC (permalink / raw)
To: Joaquin Varela; +Cc: pve-devel
On Sun Aug 2, 2026 at 5:20 AM CEST, Joaquin Varela wrote:
> Hi Max,
>
> sorry for the delayed reply. Gmail had grouped your response into the
> original RFC conversation and I missed it at the time.
>
> Thank you very much for taking the time to review the repositories and
> for the encouraging feedback.
>
> I signed and submitted the Proxmox Individual CLA on July 15.
Hi Joaquin!
All good! You're very welcome.
Thanks for all of your work and for submitting your CLA -- I will have a
look at the patch series you have sent in once I find some time. It's
definitely in my backlog, so I will see to it eventually. Thanks again!
- Max
>
> I have now applied the style changes you suggested:
>
> - the new Perl modules use `use v5.36`;
> - the relevant regular expressions are declared as constants and use
> the `n` and `x`/`xx` modifiers with named capture groups;
> - internal helpers use lexical `my sub` declarations where appropriate;
> - the new code uses postfix dereferencing;
> - the submission branches do not contain debian/changelog entries.
>
> Regarding the storage backend used for validation, the target was a
> dedicated Ubuntu 24.04 virtual machine running:
>
> - kernel 6.8.0-136-generic;
> - ZFS 2.2.2;
> - Linux nvmet;
> - nvme-cli 2.8;
> - a ZFS pool named `tank`;
> - two independent NVMe/TCP portals.
>
> The initiators were a two-node nested Proxmox VE 9.2 cluster running
> kernel 7.0.14-8-pve and nvme-cli 2.13. Each node had two independent
> NVMe/TCP paths and native kernel multipath enabled.
>
> The tests covered thin provisioning and discard, snapshots, clones,
> concurrent namespace allocation, path failures, all-path loss policies,
> target reboot reconstruction, bidirectional live migration under guest
> I/O, migration to a degraded destination, HA fencing, a live corosync
> partition and explicit dual-writer detection.
>
> The target-reboot testing also uncovered an ACL publication race. The
> backend now restores every configured Host NQN, DH-HMAC-CHAP key and
> namespace before linking the subsystem to its NVMe/TCP ports.
>
> The complete test report, machine-readable results and raw logs are
> available here:
>
> https://github.com/joaquinv98/pve-storage/tree/feature/zfs-nvme-tcp
>
> The clean branches corresponding to the patch series are:
>
> https://github.com/joaquinv98/pve-storage/tree/submission/zfs-nvme-tcp-rfc-v2
> https://github.com/joaquinv98/pve-manager/tree/submission/zfs-nvme-tcp-rfc-v2
> https://github.com/joaquinv98/pve-docs/tree/submission/zfs-nvme-tcp-rfc-v2
>
> I have prepared the formal pve-storage, pve-manager and pve-docs patch
> series and will send them to pve-devel as separate threads shortly.
>
> Thank you again for your review.
>
> Kind regards,
> Joaquin Varela
>
> On Tue, Jul 21, 2026 at 8:46 AM Max R. Carrara <m.carrara@proxmox.com>
> wrote:
>
> > On Wed Jul 15, 2026 at 6:23 PM CEST, Joaquin Varela wrote:
> > > Hello,
> > >
> > > I have implemented an in-tree Proxmox VE storage backend named `zfsnvme`.
> > > It follows the remote ZFS lifecycle model used by ZFS over iSCSI, but
> > uses
> > > Linux nvmet, NVMe/TCP and native kernel multipath.
> >
> > Hello!
> >
> > This sounds like a great contribution! Using the existing flow of the
> > ZFS-over-iSCSI plugin is also a good idea.
> >
> > >
> > > The ZFS dataset is the durable source of truth. Each owned zvol stores
> > its
> > > subsystem NQN, NSID and namespace UUID as ZFS user properties. Configfs
> > is
> > > reconciled from those properties, and the namespace UUID provides the
> > stable
> > > by-id path used by QEMU.
> > >
> > > The implementation includes:
> > >
> > > - one NVMe/TCP connection per configured portal and host interface;
> > > - native multipath and ANA state handling;
> > > - DH-HMAC-CHAP without exposing the key in process arguments;
> > > - thin provisioning, discard, snapshots, rollback and linked clones;
> > > - safe teardown and foreign-zvol identity checks;
> > > - an explicit queue-versus-fast-fail policy for complete path loss;
> > > - pve-manager and pve-docs integration.
> > >
> > > Validation covered the complete pve-storage test suite (593 assertions),
> > > two-node live migration under guest I/O, migration to a degraded
> > > destination,
> > > real ANA transitions, simultaneous allocations from both cluster nodes,
> > > single and dual path loss, configfs reconstruction, watchdog HA and a
> > live
> > > Corosync/QDevice partition. No source/destination QEMU overlap was
> > observed
> > > in
> > > the live partition test.
> > >
> > > The implementation and detailed validation report are available here:
> > >
> > > https://github.com/joaquinv98/pve-storage/tree/feature/zfs-nvme-tcp
> > > https://github.com/joaquinv98/pve-manager/tree/feature/zfs-nvme-tcp
> > > https://github.com/joaquinv98/pve-docs/tree/feature/zfs-nvme-tcp
> > >
> > > The lab results are not presented as hardware certification. TLS, online
> > > resize and target control-plane HA remain explicit limitations.
> > >
> > > I have prepared signed patch series for pve-storage, pve-manager and
> > > pve-docs.
> > > Before posting the full series, I would appreciate feedback on whether
> > this
> > > in-tree backend and its architecture are acceptable for upstream review.
> >
> > I have skimmed through the respective branches on your repositories
> > above, and from what I can tell, the commits look pretty decent.
> >
> > I do have some remarks up front that you may want to consider before
> > sending this in as a patch series -- mostly to save you some time:
> >
> > - If you haven't already, please sign our CLA. You can find the
> > respective section here:
> > https://proxmox.com/en/about/open-source/developers
> >
> > - From what I can tell, you're already adhering quite well to our style
> > guide, which is great! A few remarks:
> >
> > * I suggest using `use v5.36;` for new Perl modules instead of
> > `use strict; use warnings;`, as that enables subroutine signatures
> > by default. Helps modernizing the code base overall.
> > See our style guide for more details:
> > https://pve.proxmox.com/wiki/Perl_Style_Guide
> >
> > * While not in the style guide, I can personally recommend using the
> > `n` and `x`/`xx` modifiers for your regexes, and declaring any
> > inline regexes as constants (=> `my $RE_NVME_FOO = qr/.../nxx`)
> > in a little section at the top of your module. These flags help
> > future readers to understand your regexes a little easier, and since
> > `n` forces the use of named capture groups, they'll also more likely
> > to be "self-documenting" in a sense.
> >
> > * For subroutines that are not part of the storage plugin API, i.e.
> > helpers, utilts, etc. specific to your module, prefer declaring them
> > using `my sub` instead of a plain `sub`, as that keeps them visible
> > inside the module only (=> "private" in other languages). That
> > prevents other places from using these helpers.
> >
> > You can then also drop the `_` prefix in that case (if you prefer).
> >
> > * I also suggest using postfix dereferencing instead of the
> > "traditional" dereferencing syntax, that is, `$hashref->%*` instead
> > of `%$hashref`, for example. It's a little more legible and makes
> > nested hash access a little easier to follow as well. Note that this
> > isn't explicitly stated in our style guide either (we only have it
> > there for subref calls, hash and array accessing), so no hard
> > feelings.
> >
> > - When you submit your series, please do not any entries in
> > `debian/changelog` -- though it's nice to see that you've been
> > thorough there!
> >
> > That's all I can think of / find at the moment without giving it a
> > proper in-depth review. I'll happily review your series once you send it
> > in.
> >
> > I'd also be interested in what kind of storage backend you were using
> > for your tests, so that I can replicate your setup myself. I have
> > skimmed through your docs and validation reports, but haven't found
> > anything specific -- maybe I just missed it.
> >
> > >
> > > Kind regards,
> >
> > Thanks a lot for your interest in contributing and your work already,
> > it's much appreciated!
> >
> > Kind regards,
> > Max
> >
> >
> >
^ permalink raw reply [relevance 6%]
* qemu-img convert runs with cache=unsafe for every block storage except zfspool
@ 2026-08-28 22:22 8% Ing. Alfonso Kuen Arroyo
2026-09-03 13:15 1% ` SPAM: " Fiona Ebner
0 siblings, 1 reply; 43+ results
From: Ing. Alfonso Kuen Arroyo @ 2026-08-28 22:22 UTC (permalink / raw)
To: pve-devel
Hello,
Reporting a data-loss path in disk move / migration that we hit in production on
PVE 9.2.4 (qemu-server 9.1.18). Happy to move this to Bugzilla if that is the
preferred channel -- I do not have an account there yet.
THE ISSUE
PVE/QemuServer/QemuImage.pm protects the cache mode only when the storage is a
ZFS pool:
122: $cachemode = 'none' if $src_scfg->{type} eq 'zfspool'; # source (-T)
149: push @$cmd, '-t', 'none' if $dst_scfg->{type} eq 'zfspool'; # target (-t)
For every other destination, qemu-img convert falls back to its own default for
-t, which is 'unsafe', i.e. BDRV_O_NO_FLUSH. If a write fails while the data is
still a dirty page, the page is dropped, the errseq is never consumed by an
fsync that would report it, and qemu-img exits 0. PVE then reports TASK OK for a
copy that silently lost data.
This affects any block destination: iSCSI, FC, LVM over SAN, NVMe-oF, and
third-party storage plugins. It is not specific to any one of them.
WHY THE EXISTING SAFETY ARGUMENT DOES NOT HOLD
The pve-devel thread that introduced this (Aug 2016) asked exactly the right
question -- "is this really safe?" -- and the answer was that bdrv_close() sends
a flush. But QEMU's bdrv_co_flush() contains:
/* But don't actually force it to the disk with cache=unsafe */
if (bs->open_flags & BDRV_O_NO_FLUSH) {
goto flush_children;
}
The flush is issued, and cache=unsafe is precisely the mode in which it does
nothing. The safety argument invalidates itself, and it has been in production
for ten years.
WHAT IT COST US
Three PVE 9 nodes against a TrueNAS SCALE 25.10.4 NVMe/TCP target. The target
was failing large commands under memory pressure -- a separate bug, ours to fix,
written up at:
https://github.com/truenas/truenas-proxmox-plugin/issues/96
Those failures should have surfaced as a failed migration. Instead:
- A 2 TiB image copy lost roughly 98 GiB, and qemu-img exited 0.
- The guest then ran 41 hours on that copy, logging 2346 XFS metadata
corruption events, before we noticed.
- All 520 "lost async page write" events were on the destination.
With -t none the copy would have failed loudly and no data would have been lost.
The storage bug was ours; the silence was not.
SUGGESTED FIX
Pass -t none for any destination that is not a file-backed storage where the
performance tradeoff was deliberately accepted. More conservatively: invert the
condition so 'unsafe' is opt-in per storage type, rather than the default for
everything except one.
REPRODUCING WITHOUT A FAULTY ARRAY
dmsetup a 'flakey' or 'error' target under a test LV, qemu-img convert onto it,
and check the exit code. The point of the report is that the exit code is 0.
Regards,
Alfonso Kuen
^ permalink raw reply [relevance 8%]
* Re: SPAM: qemu-img convert runs with cache=unsafe for every block storage except zfspool
2026-08-28 22:22 8% qemu-img convert runs with cache=unsafe for every block storage except zfspool Ing. Alfonso Kuen Arroyo
@ 2026-09-03 13:15 1% ` Fiona Ebner
0 siblings, 0 replies; 43+ results
From: Fiona Ebner @ 2026-09-03 13:15 UTC (permalink / raw)
To: Ing. Alfonso Kuen Arroyo, pve-devel
Hi Alfonso,
thank you for the report!
Am 03.09.26 um 1:13 PM schrieb Ing. Alfonso Kuen Arroyo:
> Hello,
>
> Reporting a data-loss path in disk move / migration that we hit in production on
> PVE 9.2.4 (qemu-server 9.1.18). Happy to move this to Bugzilla if that is the
> preferred channel -- I do not have an account there yet.
Yes, usually the Bugzilla is the preferred place for filing issues.
>
> THE ISSUE
>
> PVE/QemuServer/QemuImage.pm protects the cache mode only when the storage is a
> ZFS pool:
>
> 122: $cachemode = 'none' if $src_scfg->{type} eq 'zfspool'; # source (-T)
> 149: push @$cmd, '-t', 'none' if $dst_scfg->{type} eq 'zfspool'; # target (-t)
>
> For every other destination, qemu-img convert falls back to its own default for
> -t, which is 'unsafe', i.e. BDRV_O_NO_FLUSH. If a write fails while the data is
> still a dirty page, the page is dropped, the errseq is never consumed by an
> fsync that would report it, and qemu-img exits 0. PVE then reports TASK OK for a
> copy that silently lost data.
>
> This affects any block destination: iSCSI, FC, LVM over SAN, NVMe-oF, and
> third-party storage plugins. It is not specific to any one of them.
This is an unfortunate default.
> WHY THE EXISTING SAFETY ARGUMENT DOES NOT HOLD
>
> The pve-devel thread that introduced this (Aug 2016) asked exactly the right
> question -- "is this really safe?" -- and the answer was that bdrv_close() sends
> a flush. But QEMU's bdrv_co_flush() contains:
>
> /* But don't actually force it to the disk with cache=unsafe */
> if (bs->open_flags & BDRV_O_NO_FLUSH) {
> goto flush_children;
> }
>
> The flush is issued, and cache=unsafe is precisely the mode in which it does
> nothing. The safety argument invalidates itself, and it has been in production
> for ten years.
>
> WHAT IT COST US
>
> Three PVE 9 nodes against a TrueNAS SCALE 25.10.4 NVMe/TCP target. The target
> was failing large commands under memory pressure -- a separate bug, ours to fix,
> written up at:
>
> https://github.com/truenas/truenas-proxmox-plugin/issues/96
>
> Those failures should have surfaced as a failed migration. Instead:
>
> - A 2 TiB image copy lost roughly 98 GiB, and qemu-img exited 0.
> - The guest then ran 41 hours on that copy, logging 2346 XFS metadata
> corruption events, before we noticed.
> - All 520 "lost async page write" events were on the destination.
>
> With -t none the copy would have failed loudly and no data would have been lost.
> The storage bug was ours; the silence was not.
>
> SUGGESTED FIX
>
> Pass -t none for any destination that is not a file-backed storage where the
> performance tradeoff was deliberately accepted. More conservatively: invert the
> condition so 'unsafe' is opt-in per storage type, rather than the default for
> everything except one.
Yes, we might want to use none or writeback depending on the storage
type, similar to PBS restore.
>
> REPRODUCING WITHOUT A FAULTY ARRAY
>
> dmsetup a 'flakey' or 'error' target under a test LV, qemu-img convert onto it,
> and check the exit code. The point of the report is that the exit code is 0.
I'm not able to reproduce this directly, could you share more details?
[I] root@pve9a1 ~# dmsetup create test-error --table '
0 8388607 linear /dev/sdu 0
8388607 8388608 error
' 8388608
[I] root@pve9a1 ~# dmsetup create test-flakey --table '
0 8388608 flakey /dev/sdu 0 1 1
' 8388608
[I] root@pve9a1 ~# /usr/bin/qemu-img convert -p -n -f qcow2 -O raw
/mnt/pve/nfs/images/100/vm-100-disk-1.qcow2 /dev/mapper/test-error
qemu-img: error while writing at byte 4292870144: Input/output error
[I] root@pve9a1 ~ [1]# /usr/bin/qemu-img convert -p -n -f qcow2 -O raw
/mnt/pve/nfs/images/100/vm-100-disk-1.qcow2 /dev/mapper/test-flakey
qemu-img: error while writing at byte 1694498816: Input/output error
Best Regards,
Fiona
^ permalink raw reply [relevance 1%]
* Re: [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend
2026-08-02 3:31 15% [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend Joaquin Varela
2026-08-02 3:31 16% ` [PATCH storage v2 2/7] zfs: add native NVMe/TCP storage backend Joaquin Varela
@ 2026-09-28 11:53 10% ` Max R. Carrara
2026-10-05 0:27 15% ` Joaquin Varela
1 sibling, 1 reply; 43+ results
From: Max R. Carrara @ 2026-09-28 11:53 UTC (permalink / raw)
To: Joaquin Varela, pve-devel
On Sun Aug 2, 2026 at 5:31 AM CEST, Joaquin Varela wrote:
> Hi,
>
> this series adds an in-tree `zfsnvme` shared storage backend. It reuses the
> remote ZFS lifecycle model of ZFS over iSCSI, publishes zvols through Linux
> nvmet, and uses native NVMe multipath on PVE initiators.
>
> The ZFS dataset remains the source of truth for namespace identity. The
> backend stores NQN, NSID and UUID as ZFS user properties and reconstructs
> derived configfs state after a target restart. Target publication is atomic:
> all namespaces, Host NQN ACLs and authentication keys are restored before
> the subsystem is linked to its NVMe/TCP ports.
>
> This revision follows the feedback on the RFC:
>
> * new Perl modules use v5.36;
> * regular expressions are named constants using n/x and named captures;
> * module-private helpers use lexical subroutines where appropriate;
> * postfix dereferencing is used throughout;
> * no debian/changelog entries are included.
>
> It also makes the all-path-loss policy explicit, checks active users before
> teardown, and handles both the current activation-hints API and the short
> activation form used by cloud-init.
>
> Test target:
>
> * Ubuntu 24.04, kernel 6.8.0-136-generic;
> * ZFS 2.2.2, Linux nvmet, nvme-cli 2.8;
> * one ZFS pool with two independent 100 Mbit/s NVMe/TCP paths.
>
> Initiators were a two-node nested PVE 9.2 cluster running kernel
> 7.0.14-8-pve and nvme-cli 2.13. The test matrix covered thin provisioning
> and discard, snapshots and clones, concurrent allocation, ANA multipath,
> single/all-path faults, bidirectional live migration under guest I/O,
> watchdog fencing, live split-brain isolation, target reboot reconstruction,
> package upgrade protection, and a verified 45.7 GB mixed-I/O soak. No
> dual-writer interval was observed.
>
> The complete report, machine-readable results and raw logs are available at:
>
> https://github.com/joaquinv98/pve-storage/tree/feature/zfs-nvme-tcp
>
> The branch corresponding exactly to this series is:
>
> https://github.com/joaquinv98/pve-storage/tree/submission/zfs-nvme-tcp-rfc-v2
>
> This remains a lab-qualified release candidate; hardware qualification and a
> long-duration production-hardware soak are intentionally not claimed.
>
> Joaquin Varela (7):
> zfs: make LUN provider dispatch overridable
> zfs: add native NVMe/TCP storage backend
> zfsnvme: harden node preflight and storage teardown
> zfsnvme: make all-path loss policy explicit
> zfsnvme: accept activation hints from storage API
> zfsnvme: accept short volume activation calls
> zfsnvme: restore ACLs before publishing target
>
> debian/control | 1 +
> src/PVE/Storage.pm | 2 +
> src/PVE/Storage/LunCmd/Makefile | 2 +-
> src/PVE/Storage/LunCmd/NVMET.pm | 722 +++++++++++++++++++++++++
> src/PVE/Storage/Makefile | 1 +
> src/PVE/Storage/Plugin.pm | 2 +-
> src/PVE/Storage/ZFSNVMePlugin.pm | 893 +++++++++++++++++++++++++++++++
> src/PVE/Storage/ZFSPlugin.pm | 45 +-
> src/test/run_plugin_tests.pl | 1 +
> src/test/zfsnvme_test.pm | 513 ++++++++++++++++++
> 10 files changed, 2158 insertions(+), 24 deletions(-)
> create mode 100644 src/PVE/Storage/LunCmd/NVMET.pm
> create mode 100644 src/PVE/Storage/ZFSNVMePlugin.pm
> create mode 100644 src/test/zfsnvme_test.pm
Thank you very much for sending in this series and for wanting to tackle
this, it's much appreciated!
Some architectural comments -- it might be a lot to read / take in, but
that's mostly because I'm trying to give you as much context as you
might need.
1. I think the overall architecture of this plugin could be simplified a
lot by inheriting from PVE::Storage::Plugin directly, instead of
inheriting from PVE::Storage::ZFSPlugin.
The inheritance chain currently looks like this:
PVE::SectionConfig -> PVE::Storage::Plugin ->
PVE::Storage::ZFSPoolPlugin -> PVE::Storage::ZFSPlugin ->
PVE::Storage::ZFSNVMePlugin
Maybe you have noticed this yourself already, it gets quite hard to
keep track of things due to the amount of inheritance we are already
using for the ZFS things... Adding another plugin in that chain adds
more complexity in that regard. And Perl doesn't really make it easy
to work with inheritance either ;)
So, I think if you instead `use base qw(PVE::Storage::Plugin);`
directly, it should be both easier for you to implement this plugin,
and also for us to maintain. "Easier to maintain" here also implies
that changes to e.g. ZFSPoolPlugin of ZFSPlugin don't accidentally
introduce bugs or unwanted behavior in ZFSNVMePlugin.
That being said, feel free to copy the helpers / implementations that
your plugin needs from ZFSPoolPlugin and ZFSPlugin, and make them
private subs (`my sub`). Code duplication is perfectly fine in this
case IMO and doesn't hurt. Please just make sure that things related
to naming volumes (in PVE) / zvols, parsing, etc. all stay the same
-- as in, that the same formats are used as with the other ZFS
plugins.
Some additional context: I have actually long been planning to make
ZFSPlugin inherit from PVE::Storage::Plugin directly as well. The
same goes for LvmThinPlugin; it should not be inheriting from
LVMPlugin anymore either. Reason for this is that we did actually
have some regressions in LvmThinPlugin when something seemingly
unrelated was changed in LVMPlugin. Inheritance always seems to make
"perfect sense" at first, and then it comes back to bite you later
on...
So, that means that whenever I'm untangling ZFSPoolPlugin and
ZFSPlugin from one another, I can make the helpers there freestanding
functions in a separate module, e.g. PVE::Storage::Common::ZFS or
something similar. The helpers you introduce in ZFSNVMePlugin would
then also be merged / unified with the other ones, if that makes
sense.
2. Since you're then inheriting from PVE::Storage::Plugin directly, you
can also omit PVE::Storage::LunCmd::NVMET and instead have those
helpers there in PVE::Storage::ZFSNVMePlugin directly (maybe with an
`nvmet_` prefix or something).
3. The `$REMOTE_HELPER` in NVMET.pm should be Perl code instead of BASH,
as in, the remote functions should all be Perl inside the plugin
instead.
Please try to only execute individual commands remotely there as much
as possible, and do the whole parsing and other logic locally. I know
that might make things more difficult to deal with and implement at
first, but it goes a *long* way in terms of maintainability and
testability later on. You already do a lot of parsing and other
things really nicely in ZFSNVMePlugin.pm, so I think following a
similar pattern for handling things on the remote host would be
optimal.
Also, the commands you execute (remotely or locally) should not
contain any BASH-isms, since it's never *really* guaranteed that the
(remote) server has BASH as default (or even installed in some rare
cases).
Finally, don't be afraid to call multiple `ssh ...` commands in
sequence if it cannot be avoided when implementing this in Perl
instead of BASH. IMO that's perfectly fine to do here.
The only other suggestion I would make is to replace some usages of Perl
builtins with other PVE-specific helpers and different modules:
- opendir / readdir / closedir --> PVE::File::dir_glob_foreach [glob-foreach]
- glob --> PVE::File::dir_glob_regex [glob-regex]
- IP::Socket::IP->new() --> PVE::Network::tcp_ping [tcp_ping]
- `my $fh = IO::File->new(); print $fh "...";` --> PVE::SysFSTools::file_write [file_write]
(Summarizing this here instead of as inline comments, since that might be
easier for you.)
Those three points are the biggest things that should be addressed IMO.
Otherwise, there is not really anything that I would change much.
I think the code quality is excellent overall, and it's really nice to
see that you added tests! :)
I'll leave you with this for now; the patches for pve-manager and
pve-docs look fine at a first glance. I'll have to see how we'll handle
the docs in particular, since it's been a little while since we
introduced a completely new plugin.
So, I would leave the docs as-is for now (unless something of your
implementation changes); if we need to format / adapt / change something
in particular, we'll follow up with our own patches there.
Overall, I'm quite happy with how this is turning out! I think once the
architectural things have been addressed, we can seriously consider
merging this. Fantastic work so far; thank you very much for your
contributions!
[glob-foreach]: https://git.proxmox.com/?p=pve-common.git;a=blob;f=src/PVE/File.pm;h=7d0f7ab95dec2ef33744243d419e882d490e6218;hb=refs/heads/master#l275
[glob-regex]: https://git.proxmox.com/?p=pve-common.git;a=blob;f=src/PVE/File.pm;h=7d0f7ab95dec2ef33744243d419e882d490e6218;hb=refs/heads/master#l260
[tcp-ping]: https://git.proxmox.com/?p=pve-common.git;a=blob;f=src/PVE/Network.pm;h=90a2bf13779e0fae6574bc4040718d0359ccfc57;hb=refs/heads/master#l713
[file-write]: https://git.proxmox.com/?p=pve-common.git;a=blob;f=src/PVE/SysFSTools.pm;h=5d007027907b1c97d3d3742afe65bae17e1039e6;hb=refs/heads/master#l251
^ permalink raw reply [relevance 10%]
* [PATCH storage v3 0/4] add ZFS over NVMe/TCP storage plugin
@ 2026-10-05 0:26 14% Joaquin Varela
2026-10-05 0:26 16% ` [PATCH storage v3 1/4] zfsnvme: " Joaquin Varela
` (3 more replies)
0 siblings, 4 replies; 43+ results
From: Joaquin Varela @ 2026-10-05 0:26 UTC (permalink / raw)
To: pve-devel
Hi,
this is v3 of the zfsnvme backend: ZFS volumes on a remote Linux
target, exported with the kernel's nvmet over NVMe/TCP and used through
native NVMe multipath and DH-HMAC-CHAP on the nodes.
The scope is one remote Linux ZFS/nvmet target and its integration with
the PVE shared-storage API. This series does not implement target high
availability, pool ownership between target machines, or target fencing.
PVE remains responsible for VM placement and node fencing. The namespace
identity and reconnect behavior are intended to allow an independently
managed target to recover, but a multi-head target has not been qualified.
v2: https://lore.proxmox.com/pve-devel/cover.1785636979.git.joaquinvarela@neatech.ar/
Changes since v2, following Max's review:
1. The plugin inherits from PVE::Storage::Plugin directly. The ZFS
helpers it needs are private copies; volume names and their parsing
are the same as in the other ZFS plugins.
2. PVE::Storage::LunCmd::NVMET is gone; the nvmet code lives in the
plugin with an nvmet_ prefix.
3. There is no remote helper anymore. ZFS/configfs parsing,
storage-configuration validation and operation planning happen locally,
in functions that are tested on their own. Optional patch 3/4 adds a
fixed target-side transport guard, described below.
The target state is read in one call: 'zfs get' on the pool and its
direct children, and one 'find' over the nvmet configfs tree that
lists its objects, prints the attributes the plugin uses with 'grep'
and reads host keys only as 'sha256sum' digests. The first such read
of an operation under the target lock starts with
'modprobe nvmet_tcp'. Other reads are 'zfs get' and 'zfs list' like
in the other ZFS plugins, 'test -b' while a new zvol appears, and
'cat /proc/mounts' when that first locked read fails, to decide
whether configfs needs to be mounted. Changes are quoted simple
commands, joined with '&&' so that a step only runs after the
previous one succeeded, plus redirections into configfs attributes
and a 'dd | tee' pipe that writes the key from standard input,
without bash-isms. An export starts with 'test -b' on its zvol, and
each publish link repeats two read-only checks right before it links
the subsystem to a port: that the subsystem denies unknown hosts and
that every configured host has its ACL. A pmxcfs domain lock per
target serializes changes within the cluster. Patch 3/4 adds the only
shell control flow, see below.
4. opendir/readdir and glob were replaced by
PVE::File::dir_glob_foreach, nested where a sysfs walk spans several
directory levels, because dir_glob_regex returns only the first
match; IO::Socket::IP was replaced by PVE::Network::tcp_ping, and
IO::File by PVE::SysFSTools::file_write.
Other changes:
- Each storage needs its own NVMe/TCP listeners (address and port) on
the target. nvmet answers a connect to a listener that does not
publish the subsystem yet with DNR, and the node then deletes the
controller regardless of the controller loss timeout. After a target
restart the plugin restores one storage at a time, so storages that
shared a listener could lose their controllers. Adding, updating and
activating a storage now refuse a portal whose listener another
zfsnvme storage uses, also a disabled one, and a target address that
another storage reaches through a different server value, since the
server value names the lock per target. IPv6 addresses are compared
in canonical form.
- Nodes create each missing path with a single write to
/dev/nvme-fabrics in a short-lived child process
(PVE::Tools::run_fork_with_timeout) instead of running
'nvme connect --config'. With the Debian trixie versions tested here,
nvme-cli 2.13-2 and libnvme 1.13-2, the invocation with an explicit
host NQN and host ID re-issues connects to existing fabrics controllers
of that host, and its sysfs scan replaces the configured DH-HMAC-CHAP
host secret with the secret of an existing controller. On a node with
another NVMe/TCP controller
of the same host NQN, such as a second zfsnvme storage on a different
target, a new path can then be attempted with the other target's key.
The same happens with nvme-cli 2.16 and libnvme 1.16.2; nvme-cli 3.1
reworked 'nvme connect --config' and did not reproduce this behavior
in our tests. The direct write also keeps the key off command lines
and avoids a temporary nvme-cli configuration file. The key still
lives in the PVE private key file and the kernel attributes described
below. It uses sysopen rather than PVE::SysFSTools::file_write,
because the kernel returns the instance of the new controller on a
read of the descriptor that wrote the options. Controllers are
deleted and rescanned through sysfs. nvme-cli stays a dependency
because it creates /etc/nvme/hostnqn and /etc/nvme/hostid.
- The plugin restricts the DH-HMAC-CHAP secret attributes of the node
controllers, and of the target host entries it writes the key to, to
mode 0600. The kernel creates them world-readable, so on the nodes
this is best effort; the docs describe the remaining exposure.
- A correction to the v2 cover letter: the "verified 45.7 GB mixed-I/O
soak" ran for only 741 seconds and was a short checksum exercise; it
is not evidence of cache-independent readback or of crash durability.
The patches:
1/4 adds the backend.
2/4 adds the tests: the plugin against mocked host interfaces, and an
emulated target that checks every command the plugin plans and
replays single and double faults during each operation.
3/4 is optional, and a question for you. ssh does not stop a remote
command when the client gives up, so a delayed command of an
abandoned operation can still change the target after the next
operation started. This patch wraps every call made inside a locked
transaction, reads included, in a small, fixed POSIX sh guard: a
flock on a file below /run on the target, a per-transaction token
that every later command of the transaction checks, and a
compare-and-set of that token when a transaction starts. Read-only
calls outside a transaction do not use it. It excludes stale
control-plane commands; it does not fence hosts or guest I/O. It
adds two SSH round trips (owner observation and claim) to every
locked operation. Without it, the backend relies on the cluster lock
like ZFS over iSCSI does. Would you prefer to keep it, a smaller
variant with only the flock and the token check, or to drop it? 4/4
applies and passes its tests with or without 3/4.
4/4 is also a question: it overrides cluster_lock_storage so that the
shared storage lock waits up to 30 seconds instead of 10 when the
caller passes no timeout, since a target change over SSH can hold
it for several seconds. Explicit timeouts are unchanged. Would you
rather have this in the plugin, as a parameter in the core, or
should I reduce the SSH round trips per operation instead?
The series is much larger than v2: the plugin has about 3,300 lines,
because the local parsing and planning replace the remote helper, and
the tests about 7,800 (two test files and two fixtures). I can split
1/4 into the schema and pvesm, the target planning, the node connect
and the volume operations, and split or trim the test patch, whatever
is easier to review.
Testing: every patch passes 'make test' on its own, unprivileged and
with stock libpve-common-perl, and the Perl files are formatted with
proxmox-perltidy. On a nested two-node PVE 9 cluster (kernel 7.0.14)
with an Ubuntu 24.04 target (kernel 6.8), I ran the checks below with
a package built from the code of this series. The only exception is
the reproduction of the shared listener problem, which deliberately
used the code before the listener check:
- activation and DH-HMAC-CHAP on both nodes and both paths through the
new connect path: one read-write open of /dev/nvme-fabrics per path,
no nvme-cli process;
- allocation, snapshot, rollback, resize, template, linked clone and
free on both nodes;
- a node that already has another NVMe/TCP controller with the same host
NQN and a different key: the plugin connects with its own key, while a
single 'nvme connect --config' in the same situation issued five
connect writes and failed authentication;
- live migration in both directions under guest writes, with readback;
- the loss and restore of one path, and a 15-second loss of both paths,
under guest writes, without guest I/O errors;
- a target reboot under guest writes: the plugin rebuilt the target
configuration and the committed data verified;
- stopping an activation task while a connect was in flight, with stock
libpve-common-perl: no process was left behind and none of the six
cancellations left a controller; a controller created out of band, as
a cancelled connect can leave behind, is adopted by the next
activation;
- the controller loss behavior the docs describe: with a 20-second
controller loss timeout, the controllers and the multipath device were
removed and an open descriptor stayed dead, while -1 with a 5-second
fast I/O fail timeout failed I/O after about 15 seconds and kept the
device, which worked again once the paths were back;
- two storages that share a listener: with the code before the
listener check, after their configuration was removed from the
target, as a target restart does, nvmet rejected the reconnects of
the storage restored second with DNR, both nodes deleted its
controllers, and an open descriptor on its multipath device stayed
dead; with this series, adding the second storage on the same
listener is refused, and with a listener per storage both recovered
from the same removal, in either order, without deleting a
controller, while an open O_DIRECT descriptor kept reading the
written data, with one read blocked for about 5 seconds in each of
the two runs.
This is lab qualification, not hardware qualification.
I also saw Dietmar's RFC "add guided remote storage setup and SAN
visibility", which adds NVMe-oF transport and path status helpers to
Diskmanage. Once it is applied, the plugin can use them instead of its
own sysfs parsing:
https://lore.proxmox.com/pve-devel/20260731102156.3947857-1-dietmar@proxmox.com/
The documentation and the editor follow as replies to this cover
letter, as separate patches for pve-docs and pve-manager.
Joaquin Varela (4):
zfsnvme: add ZFS over NVMe/TCP storage plugin
test: add zfsnvme plugin tests
zfsnvme: fence target commands of abandoned transactions
zfsnvme: wait up to 30 seconds for the shared storage lock
debian/control | 1 +
src/PVE/CLI/pvesm.pm | 21 +-
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/ZFSNVMePlugin.pm | 3319 +++++++++++
src/test/run_plugin_tests.pl | 2 +
.../zfsnvme_fixtures/configfs_snapshot.txt | 38 +
src/test/zfsnvme_fixtures/zfs_inventory.txt | 15 +
src/test/zfsnvme_target_test.pm | 5299 +++++++++++++++++
src/test/zfsnvme_test.pm | 2429 ++++++++
11 files changed, 11126 insertions(+), 3 deletions(-)
create mode 100644 src/PVE/Storage/ZFSNVMePlugin.pm
create mode 100644 src/test/zfsnvme_fixtures/configfs_snapshot.txt
create mode 100644 src/test/zfsnvme_fixtures/zfs_inventory.txt
create mode 100644 src/test/zfsnvme_target_test.pm
create mode 100644 src/test/zfsnvme_test.pm
^ permalink raw reply [relevance 14%]
* [PATCH docs v3] storage: document ZFS over NVMe/TCP
2026-10-05 0:26 14% [PATCH storage v3 0/4] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-10-05 0:26 16% ` [PATCH storage v3 1/4] zfsnvme: " Joaquin Varela
2026-10-05 0:26 10% ` [PATCH storage v3 2/4] test: add zfsnvme plugin tests Joaquin Varela
@ 2026-10-05 0:26 18% ` Joaquin Varela
2026-10-05 0:26 22% ` [PATCH manager v3] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela
3 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-10-05 0:26 UTC (permalink / raw)
To: pve-devel
Document the zfsnvme storage backend: target and node requirements,
its properties with a configuration example, native multipath and
DH-HMAC-CHAP authentication, security and availability limits, and the
lifecycle of the target configuration. Include the chapter in pvesm and
link its wiki page.
Every storage needs its own NVMe/TCP listeners on the target, and they
must not publish any other nvmet subsystem: nvmet rejects a connection
to a subsystem that is not published on the listener yet with DNR, and
the node deletes the controller regardless of the controller loss
timeout. The chapter says which portals and server values the backend
refuses for that reason, and that adding, updating or activating a
storage fails on them.
Nodes connect each path with a single write to /dev/nvme-fabrics and
delete controllers through sysfs, so nvme-cli is only needed for the
host identity files and as the administration tool. The chapter
states which connect options the running kernel must support, that
the key is never put on a command line or in a temporary file, and
which secret attributes are restricted to mode 0600 on the nodes and
on the target. Revoking a node also requires removing it from the
cluster and replacing the SSH key of every target, since every cluster
member can read the storage keys and the SSH keys give root access to
the targets.
It also explains what happens when every path stays down longer than
the controller loss timeout: the kernel removes the controllers and
the multipath block devices, and running guests have to be stopped and
started once the paths are back. A controller loss timeout of -1
needs a finite fast I/O fail timeout to keep guest I/O from blocking
for the whole outage.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
v3, accompanying "[PATCH storage v3 0/4] add ZFS over NVMe/TCP
storage plugin":
- the five v2 patches are squashed into one; the structure of the
chapter is unchanged
- changes that follow the storage v3 implementation:
- target requirements: the plugin only runs standard utilities over
SSH (listed), and the highest namespace ID handed out is kept in
the proxmox:nvme-last-nsid property of the pool
- nodes: paths are created through /dev/nvme-fabrics and deleted
through sysfs, so nvme-cli is only needed for the host identity
files (hostid must be a nonzero UUID) and as the administration
tool; the running kernel must support every connect option used,
and a failed connect is logged per portal
- every storage needs its own listeners (address and port), which
must not publish any other nvmet subsystem, because nvmet rejects
a subsystem that is not published on a listener yet with DNR and
the node then deletes the controller regardless of the controller
loss timeout; the plugin refuses a listener used by another
zfsnvme storage and a target address reached through a different
server value, and the server value is the key of the cluster-wide
lock per target
- target changes, including the restore after a target restart, take
that lock and therefore need quorum; an uncertain command result
aborts the operation and the next one reads the target again;
queries outside a transaction, such as capacity, do not take it
- one cluster per target, pools of one target must not overlap,
storages whose host NQNs overlap share the key
- nvme-host-ifaces and nvme-host-nqns are required in the schema,
an interface change is make-before-break, host NQNs can only be
added, so revoking a node has its own procedure
- sparse is no longer set by default, like in the web interface
- pvesm takes --dhchap-key as the path of a key file
- how the key reaches the kernel and the target, and the mode 0600
restriction of the secret attributes on the nodes and the target
- the connection tunables are applied to connected controllers on
the next activation
- no pvesm export/import
- removing the storage never deletes volumes; what deactivation and
the best-effort target cleanup do
- the optional transaction guard of storage 3/4: one sentence in the
target requirements and one paragraph in "Security and
Availability"; both go away if that patch is dropped
- corrections of v2 statements that were wrong or misleading:
- DH-HMAC-CHAP only authenticates the hosts to the target, with one
key shared by all nodes (v2: "authenticates the endpoints")
- the target kernel needs NVMe in-band authentication, which v2
already required but did not list
- the plugin itself loads nvmet_tcp and mounts configfs on the
target; loading the transport at boot is recommended, not required
- all-path loss: after the controller loss timeout the kernel
deletes the controllers and the multipath devices, and running
guests need a stop and start; a rejection deletes the controller
at once; -1 needs a finite fast I/O fail timeout. v2 only said
that I/O stays queued, and "600 seconds in the example" was wrong
because the example sets a fast I/O fail timeout of 30 seconds
- the configuration example uses documentation addresses and an
example NQN, and drops "shared 1", which is not a property of
this type
- the pvesm wiki link uses the page name of the chapter title
- nothing else was added, apart from wording ("controller loss
timeout" without hyphens) and the anchor for the cross-references to
"Security and Availability"; happy to trim further
v2: https://lore.proxmox.com/pve-devel/cover.1785636981.git.joaquinvarela@neatech.ar/
pve-storage-zfsnvme.adoc | 373 +++++++++++++++++++++++++++++++++++++++
pvesm.adoc | 4 +
2 files changed, 377 insertions(+)
create mode 100644 pve-storage-zfsnvme.adoc
diff --git a/pve-storage-zfsnvme.adoc b/pve-storage-zfsnvme.adoc
new file mode 100644
index 0000000..c590636
--- /dev/null
+++ b/pve-storage-zfsnvme.adoc
@@ -0,0 +1,373 @@
+[[storage_zfsnvme]]
+ZFS over NVMe/TCP Backend
+-------------------------
+ifdef::wiki[]
+:pve-toplevel:
+:title: Storage: ZFS over NVMe/TCP
+endif::wiki[]
+
+Storage pool type: `zfsnvme`
+
+This backend accesses a remote Linux machine with a ZFS pool and the kernel
+NVMe target through `ssh`. For each guest disk it creates a ZVOL, exports it as
+an NVMe namespace, and connects the {pve} nodes through native Linux NVMe/TCP
+multipath.
+
+The backend supports thin provisioning, snapshots, rollback, templates, linked
+clones, offline resize, and shared-storage live migration. Namespace UUIDs are
+stored as ZFS user properties, and the stable `nvme-uuid` device link is used
+for guest disks.
+
+Configuration
+~~~~~~~~~~~~~
+
+The target needs OpenZFS, configfs, and the `nvmet` and `nvmet-tcp` kernel
+modules with NVMe in-band authentication support. The backend runs target
+utilities over SSH and does all parsing and planning on the {pve} node, so
+neither Perl nor Bash is required on the target. Root's login shell must be a
+POSIX-compatible shell, and the target needs these standard utilities: `find`
+(with `-prune`, `-path`, and `-exec ... {} +`), `grep`, `env`, `printf`, `test`,
+`cat`, `mkdir`, `rmdir`, `rm`, `ln`, `chmod`, `dd`, `tee`, `sha256sum`,
+`modprobe`, and `mount`. The transaction guard described in
+xref:storage_zfsnvme_security[Security and Availability] also needs `/bin/sh` to
+be a POSIX-compatible shell, util-linux `flock` with `-w` and `-E` support, and
+`stat` with `-c '%u:%a'` support. Configure root SSH access like for the ZFS
+over iSCSI backend. The key for the server address is stored at
+`/etc/pve/priv/zfs/<server>_id_rsa`.
+
+The NVMe target modules must be installed on the target. The backend loads
+`nvmet_tcp` and, if necessary, mounts configfs before it restores the target
+configuration after a reboot, but loading the transport at boot is recommended.
+On a Linux target using systemd, load the transport at boot and verify the
+configfs mount:
+
+----
+# echo nvmet_tcp >/etc/modules-load.d/pve-nvmet.conf
+# modprobe nvmet_tcp
+# mountpoint /sys/kernel/config
+----
+
+The target configuration below configfs is derived state. It does not need a
+separate persistence service: after the module and ZFS pool are available, the
+backend reconstructs namespaces and UUIDs from ZFS user properties, and
+reconstructs the subsystem, host ACLs, and ports from the shared storage
+configuration during activation. The backend also records the highest
+namespace ID it handed out in the `proxmox:nvme-last-nsid` property of the
+pool dataset, so that a namespace ID is not reused for a new volume.
+
+Do not leave cloud-init device discovery enabled on a dedicated Linux target.
+A guest cloud-init ZVOL contains a `cidata` filesystem and can otherwise be
+mistaken for the target host's own NoCloud datasource during boot. After the
+target host is provisioned, remove cloud-init or disable it according to the
+distribution's documentation. For distributions supporting the standard
+disable marker, use:
+
+----
+# touch /etc/cloud/cloud-init.disabled
+----
+
+Each {pve} node needs the `nvme-tcp` module, native NVMe multipath, a unique
+`/etc/nvme/hostnqn`, and a nonzero UUID in `/etc/nvme/hostid`. The `nvme-cli`
+package creates both files and provides the NVMe administration tools.
+Interface names listed in the storage configuration must exist on every node
+where the storage is enabled.
+
+The backend does not use `nvme-cli` to connect or disconnect. It creates each
+missing path with a single write to the kernel's `/dev/nvme-fabrics` interface
+from a short-lived child process, supplying both host identities explicitly,
+and deletes controllers through sysfs. The running kernel must support every
+connect option the backend uses, including DH-HMAC-CHAP and `host_iface`;
+otherwise the connection fails with an error naming the option. A failed
+connection is logged as a warning for its portal, with the error text reported
+by the kernel.
+
+The following properties are specific to ZFS over NVMe/TCP:
+
+server::
+
+IP address or DNS name used for the SSH control connection. Connected guest I/O
+uses the independent NVMe/TCP data paths, but capacity reporting and lifecycle
+operations require this endpoint. Use a redundant management DNS name or VIP
+where the storage appliance provides one. Use the same value for a target in
+all storage definitions. A cluster-wide lock serializes transactions using this
+value. The backend can only detect another spelling of the same target, such as
+its IP address and its DNS name, when the storage definitions share a target
+address in `nvme-portals`.
+
+Use each target with only one {pve} cluster. Storage definitions on the same
+target need their own pool, NQN, and listener, see `nvme-portals`. They share
+the cluster-wide lock, which does not coordinate with other clusters.
+
+pool::
+
+ZFS pool or child dataset used exclusively by this storage definition. It must
+not contain, or be contained in, the pool of another storage definition on the
+same target. Do not share an NQN or pool with another cluster.
+
+subsysnqn::
+
+NVMe qualified name of the target subsystem. It must be unique across the
+cluster's storage definitions.
+
+nvme-portals::
+
+Comma-separated NVMe/TCP target addresses. The default service is `4420`.
+Specify IPv6 addresses in brackets, for example `[2001:db8::10]:4420`.
++
+Each portal is a listener on the target, that is, an address and port. Every
+storage definition needs its own listeners, and they must not publish any other
+nvmet subsystem, including target configuration not made by {pve}. nvmet
+rejects a connection to a subsystem that is not published on that listener yet
+with the Do Not Retry (DNR) status, for example while the target configuration
+is restored after a target restart, and the node then deletes the controller
+regardless of the controller loss timeout. The backend compares the portals
+with those of every other ZFS over NVMe/TCP storage definition, including
+disabled ones. Adding a storage, any update of its configuration, and its
+activation on a node fail if one of its portals uses an address and port that
+another storage definition already uses, whatever their `server` values, or an
+address, on any port, that another storage definition reaches through a
+different `server` value. IPv6 addresses are compared in canonical form, and an
+IPv4-mapped IPv6 address counts as the IPv4 address. Use different addresses or
+ports, and the same `server` value, for storage definitions on the same target.
+
+nvme-host-ifaces::
+
+Required. Comma-separated local interfaces, matched to `nvme-portals` by
+position. An explicit interface prevents a failed data path from reconnecting
+over the management network. Activation fails before changing target state if
+any configured interface is missing on the local node. When an interface
+changes, the backend connects the path on the new interface before it
+disconnects the old one.
+
+nvme-host-nqns::
+
+Required. Comma-separated contents of `/etc/nvme/hostnqn` from every cluster
+node that may activate the storage. The complete allow-list lets any one node
+restore all host ACLs before publishing the subsystem after a target reboot.
+Activation fails if the local node's Host NQN is absent. Update this property
+before enabling the storage on a newly added cluster node. Host NQNs can only
+be added. To revoke a host, follow the procedure in
+xref:storage_zfsnvme_security[Security and Availability], which requires
+removing the node from the cluster, a new SSH key for the target, and a new key.
+
+dhchap-key::
+
+NVMe DH-HMAC-CHAP secret in `DHHC-1` representation. The value is handled as a
+sensitive property and stored below `/etc/pve/priv/storage/` with mode `0600`.
+The target stores the key per Host NQN, so storage definitions on the same
+target whose `nvme-host-nqns` overlap must use the same key. Key rotation is
+not supported, see
+xref:storage_zfsnvme_security[Security and Availability].
+
+nvme-iopolicy::
+
+Native multipath policy: `round-robin`, `queue-depth`, or `numa`.
+
+nvme-keep-alive-tmo::
+
+Keep-alive timeout in seconds.
+
+nvme-reconnect-delay::
+
+Delay between controller reconnect attempts in seconds.
+
+nvme-ctrl-loss-tmo::
+
+Time in seconds during which the kernel keeps reconnecting a lost controller
+before it deletes the controller. `-1` retries indefinitely. See
+xref:storage_zfsnvme_security[Security and Availability] for the consequences.
+
+nvme-fast-io-fail-tmo::
+
+Optional time in seconds before outstanding I/O fails while a controller is
+reconnecting. If this property is absent, the kernel queues I/O until
+`nvme-ctrl-loss-tmo` expires. A configured value must not exceed a finite
+controller loss timeout. A value of `0` selects immediate fail-fast behavior.
+
+nvme-nr-io-queues::
+
+Optional number of I/O queues per controller.
+
+blocksize::
+
+ZFS volume block size.
+
+sparse::
+
+Use ZFS thin provisioning instead of reserving the full virtual size. If this
+property is not set, volumes are thick-provisioned, which is also the default
+in the web interface.
+
+.Configuration Example (`/etc/pve/storage.cfg`)
+----
+zfsnvme: nvme-shared
+ server 203.0.113.10
+ pool tank/pve-nvme
+ subsysnqn nqn.2026-01.com.example:pve-nvme
+ nvme-portals 192.0.2.10:4420,198.51.100.10:4420
+ nvme-host-ifaces ens1f0,ens1f1
+ nvme-host-nqns nqn.2014-08.org.nvmexpress:uuid:11111111-1111-1111-1111-111111111111,nqn.2014-08.org.nvmexpress:uuid:22222222-2222-2222-2222-222222222222
+ blocksize 16k
+ sparse 1
+ nvme-iopolicy round-robin
+ nvme-keep-alive-tmo 5
+ nvme-reconnect-delay 2
+ nvme-ctrl-loss-tmo 600
+ nvme-fast-io-fail-tmo 30
+ content images
+----
+
+The DH-HMAC-CHAP key is intentionally not shown in `storage.cfg`. Set it with
+the storage creation API or web interface. With `pvesm`, pass the path of a file
+that contains the key, for example `--dhchap-key /root/nvme-dhchap.key`. Create
+the file with mode `0600`, for example after `umask 077`, and remove it once the
+storage is created.
+
+[[storage_zfsnvme_security]]
+Security and Availability
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The target uses an ACL for the unique Host NQN of every node and never enables
+`allow_any_host`. All nodes share the DH-HMAC-CHAP key of the storage, and it
+only authenticates the hosts to the target. The target is not authenticated to
+the hosts, no Diffie-Hellman group is configured, and data is not encrypted.
+Host NQNs are not secret, so any holder of the key can connect as any allowed
+host. This backend does not configure NVMe/TCP TLS, so use isolated storage
+networks or equivalent protection.
+
+Apart from its key file, the backend keeps the key in memory. It passes the key
+to the local kernel in the connect write to `/dev/nvme-fabrics`, and to the
+target on the standard input of an SSH command. The key never appears on a
+command line, and the backend writes no temporary files.
+
+The kernel exposes the key with mode `0644` in the `dhchap_secret` sysfs
+attributes of the NVMe controllers on the nodes and in the host entries below
+`/sys/kernel/config/nvmet/hosts/` on the target. The backend attempts to
+restrict the controller attributes on the {pve} nodes to mode `0600` right after
+it creates a controller, during storage activation, and after each connection
+attempt. This is best effort: permission changes can fail, and controller
+attributes can appear or reappear after the permission check. Until then, any
+process on the node that can read sysfs, including processes in containers, can
+read the key. There is no guaranteed upper bound on the exposure interval. Check
+the actual permissions and activation warnings; do not rely on this mitigation
+to protect keys from untrusted local users. On the target, the backend restricts
+the `dhchap_key` and `dhchap_ctrl_key` attributes of a host entry to mode `0600`
+before it writes the key. A process on the target that opened one of these
+attributes before the change can still read the key through that descriptor.
+Host entries that already hold the key, for example ones created by hand, keep
+their mode. Limit shell access on both the target and the {pve} nodes to trusted
+administrators.
+
+To rotate the key, or to revoke a node:
+
+. To revoke a node, first remove it from the cluster. Every cluster member can
+ read the keys below `/etc/pve/priv/`: the DH-HMAC-CHAP key of every ZFS over
+ NVMe/TCP storage and the SSH key of every target, which gives root access to
+ the target, including its keys and volumes. Then replace the SSH key of each
+ target: create a new key pair at `/etc/pve/priv/zfs/<server>_id_rsa` (for
+ every `server` value used for the target), replace the old public key with
+ the new one in `/root/.ssh/authorized_keys` on the target, and check that
+ file for other unknown keys.
+. Move or remove every volume of the storage, including unused disks,
+ templates, VM state volumes, and disks with snapshots, which cannot be moved
+ while their snapshots exist. `pvesm list <storage>` must show no volume.
+. Remove this storage definition. The backend removes the subsystem from the
+ target once it owns no volumes. If the removal task warns that it kept the
+ NVMe target configuration, remove the remaining volumes, or the subsystem on
+ the target, before you continue.
+. On every other node that had the storage active, disconnect it with
+ `nvme disconnect --nqn <subsysnqn>` or reboot the node.
+. Create a new storage with a new key and a new `subsysnqn`, without the Host
+ NQN of a revoked node.
+
+To revoke a node, repeat this for every ZFS over NVMe/TCP storage of the
+cluster, since the node could read all of their keys. Other storage definitions
+on the same target that list any of the same Host NQNs share the key, because
+the target stores it per Host NQN. Rotate their keys together: remove all of
+them before you create the new ones.
+
+Shared access relies on {pve} cluster locking and fencing. Test quorum and
+fencing before placing production guests on the storage. Use independent
+failure domains for the configured paths and make sure the ZFS target itself
+is not a single point of failure.
+
+Changes to the target configuration, including restoring it after a target
+restart, are serialized by a cluster-wide lock per target and therefore require
+quorum. An uncertain command result aborts the operation; a subsequent
+operation reads the target again. Queries outside a transaction, such as
+capacity and namespace identity queries, do not take this lock. They can see
+intermediate state, and the underlying ZFS queries can still be delayed by
+storage activity.
+
+In addition, the transaction guard of the backend serializes the commands of
+each transaction with a lock on the target, in the runtime directory
+`/run/pve-storage-nvmet`. Before claiming a transaction, the backend observes
+the current owner without taking the target lock. The claim compares that
+observation under the lock before publishing a new token, so an abandoned claim
+cannot replace an owner that has since changed. Subsequent command groups,
+including reads, acquire the same lock and validate the token. This prevents a
+command delayed by an SSH failure or an expired cluster lock from modifying a
+volume after a newer operation has replaced it. The lock and token are shared by
+all pools and storage definitions on the target host, so they also reject
+commands from transactions that used another spelling of the server address.
+Queries outside a transaction do not wait for the target lock. The runtime
+directory must be owned by root with mode `0700`. Do not delete it or replace
+its `lock` or `owner` files while commands can still be running. A stuck command
+can block further changes; the backend does not break this lock to restore
+availability.
+
+Choose the all-path outage policy for the workload. The default configuration
+leaves `nvme-fast-io-fail-tmo` unset: transient outages can recover without
+guest block errors, but an I/O request can stall until the controller is lost.
+The default controller loss timeout is 600 seconds; the example instead
+explicitly sets a fast I/O fail timeout of 30 seconds. Set a shorter fast I/O
+fail timeout when the application prefers a prompt block error over a long
+stall. This is a service-level decision, not a universally safer default.
+
+When every path of a node stays down past the controller loss timeout, the
+kernel deletes the controllers and the multipath block devices of the storage on
+that node, and queued and new I/O fails. A running guest keeps the removed
+device open, so once the paths are back, stop and start the guest, for example
+with `qm stop <vmid>` and `qm start <vmid>`; a reboot inside the guest is not
+enough. A target that rejects the connection, for example because of an unknown
+Host NQN, a wrong key, or a listener that does not publish the subsystem yet
+(see `nvme-portals`), makes the kernel delete the controller regardless of the
+timeout. A controller loss timeout of `-1` keeps the devices, but combine it
+with a finite fast I/O fail timeout. Otherwise guest I/O, and stopping or
+migrating the guest, can block for the whole outage.
+
+Changes to `nvme-iopolicy`, `nvme-reconnect-delay`, `nvme-ctrl-loss-tmo`, and
+`nvme-fast-io-fail-tmo` are applied to connected controllers on the next
+storage activation. They do not affect an outage of all paths that is already
+in progress. `nvme-keep-alive-tmo` and `nvme-nr-io-queues` only apply to new
+controller connections, for example after a node reboot.
+
+Online resize of a running guest disk is not supported. Stop the VM before
+resizing; the new size is detected when the block device is reopened.
+
+The backend does not support volume transfer streams through `pvesm export`
+or `pvesm import`, including `raw+size`. Offline or remote migration workflows
+that require these streams cannot transfer disks to or from this backend.
+Shared-storage live migration remains supported: it does not transfer the disk
+contents.
+
+Removing the storage definition never deletes volumes. The node that removes it
+deactivates the storage, which deletes its controllers. Deactivation fails if
+one of the namespaces is still in use locally, or if the controllers cannot be
+deleted within 15 seconds (a deletion that is stuck in the kernel keeps the
+task waiting until the kernel returns); the removal then logs a warning and the
+node keeps its connections. Other nodes keep their connections. On each of
+them, run `nvme disconnect --nqn <subsysnqn>` or reboot the node. If no volumes
+of the storage remain, the backend also tries to remove the subsystem and
+unused host entries from the target. This cleanup is best effort: if it fails,
+or if volumes remain, the target configuration is kept and a warning is logged.
+
+Storage Features
+~~~~~~~~~~~~~~~~
+
+.Storage features for backend `zfsnvme`
+[width="100%",cols="m,m,3*d",options="header"]
+|==============================================================================
+|Content types |Image formats |Shared |Snapshots |Clones
+|images |raw |yes |yes |yes
+|==============================================================================
diff --git a/pvesm.adoc b/pvesm.adoc
index 5bd24b2..4ada3f0 100644
--- a/pvesm.adoc
+++ b/pvesm.adoc
@@ -439,6 +439,8 @@ See Also
* link:/wiki/Storage:_ZFS_over_ISCSI[Storage: ZFS over ISCSI]
+* link:/wiki/Storage:_ZFS_over_NVMe/TCP[Storage: ZFS over NVMe/TCP]
+
endif::wiki[]
ifndef::wiki[]
@@ -471,6 +473,8 @@ include::pve-storage-btrfs.adoc[]
include::pve-storage-zfs.adoc[]
+include::pve-storage-zfsnvme.adoc[]
+
ifdef::manvolnum[]
include::pve-copyright.adoc[]
^ permalink raw reply related [relevance 18%]
* [PATCH manager v3] ui: storage: add ZFS over NVMe/TCP editor
2026-10-05 0:26 14% [PATCH storage v3 0/4] add ZFS over NVMe/TCP storage plugin Joaquin Varela
` (2 preceding siblings ...)
2026-10-05 0:26 18% ` [PATCH docs v3] storage: document ZFS over NVMe/TCP Joaquin Varela
@ 2026-10-05 0:26 22% ` Joaquin Varela
3 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-10-05 0:26 UTC (permalink / raw)
To: pve-devel
Add an input panel for the zfsnvme storage type, so that ZFS over
NVMe/TCP storages can be added and edited in the web interface, and
register it in the storage type list and the JavaScript bundle.
The general tab covers the SSH server, ZFS pool, subsystem NQN, block
size, thin provisioning, NVMe/TCP portals, host interfaces, allowed
host NQNs, the DH-HMAC-CHAP key and the multipath I/O policy. The
connection timeouts and the number of I/O queues are advanced options.
Ranges and defaults are those of the storage plugin schema.
Apply the backend's restrictions in the form, so that they show up
before submitting: properties that are fixed after creation are
read-only when editing, host NQNs can only be added, and a fast I/O
fail timeout must not exceed a finite controller loss timeout. The key
is only requested on creation. Since the backend does not support key
rotation, editing neither shows nor resends it.
The help button links to the storage_zfsnvme section of the admin
guide, so generating OnlineHelpInfo.js requires a pve-doc-generator
that includes it.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
v3, accompanying "[PATCH storage v3 0/4] add ZFS over NVMe/TCP
storage plugin":
- rebased onto current master; the three v2 patches are squashed
- behavior changes against v2:
- thin provisioning is unchecked by default, like the API default
(the storage v3 series no longer sets sparse on creation) and the
other ZFS editors
- Allowed Host NQNs: when editing, a validator refuses to drop a
host NQN that the storage already has, since the backend refuses
it too; an edit-only hint says that host NQNs can only be added
and that revoking a host needs a new storage with a new key
- DH-HMAC-CHAP key: on creation the field checks the DHHC-1 format
(DHHC-1:0[0-3]:<base64>:) and is required; when editing it shows
"Unchanged (rotation not supported)" and sends nothing (v2 showed
"Configured"); the label is "DH-HMAC-CHAP Key" instead of "DHCHAP
Key"
- Fast I/O Fail Timeout: a validator refuses a value above a finite
Controller Loss Timeout, revalidated when that timeout changes;
an empty field shows "Off"
- layout: I/O Queues moved to the first advanced column and shows
"Default" when empty; the fast I/O fail sentence moved from the
general hint to a new advanced hint, which also says that a
Controller Loss Timeout of -1 retries forever
- placeholders use example values only, and the portals placeholder
no longer shows the default port
- the options match the storage v3 series, whose schema did not change
for the editor (nvme-host-ifaces and nvme-host-nqns are required in
the schema now, which the editor already enforced); its online help
needs the docs patch
v2: https://lore.proxmox.com/pve-devel/cover.1785636980.git.joaquinvarela@neatech.ar/
www/manager6/Makefile | 1 +
www/manager6/Utils.js | 6 +
www/manager6/storage/ZFSNVMeEdit.js | 233 ++++++++++++++++++++++++++++
3 files changed, 240 insertions(+)
create mode 100644 www/manager6/storage/ZFSNVMeEdit.js
diff --git a/www/manager6/Makefile b/www/manager6/Makefile
index d2ea786b..fa634804 100644
--- a/www/manager6/Makefile
+++ b/www/manager6/Makefile
@@ -376,6 +376,7 @@ JSSRC= \
storage/Summary.js \
storage/TemplateView.js \
storage/ZFSEdit.js \
+ storage/ZFSNVMeEdit.js \
storage/ZFSPoolEdit.js \
storage/ESXIEdit.js \
Workspace.js \
diff --git a/www/manager6/Utils.js b/www/manager6/Utils.js
index 8b99371d..7022b8df 100644
--- a/www/manager6/Utils.js
+++ b/www/manager6/Utils.js
@@ -880,6 +880,12 @@ Ext.define('PVE.Utils', {
faIcon: 'building',
backups: false,
},
+ zfsnvme: {
+ name: 'ZFS over NVMe/TCP',
+ ipanel: 'ZFSNVMeInputPanel',
+ faIcon: 'building',
+ backups: false,
+ },
zfspool: {
name: 'ZFS',
ipanel: 'ZFSPoolInputPanel',
diff --git a/www/manager6/storage/ZFSNVMeEdit.js b/www/manager6/storage/ZFSNVMeEdit.js
new file mode 100644
index 00000000..c7649cfe
--- /dev/null
+++ b/www/manager6/storage/ZFSNVMeEdit.js
@@ -0,0 +1,233 @@
+Ext.define('PVE.storage.ZFSNVMeInputPanel', {
+ extend: 'PVE.panel.StorageBase',
+
+ onlineHelp: 'storage_zfsnvme',
+
+ onGetValues: function (values) {
+ if (this.isCreate) {
+ values.content = 'images';
+ }
+ return this.callParent([values]);
+ },
+
+ initComponent: function () {
+ let me = this;
+
+ let splitList = (value) =>
+ (value || '')
+ .split(',')
+ .map((item) => item.trim())
+ .filter((item) => item !== '');
+
+ me.column1 = [
+ {
+ xtype: me.isCreate ? 'textfield' : 'displayfield',
+ name: 'server',
+ fieldLabel: gettext('SSH Server'),
+ allowBlank: false,
+ },
+ {
+ xtype: me.isCreate ? 'textfield' : 'displayfield',
+ name: 'pool',
+ fieldLabel: gettext('ZFS Pool'),
+ emptyText: 'tank/pve-nvme',
+ allowBlank: false,
+ },
+ {
+ xtype: me.isCreate ? 'textfield' : 'displayfield',
+ name: 'subsysnqn',
+ fieldLabel: gettext('Subsystem NQN'),
+ emptyText: 'nqn.2026-01.com.example:pve-nvme',
+ allowBlank: false,
+ },
+ {
+ xtype: me.isCreate ? 'textfield' : 'displayfield',
+ name: 'blocksize',
+ value: '16k',
+ fieldLabel: gettext('Block Size'),
+ validator: PVE.Utils.validateZfsBlocksize,
+ allowBlank: false,
+ },
+ {
+ xtype: 'proxmoxcheckbox',
+ name: 'sparse',
+ checked: false,
+ uncheckedValue: 0,
+ fieldLabel: gettext('Thin provision'),
+ },
+ ];
+
+ me.column2 = [
+ {
+ xtype: me.isCreate ? 'textfield' : 'displayfield',
+ name: 'nvme-portals',
+ fieldLabel: gettext('NVMe/TCP Portals'),
+ emptyText: '192.0.2.10,198.51.100.10',
+ allowBlank: false,
+ },
+ {
+ xtype: 'textfield',
+ name: 'nvme-host-ifaces',
+ fieldLabel: gettext('Host Interfaces'),
+ emptyText: 'ens1f0,ens1f1',
+ allowBlank: false,
+ },
+ {
+ xtype: 'textfield',
+ name: 'nvme-host-nqns',
+ fieldLabel: gettext('Allowed Host NQNs'),
+ emptyText: 'nqn.2014-08.org.nvmexpress:uuid:...',
+ allowBlank: false,
+ validator: function (value) {
+ // the backend refuses to drop a host NQN from an existing storage
+ let current = splitList(value);
+ let removed = splitList(this.originalValue).filter(
+ (hostnqn) => !current.includes(hostnqn),
+ );
+ if (removed.length) {
+ return Ext.String.format(
+ gettext('Host NQN {0} cannot be removed from an existing storage'),
+ Ext.htmlEncode(removed[0]),
+ );
+ }
+ return true;
+ },
+ },
+ me.isCreate
+ ? {
+ xtype: 'textfield',
+ inputType: 'password',
+ name: 'dhchap-key',
+ fieldLabel: gettext('DH-HMAC-CHAP Key'),
+ emptyText: 'DHHC-1:xx:...:',
+ regex: /^DHHC-1:0[0-3]:[A-Za-z0-9+/]+={0,2}:$/,
+ regexText: gettext('Expected format: DHHC-1:xx:...:'),
+ allowBlank: false,
+ }
+ : {
+ xtype: 'displayfield',
+ fieldLabel: gettext('DH-HMAC-CHAP Key'),
+ value: gettext('Unchanged (rotation not supported)'),
+ },
+ {
+ xtype: 'proxmoxKVComboBox',
+ name: 'nvme-iopolicy',
+ value: 'round-robin',
+ fieldLabel: gettext('I/O Policy'),
+ comboItems: [
+ ['round-robin', 'round-robin'],
+ ['queue-depth', 'queue-depth'],
+ ['numa', 'numa'],
+ ],
+ allowBlank: false,
+ },
+ ];
+
+ me.advancedColumn1 = [
+ {
+ xtype: 'proxmoxintegerfield',
+ name: 'nvme-keep-alive-tmo',
+ value: 5,
+ minValue: 1,
+ maxValue: 120,
+ fieldLabel: gettext('Keep Alive Timeout'),
+ allowBlank: false,
+ },
+ {
+ xtype: 'proxmoxintegerfield',
+ name: 'nvme-reconnect-delay',
+ value: 2,
+ minValue: 1,
+ maxValue: 120,
+ fieldLabel: gettext('Reconnect Delay'),
+ allowBlank: false,
+ },
+ {
+ xtype: 'proxmoxintegerfield',
+ name: 'nvme-nr-io-queues',
+ minValue: 1,
+ maxValue: 1024,
+ fieldLabel: gettext('I/O Queues'),
+ emptyText: Proxmox.Utils.defaultText,
+ deleteEmpty: !me.isCreate,
+ allowBlank: true,
+ },
+ ];
+
+ me.advancedColumn2 = [
+ {
+ xtype: 'proxmoxintegerfield',
+ name: 'nvme-ctrl-loss-tmo',
+ value: 600,
+ minValue: -1,
+ maxValue: 86400,
+ fieldLabel: gettext('Controller Loss Timeout'),
+ allowBlank: false,
+ listeners: {
+ change: function (field) {
+ let panel = field.up('inputpanel');
+ if (panel) {
+ panel.down('field[name=nvme-fast-io-fail-tmo]').validate();
+ }
+ },
+ },
+ },
+ {
+ xtype: 'proxmoxintegerfield',
+ name: 'nvme-fast-io-fail-tmo',
+ minValue: 0,
+ maxValue: 86400,
+ fieldLabel: gettext('Fast I/O Fail Timeout'),
+ emptyText: gettext('Off'),
+ deleteEmpty: !me.isCreate,
+ allowBlank: true,
+ validator: function (value) {
+ let panel = this.up('inputpanel');
+ if (value === '' || !panel) {
+ return true;
+ }
+ let ctrlLossTmo = panel.down('field[name=nvme-ctrl-loss-tmo]').getValue();
+ if (ctrlLossTmo === null || ctrlLossTmo < 0) {
+ return true;
+ }
+ return (
+ Number(value) <= ctrlLossTmo ||
+ gettext('Must not exceed the Controller Loss Timeout')
+ );
+ },
+ },
+ ];
+
+ me.advancedColumnB = [
+ {
+ xtype: 'displayfield',
+ userCls: 'pmx-hint',
+ value: gettext(
+ 'A Controller Loss Timeout of -1 retries forever. Leave Fast I/O Fail Timeout empty to queue I/O until the controller is lost.',
+ ),
+ },
+ ];
+
+ me.columnB = [
+ {
+ xtype: 'displayfield',
+ userCls: 'pmx-hint',
+ value: gettext(
+ 'List /etc/nvme/hostnqn from every allowed cluster node. Host interface names are matched to portals by position and must exist on every selected node.',
+ ),
+ },
+ ];
+
+ if (!me.isCreate) {
+ me.columnB.push({
+ xtype: 'displayfield',
+ userCls: 'pmx-hint',
+ value: gettext(
+ 'Host NQNs can only be added. Revoking a host requires a new storage with a new key.',
+ ),
+ });
+ }
+
+ me.callParent();
+ },
+});
^ permalink raw reply related [relevance 22%]
* Re: [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend
2026-09-28 11:53 10% ` [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend Max R. Carrara
@ 2026-10-05 0:27 15% ` Joaquin Varela
2026-10-21 8:06 6% ` Max R. Carrara
0 siblings, 1 reply; 43+ results
From: Joaquin Varela @ 2026-10-05 0:27 UTC (permalink / raw)
To: m.carrara; +Cc: pve-devel
Hi Max,
thank you very much for the detailed review, and sorry that it took a
few days. I have just sent v3 ("[PATCH storage v3 0/4] add ZFS over
NVMe/TCP storage plugin"), together with the docs and manager patches.
It addresses all three points and the helper suggestions: the plugin
inherits from PVE::Storage::Plugin, LunCmd::NVMET is gone, ZFS/configfs
parsing and operation planning are local. In patch 1/4 the target runs
quoted simple commands,
sometimes joined with '&&', plus one pipe that writes the key, and the
PVE helpers replace the builtins.
Instead of dir_glob_regex, which returns only the first match, the
sysfs walks nest dir_glob_foreach.
Two parts are questions for you, explained in the cover letter: an
optional patch that guards transaction commands on the target against a
delayed command of an abandoned operation, which adds target-side
validation and a small sh guard with the only shell control flow on the
target, and a longer default
wait for the shared storage lock. Both are separate patches, so either
can be dropped without touching the other storage patches (dropping
the guard also drops one sentence and one paragraph of the docs
patch). If the size of the series gets in the way, I can split the
backend patch and split or trim the tests.
The contribution is limited to the storage backend and its integration
with PVE. It does not implement target high availability, pool takeover
or target fencing. The optional guard protects control-plane operations
on a single target too; it is not host or guest-I/O fencing. Multi-head
target compatibility remains conditional and has not been qualified.
The v3 cover Message-ID is:
<20261005002609.571-1-joaquinvarela@neatech.ar>
v3 also refuses storages that share an NVMe/TCP listener on the
target, because after a target restart they could lose their
controllers. The cover letter has the details.
Kind regards,
Joaquin Varela
^ permalink raw reply [relevance 15%]
* [PATCH storage v3 2/4] test: add zfsnvme plugin tests
2026-10-05 0:26 14% [PATCH storage v3 0/4] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-10-05 0:26 16% ` [PATCH storage v3 1/4] zfsnvme: " Joaquin Varela
@ 2026-10-05 0:26 10% ` Joaquin Varela
2026-10-05 0:26 18% ` [PATCH docs v3] storage: document ZFS over NVMe/TCP Joaquin Varela
2026-10-05 0:26 22% ` [PATCH manager v3] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela
3 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-10-05 0:26 UTC (permalink / raw)
To: pve-devel
Add two test files to the plugin test harness and register them in
run_plugin_tests.pl.
zfsnvme_test.pm covers the host side: option and portal parsing, the
schema and the config checks, the key handling (the add and update
hooks with /etc/pve/priv/storage, and the 'dhchap-key' file mapping of
'pvesm add' and 'pvesm set'), the SSH runner and its error
classification, the /dev/nvme-fabrics option builder and the connect
child (against a pseudoterminal that answers like the fabrics device;
skipped without /dev/ptmx), the sysfs-based rescan and controller
deletion, path selection and activation, vdisk_alloc under the core
storage lock, and the volume path and QEMU blockdev options. Nothing in
it opens a connection or touches a local NVMe device.
zfsnvme_target_test.pm covers the target side: the parsers and planners
on fixture reads of an nvmet target (Linux 6.8, ZFS 2.2; addresses and
NQNs replaced by documentation values), the command renderer and
chunking, and every target flow against an in-memory target
(FakeTarget) that interprets exactly the commands the plugin sends and
records anything else as a protocol violation. A fault sweep fails
every mutating call of every flow in each way an SSH call can fail
(before or after it ran, a connection cut or lost in the middle of a
chain, or a call the target runs to its end after ssh gave up on it)
and checks that identities stay unique, nothing of other storages
changes, every change ran under one domain lock, and the next
activation converges. The rendered chains also run with /bin/sh on a
configfs stand-in in a temporary directory, which checks the quoting
and the POSIX command shapes; these tests bail out unless /bin/sh,
find, grep, sha256sum, dd and tee are available.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
src/test/run_plugin_tests.pl | 2 +
.../zfsnvme_fixtures/configfs_snapshot.txt | 38 +
src/test/zfsnvme_fixtures/zfs_inventory.txt | 15 +
src/test/zfsnvme_target_test.pm | 4849 +++++++++++++++++
src/test/zfsnvme_test.pm | 2353 ++++++++
5 files changed, 7257 insertions(+)
create mode 100644 src/test/zfsnvme_fixtures/configfs_snapshot.txt
create mode 100644 src/test/zfsnvme_fixtures/zfs_inventory.txt
create mode 100644 src/test/zfsnvme_target_test.pm
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 8bce9d3b..d063a3d2 100755
--- a/src/test/run_plugin_tests.pl
+++ b/src/test/run_plugin_tests.pl
@@ -17,6 +17,8 @@ my $res = $harness->runtests(
"get_subdir_test.pm",
"filesystem_path_test.pm",
"prune_backups_test.pm",
+ "zfsnvme_test.pm",
+ "zfsnvme_target_test.pm",
);
exit -1 if !$res || $res->{failed} || $res->{parse_errors};
diff --git a/src/test/zfsnvme_fixtures/configfs_snapshot.txt b/src/test/zfsnvme_fixtures/configfs_snapshot.txt
new file mode 100644
index 00000000..1b7672a0
--- /dev/null
+++ b/src/test/zfsnvme_fixtures/configfs_snapshot.txt
@@ -0,0 +1,38 @@
+D /sys/kernel/config/nvmet
+D /sys/kernel/config/nvmet/hosts
+D /sys/kernel/config/nvmet/hosts/nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a
+D /sys/kernel/config/nvmet/hosts/nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b
+D /sys/kernel/config/nvmet/ports
+D /sys/kernel/config/nvmet/ports/2
+D /sys/kernel/config/nvmet/ports/2/subsystems
+D /sys/kernel/config/nvmet/ports/1
+D /sys/kernel/config/nvmet/ports/1/subsystems
+D /sys/kernel/config/nvmet/subsystems
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5
+L /sys/kernel/config/nvmet/ports/2/subsystems/nqn.2026-01.com.example:zfsnvme
+L /sys/kernel/config/nvmet/ports/1/subsystems/nqn.2026-01.com.example:zfsnvme
+L /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts/nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a
+L /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts/nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b
+/sys/kernel/config/nvmet/ports/2/addr_trtype:tcp
+/sys/kernel/config/nvmet/ports/2/addr_trsvcid:4420
+/sys/kernel/config/nvmet/ports/2/addr_traddr:192.0.2.22
+/sys/kernel/config/nvmet/ports/2/addr_adrfam:ipv4
+/sys/kernel/config/nvmet/ports/1/addr_trtype:tcp
+/sys/kernel/config/nvmet/ports/1/addr_trsvcid:4420
+/sys/kernel/config/nvmet/ports/1/addr_traddr:192.0.2.21
+/sys/kernel/config/nvmet/ports/1/addr_adrfam:ipv4
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/buffered_io:0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/enable:1
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/device_uuid:0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/device_path:/dev/zvol/tank/vm-100-cloudinit
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/buffered_io:0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/enable:1
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/device_uuid:0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/device_path:/dev/zvol/tank/vm-100-disk-0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_model:Proxmox ZFS NVMe
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_serial:PVEZFS51b2c3c90ea254
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_allow_any_host:0
diff --git a/src/test/zfsnvme_fixtures/zfs_inventory.txt b/src/test/zfsnvme_fixtures/zfs_inventory.txt
new file mode 100644
index 00000000..69ba9238
--- /dev/null
+++ b/src/test/zfsnvme_fixtures/zfs_inventory.txt
@@ -0,0 +1,15 @@
+tank type filesystem -
+tank proxmox:nvme-subsys - -
+tank proxmox:nvme-nsid - -
+tank proxmox:nvme-uuid - -
+tank proxmox:nvme-last-nsid - -
+tank/vm-100-cloudinit type volume -
+tank/vm-100-cloudinit proxmox:nvme-subsys nqn.2026-01.com.example:zfsnvme local
+tank/vm-100-cloudinit proxmox:nvme-nsid 6 local
+tank/vm-100-cloudinit proxmox:nvme-uuid 0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d local
+tank/vm-100-cloudinit proxmox:nvme-last-nsid - -
+tank/vm-100-disk-0 type volume -
+tank/vm-100-disk-0 proxmox:nvme-subsys nqn.2026-01.com.example:zfsnvme local
+tank/vm-100-disk-0 proxmox:nvme-nsid 5 local
+tank/vm-100-disk-0 proxmox:nvme-uuid 0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c local
+tank/vm-100-disk-0 proxmox:nvme-last-nsid - -
diff --git a/src/test/zfsnvme_target_test.pm b/src/test/zfsnvme_target_test.pm
new file mode 100644
index 00000000..991d2084
--- /dev/null
+++ b/src/test/zfsnvme_target_test.pm
@@ -0,0 +1,4849 @@
+# Target side of the zfsnvme storage plugin: the parsers and planners on the
+# fixture reads, the command renderer, and every target flow against an
+# in-memory NVMe target (FakeTarget) that interprets exactly the commands the
+# plugin sends. Nothing here opens a connection or touches local NVMe devices.
+
+use v5.36;
+
+use lib qw(..);
+
+use Compress::Zlib qw(crc32);
+use Digest::SHA qw(sha256_hex);
+use File::Temp qw(tempdir);
+use FindBin;
+use IPC::Open3;
+use MIME::Base64 qw(encode_base64);
+use POSIX ();
+use Storable qw(dclone freeze);
+use Symbol qw(gensym);
+use Test::MockModule;
+use Test::More;
+
+use PVE::Cluster;
+use PVE::Storage;
+use PVE::Storage::ZFSNVMePlugin;
+
+my $PLUGIN = 'PVE::Storage::ZFSNVMePlugin';
+my $ROOT = '/sys/kernel/config/nvmet';
+my $MARKER = 'ZFSNVME-CONFIGFS';
+my $MODEL = 'Proxmox ZFS NVMe';
+my $FIXTURES = "$FindBin::Bin/zfsnvme_fixtures";
+my $UUID_RE = qr/\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/i;
+my $EMPTY_KEY_SHA = sha256_hex("\n");
+
+# The fixtures are the ZFS inventory and the configfs read of a target (Linux
+# 6.8 nvmet, ZFS 2.2) that serves one subsystem with two namespaces to two
+# cluster nodes, as the plugin reads them.
+my $FIXTURE_NQN = 'nqn.2026-01.com.example:zfsnvme';
+my @FIXTURE_HOSTS = (
+ 'nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a',
+ 'nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b',
+);
+my $FIXTURE_UUID5 = '0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c';
+my $FIXTURE_UUID6 = '0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d';
+
+my $NQN = 'nqn.2026-01.com.example:zfsnvme-test';
+my $FOREIGN_NQN = 'nqn.2026-01.com.example:foreign';
+my @HOSTS =
+ map { sprintf('nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-%012d', $_) } 1, 2;
+
+# A portal as parse_nvme_portals() returns it.
+sub portal($family, $address, $port) {
+ return { family => $family, address => $address, port => $port };
+}
+my $PORTALS = [portal('ipv4', '192.0.2.21', 4420), portal('ipv4', '192.0.2.22', 4420)];
+my %U = map {
+ my $d = $_;
+ ($d => join('-', $d x 8, $d x 4, '4' . $d x 3, '8' . $d x 3, $d x 12))
+} 1 .. 9;
+
+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);
+my $KEY_SHA = sha256_hex("$KEY\n");
+
+sub scfg(%override) {
+ return {
+ type => 'zfsnvme',
+ server => '192.0.2.10',
+ pool => 'tank',
+ subsysnqn => $NQN,
+ blocksize => '16k',
+ sparse => 1,
+ 'nvme-portals' => '192.0.2.21,192.0.2.22',
+ 'nvme-host-ifaces' => 'ens19,ens20',
+ 'nvme-host-nqns' => join(',', @HOSTS),
+ %override,
+ };
+}
+
+sub slurp($path) {
+ open(my $fh, '<', $path) or die "cannot open '$path': $!\n";
+ local $/;
+ return scalar(<$fh>);
+}
+
+# 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);
+}
+
+sub same($x, $y) {
+ local $Storable::canonical = 1;
+ return freeze([$x]) eq freeze([$y]);
+}
+
+# ---------------------------------------------------------------------------
+# Mocks: the only way to the target is _nvmet_run, and it reaches $FAKE.
+# The pmxcfs lock, quorum, clock, waits, UUID source, local files and local
+# devices are mocked. Waits advance $NOW.
+# ---------------------------------------------------------------------------
+
+our $FAKE;
+our $NOW = 1_000_000;
+our $SLEPT = 0;
+our $QUORATE = 1;
+our $LOCK_HOOK;
+our (%LOCK_HELD, @LOCKS, @NESTED_LOCKS, @QUORUM, @WARNINGS, @SYSFS_WRITES, %FILES, %CONFIG);
+our (%CORPUS, @VIOLATIONS, @WRITES, @UNLINKED, %BLOCK, @UUIDS);
+
+my $uuid_seq = 0;
+
+sub lock_id($scfg) {
+ return 'zfsnvme-' . ($scfg->{server} =~ s/[^A-Za-z0-9.-]/_/gr);
+}
+
+sub lock_held($scfg) {
+ return (($LOCK_HELD{ lock_id($scfg) } // 0) == $$) ? 1 : 0;
+}
+
+# Whether a step changes the target, by the vocabulary of the fake target,
+# independently of the plugin.
+sub mutating_step($step) {
+ return 1 if ref($step) ne 'ARRAY';
+ my ($command, $subcommand) = $step->@*;
+ return 0 if grep { $command eq $_ } qw(test grep cat printf env);
+ return 0 if $command eq 'zfs' && ($subcommand eq 'get' || $subcommand eq 'list');
+ return 1;
+}
+
+# Whether steps change the target, not counting the module load of a locked read.
+sub changing($steps) {
+ return scalar(grep { mutating_step($_) && !step_is($_, 'modprobe') } $steps->@*);
+}
+
+my $plugin_mock = Test::MockModule->new($PLUGIN);
+my $cluster_mock = Test::MockModule->new('PVE::Cluster');
+my $storage_mock = Test::MockModule->new('PVE::Storage');
+my $sysfs_mock = Test::MockModule->new('PVE::SysFSTools');
+my $tools_mock = Test::MockModule->new('PVE::Tools');
+
+$plugin_mock->redefine(
+ _nvmet_run => sub($scfg, $steps, %opts) {
+ die "test error: no fake target\n" if !$FAKE;
+ my $rendered = nv('_nvmet_render', $steps);
+ $CORPUS{$rendered} //= $opts{op} // '';
+ return $FAKE->run($scfg, $steps, $rendered, %opts);
+ },
+);
+# The target is the only place that runs commands, and only through _nvmet_run.
+# A command is also a violation, in case the caller handles the error.
+my $no_command = sub($cmd, %opts) {
+ my $what = 'unexpected command ' . (ref($cmd) ? $cmd->[0] : $cmd);
+ push @VIOLATIONS, $what;
+ die "test error: $what\n";
+};
+$plugin_mock->redefine(run_command => $no_command);
+$tools_mock->redefine(run_command => $no_command);
+$plugin_mock->redefine(_now => sub () { return $NOW });
+$plugin_mock->redefine(
+ _sleep => sub($seconds) {
+ $NOW += $seconds;
+ $SLEPT += $seconds;
+ return;
+ },
+);
+$plugin_mock->redefine(_block_device => sub($path) { return $BLOCK{$path} });
+$plugin_mock->redefine(
+ _unlink_file => sub($path) {
+ push @UNLINKED, $path;
+ delete $FILES{$path};
+ return 1;
+ },
+);
+$plugin_mock->redefine(log_warn => sub($message) { push @WARNINGS, $message; return });
+my $sysfs_write = sub($path, $data, $allow_existing = undef) {
+ push @SYSFS_WRITES, [$path, $data];
+ return 1;
+};
+$sysfs_mock->redefine(file_write => $sysfs_write);
+# The host side runs its kernel-facing steps in a bounded child; here they
+# run inline.
+$tools_mock->redefine(
+ run_fork_with_timeout => sub($timeout, $code, $opts = undef) {
+ my $res = $code->();
+ return wantarray ? ($res, 0) : $res;
+ },
+);
+# UUIDs come from @UUIDS first, then from a sequence.
+$plugin_mock->redefine(
+ file_read_firstline => sub($path) {
+ if ($path eq '/proc/sys/kernel/random/uuid') {
+ return shift(@UUIDS) if @UUIDS;
+ $uuid_seq++;
+ return sprintf('%08x-7e57-4000-8000-%012x', $uuid_seq, $uuid_seq);
+ }
+ return $FILES{$path};
+ },
+);
+$plugin_mock->redefine(
+ file_set_contents => sub($path, $data, $perm = undef, @rest) {
+ push @WRITES, { path => $path, data => $data, perm => $perm };
+ return;
+ },
+);
+$plugin_mock->redefine(make_path => sub(@args) { push @WRITES, { make_path => [@args] }; return });
+$plugin_mock->redefine(_namespace_openers => sub($nqn) { return [] });
+
+$cluster_mock->redefine(
+ check_cfs_quorum => sub($noerr = undef) {
+ push @QUORUM, $noerr;
+ die "cluster not ready - no quorum?\n" if !$QUORATE && !$noerr;
+ return $QUORATE;
+ },
+);
+# Keeps the cfs_lock contract: the code's result with $@ cleared, or undef
+# with $@ set. pmxcfs locks are not re-entrant: a second request for a held
+# lock times out, like a mkdir on /etc/pve/priv/lock would.
+$cluster_mock->redefine(
+ cfs_lock_domain => sub($name, $timeout, $code, @param) {
+ push @LOCKS, { name => $name, timeout => $timeout, pid => $$, now => $NOW };
+ if ($LOCK_HELD{$name}) {
+ push @NESTED_LOCKS, $name;
+ $@ = "cfs-lock 'domain-$name' error: got lock request timeout\n";
+ return undef;
+ }
+ if (my $hook = $LOCK_HOOK) {
+ local $LOCK_HOOK;
+ $hook->($name);
+ }
+ local $LOCK_HELD{$name} = $$;
+ my $res = eval { $code->(@param) };
+ my $err = $@;
+ if ($err) {
+ $@ = $err;
+ return undef;
+ }
+ $@ = undef;
+ return $res;
+ },
+);
+$storage_mock->redefine(config => sub () { return { ids => {%CONFIG} } });
+
+# ---------------------------------------------------------------------------
+# FakeTarget: ZFS datasets and an nvmet configfs tree with the kernel rules
+# the plugin depends on. It accepts only the command vocabulary of the
+# plugin; anything else is recorded as a protocol violation.
+# ---------------------------------------------------------------------------
+
+package FakeTarget {
+ use Digest::SHA qw(sha256_hex);
+ use Storable qw(dclone);
+
+ my $RR = quotemeta($ROOT);
+
+ # fail => [$match, $error, $times]: the steps that match (an argv prefix,
+ # { write => $suffix, value => $value } or a sub of the step) fail $times
+ # times with $error.
+ sub new($class, %opts) {
+ my $pools = delete($opts{pools}) // ['tank'];
+ if (my $fail = delete($opts{fail})) {
+ my ($match, $error, $times) = $fail->@*;
+ my $matches =
+ ref($match) eq 'CODE' ? $match
+ : ref($match) eq 'HASH'
+ ? sub($step) { main::write_to($step, $match->{write}, $match->{value}) }
+ : sub($step) { main::step_is($step, $match->@*) };
+ my $count = 0;
+ $opts{step_fault} = sub($step, $call) {
+ return undef if !$matches->($step) || $count >= ($times // 99);
+ $count++;
+ return $error;
+ };
+ }
+ my $self = bless {
+ m => {
+ ds => {},
+ snaps => {},
+ seq => 0,
+ subsystems => {},
+ ports => {},
+ hosts => {},
+ mounted => 1,
+ loaded => 1,
+ available => '1073741824',
+ used => '1048576',
+ },
+ calls => [],
+ violations => [],
+ faults => {}, # call index => before | after | late | cut:<step> | lost:<step>
+ late => [], # calls that ssh gave up on, applied by land()
+ # { after => call index, mode => before | unreachable | failed }
+ read_fault => undef,
+ step_fault => undef, # sub ($step, $call) returning an error text
+ before_call => undef,
+ after_call => undef,
+ udev_delay => 0, # failing `test -b` polls after a zvol (re)appears
+ unbindable => {}, # port id => 1: its address is missing on the target
+ unreachable => 0,
+ secrets => [$KEY, $KEY_B],
+ %opts,
+ }, $class;
+ $self->{m}->{ds}->{$_} = { type => 'filesystem', props => {} } for $pools->@*;
+ return $self;
+ }
+
+ sub from_state($class, $state, %opts) {
+ my $self = $class->new(%opts);
+ $self->{m} = dclone($state);
+ return $self;
+ }
+
+ # --- building a state -------------------------------------------------
+
+ sub add_zvol($self, $name, %o) {
+ my %props;
+ @props{qw(proxmox:nvme-subsys proxmox:nvme-nsid proxmox:nvme-uuid)} = $o{identity}->@*
+ if $o{identity};
+ $self->{m}->{ds}->{$name} = {
+ type => 'volume',
+ props => \%props,
+ volsize => $o{volsize} // 1073741824,
+ origin => $o{origin} // '-',
+ devwait => 0,
+ };
+ return $self;
+ }
+
+ sub add_snapshot($self, $snapshot, %o) {
+ my ($name) = split /\@/, $snapshot;
+ my $ds = $self->{m}->{ds}->{$name};
+ $self->{m}->{snaps}->{$snapshot} = {
+ props => $o{props} // dclone($ds->{props}),
+ volsize => $ds->{volsize},
+ seq => ++$self->{m}->{seq},
+ };
+ return $self;
+ }
+
+ sub add_subsystem($self, $nqn, %o) {
+ $self->{m}->{subsystems}->{$nqn} = {
+ attr => {
+ attr_model => $o{model} // $MODEL,
+ attr_serial => $o{serial} // PVE::Storage::ZFSNVMePlugin::_nvmet_serial($nqn),
+ attr_allow_any_host => $o{allow_any_host} // '0',
+ },
+ acl => { map { $_ => 1 } ($o{acl} // [])->@* },
+ ns => {},
+ };
+ return $self;
+ }
+
+ sub add_namespace($self, $nqn, $nsid, $uuid, $dev, $enable = 1) {
+ $self->{m}->{subsystems}->{$nqn}->{ns}->{$nsid} = {
+ enable => "$enable",
+ device_path => $dev,
+ device_uuid => $uuid,
+ buffered_io => '0',
+ };
+ return $self;
+ }
+
+ sub add_port($self, $id, $address, $service, %o) {
+ $self->{m}->{ports}->{$id} = {
+ attr => {
+ addr_trtype => 'tcp',
+ addr_adrfam => $o{family} // 'ipv4',
+ addr_traddr => $address,
+ addr_trsvcid => "$service",
+ },
+ links => { map { $_ => 1 } ($o{links} // [])->@* },
+ };
+ return $self;
+ }
+
+ # nvmet creates the key attributes of a host world-readable
+ sub host_entry($key = undef) {
+ return { key => $key, mode => { map { $_ => '0644' } qw(dhchap_key dhchap_ctrl_key) } };
+ }
+
+ sub add_host($self, $hostnqn, $key = undef) {
+ $self->{m}->{hosts}->{$hostnqn} = host_entry($key);
+ return $self;
+ }
+
+ # A target restart: configfs is empty and, unless $loaded, nvmet is not
+ # loaded yet.
+ sub reboot($self, $loaded = 0) {
+ my $m = $self->{m};
+ $m->{$_} = {} for qw(subsystems ports hosts);
+ $m->{loaded} = $loaded;
+ $_->{devwait} = 0 for grep { $_->{type} eq 'volume' } values $m->{ds}->%*;
+ return $self;
+ }
+
+ # --- execution --------------------------------------------------------
+
+ sub run($self, $scfg, $steps, $rendered, %opts) {
+ my $call = {
+ index => scalar($self->{calls}->@*),
+ op => $opts{op},
+ steps => dclone($steps),
+ rendered => $rendered,
+ timeout => $opts{timeout},
+ input => defined($opts{input}) ? 1 : 0,
+ locked => main::lock_held($scfg),
+ mutating => (grep { main::mutating_step($_) } $steps->@*) ? 1 : 0,
+ changing => main::changing($steps),
+ now => $main::NOW,
+ };
+ push $self->{calls}->@*, $call;
+ $self->audit($call, $opts{input});
+ $self->{before_call}->($self, $call) if $self->{before_call};
+ my $res = $self->execute($call, $steps, $opts{input});
+ $call->{rc} = $res->{rc};
+ $call->{err} = $res->{err};
+ $self->audit_text($call, $res->{err}, $res->{out}->@*);
+ $self->{after_call}->($self, $call) if $self->{after_call};
+ return $res;
+ }
+
+ # Violations are recorded for the fake and for the whole run, which the
+ # last subtest checks.
+ sub flag($self, @what) {
+ push $self->{violations}->@*, @what;
+ push @main::VIOLATIONS, @what;
+ }
+
+ sub violation($self, $what) {
+ $self->flag($what);
+ die "FAKEERR:protocol violation: $what\n";
+ }
+
+ sub err($message) {
+ die "FAKEERR:$message\n";
+ }
+
+ sub audit($self, $call, $input) {
+ my @bad;
+ my $op = $call->{op} // '';
+ push @bad, 'call without an operation label' if $op eq '';
+ for my $secret ($self->{secrets}->@*) {
+ push @bad, "key in the command of '$op'" if index($call->{rendered}, $secret) >= 0;
+ }
+ my $keys = grep { ref($_) eq 'HASH' && exists($_->{key}) } $call->{steps}->@*;
+ push @bad, "key write without stdin in '$op'" if $keys && !defined($input);
+ push @bad, "stdin without a key write in '$op'" if defined($input) && !$keys;
+ push @bad, "stdin is not a configured key in '$op'"
+ if defined($input) && !grep { $input eq "$_\n" } $self->{secrets}->@*;
+ push @bad, "target change without the target lock in '$op'"
+ if $call->{mutating} && !$call->{locked};
+ $self->flag(@bad);
+ }
+
+ sub audit_text($self, $call, @texts) {
+ for my $text (grep { defined } @texts) {
+ for my $secret ($self->{secrets}->@*) {
+ $self->flag("key in the output of '$call->{op}'") if index($text, $secret) >= 0;
+ }
+ }
+ }
+
+ # Applies the calls that ssh gave up on, as the target finally runs them:
+ # each chain stops at its first failing step.
+ sub land($self) {
+ for my $late (splice($self->{late}->@*)) {
+ for my $step ($late->{steps}->@*) {
+ last if !eval { $self->step($step, $late->{input}); 1 };
+ }
+ }
+ return $self;
+ }
+
+ # A fault mode fails a call before it runs (rc 1), after it ran (the
+ # connection breaks: 255), at one of its steps (cut: the connection breaks
+ # and the remote shell stops; lost: it breaks and the rest of the chain
+ # still runs, later), or ssh gives up on it while it runs to its end later
+ # (late: -1).
+ sub execute($self, $call, $steps, $input) {
+ my $closed = 'Connection to 192.0.2.10 closed by remote host.';
+ my $broken = { rc => 255, out => [], err => $closed };
+ my $no_route = 'ssh: connect to host 192.0.2.10: No route to host';
+ return { rc => 255, out => [], err => $no_route } if $self->{unreachable};
+ my $read_fault = $self->{read_fault};
+ if ($read_fault && !$call->{mutating} && $call->{index} > $read_fault->{after}) {
+ $self->{read_fault} = undef;
+ $call->{fault} = "read $read_fault->{mode}";
+ return { rc => 255, out => [], err => $no_route }
+ if $read_fault->{mode} eq 'unreachable';
+ return { rc => -1, out => [], err => 'ssh failed' } if $read_fault->{mode} eq 'failed';
+ return { rc => 1, out => [], err => 'injected read failure' };
+ }
+ my $mode = $self->{faults}->{ $call->{index} } // '';
+ $call->{fault} = $mode if $mode;
+ return { rc => 1, out => [], err => 'injected failure' } if $mode eq 'before';
+ if ($mode eq 'late') {
+ push $self->{late}->@*, { steps => dclone($steps), input => $input };
+ return { rc => -1, out => [], err => 'timeout' };
+ }
+ my ($cut) = $mode =~ /\Acut:([0-9]+)\z/;
+ my ($lost) = $mode =~ /\Alost:([0-9]+)\z/;
+ my @out;
+ for my $index (0 .. $steps->$#*) {
+ return $broken if defined($cut) && $index == $cut;
+ if (defined($lost) && $index == $lost) {
+ my @rest = $steps->@[$index .. $steps->$#*];
+ push $self->{late}->@*, { steps => dclone(\@rest), input => $input };
+ return $broken;
+ }
+ my $step = $steps->[$index];
+ my $error = $self->{step_fault} ? $self->{step_fault}->($step, $call) : undef;
+ if (!defined($error)) {
+ my @lines = eval { $self->step($step, $input) };
+ my $e = $@;
+ if (!$e) {
+ push @out, @lines;
+ next;
+ }
+ if ($e !~ s/\AFAKEERR://) {
+ $self->flag("fake target error: $e");
+ return { rc => 2, out => \@out, err => 'fake target error' };
+ }
+ chomp($error = $e);
+ }
+ return { rc => 1, out => \@out, err => $error eq '' ? 'exit code 1' : $error };
+ }
+ return $broken if $mode eq 'after';
+ return { rc => 0, out => \@out, err => '' };
+ }
+
+ sub step($self, $step, $input) {
+ if (ref($step) eq 'HASH' && exists($step->{write})) {
+ $self->write_attr($step->{write}, $step->{value});
+ return ();
+ }
+ if (ref($step) eq 'HASH') {
+ err('dd: error reading standard input') if !defined($input);
+ (my $key = $input) =~ s/\n\z//;
+ my @failed;
+ for my $path ($step->{key}->@*) {
+ eval { $self->write_key($path, $key) };
+ push @failed, $@ if $@;
+ }
+ die $failed[0] if @failed;
+ return ();
+ }
+ my ($command, @args) = $step->@*;
+ my $method = "cmd_$command";
+ $self->violation("command '$command'") if !$self->can($method);
+ return $self->$method(@args);
+ }
+
+ # --- configfs ---------------------------------------------------------
+
+ sub available($self) {
+ err("find: '$ROOT': No such file or directory")
+ if !$self->{m}->{mounted} || !$self->{m}->{loaded};
+ }
+
+ sub parts($self, $path) {
+ return () if $path !~ m{\A$RR/(.+)\z};
+ return split m{/}, $1;
+ }
+
+ sub zvol_name($self, $dev) {
+ return $dev =~ m{\A/dev/zvol/(.+)\z} ? $1 : undef;
+ }
+
+ sub block_device($self, $dev, $poll) {
+ my $name = $self->zvol_name($dev) // return 0;
+ my $ds = $self->{m}->{ds}->{$name} // return 0;
+ return 0 if $ds->{type} ne 'volume';
+ if ($ds->{devwait} > 0) {
+ $ds->{devwait}-- if $poll;
+ return 0;
+ }
+ return 1;
+ }
+
+ sub busy($self, $name) {
+ for my $subsys (values $self->{m}->{subsystems}->%*) {
+ return 1
+ if grep { $_->{enable} eq '1' && $_->{device_path} eq "/dev/zvol/$name" }
+ values $subsys->{ns}->%*;
+ }
+ return 0;
+ }
+
+ sub new_uuid($self) {
+ my $seq = ++$self->{m}->{seq};
+ return sprintf('%08x-dead-4000-8000-%012x', $seq, $seq);
+ }
+
+ sub write_attr($self, $path, $value) {
+ $self->available;
+ my @p = $self->parts($path) or $self->violation("write '$path'");
+ my $m = $self->{m};
+ if ($p[0] eq 'subsystems' && @p == 3) {
+ my $subsys = $m->{subsystems}->{ $p[1] } // err("$path: No such file or directory");
+ $self->violation("write '$path'")
+ if $p[2] !~ /\A(?:attr_model|attr_serial|attr_allow_any_host)\z/;
+ if ($p[2] eq 'attr_allow_any_host') {
+ err("$path: Invalid argument") if $value !~ /\A[01]\z/;
+ err("$path: Invalid argument") if $value eq '1' && $subsys->{acl}->%*;
+ }
+ $subsys->{attr}->{ $p[2] } = "$value";
+ } elsif ($p[0] eq 'subsystems' && @p == 5 && $p[2] eq 'namespaces') {
+ my $subsys = $m->{subsystems}->{ $p[1] } // err("$path: No such file or directory");
+ my $ns = $subsys->{ns}->{ $p[3] } // err("$path: No such file or directory");
+ my $attr = $p[4];
+ if ($attr eq 'enable') {
+ err("$path: Invalid argument") if $value !~ /\A[01]\z/;
+ err("$path: No such device")
+ if $value eq '1'
+ && $ns->{enable} ne '1'
+ && !$self->block_device($ns->{device_path}, 0);
+ $ns->{enable} = "$value";
+ } elsif ($attr =~ /\A(?:device_path|device_uuid|buffered_io)\z/) {
+ err("$path: Device or resource busy") if $ns->{enable} eq '1';
+ if ($attr eq 'device_uuid') {
+ err("$path: Invalid argument") if $value !~ $UUID_RE;
+ $value = lc($value);
+ }
+ $ns->{$attr} = "$value";
+ } elsif ($attr eq 'revalidate_size') {
+ err("$path: Invalid argument") if $ns->{enable} ne '1' || $value ne '1';
+ $self->{revalidated}->{"$p[1]/$p[3]"}++;
+ } else {
+ $self->violation("write '$path'");
+ }
+ } elsif ($p[0] eq 'ports' && @p == 3) {
+ my $port = $m->{ports}->{ $p[1] } // err("$path: No such file or directory");
+ $self->violation("write '$path'")
+ if $p[2] !~ /\Aaddr_(?:trtype|adrfam|traddr|trsvcid)\z/;
+ err("$path: Permission denied") if $port->{links}->%*;
+ $port->{attr}->{ $p[2] } = "$value";
+ } else {
+ $self->violation("write '$path'");
+ }
+ }
+
+ sub write_key($self, $path, $key) {
+ $self->available;
+ my @p = $self->parts($path);
+ $self->violation("key write to '$path'")
+ if @p != 3 || $p[0] ne 'hosts' || $p[2] ne 'dhchap_key';
+ my $host = $self->{m}->{hosts}->{ $p[1] } // err("tee: $path: No such file or directory");
+ err("tee: $path: Invalid argument") if $key !~ /\ADHHC-1:/;
+ $self->violation("key write to the world-readable '$path'")
+ if ($host->{mode}->{ $p[2] } // '') ne '0600';
+ $host->{key} = $key;
+ }
+
+ sub cmd_mkdir($self, @paths) {
+ $self->available;
+ my $m = $self->{m};
+ for my $path (@paths) {
+ my @p = $self->parts($path) or $self->violation("mkdir '$path'");
+ my $exists = "mkdir: cannot create directory '$path': File exists";
+ my $missing = "mkdir: cannot create directory '$path': No such file or directory";
+ if ($p[0] eq 'subsystems' && @p == 2) {
+ err($exists) if $m->{subsystems}->{ $p[1] };
+ $m->{subsystems}->{ $p[1] } = {
+ attr => {
+ attr_model => 'Linux',
+ attr_serial => substr(sha256_hex("serial $p[1]"), 0, 16),
+ attr_allow_any_host => '0',
+ },
+ acl => {},
+ ns => {},
+ };
+ } elsif ($p[0] eq 'subsystems' && @p == 4 && $p[2] eq 'namespaces') {
+ my $subsys = $m->{subsystems}->{ $p[1] } // err($missing);
+ err("mkdir: cannot create directory '$path': Invalid argument")
+ if $p[3] !~ /\A[0-9]+\z/ || $p[3] == 0 || $p[3] > 0xfffffffe;
+ err($exists) if $subsys->{ns}->{ $p[3] };
+ $subsys->{ns}->{ $p[3] } = {
+ enable => '0',
+ device_path => '(null)',
+ device_uuid => $self->new_uuid,
+ buffered_io => '0',
+ };
+ } elsif ($p[0] eq 'ports' && @p == 2 && $p[1] =~ /\A[0-9]+\z/) {
+ err($exists) if $m->{ports}->{ $p[1] };
+ $m->{ports}->{ $p[1] } = {
+ attr => { map { ("addr_$_" => '') } qw(trtype adrfam traddr trsvcid) },
+ links => {},
+ };
+ } elsif ($p[0] eq 'hosts' && @p == 2) {
+ err($exists) if $m->{hosts}->{ $p[1] };
+ $m->{hosts}->{ $p[1] } = host_entry();
+ } else {
+ $self->violation("mkdir '$path'");
+ }
+ }
+ return ();
+ }
+
+ sub cmd_chmod($self, $mode, @paths) {
+ $self->available;
+ $self->violation("chmod '$mode'") if $mode ne '0600';
+ for my $path (@paths) {
+ my @p = $self->parts($path);
+ $self->violation("chmod '$path'")
+ if @p != 3 || $p[0] ne 'hosts' || $p[2] !~ /\Adhchap_(?:ctrl_)?key\z/;
+ my $host = $self->{m}->{hosts}->{ $p[1] }
+ // err("chmod: cannot access '$path': No such file or directory");
+ $host->{mode}->{ $p[2] } = $mode;
+ }
+ return ();
+ }
+
+ sub cmd_rmdir($self, @paths) {
+ $self->available;
+ my $m = $self->{m};
+ my @errors;
+ for my $path (@paths) {
+ my @p = $self->parts($path) or $self->violation("rmdir '$path'");
+ my $fail = sub($why) { push @errors, "rmdir: failed to remove '$path': $why" };
+ if ($p[0] eq 'subsystems' && @p == 4 && $p[2] eq 'namespaces') {
+ my $subsys = $m->{subsystems}->{ $p[1] };
+ $fail->('No such file or directory')
+ if !$subsys || !delete($subsys->{ns}->{ $p[3] });
+ } elsif ($p[0] eq 'subsystems' && @p == 2) {
+ my $subsys = $m->{subsystems}->{ $p[1] };
+ if (!$subsys) {
+ $fail->('No such file or directory');
+ } elsif ($subsys->{ns}->%* || $subsys->{acl}->%*) {
+ $fail->('Directory not empty');
+ } elsif (grep { $_->{links}->{ $p[1] } } values $m->{ports}->%*) {
+ $fail->('Device or resource busy');
+ } else {
+ delete $m->{subsystems}->{ $p[1] };
+ }
+ } elsif ($p[0] eq 'hosts' && @p == 2) {
+ if (!$m->{hosts}->{ $p[1] }) {
+ $fail->('No such file or directory');
+ } elsif (grep { $_->{acl}->{ $p[1] } } values $m->{subsystems}->%*) {
+ $fail->('Device or resource busy');
+ } else {
+ delete $m->{hosts}->{ $p[1] };
+ }
+ } else {
+ $self->violation("rmdir '$path'");
+ }
+ }
+ err($errors[0]) if @errors;
+ return ();
+ }
+
+ sub cmd_rm($self, @paths) {
+ $self->available;
+ my $m = $self->{m};
+ my @errors;
+ for my $path (@paths) {
+ my @p = $self->parts($path);
+ my $missing = "rm: cannot remove '$path': No such file or directory";
+ if (@p == 4 && $p[0] eq 'ports' && $p[2] eq 'subsystems') {
+ my $port = $m->{ports}->{ $p[1] };
+ push @errors, $missing if !$port || !delete($port->{links}->{ $p[3] });
+ } elsif (@p == 4 && $p[0] eq 'subsystems' && $p[2] eq 'allowed_hosts') {
+ my $subsys = $m->{subsystems}->{ $p[1] };
+ push @errors, $missing if !$subsys || !delete($subsys->{acl}->{ $p[3] });
+ } else {
+ $self->violation("rm '$path'");
+ }
+ }
+ err($errors[0]) if @errors;
+ return ();
+ }
+
+ sub cmd_ln($self, $flag, $target, $link) {
+ $self->available;
+ my $m = $self->{m};
+ my @t = $self->parts($target);
+ my @l = $self->parts($link);
+ my $fail = sub($why) { err("ln: failed to create symbolic link '$link': $why") };
+ if (@l == 4 && $l[0] eq 'ports' && $l[2] eq 'subsystems') {
+ $self->violation("ln '$target' '$link'")
+ if @t != 2 || $t[0] ne 'subsystems' || $t[1] ne $l[3];
+ my $port = $m->{ports}->{ $l[1] } // $fail->('No such file or directory');
+ $fail->('No such file or directory') if !$m->{subsystems}->{ $t[1] };
+ $fail->('File exists') if $port->{links}->{ $l[3] };
+ my $a = $port->{attr};
+ $fail->('Invalid argument')
+ if $a->{addr_trtype} ne 'tcp'
+ || $a->{addr_adrfam} !~ /\Aipv[46]\z/
+ || $a->{addr_traddr} eq ''
+ || $a->{addr_trsvcid} eq '';
+ if (!$port->{links}->%*) { # the first link enables the port
+ $fail->('Cannot assign requested address') if $self->{unbindable}->{ $l[1] };
+ my @fields = qw(addr_trtype addr_adrfam addr_traddr addr_trsvcid);
+ my $address = join(' ', $a->@{@fields});
+ for my $id (keys $m->{ports}->%*) {
+ my $other = $m->{ports}->{$id};
+ next if $id eq $l[1] || !$other->{links}->%*;
+ $fail->('Address already in use')
+ if join(' ', $other->{attr}->@{@fields}) eq $address;
+ }
+ }
+ $port->{links}->{ $l[3] } = 1;
+ } elsif (@l == 4 && $l[0] eq 'subsystems' && $l[2] eq 'allowed_hosts') {
+ $self->violation("ln '$target' '$link'")
+ if @t != 2 || $t[0] ne 'hosts' || $t[1] ne $l[3];
+ my $subsys = $m->{subsystems}->{ $l[1] } // $fail->('No such file or directory');
+ $fail->('No such file or directory') if !$m->{hosts}->{ $t[1] };
+ $fail->('Invalid argument') if $subsys->{attr}->{attr_allow_any_host} eq '1';
+ $fail->('File exists') if $subsys->{acl}->{ $l[3] };
+ $subsys->{acl}->{ $l[3] } = 1;
+ } else {
+ $self->violation("ln '$target' '$link'");
+ }
+ return ();
+ }
+
+ sub cmd_test($self, $flag, $path) {
+ if ($flag eq '-b') {
+ err('') if !$self->block_device($path, 1);
+ return ();
+ }
+ $self->available;
+ my $m = $self->{m};
+ my @p = $self->parts($path);
+ my $found;
+ if (@p == 4 && $p[0] eq 'subsystems' && $p[2] eq 'allowed_hosts') {
+ $found = ($m->{subsystems}->{ $p[1] } // {})->{acl}->{ $p[3] };
+ } elsif (@p == 4 && $p[0] eq 'ports' && $p[2] eq 'subsystems') {
+ $found = ($m->{ports}->{ $p[1] } // {})->{links}->{ $p[3] };
+ } else {
+ $self->violation("test $flag '$path'");
+ }
+ err('') if !$found;
+ return ();
+ }
+
+ sub cmd_grep($self, $flag, $value, $path) {
+ $self->available;
+ my @p = $self->parts($path);
+ $self->violation("grep '$path'")
+ if @p != 3 || $p[0] ne 'subsystems' || $p[2] ne 'attr_allow_any_host';
+ my $subsys = $self->{m}->{subsystems}->{ $p[1] }
+ // err("grep: $path: No such file or directory");
+ err('') if $subsys->{attr}->{attr_allow_any_host} ne $value;
+ return ();
+ }
+
+ sub cmd_cat($self, $path) {
+ $self->violation("cat '$path'") if $path ne '/proc/mounts';
+ return (
+ 'sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0',
+ 'proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0',
+ (
+ $self->{m}->{mounted}
+ ? ('configfs /sys/kernel/config configfs rw,relatime 0 0')
+ : ()
+ ),
+ );
+ }
+
+ sub cmd_mount($self, @args) {
+ err('mount: /sys/kernel/config: none already mounted on /sys/kernel/config.')
+ if $self->{m}->{mounted};
+ $self->{m}->{mounted} = 1;
+ return ();
+ }
+
+ sub cmd_modprobe($self, $module) {
+ $self->violation("modprobe '$module'") if $module ne 'nvmet_tcp';
+ $self->{m}->{loaded} = 1;
+ return ();
+ }
+
+ sub cmd_printf($self, @args) {
+ $self->violation('printf') if @args != 2 || $args[0] ne '%s\n' || $args[1] ne $MARKER;
+ return ($MARKER);
+ }
+
+ # The configfs read; 'golden commands' pins its argv.
+ sub cmd_env($self, @args) {
+ my @hosts = map { $args[$_ + 1] =~ m{\A$RR/hosts/([^/]+)/dhchap_key\z} ? ($1) : () }
+ grep { $args[$_] eq '-path' } 0 .. $#args;
+ $self->available;
+ return $self->configfs_lines(\@hosts);
+ }
+
+ sub configfs_lines($self, $hosts) {
+ my $m = $self->{m};
+ my (@dirs, @links, @attrs, @digests);
+ push @dirs, "D $ROOT", map { "D $ROOT/$_" } qw(hosts ports subsystems);
+ push @dirs, map { "D $ROOT/hosts/$_" } sort keys $m->{hosts}->%*;
+ for my $id (sort { $a <=> $b } keys $m->{ports}->%*) {
+ my $port = $m->{ports}->{$id};
+ push @dirs, "D $ROOT/ports/$id", "D $ROOT/ports/$id/subsystems";
+ push @links, map { "L $ROOT/ports/$id/subsystems/$_" } sort keys $port->{links}->%*;
+ push @attrs,
+ map { "$ROOT/ports/$id/$_:$port->{attr}->{$_}" } sort keys $port->{attr}->%*;
+ }
+ for my $nqn (sort keys $m->{subsystems}->%*) {
+ my $subsys = $m->{subsystems}->{$nqn};
+ my $S = "$ROOT/subsystems/$nqn";
+ push @dirs, "D $S", "D $S/allowed_hosts", "D $S/namespaces";
+ push @links, map { "L $S/allowed_hosts/$_" } sort keys $subsys->{acl}->%*;
+ push @attrs, map { "$S/$_:$subsys->{attr}->{$_}" } sort keys $subsys->{attr}->%*;
+ for my $id (sort { $a <=> $b } keys $subsys->{ns}->%*) {
+ my $ns = $subsys->{ns}->{$id};
+ push @dirs, "D $S/namespaces/$id";
+ push @attrs,
+ map { "$S/namespaces/$id/$_:$ns->{$_}" }
+ qw(buffered_io enable device_uuid device_path);
+ }
+ }
+ for my $hostnqn ($hosts->@*) {
+ my $host = $m->{hosts}->{$hostnqn} // next;
+ push @digests,
+ sha256_hex(($host->{key} // '') . "\n") . " $ROOT/hosts/$hostnqn/dhchap_key";
+ }
+ return (@dirs, @links, @attrs, @digests);
+ }
+
+ # --- zfs --------------------------------------------------------------
+
+ sub cmd_zfs($self, $subcommand, @args) {
+ my $method = "zfs_$subcommand";
+ $self->violation("zfs $subcommand") if !$self->can($method);
+ return $self->$method(@args);
+ }
+
+ # Options with values are listed with 1, flags with 0.
+ sub options($self, $args, %spec) {
+ my %o;
+ my @rest = $args->@*;
+ while (@rest && $rest[0] =~ /\A-/) {
+ my $option = shift @rest;
+ if ($option eq '-Hp') {
+ $o{H} = $o{p} = 1;
+ next;
+ }
+ if ($option =~ /\A-d([0-9]+)\z/) {
+ $o{d} = [$1];
+ next;
+ }
+ my $name = substr($option, 1);
+ $self->violation("zfs option '$option'") if !exists($spec{$name});
+ if ($spec{$name}) {
+ push $o{$name}->@*, shift(@rest);
+ } else {
+ $o{$name} = 1;
+ }
+ }
+ return (\%o, @rest);
+ }
+
+ sub properties_of($self, $assignments) {
+ my %props;
+ for my $assignment (($assignments // [])->@*) {
+ $self->violation("zfs property '$assignment'") if $assignment !~ /\A([^=]+)=(.*)\z/;
+ $props{$1} = $2;
+ }
+ return \%props;
+ }
+
+ sub datasets_under($self, $target, $depth) {
+ my $m = $self->{m};
+ return () if !$m->{ds}->{$target};
+ return sort grep {
+ my $name = $_;
+ $name eq $target
+ || (index($name, "$target/") == 0
+ && (() = substr($name, length($target)) =~ m{/}g) <= $depth)
+ } keys $m->{ds}->%*;
+ }
+
+ sub property($self, $name, $prop) {
+ my $m = $self->{m};
+ my $ds = $m->{ds}->{$name};
+ return ($ds->{type}, '-') if $prop eq 'type';
+ if ($prop =~ /:/) {
+ return ($ds->{props}->{$prop}, 'local') if defined($ds->{props}->{$prop});
+ my $parent = $name;
+ while ($parent =~ s{/[^/]+\z}{}) {
+ my $value = ($m->{ds}->{$parent} // last)->{props}->{$prop};
+ return ($value, "inherited from $parent") if defined($value);
+ }
+ return ('-', '-');
+ }
+ return ($m->{available}, '-') if $prop eq 'available';
+ return ($m->{used}, '-') if $prop eq 'used';
+ return ($ds->{volsize} // '-', '-') if $prop eq 'volsize';
+ return ('4096', '-') if $prop eq 'usedbydataset';
+ $self->violation("zfs property '$prop'");
+ }
+
+ sub zfs_get($self, @args) {
+ my ($o, $props, @targets) = $self->options(\@args, H => 0, p => 0, d => 1, t => 1, o => 1);
+ $self->violation('zfs get') if @targets != 1 || !$o->{H};
+ $self->violation('zfs get inventory')
+ if $props =~ /\Atype,proxmox:/
+ && !main::same(['get', @args], main::expected_inventory_read($targets[0]));
+ my $target = $targets[0];
+ my @fields = split /,/, ($o->{o} // ['name,property,value,source'])->[0];
+ my %types = map { $_ => 1 } split /,/, ($o->{t} // ['filesystem,volume'])->[0];
+ my @datasets = $self->datasets_under($target, $o->{d} ? $o->{d}->[0] : 0)
+ or err("cannot open '$target': dataset does not exist");
+ my @out;
+
+ for my $name (grep { $types{ $self->{m}->{ds}->{$_}->{type} } } @datasets) {
+ for my $prop (split /,/, $props) {
+ my ($value, $source) = $self->property($name, $prop);
+ my %row = (name => $name, property => $prop, value => $value, source => $source);
+ push @out, join("\t", map { $row{$_} } @fields);
+ }
+ }
+ return @out;
+ }
+
+ sub list_field($self, $row, $field) {
+ my $m = $self->{m};
+ return $row if $field eq 'name';
+ if (my $snap = $m->{snaps}->{$row}) {
+ return 1000 + $snap->{seq} if $field eq 'guid';
+ return 1700000000 + $snap->{seq} if $field eq 'creation';
+ $self->violation("zfs list snapshot field '$field'");
+ }
+ my $ds = $m->{ds}->{$row};
+ return $ds->{type} eq 'volume' ? $ds->{volsize} : '-' if $field eq 'volsize';
+ return $ds->{origin} // '-' if $field eq 'origin';
+ return $ds->{type} if $field eq 'type';
+ $self->violation("zfs list field '$field'");
+ }
+
+ sub zfs_list($self, @args) {
+ my ($o, @targets) =
+ $self->options(\@args, H => 0, p => 0, r => 0, d => 1, t => 1, o => 1, s => 1);
+ $self->violation('zfs list') if @targets != 1 || !$o->{H};
+ my $m = $self->{m};
+ my $target = $targets[0];
+ my @fields = split /,/, ($o->{o} // ['name'])->[0];
+ my %types = map { $_ => 1 } split /,/, ($o->{t} // ['filesystem,volume'])->[0];
+ my @rows;
+ if ($target =~ /\@/) {
+ err("cannot open '$target': dataset does not exist") if !$m->{snaps}->{$target};
+ @rows = ($target);
+ } else {
+ my $depth = $o->{d} ? $o->{d}->[0] : $o->{r} ? 1000 : 0;
+ my @datasets = $self->datasets_under($target, $depth)
+ or err("cannot open '$target': dataset does not exist");
+ if ($types{snapshot}) {
+ my %under = map { $_ => 1 } @datasets;
+ push @rows, sort { $m->{snaps}->{$a}->{seq} <=> $m->{snaps}->{$b}->{seq} }
+ grep { $under{ (split /\@/)[0] } } keys $m->{snaps}->%*;
+ }
+ push @rows, grep { $types{ $m->{ds}->{$_}->{type} } } @datasets;
+ }
+ return map {
+ my $row = $_;
+ join("\t", map { $self->list_field($row, $_) } @fields)
+ } @rows;
+ }
+
+ sub zfs_create($self, @args) {
+ my ($o, @targets) = $self->options(\@args, s => 0, b => 1, o => 1, V => 1);
+ $self->violation('zfs create') if @targets != 1 || !$o->{V};
+ my $m = $self->{m};
+ my $name = $targets[0];
+ my ($parent) = $name =~ m{\A(.+)/[^/]+\z} or $self->violation('zfs create name');
+ $self->violation('zfs create size') if $o->{V}->[0] !~ /\A([0-9]+)k\z/;
+ my $size = $1 * 1024;
+ err("cannot create '$name': parent does not exist") if !$m->{ds}->{$parent};
+ err("cannot create '$name': dataset already exists") if $m->{ds}->{$name};
+ $m->{ds}->{$name} = {
+ type => 'volume',
+ props => $self->properties_of($o->{o}),
+ volsize => $size,
+ origin => '-',
+ devwait => $self->{udev_delay},
+ sparse => $o->{s} ? 1 : 0,
+ blocksize => $o->{b} ? $o->{b}->[0] : undef,
+ };
+ return ();
+ }
+
+ sub zfs_clone($self, @args) {
+ my ($o, $origin, $name, @extra) = $self->options(\@args, o => 1);
+ $self->violation('zfs clone') if @extra || !defined($name);
+ my $m = $self->{m};
+ my $snap = $m->{snaps}->{$origin} // err("cannot open '$origin': dataset does not exist");
+ err("cannot create '$name': dataset already exists") if $m->{ds}->{$name};
+ $m->{ds}->{$name} = {
+ type => 'volume',
+ props => $self->properties_of($o->{o}),
+ volsize => $snap->{volsize},
+ origin => $origin,
+ devwait => $self->{udev_delay},
+ };
+ return ();
+ }
+
+ sub zfs_destroy($self, @args) {
+ my ($o, $target, @extra) = $self->options(\@args, r => 0);
+ $self->violation('zfs destroy') if @extra || !defined($target);
+ my $m = $self->{m};
+ my $clones = sub($snapshot) {
+ return grep { ($_->{origin} // '-') eq $snapshot } values $m->{ds}->%*;
+ };
+ if ($target =~ /\@/) {
+ $self->violation('zfs destroy -r of a snapshot') if $o->{r};
+ err("could not find any snapshots to destroy; check snapshot names.")
+ if !$m->{snaps}->{$target};
+ err("cannot destroy snapshot $target: snapshot has dependent clones")
+ if $clones->($target);
+ delete $m->{snaps}->{$target};
+ return ();
+ }
+ $self->violation('zfs destroy without -r') if !$o->{r};
+ err("cannot open '$target': dataset does not exist") if !$m->{ds}->{$target};
+ err("cannot destroy '$target': dataset is busy") if $self->busy($target);
+ my @snaps = grep { index($_, "$target\@") == 0 } keys $m->{snaps}->%*;
+ err("cannot destroy '$target': filesystem has dependent clones")
+ if grep { $clones->($_) } @snaps;
+ delete $m->{snaps}->{$_} for @snaps;
+ delete $m->{ds}->{$target};
+ return ();
+ }
+
+ # Stricter than ZFS: user properties revert to their value at snapshot
+ # time, so the plugin must set the identity again after a rollback.
+ sub zfs_rollback($self, @args) {
+ $self->violation('zfs rollback') if @args != 1 || $args[0] !~ /\@/;
+ my $m = $self->{m};
+ my ($name) = split /\@/, $args[0];
+ my $snap = $m->{snaps}->{ $args[0] }
+ // err("cannot open '$args[0]': dataset does not exist");
+ err("cannot rollback to '$args[0]': more recent snapshots or bookmarks exist")
+ if grep { index($_, "$name\@") == 0 && $m->{snaps}->{$_}->{seq} > $snap->{seq} }
+ keys $m->{snaps}->%*;
+ err("cannot rollback '$name': dataset is busy") if $self->busy($name);
+ my $ds = $m->{ds}->{$name};
+ $ds->{props} = dclone($snap->{props});
+ $ds->{volsize} = $snap->{volsize};
+ $ds->{devwait} = $self->{udev_delay};
+ return ();
+ }
+
+ sub zfs_set($self, @args) {
+ my $target = pop @args;
+ $self->violation('zfs set') if !@args;
+ my $m = $self->{m};
+ my $object = $target =~ /\@/ ? $m->{snaps}->{$target} : $m->{ds}->{$target};
+ err("cannot open '$target': dataset does not exist") if !$object;
+ for my $assignment (@args) {
+ $self->violation("zfs set '$assignment'") if $assignment !~ /\A([^=]+)=(.*)\z/;
+ my ($prop, $value) = ($1, $2);
+ if ($prop eq 'volsize') {
+ $self->violation('zfs set volsize') if $value !~ /\A([0-9]+)k\z/;
+ $object->{volsize} = $1 * 1024;
+ } elsif ($prop =~ /:/) {
+ $object->{props}->{$prop} = $value;
+ } else {
+ $self->violation("zfs set '$prop'");
+ }
+ }
+ return ();
+ }
+
+ # Like OpenZFS, which renames the minor of a zvol that is open: an
+ # exported zvol is renamed under its namespace.
+ sub zfs_rename($self, @args) {
+ $self->violation('zfs rename') if @args != 2;
+ my ($old, $new) = @args;
+ my $m = $self->{m};
+ err("cannot open '$old': dataset does not exist") if !$m->{ds}->{$old};
+ err("cannot rename to '$new': dataset already exists") if $m->{ds}->{$new};
+ $m->{ds}->{$new} = delete $m->{ds}->{$old};
+ for my $snap (grep { index($_, "$old\@") == 0 } keys $m->{snaps}->%*) {
+ my $renamed = $new . substr($snap, length($old));
+ $m->{snaps}->{$renamed} = delete $m->{snaps}->{$snap};
+ for my $ds (values $m->{ds}->%*) {
+ $ds->{origin} = $renamed if ($ds->{origin} // '-') eq $snap;
+ }
+ }
+ $m->{ds}->{$new}->{devwait} = $self->{udev_delay};
+ return ();
+ }
+
+ sub zfs_snapshot($self, @args) {
+ $self->violation('zfs snapshot') if @args != 1 || $args[0] !~ /\A([^@]+)\@(.+)\z/;
+ my ($name, $snap) = ($1, $2);
+ err("cannot create snapshot '$args[0]': invalid character in name")
+ if $snap !~ /\A[A-Za-z0-9_.: -]+\z/;
+ my $m = $self->{m};
+ my $ds = $m->{ds}->{$name} // err("cannot open '$name': dataset does not exist");
+ err("cannot create snapshot '$args[0]': dataset already exists")
+ if $m->{snaps}->{ $args[0] };
+ $m->{snaps}->{ $args[0] } =
+ { props => dclone($ds->{props}), volsize => $ds->{volsize}, seq => ++$m->{seq} };
+ return ();
+ }
+}
+
+# The inventory read written down independently of the plugin code.
+my $INVENTORY_PROPS =
+ 'type,proxmox:nvme-subsys,proxmox:nvme-nsid,proxmox:nvme-uuid,proxmox:nvme-last-nsid';
+
+sub expected_inventory_read($pool) {
+ return [
+ 'get',
+ '-H',
+ '-p',
+ '-d',
+ '1',
+ '-t',
+ 'filesystem,volume',
+ '-o',
+ 'name,property,value,source',
+ $INVENTORY_PROPS,
+ $pool,
+ ];
+}
+
+# ---------------------------------------------------------------------------
+# Flow helpers and invariants
+# ---------------------------------------------------------------------------
+
+# Runs $code against $fake and returns what happened during the run.
+sub flow($fake, $code) {
+ local $FAKE = $fake;
+ local @LOCKS = ();
+ local @NESTED_LOCKS = ();
+ local @WARNINGS = ();
+ local @SYSFS_WRITES = ();
+
+ my $start = scalar($fake->{calls}->@*);
+ my $result = eval { $code->() };
+ my $error = $@;
+ my @calls = $fake->{calls}->@*;
+ return {
+ error => $error,
+ result => $result,
+ calls => [@calls[$start .. $#calls]],
+ locks => [@LOCKS],
+ nested => [@NESTED_LOCKS],
+ warnings => [@WARNINGS],
+ sysfs_writes => [@SYSFS_WRITES],
+ };
+}
+
+sub ops($res) {
+ return [map { $_->{op} } $res->{calls}->@*];
+}
+
+sub changes($res) {
+ return scalar(grep { $_->{changing} } $res->{calls}->@*);
+}
+
+# Our subsystem published on two ports to two hosts, no volumes yet.
+sub target_fake(%opts) {
+ my $fake = FakeTarget->new(pools => ['tank', 'other'], %opts);
+ $fake->add_host($_, $KEY) for @HOSTS;
+ $fake->add_subsystem($NQN, acl => [@HOSTS]);
+ $fake->add_port(1, '192.0.2.21', 4420, links => [$NQN]);
+ $fake->add_port(2, '192.0.2.22', 4420, links => [$NQN]);
+ return $fake;
+}
+
+sub add_volume($fake, $name, $nsid, $uuid, %o) {
+ $fake->add_zvol("tank/$name", identity => [$NQN, $nsid, $uuid]);
+ $fake->add_namespace($NQN, $nsid, $uuid, "/dev/zvol/tank/$name", $o{enable} // 1)
+ if !$o{unexported};
+ return $fake;
+}
+
+# A converged target with three owned volumes, an unowned leftover, a volume
+# of another subsystem in our pool, and a foreign subsystem that shares the
+# first host and port 1.
+sub lifecycle_fake(%opts) {
+ my $fake = target_fake(%opts);
+ add_volume($fake, 'vm-100-disk-0', 1, $U{1});
+ add_volume($fake, 'vm-101-disk-0', 2, $U{2});
+ add_volume($fake, 'base-102-disk-0', 3, $U{3});
+ $fake->add_snapshot('tank/vm-100-disk-0@snap1');
+ $fake->add_snapshot('tank/base-102-disk-0@__base__');
+ $fake->add_zvol('tank/vm-900-disk-0');
+ $fake->add_zvol('tank/vm-901-disk-0', identity => [$FOREIGN_NQN, 7, $U{7}]);
+ $fake->add_zvol('other/foreign-disk', identity => [$FOREIGN_NQN, 1, $U{8}]);
+ $fake->add_subsystem(
+ $FOREIGN_NQN,
+ model => 'Linux',
+ serial => '0123456789abcdef',
+ acl => [$HOSTS[0]],
+ );
+ $fake->add_namespace($FOREIGN_NQN, 1, $U{8}, '/dev/zvol/other/foreign-disk');
+ $fake->{m}->{ports}->{1}->{links}->{$FOREIGN_NQN} = 1;
+ return $fake;
+}
+
+sub owned_volumes($m, $nqn = $NQN, $pool = 'tank') {
+ my %owned;
+ for my $name (sort keys $m->{ds}->%*) {
+ my $ds = $m->{ds}->{$name};
+ next if $ds->{type} ne 'volume' || $name !~ m{\A\Q$pool\E/[^/]+\z};
+ next if ($ds->{props}->{'proxmox:nvme-subsys'} // '') ne $nqn;
+ $owned{$name} = [map { $ds->{props}->{"proxmox:nvme-$_"} } qw(nsid uuid)];
+ }
+ return \%owned;
+}
+
+# Everything on the target that does not belong to the storage under test.
+# The last NSID handed out, on its pool, belongs to the storage.
+sub foreign_view($m, $port_ids, $nqn, $hostnqns, $pool = 'tank') {
+ my %ours = map { $_ => 1 } $hostnqns->@*;
+ my $dataset = sub($name) {
+ my $ds = $m->{ds}->{$name};
+ return $ds if $name ne $pool;
+ my %props = $ds->{props}->%*;
+ delete $props{'proxmox:nvme-last-nsid'};
+ return { $ds->%*, props => \%props };
+ };
+ return {
+ subsystems =>
+ { map { $_ => $m->{subsystems}->{$_} } grep { $_ ne $nqn } keys $m->{subsystems}->%* },
+ datasets => {
+ map { $_ => $dataset->($_) }
+ grep { ($m->{ds}->{$_}->{props}->{'proxmox:nvme-subsys'} // '') ne $nqn }
+ keys $m->{ds}->%*
+ },
+ hosts => { map { $_ => $m->{hosts}->{$_} } grep { !$ours{$_} } keys $m->{hosts}->%* },
+ ports => {
+ map {
+ my $port = $m->{ports}->{$_};
+ my @links = $port ? sort grep { $_ ne $nqn } keys $port->{links}->%* : ();
+ ($_ => $port ? [$port->{attr}, \@links] : undef)
+ } $port_ids->@*
+ },
+ };
+}
+
+# (i), (ii), (vi) and (vii), checked after every call.
+sub online_violations($fake, $ctx) {
+ my $m = $fake->{m};
+ my $nqn = $ctx->{nqn};
+ my @bad;
+ if (my $subsys = $m->{subsystems}->{$nqn}) {
+ my $owned = owned_volumes($m, $nqn, $ctx->{pool});
+ my %identity = map { ("/dev/zvol/$_" => $owned->{$_}) } keys $owned->%*;
+ my %seen;
+ for my $id (sort keys $subsys->{ns}->%*) {
+ my $ns = $subsys->{ns}->{$id};
+ push @bad, "(ii) UUID $ns->{device_uuid} used by two namespaces"
+ if $seen{ lc($ns->{device_uuid}) }++;
+ next if $ns->{enable} ne '1';
+ my $want = $identity{ $ns->{device_path} };
+ push @bad, "(i) namespace $id exports $ns->{device_path} under another identity"
+ if !$want || $want->[0] ne $id || lc($want->[1]) ne lc($ns->{device_uuid});
+ }
+ if (grep { $_->{links}->{$nqn} } values $m->{ports}->%*) {
+ push @bad, '(vi) published while any host may connect'
+ if $subsys->{attr}->{attr_allow_any_host} ne '0';
+ for my $hostnqn ($ctx->{teardown} ? () : $ctx->{hosts}->@*) {
+ push @bad, "(vi) published without the ACL of $hostnqn"
+ if !$subsys->{acl}->{$hostnqn};
+ push @bad, "(vi) published without the key of $hostnqn"
+ if (($m->{hosts}->{$hostnqn} // {})->{key} // '') ne $ctx->{key};
+ }
+ }
+ }
+ push @bad,
+ '(vii) objects of other storages changed'
+ if !same(
+ foreign_view($m, $ctx->{port_ids}, $nqn, $ctx->{hosts}, $ctx->{pool}),
+ $ctx->{foreign},
+ );
+ return @bad;
+}
+
+# (iii): owned identities stay valid, unique and attached to their volume.
+sub identity_violations($m, $ctx) {
+ my @bad;
+ my $owned = owned_volumes($m, $ctx->{nqn}, $ctx->{pool});
+ my (%nsids, %uuids);
+ for my $name (sort keys $owned->%*) {
+ my ($nsid, $uuid) = $owned->{$name}->@*;
+ push @bad, "(iii) invalid identity on $name"
+ if ($nsid // '') !~ /\A[1-9][0-9]*\z/ || ($uuid // '') !~ $UUID_RE;
+ push @bad, "(iii) NSID $nsid on two volumes" if $nsids{ $nsid // '' }++;
+ push @bad, "(iii) UUID $uuid on two volumes" if $uuids{ lc($uuid // '') }++;
+ }
+ for my $name (sort keys $ctx->{initial_owned}->%*) {
+ my $identity = join('/', $ctx->{initial_owned}->{$name}->@*);
+ my @holders = grep { join('/', $owned->{$_}->@*) eq $identity } keys $owned->%*;
+ next if !@holders && ($ctx->{may_vanish} // '') eq $name;
+ my %allowed = map { $_ => 1 } $name, ($ctx->{renames}->{$name} // ());
+ push @bad, "(iii) identity of $name lost" if @holders != 1 || !$allowed{ $holders[0] };
+ }
+ return @bad;
+}
+
+# A creation cut right after its mkdir leaves an unused subsystem with the
+# kernel's default model, which another tool could have created as well.
+# Activation refuses it until an administrator removes it.
+sub default_subsystem($m, $nqn) {
+ my $subsys = $m->{subsystems}->{$nqn} // return 0;
+ return
+ $subsys->{attr}->{attr_model} eq 'Linux'
+ && !$subsys->{ns}->%*
+ && !$subsys->{acl}->%*
+ && !grep { $_->{links}->{$nqn} } values $m->{ports}->%*;
+}
+
+# (v): one more activation exports every owned volume exactly once.
+sub convergence_violations($fake, $ctx) {
+ my $res = flow($fake, sub { activate($ctx->{scfg}, $ctx->{key}, $ctx->{hosts}) });
+ if (my $error = $res->{error}) {
+ return ()
+ if $error =~ /not created by Proxmox VE/ && default_subsystem($fake->{m}, $ctx->{nqn});
+ return "(v) activation afterwards failed: $error";
+ }
+ my $m = $fake->{m};
+ my $owned = owned_volumes($m, $ctx->{nqn}, $ctx->{pool});
+ my $subsys = $m->{subsystems}->{ $ctx->{nqn} } // return '(v) subsystem missing';
+ my %want = map { $owned->{$_}->[0] => ["/dev/zvol/$_", lc($owned->{$_}->[1]), '1'] }
+ keys $owned->%*;
+ my %have = map {
+ my $ns = $subsys->{ns}->{$_};
+ ($_ => [$ns->{device_path}, lc($ns->{device_uuid}), $ns->{enable}])
+ } keys $subsys->{ns}->%*;
+ my @bad;
+ push @bad, '(v) exported namespaces differ from the owned volumes' if !same(\%want, \%have);
+ # An interrupted port creation leaves an incomplete port that is ignored;
+ # the portal is then served by a new port with the same address.
+ for my $portal ($PORTALS->@*) {
+ my ($address, $service) = $portal->@{qw(address port)};
+ push @bad, "(v) not published on $address"
+ if !grep {
+ $_->{links}->{ $ctx->{nqn} }
+ && $_->{attr}->{addr_traddr} eq $address
+ && $_->{attr}->{addr_trsvcid} eq "$service"
+ } values $m->{ports}->%*;
+ }
+ return @bad;
+}
+
+sub run_case($initial, $ctx, $faults, $read_fault = undef) {
+ my $fake = FakeTarget->from_state($initial);
+ $fake->{faults} = $faults;
+ $fake->{read_fault} = $read_fault;
+ my @online;
+ $fake->{after_call} = sub($f, $call) {
+ push @online,
+ map { "call $call->{index} ($call->{op}): $_" } online_violations($f, $ctx);
+ };
+ my $res = flow($fake, $ctx->{action});
+ $res->{fake} = $fake;
+ $res->{online} = \@online;
+ $res->{faults} = { $faults->%*, ($read_fault ? (read => $read_fault->{mode}) : ()) };
+ return $res;
+}
+
+sub case_violations($ctx, $res) {
+ my $fake = $res->{fake};
+ my @bad;
+ push @bad, 'domain lock taken ' . scalar($res->{locks}->@*) . ' times'
+ if $res->{locks}->@* > 1;
+ push @bad, 'nested domain lock request' if $res->{nested}->@*;
+ push @bad, 'key in the error text' if grep { index($res->{error}, $_) >= 0 } $KEY, $KEY_B;
+
+ # The result must match the outcome: success only when the goal is
+ # reached, and a flow whose only faults are lost replies (create and
+ # clone, which cannot settle one with a read) may fail after reaching its
+ # goal only with an unknown target state.
+ my @missing = $ctx->{done}->($fake->{m}, $res);
+ push @bad, map { "success without reaching the goal: $_" } @missing if $res->{error} eq '';
+ my @modes = values $res->{faults}->%*;
+ push @bad, "failure after reaching the goal: $res->{error}"
+ if $ctx->{lost_replies}
+ && $res->{error} ne ''
+ && $res->{error} !~ /the target state is unknown\n\z/
+ && !@missing
+ && @modes
+ && !grep { $_ ne 'after' } @modes;
+
+ # A call that ssh gave up on completes on the target afterwards. When the
+ # rest of it changes the target, the outcome was unknown.
+ if ($fake->{late}->@*) {
+ if (
+ grep {
+ grep { mutating_step($_) } $_->{steps}->@*
+ } $fake->{late}->@*
+ ) {
+ push @bad, "late call after a success" if $res->{error} eq '';
+ push @bad, "late call reported without an unknown state: $res->{error}"
+ if $res->{error} !~ /the target state is unknown\n\z/;
+ }
+ $fake->land;
+ push @bad, map { "after the late call: $_" } online_violations($fake, $ctx);
+ }
+ push @bad, identity_violations($fake->{m}, $ctx);
+ $fake->{faults} = {};
+ $fake->{read_fault} = undef;
+ if ($ctx->{retry}) {
+ my $retry = flow($fake, $ctx->{retry});
+ push @bad, "retry failed: $retry->{error}" if $retry->{error};
+ push @bad, $ctx->{goal}->($fake->{m}) if !$retry->{error};
+ } else {
+ push @bad, convergence_violations($fake, $ctx);
+ }
+ push @bad, $res->{online}->@*;
+ push @bad, map { "protocol: $_" } $fake->{violations}->@*;
+ return @bad;
+}
+
+# Fault sweep: every mutating call of a flow fails, and then every later
+# mutating call of that run fails as well, or the first read after it. After
+# each run: (i) every enabled namespace of the subsystem exports the zvol of
+# its identity, (ii) no UUID is used twice, (iii) owned identities are kept
+# and unique, (v) one more activation (or a retried removal) converges, (vi)
+# the subsystem is never published before its ACLs, keys and
+# allow_any_host=0, (vii) nothing of other storages changes, every change ran
+# under one domain lock, and the result matches the outcome. (i), (ii), (vi)
+# and (vii) are checked after every call; refusals are covered by their own
+# tests.
+sub sweep($name, $ctx) {
+ my $initial = dclone($ctx->{setup}->()->{m});
+ $ctx->{nqn} //= $NQN;
+ $ctx->{pool} //= 'tank';
+ $ctx->{hosts} //= [@HOSTS];
+ $ctx->{key} //= $KEY;
+ $ctx->{scfg} //= scfg();
+ $ctx->{initial_owned} = owned_volumes($initial, $ctx->{nqn}, $ctx->{pool});
+ $ctx->{port_ids} = [sort keys $initial->{ports}->%*];
+ $ctx->{foreign} =
+ foreign_view($initial, $ctx->{port_ids}, $ctx->{nqn}, $ctx->{hosts}, $ctx->{pool});
+
+ my $baseline = run_case($initial, $ctx, {});
+ is($baseline->{error}, '', "$name: succeeds without faults");
+ is_deeply([$ctx->{done}->($baseline->{fake}->{m}, $baseline)], [], "$name: reaches its goal");
+ is_deeply([case_violations($ctx, $baseline)], [], "$name: invariants hold without faults");
+
+ # A call fails in each mode of FakeTarget::execute, at each step of its
+ # chain. A second failure, in the compensation or the next round, is one
+ # that fails before or after its call, or the first read after the first
+ # failure fails or finds the target unreachable.
+ my $modes = sub($call) {
+ my @steps = 1 .. $call->{steps}->$#*;
+ return ('before', 'after', 'late', (map { "cut:$_" } @steps), map { "lost:$_" } @steps);
+ };
+ my @first = grep { $_->{mutating} } $baseline->{calls}->@*;
+ ok(scalar(@first), "$name: changes the target");
+ my ($runs, @failures) = (0);
+ for my $first (@first) {
+ my $k = $first->{index};
+ for my $mode ($modes->($first)) {
+ my $res = run_case($initial, $ctx, { $k => $mode });
+ $runs++;
+ my @later = grep { $_->{mutating} && $_->{index} > $k } $res->{calls}->@*;
+ push @failures, map { "call $k $mode: $_" } case_violations($ctx, $res);
+ for my $second (@later) {
+ my $j = $second->{index};
+ for my $again_mode (qw(before after)) {
+ my $again = run_case($initial, $ctx, { $k => $mode, $j => $again_mode });
+ $runs++;
+ push @failures,
+ map { "call $k $mode, call $j $again_mode: $_" }
+ case_violations($ctx, $again);
+ }
+ }
+ for my $read_mode (qw(before unreachable)) {
+ my $read_fault = { after => $k, mode => $read_mode };
+ my $again = run_case($initial, $ctx, { $k => $mode }, $read_fault);
+ $runs++;
+ push @failures,
+ map { "call $k $mode, next read $read_mode: $_" } case_violations($ctx, $again);
+ }
+ }
+ }
+ ok(!@failures, "$name: the invariants hold in $runs fault injections")
+ or diag(join("\n", @failures));
+}
+
+# ---------------------------------------------------------------------------
+# Fixtures and the fake target formats
+# ---------------------------------------------------------------------------
+
+my $FIXTURE_ZFS = slurp("$FIXTURES/zfs_inventory.txt");
+my $FIXTURE_CFS = slurp("$FIXTURES/configfs_snapshot.txt");
+my $FIXTURE_DIGESTS = join('', map { "$KEY_SHA $ROOT/hosts/$_/dhchap_key\n" } @FIXTURE_HOSTS);
+
+sub fixture_fake() {
+ my $fake = FakeTarget->new(pools => ['tank']);
+ $fake->add_host($_) for @FIXTURE_HOSTS;
+ $fake->add_subsystem($FIXTURE_NQN, acl => [@FIXTURE_HOSTS]);
+ $fake->add_port($_, "192.0.2.2$_", 4420, links => [$FIXTURE_NQN]) for 1, 2;
+ $fake->add_zvol('tank/vm-100-disk-0', identity => [$FIXTURE_NQN, 5, $FIXTURE_UUID5]);
+ $fake->add_zvol('tank/vm-100-cloudinit', identity => [$FIXTURE_NQN, 6, $FIXTURE_UUID6]);
+ $fake->add_namespace($FIXTURE_NQN, 5, $FIXTURE_UUID5, '/dev/zvol/tank/vm-100-disk-0');
+ $fake->add_namespace($FIXTURE_NQN, 6, $FIXTURE_UUID6, '/dev/zvol/tank/vm-100-cloudinit');
+ return $fake;
+}
+
+subtest 'the fake target answers in the formats of the fixture target' => sub {
+ my $fake = fixture_fake();
+ my @zfs = $fake->zfs_get(expected_inventory_read('tank')->@[1 .. 10]);
+ is(join('', map { "$_\n" } @zfs), $FIXTURE_ZFS, 'the ZFS inventory equals the fixture');
+ my $cfs = join('', map { "$_\n" } $fake->configfs_lines([]));
+ is_deeply(
+ nv('_nvmet_parse_configfs', $cfs),
+ nv('_nvmet_parse_configfs', $FIXTURE_CFS),
+ 'the configfs read parses to the fixture',
+ );
+};
+
+# ---------------------------------------------------------------------------
+# Parsers
+# ---------------------------------------------------------------------------
+
+sub zfs_rows($name, $type, $nqn = '-', $nsid = '-', $uuid = '-', $source = 'local', $last = '-') {
+ my $source_of = sub($value) { $value eq '-' ? '-' : $source };
+ return (
+ "$name\ttype\t$type\t-",
+ "$name\tproxmox:nvme-subsys\t$nqn\t" . $source_of->($nqn),
+ "$name\tproxmox:nvme-nsid\t$nsid\t" . $source_of->($nsid),
+ "$name\tproxmox:nvme-uuid\t$uuid\t" . $source_of->($uuid),
+ "$name\tproxmox:nvme-last-nsid\t$last\t" . $source_of->($last),
+ );
+}
+
+sub inventory(@rows) {
+ return nv('_nvmet_parse_zfs_inventory', join('', map { "$_\n" } @rows), 'tank');
+}
+
+my @POOL = zfs_rows('tank', 'filesystem');
+my @ONE = zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $U{1});
+my @TWO = zfs_rows('tank/vm-101-disk-0', 'volume', $NQN, 2, $U{2});
+
+subtest 'ZFS inventory parser' => sub {
+ is_deeply(
+ inventory(@POOL, @ONE, @TWO),
+ {
+ types => {
+ tank => 'filesystem',
+ 'tank/vm-100-disk-0' => 'volume',
+ 'tank/vm-101-disk-0' => 'volume',
+ },
+ volumes => {
+ 'tank/vm-100-disk-0' => { nqn => $NQN, nsid => 1, uuid => $U{1} },
+ 'tank/vm-101-disk-0' => { nqn => $NQN, nsid => 2, uuid => $U{2} },
+ },
+ last_nsid => 0,
+ },
+ 'complete inventory',
+ );
+ my $pool_last = sub($last, $source = 'local') {
+ return inventory(
+ zfs_rows('tank', 'filesystem', '-', '-', '-', $source, $last),
+ zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $U{1}, 'local', '-'),
+ )->{last_nsid};
+ };
+ is($pool_last->(7), 7, 'the last NSID handed out is read from the pool');
+ is($pool_last->(7, 'inherited from tank'), 0, 'but not inherited');
+ is($pool_last->('x'), 0, 'and only when it is a valid NSID');
+ is(
+ inventory(@POOL, zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $U{1}, 'local', 9))
+ ->{last_nsid},
+ 0,
+ 'a volume does not carry it',
+ );
+ my $short_owner = "tank/vm-101-disk-0\tproxmox:nvme-subsys\t$NQN";
+ my $foreign_source = "tank/vm-101-disk-0\tproxmox:nvme-uuid\t$U{2}\tgarbage";
+ for my $case (
+ [
+ 'missing owner row',
+ [@POOL, @ONE, @TWO[0, 2, 3]],
+ qr/incomplete ZFS properties on 'tank\/vm-101-disk-0'/,
+ ],
+ [
+ 'short row',
+ [@POOL, @ONE, $TWO[0], $short_owner, @TWO[2, 3]],
+ qr/malformed ZFS inventory row/,
+ ],
+ [
+ 'duplicate property',
+ [@POOL, @ONE, @TWO, $TWO[1]],
+ qr/duplicate ZFS property 'proxmox:nvme-subsys'/,
+ ],
+ [
+ 'unknown property',
+ [@POOL, @ONE, @TWO, "tank/vm-101-disk-0\tcompression\ton\tlocal"],
+ qr/unexpected ZFS property on 'tank\/vm-101-disk-0'/,
+ ],
+ [
+ 'extra field',
+ [@POOL, @ONE, @TWO[0 .. 2], "$TWO[3]\textra"],
+ qr/malformed ZFS inventory row/,
+ ],
+ [
+ 'unknown source',
+ [@POOL, @ONE, @TWO[0 .. 2], $foreign_source],
+ qr/invalid ZFS property source/,
+ ],
+ ['missing pool rows', [@ONE, @TWO], qr/missing the configured pool/],
+ [
+ 'missing pool type row',
+ [@POOL[1 .. 4], @ONE],
+ qr/incomplete ZFS properties on 'tank'/,
+ ],
+ [
+ 'pool name prefix',
+ [@POOL, zfs_rows('tank2/vm-1-disk-0', 'volume')],
+ qr/outside configured pool/,
+ ],
+ [
+ 'depth 2 dataset',
+ [@POOL, zfs_rows('tank/sub/vm-1-disk-0', 'volume')],
+ qr/outside configured pool/,
+ ],
+ [
+ 'invalid type',
+ [@POOL, "tank/vm-100-disk-0\ttype\tsnapshot\t-", @ONE[1 .. 3]],
+ qr/invalid ZFS dataset type/,
+ ],
+ [
+ 'value with CR',
+ [@POOL, @ONE[0 .. 2], "tank/vm-100-disk-0\tproxmox:nvme-uuid\t$U{1}\r\tlocal"],
+ qr/malformed ZFS inventory row/,
+ ],
+ [
+ 'inherited from a malformed pool',
+ [
+ @POOL,
+ @ONE[0 .. 2],
+ "tank/vm-100-disk-0\tproxmox:nvme-uuid\t$U{1}\tinherited from bad pool",
+ ],
+ qr/invalid ZFS pool name/,
+ ],
+ ) {
+ my ($name, $rows, $error) = $case->@*;
+ eval { inventory($rows->@*) };
+ like($@, $error, "rejects $name");
+ }
+
+ is_deeply(
+ inventory(@POOL),
+ { types => { tank => 'filesystem' }, volumes => {}, last_nsid => 0 },
+ 'a verified empty pool',
+ );
+ my $received = inventory(
+ @POOL, zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $U{1}, 'received'),
+ );
+ is($received->{volumes}->{'tank/vm-100-disk-0'}->{nqn}, $NQN, 'received properties count');
+ my $inherited = inventory(
+ zfs_rows('tank', 'filesystem', $NQN, '-', '-'),
+ zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $U{1}, 'inherited from tank'),
+ );
+ is_deeply(
+ $inherited->{volumes}->{'tank/vm-100-disk-0'},
+ { nqn => '-', nsid => '-', uuid => '-' },
+ 'inherited properties never own a volume',
+ );
+ my $subvol = inventory(@POOL, zfs_rows('tank/subvol-100-disk-0', 'filesystem'));
+ ok(
+ $subvol->{types}->{'tank/subvol-100-disk-0'} eq 'filesystem'
+ && !$subvol->{volumes}->{'tank/subvol-100-disk-0'},
+ 'a filesystem child is a dataset but not a volume',
+ );
+
+ # a direct child with a name PVE never uses is carried as not owned
+ my $spaced = inventory(@POOL, zfs_rows('tank/my data', 'volume', $NQN, 9, $U{9}));
+ is($spaced->{types}->{'tank/my data'}, 'volume',
+ 'a name with a space is kept as a dataset');
+ is($spaced->{volumes}->{'tank/my data'}->{nqn}, '-', 'a name with a space is never owned');
+ is_deeply(nv('_nvmet_desired_namespaces', $spaced, $NQN), {}, 'and never exported');
+ eval { inventory(@POOL, "tank/my data\tcompression\ton\tlocal") };
+ is($@, "unexpected ZFS property\n", 'errors do not echo names PVE never uses');
+
+ my $fixture = nv('_nvmet_parse_zfs_inventory', $FIXTURE_ZFS, 'tank');
+ is_deeply(
+ $fixture->{volumes},
+ {
+ 'tank/vm-100-disk-0' => { nqn => $FIXTURE_NQN, nsid => 5, uuid => $FIXTURE_UUID5 },
+ 'tank/vm-100-cloudinit' =>
+ { nqn => $FIXTURE_NQN, nsid => 6, uuid => $FIXTURE_UUID6 },
+ },
+ 'the fixture inventory',
+ );
+ eval { nv('_nvmet_parse_zfs_inventory', $FIXTURE_ZFS, 'bad pool') };
+ like($@, qr/invalid ZFS pool name/, 'the configured pool is validated');
+};
+
+subtest 'ZFS property values and sources' => sub {
+ for my $case (
+ [undef, 'local'],
+ ['', 'local'],
+ ["a\nb", 'local'],
+ ["a\tb", 'local'],
+ ['x', ''],
+ ['x', undef],
+ ['x', "local\r"],
+ ) {
+ eval { nv('_nvmet_property_value', $case->@*) };
+ like($@, qr/malformed ZFS property value/, 'rejects a malformed value or source');
+ }
+ is(nv('_nvmet_property_value', $NQN, 'local'), $NQN, 'local values count');
+ is(nv('_nvmet_property_value', $NQN, 'received'), $NQN, 'received values count');
+ is(nv('_nvmet_property_value', '-', '-'), '-', 'unset values');
+ is(
+ nv('_nvmet_property_value', $NQN, 'inherited from tank/a'),
+ '-',
+ 'inherited values do not',
+ );
+ eval { nv('_nvmet_property_value', $NQN, 'default') };
+ like($@, qr/invalid ZFS property source/, 'rejects other sources');
+ eval { nv('_nvmet_property_value', $NQN, '-') };
+ like($@, qr/invalid ZFS property source/, 'rejects a value without a source');
+ eval { nv('_nvmet_property_value', $NQN, 'inherited from tank;x') };
+ like($@, qr/invalid ZFS pool name/, 'rejects an inherited source outside pool names');
+};
+
+subtest 'configfs parser' => sub {
+ my $with_digests = nv('_nvmet_parse_configfs', $FIXTURE_CFS . $FIXTURE_DIGESTS);
+ is($with_digests->{hosts}->{$_}->{key_sha256}, $KEY_SHA, 'key digest of a fixture host')
+ for @FIXTURE_HOSTS;
+ my $binary = nv(
+ '_nvmet_parse_configfs',
+ $FIXTURE_CFS . join('', map { "$KEY_SHA *$ROOT/hosts/$_/dhchap_key\n" } @FIXTURE_HOSTS),
+ );
+ is($binary->{hosts}->{ $FIXTURE_HOSTS[0] }->{key_sha256}, $KEY_SHA, 'binary-mode digests');
+
+ my $without = sub($re) { return $FIXTURE_CFS =~ s/^$re\n//mr };
+ for my $case (
+ [
+ 'missing root',
+ $without->(qr{D \Q$ROOT\E}),
+ qr/^NVMe target configfs is unavailable$/,
+ ],
+ [
+ 'a namespace without enable',
+ $without->(qr{.*namespaces/5/enable:1}),
+ qr/incomplete NVMe namespace '5' of subsystem '\Q$FIXTURE_NQN\E'/,
+ ],
+ [
+ 'a port without address',
+ $without->(qr{.*ports/2/addr_traddr.*}),
+ qr/incomplete NVMe port '2'/,
+ ],
+ [
+ 'a duplicate attribute',
+ "$FIXTURE_CFS$ROOT/subsystems/$FIXTURE_NQN/attr_serial:X\n",
+ qr/duplicate NVMe target configfs attribute/,
+ ],
+ [
+ 'an attribute without its directory',
+ "$FIXTURE_CFS$ROOT/subsystems/nqn.x:y/attr_model:Z\n",
+ qr/incomplete NVMe subsystem 'nqn.x:y'/,
+ ],
+ [
+ 'a link to a missing port',
+ "${FIXTURE_CFS}L $ROOT/ports/9/subsystems/$FIXTURE_NQN\n",
+ qr/incomplete NVMe port '9'/,
+ ],
+ [
+ 'a digest for a missing host',
+ "$FIXTURE_CFS$KEY_SHA $ROOT/hosts/nqn.x:gone/dhchap_key\n",
+ qr/key digest for unknown NVMe host 'nqn.x:gone'/,
+ ],
+ [
+ 'a malformed digest',
+ $FIXTURE_CFS . substr($KEY_SHA, 1) . " $ROOT/hosts/$FIXTURE_HOSTS[0]/dhchap_key\n",
+ qr/unexpected NVMe target configfs line/,
+ ],
+ [
+ 'a duplicate digest',
+ "$FIXTURE_CFS$FIXTURE_DIGESTS$FIXTURE_DIGESTS",
+ qr/duplicate DH-HMAC-CHAP key digest/,
+ ],
+ ) {
+ my ($name, $text, $error) = $case->@*;
+ eval { nv('_nvmet_parse_configfs', $text) };
+ like($@, $error, "rejects $name");
+ }
+ eval { nv('_nvmet_parse_configfs', "$FIXTURE_CFS$KEY and more\n") };
+ is($@, "unexpected NVMe target configfs line\n", 'a garbage line is rejected without echo');
+ eval { nv('_nvmet_parse_configfs', "${FIXTURE_CFS}D $ROOT/subsystems/bad name\n") };
+ is($@, "incomplete NVMe subsystem\n", 'malformed names are not echoed');
+
+ my $tolerated = nv(
+ '_nvmet_parse_configfs',
+ join(
+ '',
+ $FIXTURE_CFS,
+ "D $ROOT/ports/1/referrals/x\n",
+ "L $ROOT/subsystems/$FIXTURE_NQN/passthru/x\n",
+ "D $ROOT/subsystems/$FIXTURE_NQN/namespaces/5/ana\n",
+ "$ROOT/ports/1/param_inline_data_size:16384\n",
+ "$ROOT/subsystems/$FIXTURE_NQN/attr_version:1.3\n",
+ ),
+ );
+ is_deeply(
+ $tolerated,
+ nv('_nvmet_parse_configfs', $FIXTURE_CFS),
+ 'other objects are ignored',
+ );
+ my $unset = $FIXTURE_CFS =~ s{(namespaces/6/device_path:).*}{$1(null)}r;
+ $unset =~ s{(namespaces/5/device_path:).*}{$1};
+ my $null = nv('_nvmet_parse_configfs', $unset);
+ is(
+ $null->{subsystems}->{$FIXTURE_NQN}->{namespaces}->{6}->{device_path},
+ '(null)',
+ 'a (null) device',
+ );
+ is(
+ $null->{subsystems}->{$FIXTURE_NQN}->{namespaces}->{5}->{device_path},
+ '',
+ 'an empty device',
+ );
+};
+
+subtest 'state marker and mount table' => sub {
+ my ($zfs, $cfs) = nv('_nvmet_split_state', "a\tb\n$MARKER\nD x\n");
+ is_deeply([$zfs, $cfs], ["a\tb\n", "D x\n"], 'splits at the marker');
+ for my $text ("a\n", "a\n$MARKER\nb\n$MARKER\n", "a\n $MARKER\n", "a\n${MARKER}x\n") {
+ eval { nv('_nvmet_split_state', $text) };
+ like(
+ $@,
+ qr/malformed NVMe target state/,
+ 'rejects a missing, repeated or altered marker',
+ );
+ }
+ my $mounts = "sysfs /sys sysfs rw 0 0\nnone /sys/kernel/config configfs rw 0 0\n";
+ ok(nv('_nvmet_parse_mounts', $mounts), 'configfs is mounted');
+ ok(!nv('_nvmet_parse_mounts', "sysfs /sys sysfs rw 0 0\n"), 'configfs is not mounted');
+ ok(!nv('_nvmet_parse_mounts', "none /mnt configfs rw 0 0\n"), 'configfs elsewhere');
+ ok(!nv('_nvmet_parse_mounts', "x /sys/kernel/config tmpfs rw 0 0\n"),
+ 'another file system');
+ ok(!nv('_nvmet_parse_mounts', ''), 'empty mount table');
+};
+
+# ---------------------------------------------------------------------------
+# Planners
+# ---------------------------------------------------------------------------
+
+my $S = "$ROOT/subsystems/$NQN";
+sub write_step($path, $value) { return { write => $path, value => $value } }
+
+# The step that makes the key attributes of hosts readable by root only.
+sub chmod_step(@hosts) {
+ return ['chmod', '0600', map { ("$_/dhchap_key", "$_/dhchap_ctrl_key") } @hosts];
+}
+
+sub cfs_model(%o) {
+ my $model = { subsystems => {}, ports => {}, hosts => {} };
+ if (!$o{no_subsystem}) {
+ $model->{subsystems}->{$NQN} = {
+ attr_model => $MODEL,
+ attr_serial => nv('_nvmet_serial', $NQN),
+ attr_allow_any_host => '0',
+ acl => {},
+ namespaces => {},
+ ($o{subsystem} // {})->%*,
+ };
+ }
+ return $model;
+}
+
+sub ns_model($uuid, $dev, $enable = '1') {
+ return { enable => $enable, device_path => $dev, device_uuid => $uuid, buffered_io => '0' };
+}
+
+sub build_steps($nsid, $uuid, $dev) {
+ my $ns = "$S/namespaces/$nsid";
+ return [
+ ['test', '-b', $dev],
+ ['mkdir', $ns],
+ write_step("$ns/device_path", $dev),
+ write_step("$ns/device_uuid", $uuid),
+ write_step("$ns/buffered_io", 0),
+ write_step("$ns/enable", 1),
+ ];
+}
+
+subtest 'owned identity' => sub {
+ my $inv = inventory(
+ @POOL,
+ @ONE,
+ @TWO,
+ zfs_rows('tank/vm-102-disk-0', 'filesystem'),
+ zfs_rows('tank/vm-103-disk-0', 'volume'),
+ zfs_rows('tank/vm-104-disk-0', 'volume', $FOREIGN_NQN, 1, $U{1}),
+ );
+ is_deeply(
+ [nv('_nvmet_owned_identity', $inv, $NQN, 'tank/vm-100-disk-0')],
+ [1, $U{1}],
+ 'identity of an owned volume; the same identity under another NQN is allowed',
+ );
+ for my $case (
+ ['tank/vm-999-disk-0', qr/does not exist/],
+ ['tank/vm-102-disk-0', qr/is not a ZFS volume/],
+ ['tank/vm-103-disk-0', qr/is not owned by NVMe subsystem/],
+ ['tank/vm-104-disk-0', qr/is not owned by NVMe subsystem/],
+ ) {
+ eval { nv('_nvmet_owned_identity', $inv, $NQN, $case->[0]) };
+ like($@, $case->[1], "refuses $case->[0]");
+ }
+ for my $nsid (0, 0xffffffff, 'x', '01') {
+ my $bad =
+ inventory(@POOL, zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, $nsid, $U{1}));
+ eval { nv('_nvmet_owned_identity', $bad, $NQN, 'tank/vm-100-disk-0') };
+ like($@, qr/invalid NSID/, "refuses NSID '$nsid'");
+ }
+ my $bad = inventory(@POOL, zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, 'nope'));
+ eval { nv('_nvmet_owned_identity', $bad, $NQN, 'tank/vm-100-disk-0') };
+ like($@, qr/invalid namespace UUID/, 'refuses a malformed UUID');
+ for my $other ([1, $U{2}], [2, $U{1}]) {
+ my $dup = inventory(
+ @POOL, @ONE, zfs_rows('tank/vm-101-disk-0', 'volume', $NQN, $other->@*),
+ );
+ eval { nv('_nvmet_owned_identity', $dup, $NQN, 'tank/vm-100-disk-0') };
+ like($@, qr/duplicate NVMe identity on 'tank\/vm-100-disk-0'/, 'refuses a duplicate');
+ }
+ is(nv('_nvmet_serial', $NQN), 'PVEZFS' . substr(sha256_hex($NQN), 0, 14), 'serial formula');
+ is(
+ nv('_nvmet_parse_configfs', $FIXTURE_CFS)->{subsystems}->{$FIXTURE_NQN}->{attr_serial},
+ nv('_nvmet_serial', $FIXTURE_NQN),
+ 'the fixture subsystem carries the serial of its NQN',
+ );
+};
+
+subtest 'namespace ID allocation' => sub {
+ my $rows = sub(@ids) {
+ my $uuid = sub($id) { sprintf('%08d-0000-4000-8000-000000000000', $id) };
+ return inventory(
+ @POOL,
+ map { zfs_rows("tank/vm-$_-disk-0", 'volume', $NQN, $_, $uuid->($_)) } @ids,
+ );
+ };
+ my $cfs = cfs_model();
+ is(nv('_nvmet_allocate_nsid', inventory(@POOL), $cfs, $NQN), 1, 'first NSID');
+ is(nv('_nvmet_allocate_nsid', $rows->(1, 3), $cfs, $NQN), 4, 'a gap is not reused');
+ my $dirs =
+ cfs_model(subsystem => { namespaces => { 7 => ns_model($U{7}, '(null)', '0') } });
+ is(nv('_nvmet_allocate_nsid', $rows->(1), $dirs, $NQN), 8,
+ 'configfs-only namespaces count');
+ my $foreign =
+ inventory(@POOL, zfs_rows('tank/vm-9-disk-0', 'volume', $FOREIGN_NQN, 9, $U{9}));
+ my $foreign_cfs = cfs_model();
+ $foreign_cfs->{subsystems}->{$FOREIGN_NQN} = { namespaces => { 12 => {} } };
+ is(nv('_nvmet_allocate_nsid', $foreign, $foreign_cfs, $NQN), 1, 'others do not count');
+ my $invalid = inventory(@POOL, zfs_rows('tank/vm-1-disk-0', 'volume', $NQN, 'x', $U{1}));
+ is(nv('_nvmet_allocate_nsid', $invalid, $cfs, $NQN), 1, 'invalid NSIDs do not count');
+ my $top = inventory(
+ @POOL,
+ zfs_rows('tank/vm-1-disk-0', 'volume', $NQN, 1, $U{1}),
+ zfs_rows('tank/vm-2-disk-0', 'volume', $NQN, 0xfffffffe, $U{2}),
+ );
+ is(
+ nv('_nvmet_allocate_nsid', $top, $cfs, $NQN),
+ 2,
+ 'after the last NSID the lowest free one',
+ );
+ my $reserved = $rows->(1);
+ $reserved->{last_nsid} = 9;
+ is(nv('_nvmet_allocate_nsid', $reserved, $cfs, $NQN), 10, 'a reserved NSID is not reused');
+ $reserved->{last_nsid} = 0xfffffffe;
+ is(
+ nv('_nvmet_allocate_nsid', $reserved, $cfs, $NQN),
+ 2,
+ 'until the last NSID was handed out',
+ );
+};
+
+subtest 'export planner' => sub {
+ my $dev = '/dev/zvol/tank/vm-100-disk-0';
+ my $case = sub($namespaces) {
+ return cfs_model(subsystem => { namespaces => $namespaces });
+ };
+ my $build = build_steps(1, $U{1}, $dev);
+ my @plans = (
+ ['absent', {}, [$build], 'absent'],
+ ['present', { 1 => ns_model($U{1}, $dev) }, [], 'present'],
+ [
+ 'disabled',
+ { 1 => ns_model($U{1}, $dev, '0') },
+ [[['test', '-b', $dev], write_step("$S/namespaces/1/enable", 1)]],
+ 'disabled',
+ ],
+ [
+ 'disabled and incomplete',
+ { 1 => ns_model($U{9}, '(null)', '0') },
+ [[['rmdir', "$S/namespaces/1"], $build->@*]],
+ 'reclaim',
+ ],
+ [
+ 'enabled on the template name of the zvol',
+ { 1 => ns_model($U{1}, '/dev/zvol/tank/base-100-disk-0') },
+ [[
+ write_step("$S/namespaces/1/enable", 0),
+ ['rmdir', "$S/namespaces/1"],
+ $build->@*,
+ ]],
+ 'stale',
+ ],
+ );
+ for my $plan (@plans) {
+ my ($name, $namespaces, $units, $state) = $plan->@*;
+ is_deeply(
+ [nv('_nvmet_plan_export', $case->($namespaces), $NQN, 1, $U{1}, $dev)],
+ [$units, $state],
+ "plan for a namespace that is $name",
+ );
+ }
+ my $incomplete = $case->({ 1 => ns_model($U{9}, '(null)', '0') });
+ is(
+ nv('_nvmet_export_state', $incomplete, $NQN, 1, $U{1}, $dev),
+ 'incomplete',
+ 'a disabled namespace with another identity is incomplete',
+ );
+ is(
+ nv('_nvmet_export_state', cfs_model(no_subsystem => 1), $NQN, 1, $U{1}, $dev),
+ 'nosubsys',
+ 'no subsystem',
+ );
+ for my $refusal (
+ [
+ 'enabled with another UUID',
+ { 1 => ns_model($U{9}, $dev) },
+ qr/NVMe namespace ID '1' has a different identity/,
+ ],
+ [
+ 'enabled with another device',
+ { 1 => ns_model($U{1}, '/dev/zvol/tank/other') },
+ qr/different identity/,
+ ],
+ [
+ 'enabled with another UUID on the template name',
+ { 1 => ns_model($U{9}, '/dev/zvol/tank/base-100-disk-0') },
+ qr/different identity/,
+ ],
+ [
+ 'UUID in use at another NSID',
+ { 2 => ns_model($U{1}, '/dev/zvol/tank/other') },
+ qr/namespace UUID '\Q@{[ $U{1} ]}\E' is already in use/,
+ ],
+ ) {
+ my ($name, $namespaces, $error) = $refusal->@*;
+ eval { nv('_nvmet_plan_export', $case->($namespaces), $NQN, 1, $U{1}, $dev) };
+ like($@, $error, "refuses a namespace $name");
+ }
+ eval { nv('_nvmet_plan_export', cfs_model(no_subsystem => 1), $NQN, 1, $U{1}, $dev) };
+ like($@, qr/NVMe subsystem does not exist/, 'refuses without subsystem');
+};
+
+subtest 'unexport planner' => sub {
+ my $dev = '/dev/zvol/tank/vm-100-disk-0';
+ is_deeply(
+ [nv('_nvmet_plan_unexport', cfs_model(), $NQN, $U{1})],
+ [[], undef],
+ 'nothing to remove',
+ );
+ is_deeply(
+ [nv('_nvmet_plan_unexport', cfs_model(no_subsystem => 1), $NQN, $U{1})],
+ [[], undef],
+ 'no subsystem',
+ );
+ my ($units, $pre) = nv(
+ '_nvmet_plan_unexport',
+ cfs_model(subsystem => { namespaces => { 4 => ns_model($U{1}, $dev) } }),
+ $NQN,
+ $U{1},
+ );
+ is_deeply(
+ $units,
+ [[write_step("$S/namespaces/4/enable", 0), ['rmdir', "$S/namespaces/4"]]],
+ 'an enabled namespace is disabled, then removed',
+ );
+ ok($pre->{nsid} == 4 && $pre->{enabled}, 'and was enabled');
+ ($units, $pre) = nv(
+ '_nvmet_plan_unexport',
+ cfs_model(subsystem => { namespaces => { 4 => ns_model($U{1}, $dev, '0') } }),
+ $NQN,
+ $U{1},
+ );
+ is_deeply($units, [[['rmdir', "$S/namespaces/4"]]], 'a disabled namespace is only removed');
+ ok($pre->{nsid} == 4 && !$pre->{enabled}, 'and was disabled');
+ eval {
+ nv(
+ '_nvmet_plan_unexport',
+ cfs_model(
+ subsystem => {
+ namespaces =>
+ { 4 => ns_model($U{1}, $dev), 5 => ns_model($U{1}, $dev, '0') },
+ },
+ ),
+ $NQN,
+ $U{1},
+ );
+ };
+ like($@, qr/duplicate namespace UUID/, 'refuses a duplicate UUID');
+};
+
+subtest 'port lookup' => sub {
+ my $port = sub($family, $address, $service, %links) {
+ return {
+ addr_trtype => 'tcp',
+ addr_adrfam => $family,
+ addr_traddr => $address,
+ addr_trsvcid => $service,
+ links => {%links},
+ };
+ };
+ my $cfs = {
+ ports => {
+ 3 => $port->('ipv4', '192.0.2.21', '4420'),
+ 5 => $port->('ipv4', '192.0.2.21', '4420', $NQN => 1),
+ 6 => $port->('ipv4', '192.0.2.22', '4420'),
+ 7 => $port->('ipv6', '2001:db8:0:0::11', '4420'),
+ 8 => { $port->('ipv4', '192.0.2.23', '4420')->%*, addr_trtype => '' },
+ 9 => { $port->('ipv4', '', '4420')->%* },
+ },
+ };
+ my $find =
+ sub($nqn, @portal) { return nv('_nvmet_find_port', $cfs, $nqn, portal(@portal)) };
+ is($find->($NQN, 'ipv4', '192.0.2.21', 4420), 5, 'the linked port wins');
+ is($find->($FOREIGN_NQN, 'ipv4', '192.0.2.21', 4420), 3, 'else the lowest');
+ is($find->($NQN, 'ipv4', '192.0.2.22', 4420), 6, 'exact match');
+ ok(!defined($find->($NQN, 'ipv6', '192.0.2.22', 4420)), 'wrong family');
+ ok(!defined($find->($NQN, 'ipv4', '192.0.2.22', 4421)), 'wrong service');
+ ok(!defined($find->($NQN, 'ipv4', '192.0.2.23', 4420)), 'incomplete port');
+ is($find->($NQN, 'ipv6', '2001:db8::11', 4420), 7, 'IPv6 spellings match');
+};
+
+subtest 'activation planner' => sub {
+ my $conf = { nqn => $NQN, portals => $PORTALS, hostnqns => [@HOSTS], keysha => $KEY_SHA };
+ my $inv = inventory(@POOL, @ONE);
+ my $empty = { subsystems => {}, ports => {}, hosts => {} };
+ my $dev = '/dev/zvol/tank/vm-100-disk-0';
+ my $serial = nv('_nvmet_serial', $NQN);
+
+ # A creation interrupted after the model write is completed while the
+ # subsystem is still unused ('an interrupted subsystem creation' below).
+ my $unfinished = sub(%attr) {
+ return {
+ $empty->%*,
+ subsystems => {
+ $NQN => {
+ attr_serial => '0f1e2d3c4b5a6978',
+ attr_allow_any_host => '0',
+ acl => {},
+ namespaces => {},
+ %attr,
+ },
+ },
+ };
+ };
+ is_deeply(
+ nv(
+ '_nvmet_plan_activation',
+ $inv,
+ $unfinished->(attr_model => $MODEL, attr_allow_any_host => '1'),
+ $conf,
+ )->{prepublish}->[0],
+ [write_step("$S/attr_serial", $serial), write_step("$S/attr_allow_any_host", 0)],
+ 'an unused subsystem with our model is completed and denies unknown hosts',
+ );
+ for my $case (
+ [
+ 'a namespace',
+ sub($c) { $c->{subsystems}->{$NQN}->{namespaces}->{1} = ns_model($U{1}, $dev) },
+ ],
+ ['an ACL', sub($c) { $c->{subsystems}->{$NQN}->{acl}->{ $HOSTS[0] } = 1 }],
+ [
+ 'a port link',
+ sub($c) {
+ $c->{ports}->{7} = {
+ addr_trtype => 'tcp',
+ addr_adrfam => 'ipv4',
+ addr_traddr => '192.0.2.99',
+ addr_trsvcid => '4420',
+ links => { $NQN => 1 },
+ };
+ },
+ ],
+ ) {
+ my ($name, $change) = $case->@*;
+ my $used = $unfinished->(attr_model => $MODEL);
+ $change->($used);
+ eval { nv('_nvmet_plan_activation', $inv, $used, $conf) };
+ like(
+ $@,
+ qr/refusing to take over existing NVMe subsystem/,
+ "a subsystem with our model and another serial and $name is refused",
+ );
+ }
+ # the identities of every owned volume are validated before any unit
+ for my $case (
+ ['a duplicate NSID', [$NQN, 1, $U{2}], qr/duplicate NSID '1'/],
+ ['a duplicate UUID', [$NQN, 2, $U{1}], qr/duplicate namespace UUID/],
+ ['an invalid UUID', [$NQN, 2, 'bad'], qr/invalid namespace UUID/],
+ ) {
+ my ($name, $identity, $error) = $case->@*;
+ my $bad =
+ inventory(@POOL, @ONE, zfs_rows('tank/vm-101-disk-0', 'volume', $identity->@*));
+ eval { nv('_nvmet_desired_namespaces', $bad, $NQN) };
+ like($@, $error, "$name is refused");
+ }
+
+ my $state = sub(%o) {
+ my $cfs = cfs_model(
+ subsystem => {
+ acl => { map { $_ => 1 } @HOSTS },
+ namespaces => { 1 => ns_model($U{1}, $dev) },
+ ($o{subsystem} // {})->%*,
+ },
+ );
+ $cfs->{ports} = {
+ map {
+ $_ => {
+ addr_trtype => 'tcp',
+ addr_adrfam => 'ipv4',
+ addr_traddr => "192.0.2.2$_",
+ addr_trsvcid => '4420',
+ links => { $NQN => 1 },
+ }
+ } 1,
+ 2,
+ };
+ $cfs->{hosts} = { map { $_ => { key_sha256 => $KEY_SHA } } @HOSTS };
+ $o{change}->($cfs) if $o{change};
+ return $cfs;
+ };
+ is_deeply(
+ nv('_nvmet_plan_activation', $inv, $state->(), $conf),
+ { prepublish => [], port_ids => [1, 2] },
+ 'a converged target plans nothing',
+ );
+ is_deeply(
+ nv('_nvmet_plan_publish', $state->(), $NQN, [1, 2], [@HOSTS]),
+ [],
+ 'nor publishes',
+ );
+ is_deeply(
+ nv(
+ '_nvmet_plan_activation',
+ $inv,
+ $state->(subsystem => { attr_allow_any_host => '1' }),
+ $conf,
+ )->{prepublish},
+ [[write_step("$S/attr_allow_any_host", 0)]],
+ 'allow_any_host is reset',
+ );
+
+ # the key matrix for the second host
+ my $h = $HOSTS[1];
+ my $H = "$ROOT/hosts/$h";
+ my $other = sha256_hex("$KEY_B\n");
+ my $foreign_acl = sub($cfs) {
+ $cfs->{subsystems}->{$FOREIGN_NQN} = { acl => { $h => 1 }, namespaces => {} };
+ };
+ for my $case (
+ [
+ 'absent',
+ sub($c) { delete $c->{hosts}->{$h} },
+ [[['mkdir', $H]], [chmod_step($H), { key => ["$H/dhchap_key"] }]],
+ ],
+ ['matching', sub($c) { }, []],
+ [
+ 'different and unlinked',
+ sub($c) {
+ $c->{hosts}->{$h}->{key_sha256} = $other;
+ delete $c->{subsystems}->{$NQN}->{acl}->{$h};
+ },
+ [
+ [chmod_step($H), { key => ["$H/dhchap_key"] }],
+ [['ln', '-s', $H, "$S/allowed_hosts/$h"]],
+ ],
+ ],
+ [
+ 'empty and unlinked',
+ sub($c) {
+ $c->{hosts}->{$h}->{key_sha256} = $EMPTY_KEY_SHA;
+ delete $c->{subsystems}->{$NQN}->{acl}->{$h};
+ },
+ [
+ [chmod_step($H), { key => ["$H/dhchap_key"] }],
+ [['ln', '-s', $H, "$S/allowed_hosts/$h"]],
+ ],
+ ],
+ ) {
+ my ($name, $change, $units) = $case->@*;
+ my $plan = nv('_nvmet_plan_activation', $inv, $state->(change => $change), $conf);
+ is_deeply($plan->{prepublish}, $units, "key of a host that is $name");
+ }
+ for my $case (
+ [
+ 'different and linked by us',
+ sub($c) { $c->{hosts}->{$h}->{key_sha256} = $other },
+ qr/refusing to replace an in-use DH-HMAC-CHAP key/,
+ ],
+ [
+ 'different and linked elsewhere',
+ sub($c) {
+ $c->{hosts}->{$h}->{key_sha256} = $other;
+ delete $c->{subsystems}->{$NQN}->{acl}->{$h};
+ $foreign_acl->($c);
+ },
+ qr/in-use DH-HMAC-CHAP key/,
+ ],
+ [
+ 'empty and linked',
+ sub($c) { $c->{hosts}->{$h}->{key_sha256} = $EMPTY_KEY_SHA },
+ qr/in-use DH-HMAC-CHAP key/,
+ ],
+ [
+ 'without a digest',
+ sub($c) { $c->{hosts}->{$h}->{key_sha256} = undef },
+ qr/does not expose a DH-HMAC-CHAP key for host/,
+ ],
+ ) {
+ my ($name, $change, $error) = $case->@*;
+ eval { nv('_nvmet_plan_activation', $inv, $state->(change => $change), $conf) };
+ like($@, $error, "refuses the key of a host that is $name");
+ }
+
+ my $undesired = $state->(
+ change => sub($c) {
+ $c->{subsystems}->{$NQN}->{namespaces}->{7} =
+ ns_model($U{7}, '/dev/zvol/tank/gone');
+ $c->{subsystems}->{$NQN}->{namespaces}->{8} = ns_model($U{8}, '(null)', '0');
+ },
+ );
+ is_deeply(
+ nv('_nvmet_plan_activation', $inv, $undesired, $conf)->{prepublish},
+ [
+ [write_step("$S/namespaces/7/enable", 0), ['rmdir', "$S/namespaces/7"]],
+ [['rmdir', "$S/namespaces/8"]],
+ ],
+ 'undesired namespaces are disabled and removed',
+ );
+};
+
+subtest 'publish planner' => sub {
+ my $cfs = cfs_model(subsystem => { acl => { map { $_ => 1 } @HOSTS } });
+ $cfs->{ports} = {
+ 1 => { links => { $NQN => 1 } },
+ 2 => { links => {} },
+ 5 => { links => { $NQN => 1, $FOREIGN_NQN => 1 } },
+ 6 => { links => { $FOREIGN_NQN => 1 } },
+ };
+ my @guards = (
+ ['grep', '-qx', '0', "$S/attr_allow_any_host"],
+ map { ['test', '-L', "$S/allowed_hosts/$_"] } @HOSTS,
+ );
+ is_deeply(
+ nv('_nvmet_plan_publish', $cfs, $NQN, [1, 2], [@HOSTS]),
+ [
+ {
+ port => 2,
+ action => 'link',
+ steps => [@guards, ['ln', '-s', $S, "$ROOT/ports/2/subsystems/$NQN"]],
+ },
+ {
+ port => 5,
+ action => 'unlink',
+ steps => [['rm', "$ROOT/ports/5/subsystems/$NQN"]],
+ },
+ ],
+ 'links a missing port behind the guards and unlinks a stray port',
+ );
+ $cfs->{ports}->{2}->{links}->{$NQN} = 1;
+ delete $cfs->{ports}->{5};
+ is_deeply(nv('_nvmet_plan_publish', $cfs, $NQN, [1, 2], [@HOSTS]), [], 'converged');
+};
+
+subtest 'target removal planners' => sub {
+ my $conf_hosts =
+ [@HOSTS, 'nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-000000000003'];
+ my $cfs = cfs_model(subsystem => { acl => { map { $_ => 1 } @HOSTS } });
+ $cfs->{ports} = {
+ 2 => { links => { $NQN => 1 } },
+ 1 => { links => { $NQN => 1 } },
+ 3 => { links => {} },
+ };
+ is_deeply(
+ [nv('_nvmet_plan_delete_target', inventory(@POOL), $cfs, $NQN, $conf_hosts)],
+ [
+ [[
+ [
+ 'rm',
+ "$ROOT/ports/1/subsystems/$NQN",
+ "$ROOT/ports/2/subsystems/$NQN",
+ map { "$S/allowed_hosts/$_" } @HOSTS,
+ ],
+ ['rmdir', $S],
+ ]],
+ [sort $conf_hosts->@*],
+ ],
+ 'teardown removes port links first, then ACLs, then the subsystem',
+ );
+ # The candidates are the ACL and the configured hosts: a retry after a
+ # teardown that removed the ACLs but not the subsystem still finds them.
+ my $stale_host = 'nqn.2026-01.com.example:stale';
+ my $stale = cfs_model(subsystem => { acl => { $stale_host => 1 } });
+ is_deeply(
+ (nv('_nvmet_plan_delete_target', inventory(@POOL), $stale, $NQN, [@HOSTS]))[1],
+ [sort $stale_host, @HOSTS],
+ 'a host that is only in the ACL is a candidate too',
+ );
+ is_deeply(
+ [nv('_nvmet_plan_delete_target', inventory(@POOL), cfs_model(), $NQN, [@HOSTS])],
+ [[[['rmdir', $S]]], [sort @HOSTS]],
+ 'without ACLs the configured hosts are candidates',
+ );
+
+ my $orphans = {
+ subsystems => { $FOREIGN_NQN => { acl => { $HOSTS[0] => 1 } } },
+ hosts => { map { $_ => {} } @HOSTS },
+ };
+ is_deeply(
+ nv('_nvmet_plan_orphan_hosts', $orphans, [@HOSTS, @HOSTS, 'nqn.x:gone']),
+ [[['rmdir', "$ROOT/hosts/$HOSTS[1]"]]],
+ 'orphans exclude linked and missing hosts',
+ );
+ is_deeply(nv('_nvmet_plan_orphan_hosts', $orphans, [$HOSTS[0]]), [], 'no orphans');
+ $orphans->{hosts}->{'..'} = {};
+ is_deeply(
+ nv('_nvmet_plan_orphan_hosts', $orphans, ['..']),
+ [],
+ 'a host name read from the target is only used when it is an NQN',
+ );
+ my $odd = cfs_model(subsystem => { acl => { $HOSTS[0] => 1, '..' => 1 } });
+ eval { nv('_nvmet_plan_delete_target', inventory(@POOL), $odd, $NQN, [@HOSTS]) };
+ like($@, qr/it allows a malformed host name/, 'an ACL with a malformed name is refused');
+};
+
+subtest 'template name and chunking' => sub {
+ is(nv('_nvmet_template_name', 'tank/vm-100-disk-0'), 'tank/base-100-disk-0', 'vm to base');
+ is(nv('_nvmet_template_name', 'tank/sub/vm-1-disk-2'), 'tank/sub/base-1-disk-2', 'nested');
+ for my $name ('tank/base-100-disk-0', 'tank/subvol-100-disk-0', 'tank/xvm-1-disk-0') {
+ eval { nv('_nvmet_template_name', $name) };
+ like($@, qr/only VM zvols can become templates/, "refuses $name");
+ }
+
+ my @units = map { build_steps($_, $U{1}, "/dev/zvol/tank/vm-$_-disk-0") } 1 .. 400;
+ my $chunks = nv('_nvmet_chunk', \@units);
+ ok($chunks->@* > 1, 'large plans are split');
+ ok(
+ !grep({ length(nv('_nvmet_render', $_)) > 65536 } $chunks->@*),
+ 'no call exceeds 64 KiB',
+ );
+ ok(!grep({ $_->[0]->[0] ne 'test' || $_->@* % 6 } $chunks->@*), 'chunks hold whole units');
+ is_deeply([map { $_->@* } $chunks->@*], [map { $_->@* } @units], 'order is preserved');
+ is_deeply(nv('_nvmet_chunk', []), [], 'no units, no calls');
+ my $small = nv(
+ '_nvmet_chunk',
+ [@units[0 .. 3]],
+ length(nv('_nvmet_render', [map { $_->@* } @units[0 .. 1]])),
+ );
+ is(scalar($small->@*), 2, 'the limit is configurable');
+ eval { nv('_nvmet_chunk', [$units[0]], 10) };
+ like($@, qr/NVMe target command too long/, 'a unit over the limit is refused');
+ my $key_unit = [{ key => ["$ROOT/hosts/$HOSTS[0]/dhchap_key"] }];
+ my $mixed = nv('_nvmet_chunk', [@units[0 .. 199], $key_unit, @units[200 .. 399]]);
+ is(
+ scalar(
+ grep {
+ grep { ref($_) eq 'HASH' && $_->{key} } $_->@*
+ } $mixed->@*
+ ),
+ 1,
+ 'the key step is in exactly one call',
+ );
+};
+
+# ---------------------------------------------------------------------------
+# Flows against the fake target
+# ---------------------------------------------------------------------------
+
+sub secret_file($storeid) {
+ return "/etc/pve/priv/storage/$storeid.nvme-dhchap";
+}
+
+# The target part of a storage activation, with the key stored for the storage.
+sub activate($scfg = scfg(), $key = $KEY, $hostnqns = [@HOSTS], $portals = $PORTALS) {
+ local $FILES{ secret_file('st') } = $key;
+ return nv('_nvmet_activate_target', 'st', $scfg, $portals, $hostnqns, $key);
+}
+
+# The public operations of the flows, on lifecycle_fake().
+my %ACT = (
+ activate => sub { activate() },
+ alloc => sub { $PLUGIN->alloc_image('st', scfg(), 200, 'raw', undef, 1024) },
+ clone => sub { $PLUGIN->clone_image(scfg(), 'st', 'base-102-disk-0', 201) },
+ free => sub { $PLUGIN->free_image('st', scfg(), 'vm-101-disk-0') },
+ rollback =>
+ sub { $PLUGIN->volume_snapshot_rollback(scfg(), 'st', 'vm-100-disk-0', 'snap1') },
+ template => sub { $PLUGIN->create_base('st', scfg(), 'vm-101-disk-0') },
+ resize => sub { $PLUGIN->volume_resize(scfg(), 'st', 'vm-100-disk-0', 2 * 1024**3) },
+ remove => sub { nv('_nvmet_delete_target', scfg()) },
+);
+
+# Runs an action against a new lifecycle_fake(%opts).
+sub run_on($action, %opts) {
+ my $fake = lifecycle_fake(%opts);
+ return ($fake, flow($fake, $ACT{$action}));
+}
+
+# An action (a name of %ACT or a sub) that is refused without changing the target.
+sub refused($fake, $action, $error, $name) {
+ my $before = dclone($fake->{m});
+ my $res = flow($fake, ref($action) ? $action : $ACT{$action});
+ like($res->{error}, $error, "refuses $name");
+ ok(!changes($res) && same($before, $fake->{m}), "without changes for $name");
+ return $res;
+}
+
+sub ns_of($fake, $nsid, $nqn = $NQN) {
+ return ($fake->{m}->{subsystems}->{$nqn} // {})->{ns}->{$nsid};
+}
+
+sub exported($fake, $nsid, $uuid, $dev) {
+ my $ns = ns_of($fake, $nsid) // return 0;
+ return $ns->{enable} eq '1' && $ns->{device_uuid} eq $uuid && $ns->{device_path} eq $dev;
+}
+
+sub step_is($step, @prefix) {
+ return
+ ref($step) eq 'ARRAY'
+ && $step->@* >= @prefix
+ && join("\0", $step->@[0 .. $#prefix]) eq join("\0", @prefix);
+}
+
+sub write_to($step, $suffix, $value = undef) {
+ return
+ ref($step) eq 'HASH'
+ && exists($step->{write})
+ && $step->{write} =~ m{\Q$suffix\E\z}
+ && (!defined($value) || $step->{value} eq $value);
+}
+
+subtest 'path() is one read-only ZFS query' => sub {
+ my $fake = lifecycle_fake();
+ my $res = flow($fake, sub { [$PLUGIN->path(scfg(), 'vm-100-disk-0', 'st')] });
+ is($res->{error}, '', 'lookup succeeds');
+ is_deeply(
+ $res->{result},
+ ["/dev/disk/by-id/nvme-uuid.$U{1}", 100, 'images'],
+ 'the UUID link',
+ );
+ is_deeply(ops($res), ['read ZFS inventory'], 'one call');
+ is(scalar($res->{locks}->@*), 0, 'without the lock');
+ $res = flow($fake, sub { [$PLUGIN->path(scfg(), 'vm-100-disk-0', 'st', 'snap1')] });
+ like($res->{error}, qr/direct access to snapshots not implemented/, 'snapshots');
+ is(scalar($res->{calls}->@*), 0, 'are refused locally');
+};
+
+subtest 'a failed read is retried' => sub {
+ local $SLEPT = 0;
+ my $fake = lifecycle_fake(read_fault => { after => -1, mode => 'before' });
+ my $res = flow($fake, sub { [$PLUGIN->path(scfg(), 'vm-100-disk-0', 'st')] });
+ is($res->{error}, '', 'a read that fails once');
+ is_deeply(ops($res), ['read ZFS inventory', 'read ZFS inventory'], 'is repeated');
+ is($SLEPT, 0.2, 'after 200 ms');
+
+ $fake = lifecycle_fake(fail => [['zfs', 'get'], 'I/O error']);
+ $res = flow($fake, sub { [$PLUGIN->path(scfg(), 'vm-100-disk-0', 'st')] });
+ is($res->{error}, "cannot read NVMe target state: I/O error\n",
+ 'a read that keeps failing');
+ is(scalar($res->{calls}->@*), 3, 'is tried three times');
+
+ $fake = lifecycle_fake(read_fault => { after => -1, mode => 'unreachable' });
+ $res = flow($fake, sub { [$PLUGIN->path(scfg(), 'vm-100-disk-0', 'st')] });
+ like($res->{error}, qr/NVMe target '192\.0\.2\.10' is unreachable/,
+ 'an unreachable target');
+ is(scalar($res->{calls}->@*), 1, 'is not tried again');
+};
+
+subtest 'activate_volume' => sub {
+ my %forced;
+ my $activations = 0;
+ my $activation = sub($class, $storeid, $scfg, $cache = undef) {
+ $activations++;
+ $forced{$storeid} = $cache->{'zfsnvme-force-reconcile'}->{$storeid};
+ die "activation attempted\n";
+ };
+ $plugin_mock->redefine(activate_storage => $activation);
+
+ my $fake = lifecycle_fake();
+ delete $fake->{m}->{subsystems}->{$NQN}->{ns}->{2};
+ my $res = flow($fake, sub { $PLUGIN->activate_volume('st', scfg(), 'vm-101-disk-0') });
+ like($res->{error}, qr/activation attempted/, 'a missing namespace forces an activation');
+ is($forced{st}, 1, 'the activation is forced past its fast path');
+ is_deeply(ops($res), ['read target state'], 'after one read');
+ ok(!$res->{calls}->[0]->{mutating} && !$res->{locks}->@*, 'without a change or the lock');
+
+ $fake = lifecycle_fake();
+ ns_of($fake, 2)->{device_uuid} = $U{9};
+ $activations = 0;
+ $res = flow($fake, sub { $PLUGIN->activate_volume('st', scfg(), 'vm-101-disk-0') });
+ like(
+ $res->{error},
+ qr/NVMe namespace ID '2' has a different identity/,
+ 'refuses an enabled namespace with another identity',
+ );
+ is($activations, 0, 'without activating');
+ $res = flow($fake, sub { $PLUGIN->activate_volume('st', scfg(), 'vm-101-disk-0', 'snap') });
+ like($res->{error}, qr/unable to activate snapshot/, 'snapshots are refused');
+
+ # The local device: its udev link and whether it is the namespace.
+ my $ok = 1;
+ $plugin_mock->redefine(_nvmet_local_namespace_ok => sub(@args) { return $ok });
+ my $link = "/dev/disk/by-id/nvme-uuid.$U{1}";
+ local %BLOCK = ($link => 1);
+ $fake = target_fake();
+ add_volume($fake, 'vm-100-disk-0', 1, $U{1});
+ $activations = 0;
+ $res = flow($fake, sub { $PLUGIN->activate_volume('st', scfg(), 'vm-100-disk-0') });
+ is($res->{error}, '', 'a converged volume activates');
+ is_deeply(ops($res), ['read target state'], 'with one read');
+ is(scalar($res->{locks}->@*) + $activations, 0, 'without lock or activation');
+
+ for my $case (
+ ['disabled', sub($f) { ns_of($f, 1)->{enable} = '0' }],
+ ['absent', sub($f) { delete $f->{m}->{subsystems}->{$NQN}->{ns}->{1} }],
+ ['without subsystem', sub($f) { delete $f->{m}->{subsystems}->{$NQN} }],
+ [
+ 'on the template name of the zvol',
+ sub($f) { ns_of($f, 1)->{device_path} = '/dev/zvol/tank/base-100-disk-0' },
+ ],
+ [
+ 'being built',
+ sub($f) {
+ $f->{m}->{subsystems}->{$NQN}->{ns}->{1} = ns_model($U{9}, '(null)', '0');
+ },
+ ],
+ ) {
+ my ($name, $change) = $case->@*;
+ $fake = target_fake();
+ add_volume($fake, 'vm-100-disk-0', 1, $U{1});
+ $change->($fake);
+ %forced = ();
+ $res = flow($fake, sub { $PLUGIN->activate_volume('st', scfg(), 'vm-100-disk-0') });
+ is($forced{st}, 1, "a namespace that is $name on the target is exported again");
+ }
+
+ $fake = target_fake();
+ add_volume($fake, 'vm-100-disk-0', 1, $U{1});
+ $ok = 0;
+ $activations = 0;
+ $plugin_mock->redefine(activate_storage => sub(@args) { $activations++; return 1 });
+ $res = flow($fake, sub { $PLUGIN->activate_volume('st', scfg(), 'vm-100-disk-0') });
+ like(
+ $res->{error},
+ qr/NVMe namespace for 'vm-100-disk-0' has an unexpected identity/,
+ 'a local device of another namespace is never used',
+ );
+ is($activations, 1, 'after one forced activation');
+ is_deeply(ops($res), ['read target state'], 'and one read');
+ $plugin_mock->unmock('_nvmet_local_namespace_ok');
+
+ # While the device is missing, live controllers are rescanned.
+ my $file_mock = Test::MockModule->new('PVE::File');
+ $file_mock->redefine(
+ dir_glob_foreach => sub($dir, $regex, $func) {
+ return if $dir ne '/sys/class/nvme';
+ $func->($_) for qw(nvme7 nvme8 nvme9);
+ },
+ );
+ local %FILES = (
+ '/sys/class/nvme/nvme7/subsysnqn' => $NQN,
+ '/sys/class/nvme/nvme7/state' => 'live',
+ '/sys/class/nvme/nvme8/subsysnqn' => $NQN,
+ '/sys/class/nvme/nvme8/state' => 'connecting',
+ '/sys/class/nvme/nvme9/subsysnqn' => $FOREIGN_NQN,
+ '/sys/class/nvme/nvme9/state' => 'live',
+ );
+ $plugin_mock->redefine(activate_storage => sub(@args) { return 1 });
+ $fake = lifecycle_fake();
+ delete $fake->{m}->{subsystems}->{$NQN}->{ns}->{2};
+ my $start = $NOW;
+ $res = flow($fake, sub { $PLUGIN->activate_volume('st', scfg(), 'vm-101-disk-0') });
+ like(
+ $res->{error},
+ qr/NVMe namespace for 'vm-101-disk-0' did not appear/,
+ 'a missing device',
+ );
+ is($NOW - $start, 10, 'after 10 seconds');
+ my $rescan = ['/sys/class/nvme/nvme7/rescan_controller', "1\n"];
+ is_deeply(
+ $res->{sysfs_writes},
+ [($rescan) x 5],
+ 'the live controller is rescanned every 2 s',
+ );
+ is_deeply($res->{warnings}, [], 'without a warning');
+
+ # The stock file_write on files that fail: a rescan that fails is a task
+ # warning with the errno text, and a controller that went away since it
+ # was listed needs none.
+ my $file_write = $sysfs_mock->original('file_write');
+ my $dir = tempdir(CLEANUP => 1);
+ my @perl_warnings;
+ local $SIG{__WARN__} = sub($warning) { push @perl_warnings, $warning };
+ for my $case (
+ ['/dev/full', 'No space left on device'],
+ [$dir, 'Is a directory'],
+ ["$dir/gone/rescan_controller", undef],
+ ) {
+ my ($path, $reason) = $case->@*;
+ $sysfs_mock->redefine(file_write => sub($file, @args) { $file_write->($path, @args) });
+ $res = flow($fake, sub { $PLUGIN->activate_volume('st', scfg(), 'vm-101-disk-0') });
+ is_deeply(
+ $res->{warnings},
+ defined($reason) ? [("cannot rescan NVMe controller 'nvme7': $reason") x 5] : [],
+ defined($reason)
+ ? "a failed rescan is a task warning with the errno text ($reason)"
+ : 'a controller that went away is not',
+ );
+ }
+ is_deeply(\@perl_warnings, [], 'and file_write warns about none');
+ $sysfs_mock->redefine(file_write => $sysfs_write);
+ $file_mock->unmock_all();
+ $plugin_mock->unmock('activate_storage');
+};
+
+subtest 'activation of an empty target' => sub {
+ my $fake = FakeTarget->new(pools => ['tank']);
+ $fake->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $U{1}]);
+ my $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'the target is configured');
+ is_deeply(
+ [map { $_->{locked} } $res->{calls}->@*],
+ [0, 1, 1, 1, 1, 1],
+ 'read, then lock, read, apply, verify and publish',
+ );
+ is_deeply(
+ [map { [$_->@{qw(name timeout)}] } $res->{locks}->@*],
+ [['zfsnvme-192.0.2.10', 30]],
+ 'under the domain lock of the target, waiting up to 30 seconds for it',
+ );
+ my $m = $fake->{m};
+ my $subsys = $m->{subsystems}->{$NQN};
+ is_deeply(
+ $subsys->{attr},
+ {
+ attr_model => $MODEL,
+ attr_serial => nv('_nvmet_serial', $NQN),
+ attr_allow_any_host => '0',
+ },
+ 'the subsystem carries our marker',
+ );
+ is_deeply($subsys->{acl}, { map { $_ => 1 } @HOSTS }, 'every host has an ACL');
+ is_deeply([map { $m->{hosts}->{$_}->{key} } @HOSTS], [$KEY, $KEY], 'and the key');
+ ok(exported($fake, 1, $U{1}, '/dev/zvol/tank/vm-100-disk-0'), 'the volume is exported');
+
+ $res = flow($fake, $ACT{activate});
+ is_deeply(ops($res), ['read target state'], 'a converged target costs one read');
+ ok(!$res->{locks}->@* && !$res->{calls}->[0]->{mutating}, 'without lock or change');
+};
+
+subtest 'activation refusals change nothing' => sub {
+ for my $case (
+ [
+ 'a foreign subsystem at our NQN',
+ sub($f) { $f->add_subsystem($NQN, model => 'Other Storage', serial => 'abc') },
+ qr/refusing to take over existing NVMe subsystem/,
+ ],
+ [
+ 'a used subsystem with the default model',
+ sub($f) {
+ $f->add_host($HOSTS[0], $KEY);
+ $f->add_subsystem($NQN, model => 'Linux', serial => 'abc', acl => [$HOSTS[0]]);
+ },
+ qr/refusing to take over existing NVMe subsystem/,
+ ],
+ [
+ 'a duplicate UUID on a published target',
+ sub($f) {
+ $f->{m} = lifecycle_fake()->{m};
+ $f->add_zvol('tank/vm-150-disk-0', identity => [$NQN, 7, $U{5}]);
+ $f->add_zvol('tank/vm-151-disk-0', identity => [$NQN, 8, $U{5}]);
+ },
+ qr/duplicate namespace UUID '\Q@{[ $U{5} ]}\E'/,
+ ],
+ [
+ 'an enabled namespace of another volume',
+ sub($f) {
+ $f->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $U{1}]);
+ $f->add_subsystem($NQN);
+ $f->add_namespace($NQN, 1, $U{9}, '/dev/zvol/tank/other');
+ },
+ qr/NVMe namespace ID '1' has a different identity/,
+ ],
+ ) {
+ my ($name, $setup, $error) = $case->@*;
+ my $fake = FakeTarget->new(pools => ['tank']);
+ $setup->($fake);
+ my $res = refused($fake, 'activate', $error, $name);
+ unlike($res->{error}, qr/DHHC-1/, 'without key material in the message');
+ }
+};
+
+subtest 'nothing is published unless a fresh read converges' => sub {
+ my $acl = "$S/allowed_hosts/$HOSTS[1]";
+ my $failing = sub($limit) {
+ my $failures = 0;
+ return sub($step, $call) {
+ return undef
+ if !step_is($step, 'ln', '-s') || $step->[3] ne $acl || $failures >= $limit;
+ $failures++;
+ return "ln: failed to create symbolic link '$acl': Invalid argument";
+ };
+ };
+ my $fake = FakeTarget->new(pools => ['tank'], step_fault => $failing->(99));
+ my $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/NVMe target did not converge: ln: failed to create symbolic link/,
+ 'a plan that fails twice stops',
+ );
+ is(
+ scalar(grep { $_->{op} eq 'configure NVMe target' } $res->{calls}->@*),
+ 2,
+ 'in two rounds',
+ );
+ is(scalar(grep { $_->{op} =~ /\Alink / } $res->{calls}->@*), 0, 'and publishes nothing');
+ ok(!grep({ $_->{links}->%* } values $fake->{m}->{ports}->%*),
+ 'no port links the subsystem');
+
+ $fake = FakeTarget->new(pools => ['tank'], step_fault => $failing->(1));
+ $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'a transient failure is repaired by the second round');
+ is(scalar(grep { $_->{op} =~ /\Alink / } $res->{calls}->@*), 2, 'which then publishes');
+
+ $fake = FakeTarget->new(pools => ['tank']);
+ $fake->{m}->{mounted} = 0;
+ $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'configfs is mounted when it is missing');
+ my @seen = grep { /mount/ } ops($res)->@*;
+ is_deeply(\@seen, ['read mounts', 'mount configfs'], 'after reading the mount table');
+ is(
+ $res->{calls}->[-1]->{op},
+ 'link NVMe subsystem on port 2',
+ 'and the target is published',
+ );
+
+ $fake = FakeTarget->new(pools => ['tank']);
+ $fake->{step_fault} = sub($step, $call) {
+ return step_is($step, 'env') ? "find: '$ROOT/hosts': Permission denied" : undef;
+ };
+ $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/cannot read NVMe target state: find: '\Q$ROOT\E\/hosts': Permission denied/,
+ 'an unreadable, mounted configfs stops the activation',
+ );
+ ok(!grep({ $_ eq 'mount configfs' } ops($res)->@*), 'without mounting');
+ is(changes($res), 0, 'and without changes');
+};
+
+subtest 'an interrupted subsystem creation' => sub {
+ # The chain that creates the subsystem stops after its mkdir or after the
+ # model write, for example when the remote shell is killed. Call 2 is the
+ # configuration. Its outcome is unknown; the next activation repairs it.
+ my $marker = {
+ attr_model => $MODEL,
+ attr_serial => nv('_nvmet_serial', $NQN),
+ attr_allow_any_host => '0',
+ };
+ my $completed = sub($fake, $what) {
+ is_deeply($fake->{m}->{subsystems}->{$NQN}->{attr}, $marker, "$what: our marker");
+ ok(
+ exported($fake, 1, $U{1}, '/dev/zvol/tank/vm-100-disk-0'),
+ "$what: exports the volume",
+ );
+ ok(
+ $fake->{m}->{ports}->{1}->{links}->{$NQN}
+ && $fake->{m}->{ports}->{2}->{links}->{$NQN},
+ "$what: and publishes it",
+ );
+ is_deeply($fake->{violations}, [], "$what: no protocol violation");
+ };
+ my $new = sub(%faults) {
+ my $fake = FakeTarget->new(pools => ['tank'], faults => {%faults});
+ $fake->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $U{1}]);
+ return $fake;
+ };
+
+ # After the model write, only this plugin can have created the subsystem.
+ my $fake = $new->(2 => 'cut:2');
+ my $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/'configure NVMe target' did not complete .* state is unknown\n\z/,
+ 'a cut after the model write',
+ );
+ ok(!grep({ $_->{links}->%* } values $fake->{m}->{ports}->%*), 'is unpublished');
+ $fake->{faults} = {};
+ $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'the next activation completes the subsystem');
+ my ($configure) = grep { $_->{op} eq 'configure NVMe target' } $res->{calls}->@*;
+ is_deeply(
+ $configure->{steps}->[0],
+ write_step("$S/attr_serial", $marker->{attr_serial}),
+ 'by writing the serial',
+ );
+ $completed->($fake, 'next activation after the model write');
+
+ # Right after the mkdir, the subsystem looks like one of another tool.
+ $fake = $new->(2 => 'cut:1');
+ $res = flow($fake, $ACT{activate});
+ like($res->{error}, qr/state is unknown\n\z/, 'a cut right after the mkdir');
+ $fake->{faults} = {};
+ $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/refusing to take over existing NVMe subsystem .* not created by Proxmox VE/,
+ 'is refused by the next activation',
+ );
+ is($fake->{m}->{subsystems}->{$NQN}->{attr}->{attr_model}, 'Linux',
+ 'the subsystem is kept');
+ ok(!grep({ $_->{links}->%* } values $fake->{m}->{ports}->%*), 'and unpublished');
+ delete $fake->{m}->{subsystems}->{$NQN};
+ $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'once an administrator removed it, the next activation creates it');
+ $completed->($fake, 'activation after the removal');
+};
+
+subtest 'quorum and reachability' => sub {
+ my $fake = FakeTarget->new(pools => ['tank']);
+ local $QUORATE = 0;
+ local @QUORUM = ();
+ my $res = flow($fake, $ACT{activate});
+ like($res->{error}, qr/cluster not quorate - refusing NVMe target changes/, 'no quorum');
+ is_deeply(\@QUORUM, [1], 'with a quorum check that does not wait');
+ is(scalar($res->{locks}->@*), 0, 'before requesting the lock');
+ is_deeply(ops($res), ['read target state'], 'after the lockless read');
+ $QUORATE = 1;
+
+ $fake->{unreachable} = 1;
+ $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/NVMe target '192\.0\.2\.10' is unreachable: ssh: connect/,
+ 'an unreachable target fails in the lockless read',
+ );
+ ok(!$res->{locks}->@* && $res->{calls}->@* == 1, 'without lock or retry');
+
+ $fake = lifecycle_fake();
+ local $QUORATE = 0;
+ $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'a converged target needs no quorum');
+};
+
+subtest 'create' => sub {
+ my ($fake, $res) = run_on('alloc');
+ is($res->{error}, '', 'allocation succeeds');
+ is($res->{result}, 'vm-200-disk-0', 'with the next free name');
+ is_deeply(
+ [map { $_->{locked} } $res->{calls}->@*],
+ [0, 1, 1, 1, 1, 1, 1],
+ 'the name lookup without the lock, the rest under it',
+ );
+ my $uuid = $fake->{m}->{ds}->{'tank/vm-200-disk-0'}->{props}->{'proxmox:nvme-uuid'};
+ like($uuid, $UUID_RE, 'a new UUID');
+ ok(exported($fake, 4, $uuid, '/dev/zvol/tank/vm-200-disk-0'), 'exported at the next NSID');
+
+ my $thick = scfg();
+ delete $thick->@{qw(sparse blocksize)};
+ $fake = lifecycle_fake();
+ $res =
+ flow($fake, sub { $PLUGIN->alloc_image('st', $thick, 200, 'raw', 'vm-200-disk-1', 4000) });
+ is($res->{result}, 'vm-200-disk-1', 'an explicit name is used');
+ my ($create) = grep { $_->{op} eq 'create zvol' } $res->{calls}->@*;
+ is_deeply(
+ [grep { /\A(?:-[sb]|[0-9]+k)\z/ } $create->{steps}->[0]->@*],
+ ['4096k'],
+ 'the size is rounded up to KiB; without sparse and blocksize the zvol is thick',
+ );
+
+ ($fake, $res) = run_on('alloc', udev_delay => 3);
+ is($res->{error}, '', 'a slow udev');
+ is(scalar(grep { $_ eq 'wait for zvol' } ops($res)->@*), 4, 'adds polls');
+
+ local @UUIDS = ($U{1}, $U{9});
+ ($fake, $res) = run_on('alloc');
+ is(
+ $fake->{m}->{ds}->{'tank/vm-200-disk-0'}->{props}->{'proxmox:nvme-uuid'},
+ $U{9},
+ 'a UUID that is in use is drawn again',
+ );
+ local @UUIDS = ($U{1}) x 10;
+ ($fake, $res) = run_on('alloc');
+ is($res->{error}, "cannot generate an unused namespace UUID\n", 'but not forever');
+ is(changes($res), 0, 'and nothing changes');
+ @UUIDS = ();
+
+ ($fake, $res) = run_on('alloc', faults => { 3 => 'after' });
+ like(
+ $res->{error},
+ qr/'create zvol' did not complete .*state is unknown\n\z/,
+ 'a lost reply aborts even when the create reached the target',
+ );
+ is($res->{calls}->[-1]->{op}, 'create zvol', 'no read tries to settle it');
+ ok(!ns_of($fake, 4), 'the abandoned operation does not export it');
+ $fake->{faults} = {};
+ $res = flow($fake, $ACT{activate});
+ ok(!$res->{error} && ns_of($fake, 4), 'the next activation exports the owned zvol');
+
+ ($fake, $res) = run_on('alloc', faults => { 5 => 'before' });
+ like($res->{error}, qr/'export namespace' failed: injected failure/, 'a failed export');
+ ok(!$fake->{m}->{ds}->{'tank/vm-200-disk-0'} && !ns_of($fake, 4), 'destroys the new zvol');
+ is($res->{locks}->@* + $res->{nested}->@*, 1, 'the compensation reuses the lock');
+
+ # The export may still run on the target after its connection broke.
+ ($fake, $res) = run_on('alloc', faults => { 5 => 'after' });
+ like(
+ $res->{error},
+ qr/\A.*'export namespace' did not complete \(Connection.*state is unknown\n\z/,
+ 'a lost reply of the export leaves the state unknown',
+ );
+ ok(!grep({ /destroy|remove/ } ops($res)->@*), 'and is not compensated');
+ ok($fake->{m}->{ds}->{'tank/vm-200-disk-0'} && ns_of($fake, 4), 'so the disk is kept');
+
+ ($fake, $res) = run_on(
+ 'alloc',
+ before_call => sub($f, $call) {
+ $f->add_zvol('tank/vm-777-disk-0', identity => [$NQN, 4, $U{9}])
+ if $call->{index} == 6 && !$f->{m}->{ds}->{'tank/vm-777-disk-0'};
+ },
+ );
+ like(
+ $res->{error},
+ qr/duplicate NVMe identity on 'tank\/vm-200-disk-0'/,
+ 'a duplicate that appears before the verify read is refused',
+ );
+ ok(
+ !$fake->{m}->{ds}->{'tank/vm-200-disk-0'} && !ns_of($fake, 4),
+ 'the new zvol is destroyed',
+ );
+ ok($fake->{m}->{ds}->{'tank/vm-777-disk-0'}, 'the other zvol is kept');
+
+ ($fake, $res) = run_on(
+ 'alloc',
+ before_call => sub($f, $call) {
+ my $ds = $f->{m}->{ds}->{'tank/vm-200-disk-0'};
+ $ds->{props}->{'proxmox:nvme-uuid'} = $U{9} if $ds && $call->{index} == 6;
+ },
+ );
+ is(
+ $res->{error},
+ "NVMe identity of zvol 'tank/vm-200-disk-0' changed\n",
+ 'an identity that changes before the verify read is refused',
+ );
+ ok(!ns_of($fake, 4), 'the new namespace is removed');
+ ok($fake->{m}->{ds}->{'tank/vm-200-disk-0'}, 'but a zvol without our identity is kept');
+
+ # A namespace of another zvol that was renamed away while exported uses
+ # the device path of the new zvol: only what this call built is removed.
+ ($fake, $res) = run_on(
+ 'alloc',
+ faults => { 5 => 'before' },
+ before_call => sub($f, $call) {
+ $f->add_namespace($NQN, 9, $U{9}, '/dev/zvol/tank/vm-200-disk-0')
+ if $call->{index} == 0;
+ },
+ );
+ like($res->{error}, qr/'export namespace' failed: injected failure/, 'a failed export');
+ ok(
+ exported($fake, 9, $U{9}, '/dev/zvol/tank/vm-200-disk-0'),
+ 'keeps an enabled namespace of another UUID with the same device path',
+ );
+ ok(
+ !grep({ grep { write_to($_, '/namespaces/9/enable') } $_->{steps}->@* }
+ $res->{calls}->@*),
+ 'without touching it',
+ );
+
+ ($fake, $res) = run_on(
+ 'alloc',
+ faults => { 5 => 'before' },
+ fail => [['zfs', 'destroy'], "cannot destroy 'tank/vm-200-disk-0': dataset is busy"],
+ );
+ like(
+ $res->{error},
+ qr/'export namespace' failed: injected failure/,
+ 'keeps the first error',
+ );
+ my $cleanup = qr/\Afailed to clean up zvol 'vm-200-disk-0': NVMe target operation/;
+ is(
+ scalar(grep { /$cleanup 'destroy zvol' failed: cannot destroy/ } $res->{warnings}->@*),
+ 1,
+ 'a failed cleanup is reported',
+ );
+
+ # ssh gives up on a call, which the target still runs to its end later
+ ($fake, $res) = run_on('alloc', faults => { 3 => 'late' });
+ is(
+ $res->{error},
+ "NVMe target operation 'create zvol' did not complete (timeout);"
+ . " the target state is unknown\n",
+ 'a create that did not complete in time',
+ );
+ is($res->{calls}->[-1]->{op}, 'create zvol', 'is not followed by anything');
+ my $second =
+ flow($fake, sub { $PLUGIN->alloc_image('st', scfg(), 201, 'raw', undef, 1024) });
+ is($second->{error}, '', 'another allocation meanwhile');
+ $fake->land;
+ is_deeply(
+ [map { owned_volumes($fake->{m})->{"tank/vm-$_-disk-0"}->[0] } 200, 201],
+ [4, 5],
+ 'never gets the NSID of the create that completes afterwards',
+ );
+ $res = flow($fake, $ACT{activate});
+ ok(
+ !$res->{error} && ns_of($fake, 4) && ns_of($fake, 5),
+ 'and the next activation exports both',
+ );
+
+ ($fake, $res) = run_on(
+ 'alloc',
+ before_call =>
+ sub($f, $call) { die "received interrupt\n" if $call->{op} eq 'export namespace' },
+ );
+ is($res->{error}, "received interrupt\n", 'a stopped task');
+ ok(!grep({ /destroy|remove/ } ops($res)->@*), 'is not compensated either');
+
+ ($fake, $res) = run_on('alloc', read_fault => { after => 5, mode => 'failed' });
+ is(
+ $res->{error},
+ "NVMe target operation 'read target state' did not complete (ssh failed);"
+ . " the target state is unknown\n",
+ 'a read under the lock that ssh did not run to its end',
+ );
+ ok(!grep({ /destroy|remove/ } ops($res)->@*), 'is not followed by a compensation');
+
+ $fake = lifecycle_fake();
+ $fake->add_zvol('tank/vm-200-disk-0');
+ my $named = sub { $PLUGIN->alloc_image('st', scfg(), 200, 'raw', 'vm-200-disk-0', 1024) };
+ refused($fake, $named, qr/zvol 'tank\/vm-200-disk-0' already exists/, 'an existing zvol');
+ $fake = lifecycle_fake();
+ delete $fake->{m}->{subsystems}->{$NQN};
+ refused(
+ $fake,
+ 'alloc',
+ qr/NVMe subsystem does not exist; activate the storage first/,
+ 'an allocation without the subsystem',
+ );
+ $res =
+ flow($fake, sub { $PLUGIN->alloc_image('st', scfg(), 200, 'raw', 'vm-201-disk-0', 1024) });
+ like($res->{error}, qr/illegal name 'vm-201-disk-0'/, 'names must belong to the VM');
+};
+
+subtest 'clone' => sub {
+ my ($fake, $res) = run_on('clone');
+ is($res->{error}, '', 'a linked clone');
+ is($res->{result}, 'base-102-disk-0/vm-201-disk-0', 'is named after its base');
+ my $clone = $fake->{m}->{ds}->{'tank/vm-201-disk-0'};
+ is($clone->{origin}, 'tank/base-102-disk-0@__base__', 'from the base snapshot');
+ my $uuid = $clone->{props}->{'proxmox:nvme-uuid'};
+ ok(exported($fake, 4, $uuid, '/dev/zvol/tank/vm-201-disk-0'), 'with its own identity');
+
+ $fake = lifecycle_fake();
+ $res =
+ flow($fake, sub { $PLUGIN->clone_image(scfg(), 'st', 'base-102-disk-0', 201, 'missing') });
+ like(
+ $res->{error},
+ qr/'create zvol' failed: cannot open 'tank\/base-102-disk-0\@missing'/,
+ 'a missing snapshot',
+ );
+ ok(!$fake->{m}->{ds}->{'tank/vm-201-disk-0'}, 'leaves nothing behind');
+ $res = flow($fake, sub { $PLUGIN->clone_image(scfg(), 'st', 'base-102-disk-0', 201, '') });
+ is($res->{error}, '', 'an empty snapshot name');
+ is(
+ $fake->{m}->{ds}->{'tank/vm-201-disk-0'}->{origin},
+ 'tank/base-102-disk-0@__base__',
+ 'means the base snapshot',
+ );
+
+ for my $case (
+ ['basevol-102-disk-0', qr/clone_image requires a ZFS volume/],
+ ['vm-100-disk-0', qr/clone_image only works on base images/],
+ ) {
+ $res = flow($fake, sub { $PLUGIN->clone_image(scfg(), 'st', $case->[0], 201) });
+ like($res->{error}, $case->[1], "refuses $case->[0]");
+ is(scalar($res->{calls}->@*), 0, 'locally');
+ }
+ $res =
+ flow($fake, sub { $PLUGIN->clone_image(scfg(), 'st', 'base-102-disk-0', 201, 'a b') });
+ like($res->{error}, qr/invalid snapshot name/, 'refuses a malformed snapshot name');
+};
+
+subtest 'destroy' => sub {
+ my $dev = '/dev/zvol/tank/vm-101-disk-0';
+ my ($fake, $res) = run_on('free');
+ is($res->{error}, '', 'a volume is freed');
+ is_deeply(ops($res), ['read target state', 'destroy zvol'], 'in two calls');
+ ok(!$fake->{m}->{ds}->{'tank/vm-101-disk-0'} && !ns_of($fake, 2), 'both are gone');
+ $res = flow($fake, $ACT{free});
+ is($res->{error}, '', 'a missing volume is already freed');
+ is(changes($res), 0, 'without changes');
+
+ for my $case (
+ [
+ 'a volume that is not owned',
+ 'vm-900-disk-0',
+ undef,
+ qr/is not owned by NVMe subsystem/,
+ ],
+ [
+ 'a UUID exported at another NSID',
+ 'vm-101-disk-0',
+ sub($f) { $f->add_namespace($NQN, 9, $U{2}, '/dev/zvol/tank/x', 0) },
+ qr/namespace UUID '\Q@{[ $U{2} ]}\E' is already in use/,
+ ],
+ [
+ 'another identity at its NSID',
+ 'vm-101-disk-0',
+ sub($f) { ns_of($f, 2)->{device_uuid} = $U{9} },
+ qr/NVMe namespace ID '2' has a different identity/,
+ ],
+ [
+ 'a duplicate identity',
+ 'vm-101-disk-0',
+ sub($f) { $f->add_zvol('tank/vm-104-disk-0', identity => [$NQN, 2, $U{9}]) },
+ qr/duplicate NVMe identity/,
+ ],
+ ) {
+ my ($name, $volume, $change, $error) = $case->@*;
+ $fake = lifecycle_fake();
+ $change->($fake) if $change;
+ refused($fake, sub { $PLUGIN->free_image('st', scfg(), $volume) }, $error, $name);
+ }
+ $res = flow($fake, sub { $PLUGIN->free_image('st', scfg(), 'subvol-100-disk-0') });
+ like($res->{error}, qr/free_image requires a ZFS volume/, 'subvolumes are refused');
+
+ my $busy = 'Device or resource busy';
+ ($fake, $res) =
+ run_on('free', fail => [{ write => '/namespaces/2/enable', value => 0 }, $busy]);
+ like($res->{error}, qr/cannot disable namespace '2': .*busy/, 'a failed disable');
+ ok(exported($fake, 2, $U{2}, $dev), 'keeps the namespace');
+
+ ($fake, $res) = run_on('free', fail => [['rmdir', "$S/namespaces/2"], $busy]);
+ like(
+ $res->{error},
+ qr/cannot remove namespace '2': Device or resource busy\n\z/,
+ 'a failed rmdir',
+ );
+ ok(exported($fake, 2, $U{2}, $dev), 're-enables the namespace');
+ is($res->{calls}->[-1]->{op}, 'enable namespace', 'from a fresh read');
+
+ my $rmdir_and_enable = sub($s) {
+ step_is($s, 'rmdir', "$S/namespaces/2") || write_to($s, '/namespaces/2/enable', 1);
+ };
+ ($fake, $res) = run_on('free', fail => [$rmdir_and_enable, $busy]);
+ like(
+ $res->{error},
+ qr/cannot remove namespace '2': .*; cannot restore namespace: /,
+ 'a failed restore is reported too',
+ );
+
+ my $destroy = ['zfs', 'destroy', '-r', 'tank/vm-101-disk-0'];
+ local $SLEPT = 0;
+ ($fake, $res) = run_on('free', fail => [$destroy, $busy]);
+ like(
+ $res->{error},
+ qr/\Afailed to destroy 'tank\/vm-101-disk-0': Device or resource busy; namespace restored/,
+ 'a zvol that stays busy',
+ );
+ is(scalar(grep { $_ eq 'destroy zvol' } ops($res)->@*), 6, 'is destroyed six times');
+ is($SLEPT, 5, 'a second apart');
+ ok(exported($fake, 2, $U{2}, $dev), 'and its namespace is restored');
+
+ ($fake, $res) = run_on('free', fail => [$destroy, $busy, 3]);
+ is($res->{error}, '', 'a zvol that becomes free is destroyed by a retry');
+ ok(!$fake->{m}->{ds}->{'tank/vm-101-disk-0'}, 'and is gone');
+
+ ($fake, $res) = run_on('free', fail => [$destroy, $busy, 1], faults => { 3 => 'after' });
+ like(
+ $res->{error},
+ qr/'destroy zvol' did not complete .* state is unknown\n\z/,
+ 'a retry whose reply is lost',
+ );
+ is($res->{calls}->[-1]->{op}, 'destroy zvol', 'is not followed by anything');
+
+ ($fake, $res) = run_on(
+ 'free',
+ fail => [$destroy, $busy],
+ read_fault => { after => 1, mode => 'unreachable' },
+ );
+ is(
+ $res->{error},
+ "failed to destroy 'tank/vm-101-disk-0': Device or resource busy\n",
+ 'a failed destroy whose outcome cannot be read is a failure',
+ );
+ ok($fake->{m}->{ds}->{'tank/vm-101-disk-0'}, 'and the zvol is still there');
+
+ ($fake, $res) = run_on(
+ 'free',
+ step_fault => sub($step, $call) {
+ return 'dataset is busy' if step_is($step, $destroy->@*);
+ return 'File exists' if step_is($step, 'mkdir', "$S/namespaces/2");
+ return undef;
+ },
+ );
+ like(
+ $res->{error},
+ qr/failed to destroy 'tank\/vm-101-disk-0': dataset is busy; namespace restoration also/,
+ 'a failed restore after the retries',
+ );
+
+ $fake = lifecycle_fake(fail => [$destroy, $busy]);
+ delete $fake->{m}->{subsystems}->{$NQN}->{ns}->{2};
+ $res = flow($fake, $ACT{free});
+ like(
+ $res->{error},
+ qr/\Afailed to destroy 'tank\/vm-101-disk-0': Device or resource busy\n\z/,
+ 'an unexported busy zvol is reported without restore',
+ );
+ ok(!ns_of($fake, 2), 'and stays unexported');
+
+ $fake = lifecycle_fake();
+ delete $fake->{m}->{subsystems}->{$NQN};
+ delete $_->{links}->{$NQN} for values $fake->{m}->{ports}->%*;
+ $res = flow($fake, $ACT{free});
+ is($res->{error}, '', 'a volume is freed without subsystem');
+ ok(!$fake->{m}->{ds}->{'tank/vm-101-disk-0'}, 'nothing exports it');
+};
+
+subtest 'rollback' => sub {
+ my $dev = '/dev/zvol/tank/vm-100-disk-0';
+ my ($fake, $res) = run_on('rollback');
+ is($res->{error}, '', 'a rollback');
+ is_deeply(
+ ops($res),
+ ['read target state', 'rollback zvol', 'wait for zvol', 'restore namespace'],
+ 'unexports, rolls back and exports again',
+ );
+ ok(exported($fake, 1, $U{1}, $dev), 'with the same identity');
+
+ # A snapshot without the identity properties: the rollback loses them.
+ my $bare = sub(%opts) {
+ my $f = lifecycle_fake(%opts);
+ $f->add_snapshot('tank/vm-100-disk-0@bare', props => {});
+ return $f;
+ };
+ for my $case (
+ ['the disable', { write => '/namespaces/1/enable', value => 0 }],
+ ['the rmdir', ['rmdir', "$S/namespaces/1"]],
+ ['the rollback', ['zfs', 'rollback']],
+ ['the identity', ['zfs', 'set']],
+ ) {
+ my ($name, $match) = $case->@*;
+ $fake = $bare->(fail => [$match, "injected $name failure", 1]);
+ $res = flow(
+ $fake,
+ sub { $PLUGIN->volume_snapshot_rollback(scfg(), 'st', 'vm-100-disk-0', 'bare') },
+ );
+ like(
+ $res->{error},
+ qr/\ANVMe target operation 'rollback zvol' failed: injected \Q$name\E failure\n\z/,
+ "a failure at $name is reported",
+ );
+ ok(exported($fake, 1, $U{1}, $dev), "the namespace is restored after $name");
+ is_deeply(
+ owned_volumes($fake->{m})->{'tank/vm-100-disk-0'},
+ [1, $U{1}],
+ 'with identity',
+ );
+ }
+ my @restore = grep { $_->{op} eq 'restore namespace' } $res->{calls}->@*;
+ ok(step_is($restore[0]->{steps}->[0], 'zfs', 'set'), 'a lost identity is written first');
+
+ ($fake, $res) = run_on(
+ 'rollback',
+ step_fault => sub($step, $call) {
+ return 'rollback failed' if step_is($step, 'zfs', 'rollback');
+ return 'mkdir failed' if step_is($step, 'mkdir');
+ return undef;
+ },
+ );
+ like(
+ $res->{error},
+ qr/
+ \Arollback\ failed:\ NVMe\ target\ operation\ 'rollback\ zvol'\ failed:
+ \ rollback\ failed;
+ \ namespace\ restoration\ failed:\ NVMe\ target\ operation\ 'restore\ namespace'
+ \ failed:\ mkdir\ failed\n\z
+ /x,
+ 'both failures are reported',
+ );
+ ($fake, $res) = run_on('rollback', fail => [['mkdir'], 'mkdir failed']);
+ like(
+ $res->{error},
+ qr/\Anamespace restoration failed after rollback: .*mkdir failed\n\z/,
+ 'a failed export after a good rollback is reported',
+ );
+
+ $fake = lifecycle_fake();
+ for my $case (
+ ['a malformed snapshot name', 'vm-100-disk-0', 'a b', qr/invalid snapshot name/],
+ [
+ 'a subvolume',
+ 'subvol-100-disk-0',
+ 'snap1',
+ qr/snapshot rollback requires a ZFS volume/,
+ ],
+ ['a volume that is not owned', 'vm-900-disk-0', 'snap1', qr/is not owned/],
+ ) {
+ my ($name, $volume, $snap, $error) = $case->@*;
+ my $rollback = sub { $PLUGIN->volume_snapshot_rollback(scfg(), 'st', $volume, $snap) };
+ refused($fake, $rollback, $error, $name);
+ }
+ my $taken = lifecycle_fake();
+ $taken->add_namespace($NQN, 1, $U{9}, '/dev/zvol/tank/vm-900-disk-0');
+ refused(
+ $taken,
+ 'rollback',
+ qr/NVMe namespace ID '1' has a different identity/,
+ 'a namespace ID that holds another identity',
+ );
+ delete $fake->{m}->{subsystems}->{$NQN};
+ refused(
+ $fake,
+ 'rollback',
+ qr/NVMe subsystem does not exist/,
+ 'a rollback without the subsystem',
+ );
+};
+
+subtest 'template' => sub {
+ my $old = '/dev/zvol/tank/vm-101-disk-0';
+ my $new = '/dev/zvol/tank/base-101-disk-0';
+ my ($fake, $res) = run_on('template');
+ is($res->{result}, 'base-101-disk-0', 'a template');
+ is_deeply(
+ ops($res),
+ ['read target state', 'rename zvol', 'wait for zvol', 'create template'],
+ 'is renamed, exported and snapshotted',
+ );
+ ok(exported($fake, 2, $U{2}, $new), 'under the same identity');
+ ok($fake->{m}->{snaps}->{'tank/base-101-disk-0@__base__'}, 'with its base snapshot');
+
+ my $restored = sub($f) {
+ return
+ exported($f, 2, $U{2}, $old)
+ && $f->{m}->{ds}->{'tank/vm-101-disk-0'}
+ && !$f->{m}->{ds}->{'tank/base-101-disk-0'};
+ };
+ for my $case (
+ ['the unexport', sub($s, $c) { write_to($s, '/namespaces/2/enable', 0) }],
+ ['the rename', sub($s, $c) { step_is($s, 'zfs', 'rename', 'tank/vm-101-disk-0') }],
+ ['the export', sub($s, $c) { step_is($s, 'mkdir') && $c->{op} eq 'create template' }],
+ ['the snapshot', sub($s, $c) { step_is($s, 'zfs', 'snapshot') }],
+ ) {
+ my ($name, $match) = $case->@*;
+ my $fault =
+ sub($step, $call) { $match->($step, $call) ? "injected $name failure" : undef };
+ ($fake, $res) = run_on('template', step_fault => $fault);
+ my $prefix = qr/\Atemplate conversion failed: NVMe target operation '[a-z ]+' failed:/;
+ like(
+ $res->{error},
+ qr/$prefix injected \Q$name\E failure\n\z/,
+ "a failure at $name is reported",
+ );
+ ok($restored->($fake), "the old name is exported again after $name");
+ }
+
+ ($fake, $res) = run_on(
+ 'template',
+ after_call => sub($f, $call) {
+ $f->{m}->{ds}->{'tank/base-101-disk-0'}->{devwait} = 1000
+ if $call->{op} eq 'rename zvol';
+ },
+ );
+ like(
+ $res->{error},
+ qr/\Atemplate conversion failed: zvol '\Q$new\E' is not a block device after 10 seconds\n/,
+ 'a device that never appears',
+ );
+ ok($restored->($fake), 'is renamed back');
+
+ ($fake, $res) = run_on('template', faults => { 1 => 'late' });
+ like(
+ $res->{error},
+ qr/\ANVMe target operation 'rename zvol' did not complete .* state is unknown\n\z/,
+ 'a rename that does not complete in time is passed on as it is',
+ );
+ ok(!grep({ $_->{op} =~ /back|restore/ } $res->{calls}->@*), 'is not compensated');
+ $fake->land;
+ $res = flow($fake, $ACT{activate});
+ ok(!$res->{error} && exported($fake, 2, $U{2}, $new), 'the next activation exports it');
+
+ my $taken = lifecycle_fake();
+ $taken->add_namespace($NQN, 2, $U{9}, '/dev/zvol/tank/vm-900-disk-0');
+ refused(
+ $taken,
+ 'template',
+ qr/NVMe namespace ID '2' has a different identity/,
+ 'a namespace ID that holds another identity',
+ );
+ $fake = lifecycle_fake();
+ $fake->add_zvol('tank/base-101-disk-0');
+ refused(
+ $fake,
+ 'template',
+ qr/template zvol 'tank\/base-101-disk-0' already exists/,
+ 'a taken name',
+ );
+ $res = flow($fake, sub { $PLUGIN->create_base('st', scfg(), 'base-102-disk-0') });
+ like($res->{error}, qr/create_base not possible with base image/, 'refuses a base');
+ refused(
+ $fake,
+ sub { $PLUGIN->create_base('st', scfg(), 'vm-900-disk-0') },
+ qr/is not owned/,
+ 'a volume that is not owned',
+ );
+};
+
+subtest 'resize' => sub {
+ my ($fake, $res) = run_on('resize');
+ is($res->{error}, '', 'an exported volume grows');
+ is($res->{result}, 2 * 1024**2, 'the new size in KiB is returned');
+ is_deeply(ops($res), ['read target state', 'resize zvol'], 'read, then resize');
+ ok(!grep({ !$_->{locked} } $res->{calls}->@*), 'under the lock');
+ is($fake->{revalidated}->{"$NQN/1"}, 1,
+ 'the namespace reads the new size in the same call');
+
+ $fake = lifecycle_fake();
+ delete $fake->{m}->{subsystems}->{$NQN}->{ns}->{1};
+ $res = flow($fake, $ACT{resize});
+ is($res->{error}, '', 'an unexported volume grows');
+ is(scalar($res->{calls}->[1]->{steps}->@*), 1, 'without revalidation');
+ $fake = lifecycle_fake();
+ ns_of($fake, 1)->{enable} = '0';
+ $res = flow($fake, $ACT{resize});
+ is(scalar($res->{calls}->[1]->{steps}->@*), 1, 'a disabled namespace is not revalidated');
+ $fake = lifecycle_fake()->reboot(0);
+ $res = flow($fake, $ACT{resize});
+ is($res->{error}, '', 'a volume grows after a target restart');
+ is($fake->{m}->{ds}->{'tank/vm-100-disk-0'}->{volsize}, 2 * 1024**3,
+ 'once nvmet is loaded');
+
+ for my $case (
+ [
+ 'a duplicate UUID',
+ 'vm-100-disk-0',
+ sub($f) { $f->add_namespace($NQN, 9, $U{1}, '/dev/zvol/tank/x', 0) },
+ qr/duplicate namespace UUID/,
+ ],
+ ['a volume that is not owned', 'vm-900-disk-0', sub($f) { }, qr/is not owned/],
+ ['a volume of another subsystem', 'vm-901-disk-0', sub($f) { }, qr/is not owned/],
+ ) {
+ my ($name, $volname, $change, $error) = $case->@*;
+ $fake = lifecycle_fake();
+ $change->($fake);
+ my $resize = sub { $PLUGIN->volume_resize(scfg(), 'st', $volname, 2 * 1024**3) };
+ refused($fake, $resize, $error, $name);
+ }
+ ($fake, $res) = run_on('resize', fail => [['zfs', 'set'], 'out of space']);
+ like($res->{error}, qr/'resize zvol' failed: out of space/, 'a failed resize');
+ is_deeply(ops($res), ['read target state', 'resize zvol'], 'stops there');
+ ($fake, $res) =
+ run_on('resize', fail => [{ write => 'revalidate_size' }, 'Invalid argument']);
+ like($res->{error}, qr/'resize zvol' failed: Invalid argument/, 'a failed revalidation');
+ is($fake->{m}->{ds}->{'tank/vm-100-disk-0'}->{volsize}, 2 * 1024**3, 'keeps the new size');
+};
+
+sub removal_fake(%opts) {
+ my $fake = target_fake(%opts);
+ $fake->add_zvol('other/foreign-disk', identity => [$FOREIGN_NQN, 1, $U{8}]);
+ $fake->add_subsystem(
+ $FOREIGN_NQN,
+ model => 'Linux',
+ serial => '0123456789abcdef',
+ acl => [$HOSTS[0]],
+ );
+ $fake->add_namespace($FOREIGN_NQN, 1, $U{8}, '/dev/zvol/other/foreign-disk');
+ $fake->{m}->{ports}->{1}->{links}->{$FOREIGN_NQN} = 1;
+ return $fake;
+}
+
+subtest 'target removal' => sub {
+ my $fake = removal_fake();
+ my $res = flow($fake, $ACT{remove});
+ is($res->{error}, '', 'the subsystem is removed');
+ is_deeply(
+ ops($res),
+ [
+ 'read target state',
+ 'remove NVMe subsystem',
+ 'read target state',
+ 'remove orphan NVMe hosts',
+ ],
+ 'teardown, then orphans from a fresh read',
+ );
+ my $m = $fake->{m};
+ ok(
+ !$m->{subsystems}->{$NQN} && $m->{hosts}->{ $HOSTS[0] } && !$m->{hosts}->{ $HOSTS[1] },
+ 'subsystem and orphan host are gone, the host linked by another subsystem stays',
+ );
+ ok($m->{ports}->{1} && $m->{ports}->{2}, 'ports are never removed');
+ $res = flow($fake, $ACT{remove});
+ is($res->{error}, '', 'a removed subsystem is already removed');
+ is_deeply(ops($res), ['read target state'], 'with nothing left to do');
+
+ $fake = removal_fake();
+ delete $fake->{m}->{subsystems}->{$NQN};
+ delete $_->{links}->{$NQN} for values $fake->{m}->{ports}->%*;
+ $res = flow($fake, $ACT{remove});
+ is_deeply(
+ ops($res),
+ ['read target state', 'remove orphan NVMe hosts'],
+ 'without subsystem the configured hosts are candidates',
+ );
+ ok(
+ $fake->{m}->{hosts}->{ $HOSTS[0] } && !$fake->{m}->{hosts}->{ $HOSTS[1] },
+ 'only unlinked hosts go',
+ );
+
+ for my $case (
+ [
+ 'an owned volume',
+ sub($f) { add_volume($f, 'vm-100-disk-0', 1, $U{1}, unexported => 1) },
+ qr/owned ZFS volume 'tank\/vm-100-disk-0' exists/,
+ ],
+ [
+ 'a foreign subsystem',
+ sub($f) { $f->{m}->{subsystems}->{$NQN}->{attr}->{attr_model} = 'Linux' },
+ qr/refusing to delete foreign NVMe subsystem/,
+ ],
+ [
+ 'remaining namespaces',
+ sub($f) { $f->add_namespace($NQN, 3, $U{3}, '(null)', 0) },
+ qr/namespaces remain/,
+ ],
+ ) {
+ my ($name, $change, $error) = $case->@*;
+ $fake = removal_fake();
+ $change->($fake);
+ refused($fake, 'remove', $error, $name);
+ }
+
+ $fake =
+ removal_fake(fail => [['rmdir', "$ROOT/hosts/$HOSTS[1]"], 'Device or resource busy']);
+ $res = flow($fake, $ACT{remove});
+ is($res->{error}, '', 'a failed orphan removal');
+ like(
+ $res->{warnings}->[0],
+ qr/could not remove orphan NVMe host\(s\): Device or resource busy/,
+ 'only warns',
+ );
+
+ $fake = removal_fake(fail => [['rmdir', $S], 'Directory not empty']);
+ $res = flow($fake, $ACT{remove});
+ like(
+ $res->{error},
+ qr/cannot remove NVMe subsystem '\Q$NQN\E': Directory not empty/,
+ 'a failed teardown is reported',
+ );
+ ok($fake->{m}->{subsystems}->{$NQN}, 'and the subsystem stays');
+};
+
+subtest 'snapshots and the generic ZFS calls' => sub {
+ my $fake = lifecycle_fake();
+ my $res =
+ flow($fake, sub { $PLUGIN->volume_snapshot(scfg(), 'st', 'vm-100-disk-0', 'snap_2.0') });
+ is($res->{error}, '', 'a snapshot');
+ ok($fake->{m}->{snaps}->{'tank/vm-100-disk-0@snap_2.0'}, 'is taken');
+ is(scalar($res->{locks}->@*), 1, 'under the target lock');
+ $res = flow(
+ $fake,
+ sub { $PLUGIN->volume_rollback_is_possible(scfg(), 'st', 'vm-100-disk-0', 'snap1') },
+ );
+ like(
+ $res->{error},
+ qr/'snap1' is not most recent snapshot/,
+ 'only from the latest snapshot',
+ );
+ $res = flow(
+ $fake,
+ sub { $PLUGIN->volume_snapshot_delete(scfg(), 'st', 'vm-100-disk-0', 'snap_2.0') },
+ );
+ ok(
+ !$res->{error} && !$fake->{m}->{snaps}->{'tank/vm-100-disk-0@snap_2.0'},
+ 'deleted by name',
+ );
+ is(scalar($res->{locks}->@*), 1, 'under the target lock too');
+ $res = flow(
+ $fake,
+ sub { $PLUGIN->volume_rollback_is_possible(scfg(), 'st', 'vm-100-disk-0', 'snap1') },
+ );
+ is($res->{result}, 1, 'now the rollback is possible');
+ $res = flow(
+ $fake,
+ sub { $PLUGIN->volume_rollback_is_possible(scfg(), 'st', 'vm-100-disk-0', 'gone') },
+ );
+ like($res->{error}, qr/snapshot 'gone' does not exist/, 'and needs an existing snapshot');
+ $res = flow($fake, sub { $PLUGIN->volume_snapshot_info(scfg(), 'st', 'vm-100-disk-0') });
+ is_deeply([sort keys $res->{result}->%*], ['snap1'], 'snapshot information');
+
+ $res = flow($fake, sub { [$PLUGIN->volume_size_info(scfg(), 'st', 'vm-100-disk-0', 7)] });
+ is_deeply($res->{result}, [1073741824, 'raw', 4096, undef], 'size information');
+ is($res->{calls}->[0]->{timeout}, 7, 'with the timeout of the caller');
+ $res =
+ flow($fake, sub { scalar($PLUGIN->volume_size_info(scfg(), 'st', 'vm-100-disk-0')) });
+ is($res->{result}, 1073741824, 'the size alone in scalar context');
+
+ # Snapshot names are validated before zfs reads '%' and ',' in them as a
+ # range and a list, and the pool name wherever a call uses it.
+ for my $case (
+ ['volume_snapshot', 'a b'],
+ ['volume_snapshot_delete', 'snap1%'],
+ ['volume_rollback_is_possible', 'snap1,snap2'],
+ ) {
+ my ($method, $snap) = $case->@*;
+ $res = refused(
+ $fake,
+ sub { $PLUGIN->$method(scfg(), 'st', 'vm-100-disk-0', $snap) },
+ qr/\Ainvalid snapshot name\n\z/,
+ "$method with the snapshot name '$snap'",
+ );
+ is(scalar($res->{calls}->@*), 0, 'locally');
+ }
+ my $bad_pool = scfg(pool => '-rH');
+ for my $case (
+ ['list_images', sub { $PLUGIN->list_images('st', $bad_pool) }],
+ [
+ 'volume_size_info',
+ sub { $PLUGIN->volume_size_info($bad_pool, 'st', 'vm-100-disk-0') },
+ ],
+ [
+ 'volume_snapshot_info',
+ sub { $PLUGIN->volume_snapshot_info($bad_pool, 'st', 'vm-100-disk-0') },
+ ],
+ [
+ 'volume_snapshot',
+ sub { $PLUGIN->volume_snapshot($bad_pool, 'st', 'vm-100-disk-0', 'snap2') },
+ ],
+ ) {
+ $res = refused(
+ $fake,
+ $case->[1],
+ qr/\Ainvalid ZFS pool name\n\z/,
+ "$case->[0] with an invalid pool name",
+ );
+ is(scalar($res->{calls}->@*), 0, 'locally');
+ }
+ my @warnings;
+ {
+ local $SIG{__WARN__} = sub($warning) { push @warnings, $warning };
+ $res = flow($fake, sub { [$PLUGIN->status('st', $bad_pool)] });
+ }
+ is_deeply(
+ [$res->{result}, $res->{calls}, \@warnings],
+ [[0, 0, 0, 0], [], ["storage 'st': invalid ZFS pool name\n"]],
+ 'status with an invalid pool name is inactive, locally',
+ );
+
+ # The plugin creates zvols only.
+ for my $case (
+ [
+ 'volume_snapshot',
+ sub { $PLUGIN->volume_snapshot(scfg(), 'st', 'subvol-100-disk-0', 's') },
+ ],
+ [
+ 'volume_size_info',
+ sub { $PLUGIN->volume_size_info(scfg(), 'st', 'subvol-100-disk-0') },
+ ],
+ ) {
+ $res = refused(
+ $fake,
+ $case->[1],
+ qr/\A$case->[0] requires a ZFS volume\n\z/,
+ "$case->[0] of a subvolume",
+ );
+ is(scalar($res->{calls}->@*), 0, 'locally');
+ }
+};
+
+subtest 'lock ownership' => sub {
+ my $fake = lifecycle_fake();
+ pipe(my $reader, my $writer) or die "pipe: $!\n";
+ my $child;
+ $fake->{before_call} = sub($f, $call) {
+ return if $child || $call->{op} ne 'create zvol';
+ $child = fork() // die "fork: $!\n";
+ return if $child;
+ close($reader);
+ my $res = flow(
+ $f, sub { $PLUGIN->volume_resize(scfg(), 'st', 'vm-100-disk-0', 2 * 1024**3, 0) },
+ );
+ my $locked = grep { $_->{pid} == $$ } $res->{locks}->@*;
+ my @counts = ($locked, scalar($res->{nested}->@*), scalar($res->{calls}->@*));
+ print {$writer} "@counts\n";
+ close($writer);
+ POSIX::_exit(0);
+ };
+ my $res = flow($fake, sub { $PLUGIN->alloc_image('st', scfg(), 200, 'raw', undef, 1024) });
+ close($writer);
+ my $line = <$reader>;
+ waitpid($child, 0);
+ is($res->{error}, '', 'the parent keeps its lock');
+ is($line, "1 1 0\n", 'a child requests the lock itself, waits and changes nothing');
+
+ local $QUORATE = 0;
+ $fake = lifecycle_fake();
+ for my $action (qw(alloc free rollback template resize remove)) {
+ $res = flow($fake, $ACT{$action});
+ like($res->{error}, qr/cluster not quorate/, "$action needs quorum");
+ ok(!$res->{locks}->@* && !changes($res), 'and fails before the lock');
+ }
+};
+
+subtest 'target call timeouts' => sub {
+ my ($fake, $res) = run_on('alloc', after_call => sub($f, $call) { $NOW += 100 });
+ is($res->{error}, '', 'slow target calls do not end an operation');
+ is_deeply(
+ [map { $_->{timeout} } grep { $_->{locked} } $res->{calls}->@*],
+ [15, 60, 60, 15, 30, 15],
+ 'reads take up to 15 s, zfs changes 60 s and configfs changes 30 s',
+ );
+
+ # in a worker, a zfs change may take an hour, like in the other ZFS plugins
+ my $rpcenv_mock = Test::MockModule->new('PVE::RPCEnvironment');
+ $rpcenv_mock->redefine(is_worker => sub(@args) { return 1 });
+ my %timeouts;
+ for my $action (qw(alloc template resize rollback free)) {
+ (undef, $res) = run_on($action);
+ $timeouts{ $_->{op} } = $_->{timeout} for $res->{calls}->@*;
+ }
+ is_deeply(
+ [
+ @timeouts{
+ 'reserve namespace ID',
+ 'create zvol',
+ 'rename zvol',
+ 'create template',
+ 'resize zvol',
+ 'rollback zvol',
+ 'restore namespace',
+ 'destroy zvol',
+ },
+ ],
+ [(3600) x 8],
+ 'every zfs change',
+ );
+ $rpcenv_mock->unmock_all();
+};
+
+# ---------------------------------------------------------------------------
+# Fault sweep
+# ---------------------------------------------------------------------------
+
+# The goals of the swept flows. They only read the state: a lookup that
+# created a missing namespace would change the outcome of the next check.
+sub exported_ns($m, $nsid) {
+ my $subsys = $m->{subsystems}->{$NQN} // return undef;
+ return $subsys->{ns}->{$nsid};
+}
+
+sub template_done($m, $res) {
+ my $ds = owned_volumes($m)->{'tank/base-101-disk-0'} // return 'template missing';
+ my $ns = exported_ns($m, 2) // return 'template not exported';
+ return 'template not exported' if $ns->{device_path} ne '/dev/zvol/tank/base-101-disk-0';
+ return $m->{snaps}->{'tank/base-101-disk-0@__base__'} ? () : 'base snapshot missing';
+}
+
+sub new_volume_done($name) {
+ return sub($m, $res) {
+ my $owned = owned_volumes($m)->{"tank/$name"} // return "$name missing";
+ my $ns = exported_ns($m, $owned->[0]) // return "$name not exported";
+ return () if $ns->{enable} eq '1' && $ns->{device_uuid} eq $owned->[1];
+ return "$name not exported";
+ };
+}
+
+sub removal_goal($m) {
+ my @bad;
+ push @bad, 'subsystem left' if $m->{subsystems}->{$NQN};
+ push @bad, 'orphan host left' if $m->{hosts}->{ $HOSTS[1] };
+ push @bad, 'shared host removed' if !$m->{hosts}->{ $HOSTS[0] };
+ push @bad, 'port removed' if !$m->{ports}->{1} || !$m->{ports}->{2};
+ return @bad;
+}
+
+subtest 'fault sweep' => sub {
+ sweep(
+ 'create',
+ {
+ setup => \&lifecycle_fake,
+ lost_replies => 1,
+ action => $ACT{alloc},
+ done => new_volume_done('vm-200-disk-0'),
+ },
+ );
+ sweep(
+ 'clone',
+ {
+ setup => \&lifecycle_fake,
+ lost_replies => 1,
+ action => $ACT{clone},
+ done => new_volume_done('vm-201-disk-0'),
+ },
+ );
+ sweep(
+ 'destroy',
+ {
+ setup => \&lifecycle_fake,
+ action => $ACT{free},
+ may_vanish => 'tank/vm-101-disk-0',
+ done => sub($m, $res) { $m->{ds}->{'tank/vm-101-disk-0'} ? 'volume left' : () },
+ },
+ );
+ sweep(
+ 'rollback',
+ {
+ setup => \&lifecycle_fake,
+ action => $ACT{rollback},
+ done => sub($m, $res) {
+ my $ns = exported_ns($m, 1) // return 'not exported';
+ return $ns->{enable} eq '1' ? () : 'not exported';
+ },
+ },
+ );
+ sweep(
+ 'template',
+ {
+ setup => \&lifecycle_fake,
+ action => $ACT{template},
+ renames => { 'tank/vm-101-disk-0' => 'tank/base-101-disk-0' },
+ done => \&template_done,
+ },
+ );
+ sweep(
+ 'resize',
+ {
+ setup => \&lifecycle_fake,
+ action => $ACT{resize},
+ done => sub($m, $res) {
+ my $ds = $m->{ds}->{'tank/vm-100-disk-0'} // return 'volume missing';
+ return 'not resized' if $ds->{volsize} != 2 * 1024**3;
+ return $res->{fake}->{revalidated}->{"$NQN/1"} ? () : 'not revalidated';
+ },
+ },
+ );
+ sweep(
+ 'activation after a configfs loss',
+ {
+ setup => sub () { lifecycle_fake()->reboot(1) },
+ action => $ACT{activate},
+ done => sub($m, $res) { () },
+ },
+ );
+ sweep(
+ 'target removal',
+ {
+ setup => \&removal_fake,
+ action => $ACT{remove},
+ retry => $ACT{remove},
+ goal => \&removal_goal,
+ teardown => 1,
+ done => sub($m, $res) { $m->{subsystems}->{$NQN} ? 'subsystem left' : () },
+ },
+ );
+};
+
+# ---------------------------------------------------------------------------
+# Two storages on one target, serialized by the lock mock
+# ---------------------------------------------------------------------------
+
+subtest 'two storages on one target' => sub {
+ my $nqn_b = 'nqn.2026-01.com.example:zfsnvme-b';
+ my $scfg_a = scfg(pool => 'tank/a');
+ my $scfg_b = scfg(pool => 'tank/b', subsysnqn => $nqn_b);
+ my $new = sub () { FakeTarget->new(pools => [qw(tank tank/a tank/b)]) };
+
+ # B, with another key, takes the lock first, between A's lockless read
+ # and A's locked read
+ my $fake = $new->();
+ my ($res, $b_res);
+ {
+ local $LOCK_HOOK = sub($name) {
+ $b_res = flow($fake, sub { activate($scfg_b, $KEY_B) });
+ };
+ $res = flow($fake, sub { activate($scfg_a, $KEY) });
+ }
+ is($b_res->{error}, '', 'B configures the target first');
+ like($res->{error}, qr/in-use DH-HMAC-CHAP key/, 'A is refused by its locked read');
+ ok(!$fake->{m}->{subsystems}->{$NQN}, 'without creating anything');
+ is_deeply(
+ [map { $fake->{m}->{hosts}->{$_}->{key} } @HOSTS],
+ [$KEY_B, $KEY_B],
+ "B's key is kept",
+ );
+
+ # (a) a target restart between the verify read and the publish
+ for my $loaded (0, 1) {
+ $fake = FakeTarget->new(pools => ['tank']);
+ my $restarted = 0;
+ my @online;
+ my $ctx =
+ { nqn => $NQN, pool => 'tank', hosts => [@HOSTS], key => $KEY, port_ids => [] };
+ $ctx->{foreign} = foreign_view($fake->{m}, [], $NQN, [@HOSTS]);
+ $fake->{before_call} = sub($f, $call) {
+ $f->reboot($loaded) if $call->{op} =~ /\Alink / && !$restarted++;
+ };
+ $fake->{after_call} = sub($f, $call) { push @online, online_violations($f, $ctx) };
+ $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/cannot publish NVMe subsystem '\Q$NQN\E'/,
+ 'a restart before the publish fails it',
+ );
+ ok(!grep({ $_->{links}->%* } values $fake->{m}->{ports}->%*), 'nothing is linked');
+ $fake->{before_call} = undef;
+ $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'the next activation restores the target');
+ is_deeply(\@online, [], 'never published before the ACLs and keys');
+ ok(
+ $fake->{m}->{ports}->{1}->{links}->{$NQN}
+ && $fake->{m}->{ports}->{2}->{links}->{$NQN},
+ 'and publishes it',
+ );
+ }
+
+ # ports are shared, whoever creates them
+ $fake = $new->();
+ {
+ local $LOCK_HOOK = sub($name) {
+ $b_res = flow($fake, sub { activate($scfg_b, $KEY) });
+ };
+ $res = flow($fake, sub { activate($scfg_a, $KEY) });
+ }
+ ok(!$res->{error} && !$b_res->{error}, 'two storages with one key on the same portals');
+ is_deeply(
+ [sort map { $_->{attr}->{addr_traddr} } values $fake->{m}->{ports}->%*],
+ ['192.0.2.21', '192.0.2.22'],
+ 'share one port per address',
+ );
+ ok(
+ !grep({ !($_->{links}->{$NQN} && $_->{links}->{$nqn_b}) }
+ values $fake->{m}->{ports}->%*),
+ 'both subsystems are published on both',
+ );
+
+ # lifecycle operations of both storages
+ my ($a_vol, $b_vol);
+ {
+ local $LOCK_HOOK = sub($name) {
+ $b_vol = flow(
+ $fake, sub { $PLUGIN->alloc_image('b', $scfg_b, 300, 'raw', undef, 1024) },
+ );
+ };
+ $a_vol =
+ flow($fake, sub { $PLUGIN->alloc_image('a', $scfg_a, 300, 'raw', undef, 1024) });
+ }
+ is_deeply(
+ [$a_vol->{result}, $b_vol->{result}],
+ ['vm-300-disk-0', 'vm-300-disk-0'],
+ 'volumes in both pools',
+ );
+ is_deeply(
+ [
+ sort keys $fake->{m}->{subsystems}->{$NQN}->{ns}->%*,
+ sort keys $fake->{m}->{subsystems}->{$nqn_b}->{ns}->%*,
+ ],
+ [1, 1],
+ 'with independent namespace IDs',
+ );
+};
+
+# ---------------------------------------------------------------------------
+# Target details
+# ---------------------------------------------------------------------------
+
+subtest 'each port is published on its own' => sub {
+ my $fake = FakeTarget->new(pools => ['tank'], unbindable => { 2 => 1 });
+ my $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'a port that cannot bind its address');
+ like(
+ join("\n", $res->{warnings}->@*),
+ qr/cannot publish NVMe subsystem '\Q$NQN\E' on port 2: .*Cannot assign requested address/,
+ 'only warns',
+ );
+ ok(
+ $fake->{m}->{ports}->{1}->{links}->{$NQN} && !$fake->{m}->{ports}->{2}->{links}->{$NQN},
+ 'while the other port serves the subsystem',
+ );
+ $res = flow($fake, $ACT{activate});
+ ok(grep({ $_ eq 'link NVMe subsystem on port 2' } ops($res)->@*), 'and is retried');
+
+ $fake = FakeTarget->new(pools => ['tank'], unbindable => { 1 => 1, 2 => 1 });
+ $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/\Acannot publish NVMe subsystem '\Q$NQN\E': ln: .*Cannot assign requested address\n\z/,
+ 'without any port the activation fails',
+ );
+};
+
+subtest 'UUIDs are compared in lower case' => sub {
+ my $upper = uc($U{9} =~ tr/9/a/r);
+ my $lower = lc($upper);
+ is(
+ inventory(@POOL, zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $upper))->{volumes}
+ ->{'tank/vm-100-disk-0'}->{uuid},
+ $lower,
+ 'the inventory normalizes the UUID',
+ );
+ my $dup = inventory(
+ @POOL,
+ zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $upper),
+ zfs_rows('tank/vm-101-disk-0', 'volume', $NQN, 2, $lower),
+ );
+ eval { nv('_nvmet_owned_identity', $dup, $NQN, 'tank/vm-100-disk-0') };
+ like($@, qr/duplicate NVMe identity/, 'a UUID that differs only in case is a duplicate');
+
+ my $fake = target_fake();
+ $fake->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $upper]);
+ my $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'the volume is exported');
+ ok(exported($fake, 1, $lower, '/dev/zvol/tank/vm-100-disk-0'), 'under its UUID');
+ $res = flow($fake, $ACT{activate});
+ is_deeply(ops($res), ['read target state'], 'which then is converged');
+};
+
+subtest 'removing the storage is best effort' => sub {
+ my $file_mock = Test::MockModule->new('PVE::File');
+ $file_mock->redefine(
+ dir_glob_foreach => sub($dir, $regex, $func) {
+ $func->('nvme7') if $dir eq '/sys/class/nvme';
+ },
+ );
+ local %FILES = (%FILES, '/sys/class/nvme/nvme7/subsysnqn' => $NQN);
+ my $remove = sub($fake) {
+ local @UNLINKED = ();
+ my $res = flow($fake, sub { $PLUGIN->on_delete_hook('st', scfg()) });
+ $res->{unlinked} = [sort @UNLINKED];
+ $res->{disconnects} =
+ scalar(grep { $_->[0] eq '/sys/class/nvme/nvme7/delete_controller' }
+ $res->{sysfs_writes}->@*);
+ return $res;
+ };
+
+ my $fake = lifecycle_fake();
+ my $before = dclone($fake->{m});
+ my $res = $remove->($fake);
+ is($res->{error}, '', 'a storage that owns volumes can be removed');
+ my $owned = "refusing to delete NVMe subsystem '$NQN': owned ZFS volume"
+ . " 'tank/base-102-disk-0' exists";
+ like(
+ join("\n", $res->{warnings}->@*),
+ qr/keeping the NVMe target configuration of storage 'st': \Q$owned\E/,
+ 'its volumes and subsystem are kept',
+ );
+ ok(!changes($res) && same($before, $fake->{m}), 'the target is untouched');
+ is_deeply($res->{unlinked}, [secret_file('st')], 'the key file is removed');
+ is($res->{disconnects}, 1, 'the local paths are disconnected');
+
+ $fake = removal_fake();
+ local $FILES{ secret_file('st') } = $KEY;
+ my $key_at_first_call;
+ $fake->{before_call} =
+ sub($f, $call) { $key_at_first_call //= $FILES{ secret_file('st') } };
+ $res = $remove->($fake);
+ is($res->{error}, '', 'an empty storage is removed');
+ ok(
+ !$fake->{m}->{subsystems}->{$NQN} && !$fake->{m}->{hosts}->{ $HOSTS[1] },
+ 'with its subsystem and orphan hosts',
+ );
+ ok(scalar($res->{calls}->@*) && !defined($key_at_first_call), 'after its key is removed');
+ $fake->{before_call} = undef;
+
+ # Another node read the key before the removal, and its activation waited
+ # for the target lock until the removal released it.
+ $res =
+ flow($fake, sub { nv('_nvmet_activate_target', 'st', scfg(), $PORTALS, [@HOSTS], $KEY) });
+ is($res->{error}, "storage 'st' is being removed or its key changed\n",
+ 'a late activation');
+ ok(
+ !changes($res)
+ && !$fake->{m}->{subsystems}->{$NQN}
+ && !$fake->{m}->{hosts}->{ $HOSTS[1] },
+ 'does not restore the target',
+ );
+
+ $plugin_mock->redefine(
+ _namespace_openers => sub($nqn) { return ['qemu (PID 7, /dev/nvme0n1p1)'] });
+ $fake = removal_fake();
+ $res = $remove->($fake);
+ is($res->{error}, '', 'a storage with open namespaces can be removed');
+ like(
+ $res->{warnings}->[0],
+ qr/not disconnecting NVMe storage 'st': .*in use by qemu \(PID 7, \/dev\/nvme0n1p1/,
+ 'without disconnecting',
+ );
+ is($res->{disconnects}, 0, 'the paths stay connected');
+ is_deeply($res->{unlinked}, [secret_file('st')], 'and its key file is removed');
+ $plugin_mock->redefine(_namespace_openers => sub($nqn) { return [] });
+};
+
+# ---------------------------------------------------------------------------
+# Renderer
+# ---------------------------------------------------------------------------
+
+my $INVENTORY_TEXT = 'zfs get -H -p -d 1 -t filesystem,volume -o name,property,value,source'
+ . ' type,proxmox:nvme-subsys,proxmox:nvme-nsid,proxmox:nvme-uuid,proxmox:nvme-last-nsid tank';
+my $MARKER_TEXT = q{printf '%s\n' ZFSNVME-CONFIGFS};
+my $CONFIGFS_TEXT =
+ q{env 'LC_ALL=C' find /sys/kernel/config/nvmet}
+ . q{ '(' -path '/sys/kernel/config/nvmet/subsystems/*/passthru'}
+ . q{ -o -path '/sys/kernel/config/nvmet/ports/*/ana_groups'}
+ . q{ -o -path '/sys/kernel/config/nvmet/ports/*/referrals' ')' -type d -prune}
+ . q{ -o -type d -exec printf 'D %s\n' '{}' +}
+ . q{ -o -type l -exec printf 'L %s\n' '{}' +}
+ . q{ -o -type f '(' -name enable -o -name device_path -o -name device_uuid -o -name buffered_io}
+ . q{ -o -name attr_model -o -name attr_serial -o -name attr_allow_any_host}
+ . q{ -o -name addr_trtype -o -name addr_adrfam -o -name addr_traddr -o -name addr_trsvcid ')'}
+ . q{ -exec grep '' /dev/null '{}' +};
+my $CONFIGFS_KEYS_TEXT =
+ $CONFIGFS_TEXT
+ . q{ -o -type f '('}
+ . join(' -o', map { " -path $ROOT/hosts/$_/dhchap_key" } @HOSTS)
+ . q{ ')' -exec sha256sum '{}' +};
+my $STATE_TEXT = "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_TEXT";
+my $LOCKED_STATE_TEXT = "modprobe nvmet_tcp && $STATE_TEXT";
+
+sub w_text($path, $value) {
+ return "printf '%s\\n' $value > $path";
+}
+
+sub build_text($nsid, $uuid, $dev) {
+ my $ns = "$S/namespaces/$nsid";
+ return join(
+ ' && ',
+ "test -b $dev", "mkdir $ns",
+ w_text("$ns/device_path", $dev),
+ w_text("$ns/device_uuid", $uuid),
+ w_text("$ns/buffered_io", 0),
+ w_text("$ns/enable", 1),
+ );
+}
+
+sub rendered($res) {
+ return [map { $_->{rendered} } $res->{calls}->@*];
+}
+
+subtest 'golden commands' => sub {
+ my @H = map { "$ROOT/hosts/$_" } @HOSTS;
+ my $serial = 'PVEZFS' . substr(sha256_hex($NQN), 0, 14);
+ my $port = sub($id, $address) {
+ my $P = "$ROOT/ports/$id";
+ return join(
+ ' && ',
+ "mkdir $P",
+ w_text("$P/addr_trtype", 'tcp'),
+ w_text("$P/addr_adrfam", 'ipv4'),
+ w_text("$P/addr_traddr", $address),
+ w_text("$P/addr_trsvcid", 4420),
+ );
+ };
+ my $link = sub($id) {
+ return join(
+ ' && ',
+ "grep -qx 0 $S/attr_allow_any_host",
+ (map { "test -L $S/allowed_hosts/$_" } @HOSTS),
+ "ln -s $S $ROOT/ports/$id/subsystems/$NQN",
+ );
+ };
+
+ my $fake = FakeTarget->new(pools => ['tank']);
+ $fake->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $U{1}]);
+ is_deeply(
+ rendered(flow($fake, $ACT{activate})),
+ [
+ "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+ "modprobe nvmet_tcp && $INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+ join(
+ ' && ',
+ "mkdir $S",
+ w_text("$S/attr_model", q{'Proxmox ZFS NVMe'}),
+ w_text("$S/attr_serial", $serial),
+ w_text("$S/attr_allow_any_host", 0),
+ $port->(1, '192.0.2.21'),
+ $port->(2, '192.0.2.22'),
+ "mkdir $H[0]",
+ "mkdir $H[1]",
+ "chmod 0600 $H[0]/dhchap_key $H[0]/dhchap_ctrl_key $H[1]/dhchap_key"
+ . " $H[1]/dhchap_ctrl_key",
+ "dd ibs=4096 obs=8192 2>/dev/null | tee $H[0]/dhchap_key $H[1]/dhchap_key"
+ . ' >/dev/null',
+ "ln -s $H[0] $S/allowed_hosts/$HOSTS[0]",
+ "ln -s $H[1] $S/allowed_hosts/$HOSTS[1]",
+ build_text(1, $U{1}, '/dev/zvol/tank/vm-100-disk-0'),
+ ),
+ "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+ $link->(1),
+ $link->(2),
+ ],
+ 'read, configure with a key from stdin, verify and publish',
+ );
+ $fake = lifecycle_fake();
+ is_deeply(
+ rendered(flow($fake, sub { $PLUGIN->path(scfg(), 'vm-100-disk-0', 'st') })),
+ [$INVENTORY_TEXT],
+ 'the ZFS inventory',
+ );
+ my $res = flow($fake, sub { $PLUGIN->alloc_image('st', scfg(), 200, 'raw', undef, 1024) });
+ my $uuid = $fake->{m}->{ds}->{'tank/vm-200-disk-0'}->{props}->{'proxmox:nvme-uuid'};
+ is_deeply(
+ rendered($res),
+ [
+ 'zfs list -o name,volsize,origin,type -t volume,filesystem -d1 -Hp tank',
+ $LOCKED_STATE_TEXT,
+ "zfs set 'proxmox:nvme-last-nsid=4' tank",
+ "zfs create -s -b 16k -o 'proxmox:nvme-subsys=$NQN' -o 'proxmox:nvme-nsid=4'"
+ . " -o 'proxmox:nvme-uuid=$uuid' -V 1024k tank/vm-200-disk-0",
+ 'test -b /dev/zvol/tank/vm-200-disk-0',
+ build_text(4, $uuid, '/dev/zvol/tank/vm-200-disk-0'),
+ $STATE_TEXT,
+ ],
+ 'read, reserve, create, wait, export and verify',
+ );
+ is_deeply(
+ rendered(flow(
+ $fake,
+ sub { $PLUGIN->volume_resize(scfg(), 'st', 'vm-200-disk-0', 2 * 1024**3, 0) },
+ )),
+ [
+ $LOCKED_STATE_TEXT,
+ "zfs set 'volsize=2097152k' tank/vm-200-disk-0 && "
+ . w_text("$S/namespaces/4/revalidate_size", 1),
+ ],
+ 'read, then resize and revalidate',
+ );
+ is_deeply(
+ rendered(flow($fake, sub { $PLUGIN->free_image('st', scfg(), 'vm-101-disk-0') })),
+ [
+ $LOCKED_STATE_TEXT,
+ join(
+ ' && ',
+ w_text("$S/namespaces/2/enable", 0),
+ "rmdir $S/namespaces/2",
+ 'zfs destroy -r tank/vm-101-disk-0',
+ ),
+ ],
+ 'unexport and destroy',
+ );
+ is_deeply(
+ rendered(flow(
+ $fake,
+ sub { $PLUGIN->volume_snapshot_rollback(scfg(), 'st', 'vm-100-disk-0', 'snap1') },
+ )),
+ [
+ $LOCKED_STATE_TEXT,
+ join(' && ',
+ w_text("$S/namespaces/1/enable", 0),
+ "rmdir $S/namespaces/1",
+ 'zfs rollback tank/vm-100-disk-0@snap1',
+ "zfs set 'proxmox:nvme-subsys=$NQN' 'proxmox:nvme-nsid=1'"
+ . " 'proxmox:nvme-uuid=$U{1}' tank/vm-100-disk-0"),
+ 'test -b /dev/zvol/tank/vm-100-disk-0',
+ build_text(1, $U{1}, '/dev/zvol/tank/vm-100-disk-0'),
+ ],
+ 'unexport, roll back, write the identity and export again',
+ );
+ is_deeply(
+ rendered(flow($fake, sub { $PLUGIN->create_base('st', scfg(), 'vm-100-disk-0') })),
+ [
+ $LOCKED_STATE_TEXT,
+ join(' && ',
+ w_text("$S/namespaces/1/enable", 0),
+ "rmdir $S/namespaces/1",
+ 'zfs rename tank/vm-100-disk-0 tank/base-100-disk-0'),
+ 'test -b /dev/zvol/tank/base-100-disk-0',
+ build_text(1, $U{1}, '/dev/zvol/tank/base-100-disk-0')
+ . ' && zfs snapshot tank/base-100-disk-0@__base__',
+ ],
+ 'unexport, rename, export and snapshot',
+ );
+ $res = flow($fake, sub { $PLUGIN->clone_image(scfg(), 'st', 'base-102-disk-0', 201) });
+ $uuid = $fake->{m}->{ds}->{'tank/vm-201-disk-0'}->{props}->{'proxmox:nvme-uuid'};
+ is_deeply(
+ [map { $_->{rendered} } $res->{calls}->@[2, 3]],
+ [
+ "zfs set 'proxmox:nvme-last-nsid=5' tank",
+ "zfs clone -o 'proxmox:nvme-subsys=$NQN' -o 'proxmox:nvme-nsid=5'"
+ . " -o 'proxmox:nvme-uuid=$uuid' tank/base-102-disk-0\@__base__ tank/vm-201-disk-0",
+ ],
+ 'reserve and clone',
+ );
+
+ $fake = lifecycle_fake(
+ step_fault => sub($s, $c) { step_is($s, 'rmdir', "$S/namespaces/2") ? 'busy' : undef },
+ );
+ $res = flow($fake, sub { $PLUGIN->free_image('st', scfg(), 'vm-101-disk-0') });
+ is(
+ $res->{calls}->[-1]->{rendered},
+ 'test -b /dev/zvol/tank/vm-101-disk-0 && ' . w_text("$S/namespaces/2/enable", 1),
+ 'enable again',
+ );
+
+ $fake = removal_fake();
+ is_deeply(
+ rendered(flow($fake, sub { nv('_nvmet_delete_target', scfg()) })),
+ [
+ $LOCKED_STATE_TEXT,
+ "rm $ROOT/ports/1/subsystems/$NQN $ROOT/ports/2/subsystems/$NQN"
+ . " $S/allowed_hosts/$HOSTS[0] $S/allowed_hosts/$HOSTS[1] && rmdir $S",
+ $STATE_TEXT,
+ "rmdir $H[1]",
+ ],
+ 'teardown and orphan hosts',
+ );
+
+ $fake = FakeTarget->new(pools => ['tank']);
+ $fake->{m}->{mounted} = 0;
+ $res = flow($fake, $ACT{activate});
+ ok(grep({ $_ eq 'cat /proc/mounts' } rendered($res)->@*), 'the mount table');
+ ok(
+ grep({ $_ eq 'mount -t configfs none /sys/kernel/config' } rendered($res)->@*),
+ 'the mount',
+ );
+
+ $fake = target_fake();
+ $fake->add_port(5, '192.0.2.99', 4420, links => [$NQN]);
+ is(
+ rendered(flow($fake, $ACT{activate}))->[-1],
+ "rm $ROOT/ports/5/subsystems/$NQN",
+ 'unlink',
+ );
+
+ $fake = lifecycle_fake();
+ $fake->{m}->{subsystems}->{$NQN}->{attr}->{attr_allow_any_host} = '1';
+ $fake->{m}->{subsystems}->{$NQN}->{acl} = {};
+ is(
+ rendered(flow($fake, $ACT{activate}))->[2],
+ join(
+ ' && ',
+ w_text("$S/attr_allow_any_host", 0),
+ map { "ln -s $ROOT/hosts/$_ $S/allowed_hosts/$_" } @HOSTS,
+ ),
+ 'allow_any_host before the ACLs',
+ );
+
+ $fake = lifecycle_fake();
+ my @generic = (
+ [sub { [$PLUGIN->status('st', scfg())] }, 'zfs get -o value -Hp available,used tank'],
+ [
+ sub { $PLUGIN->volume_snapshot_info(scfg(), 'st', 'vm-100-disk-0') },
+ 'zfs list -Hp -r -t snapshot -o name,guid,creation tank/vm-100-disk-0',
+ ],
+ [
+ sub { $PLUGIN->volume_rollback_is_possible(scfg(), 'st', 'vm-100-disk-0', 'snap1') }
+ ,
+ 'zfs list -H -r -t snapshot -o name -s creation tank/vm-100-disk-0',
+ ],
+ [
+ sub { [$PLUGIN->volume_size_info(scfg(), 'st', 'vm-100-disk-0')] },
+ 'zfs get -o value -Hp volsize,usedbydataset tank/vm-100-disk-0',
+ ],
+ [
+ sub { $PLUGIN->volume_snapshot(scfg(), 'st', 'vm-100-disk-0', 'snap2') },
+ 'zfs snapshot tank/vm-100-disk-0@snap2',
+ ],
+ [
+ sub { $PLUGIN->volume_snapshot_delete(scfg(), 'st', 'vm-100-disk-0', 'snap2') },
+ 'zfs destroy tank/vm-100-disk-0@snap2',
+ ],
+ );
+
+ for my $case (@generic) {
+ is(rendered(flow($fake, $case->[0]))->[0], $case->[1], $case->[1]);
+ }
+ is(
+ rendered(flow($fake, sub { $PLUGIN->list_images('st', scfg()) }))->[1],
+ 'zfs get -H -d 1 -o name,value,source proxmox:nvme-subsys tank',
+ 'the ownership query',
+ );
+};
+
+sub sh($command, $input = undef) {
+ my $err = gensym;
+ my $pid = open3(my $in, my $out, $err, '/bin/sh', '-c', $command);
+ print {$in} $input if defined($input);
+ close($in);
+ my $stdout = do { local $/; <$out> }
+ // '';
+ my $stderr = do { local $/; <$err> }
+ // '';
+ waitpid($pid, 0) == $pid or die "wait for test shell: $!\n";
+ my $status = $?;
+ return ($status & 127 ? 128 + ($status & 127) : $status >> 8, $stdout, $stderr);
+}
+
+# The subtests that run rendered commands need these tools. A Debian build
+# has them, so a missing one is an error, never a silently skipped test.
+{
+ my @tools = qw(find grep sha256sum dd tee);
+ BAIL_OUT('needs /bin/sh with ' . join(', ', @tools))
+ if !-x '/bin/sh' || (sh('command -v ' . join(' ', @tools)))[0] != 0;
+}
+
+subtest 'quoting' => sub {
+ my $dir = tempdir(CLEANUP => 1);
+ for my $value (
+ 'a b',
+ q{it's},
+ "\$(touch $dir/pwned)",
+ "`touch $dir/pwned`",
+ '-n',
+ '*',
+ '%s\n',
+ q{"x"},
+ 'x;y',
+ 'a && b',
+ '|',
+ '~root',
+ "tab\there",
+ '',
+ '$HOME',
+ 'a\\b',
+ '#c',
+ ) {
+ my $file = "$dir/value";
+ my ($rc) = sh(nv('_nvmet_render', [write_step($file, $value)]));
+ is($rc . slurp($file), "0$value\n", 'a write keeps ' . ($value =~ s/\t/\\t/r));
+ my (undef, $out) = sh(nv('_nvmet_render', [['printf', '%s\n', $value]]));
+ is($out, "$value\n", 'an argument keeps ' . ($value =~ s/\t/\\t/r));
+ }
+ ok(!-e "$dir/pwned", 'no value is executed');
+};
+
+subtest 'renderer rejections' => sub {
+ for my $case (
+ ['a newline in a value', [write_step("$S/x", "a\nb")]],
+ ['a NUL in a value', [write_step("$S/x", "a\0b")]],
+ ['a CR in an argument', [['zfs', 'get', "a\rb"]]],
+ ['an undefined argument', [['zfs', 'get', undef]]],
+ ['an undefined value', [write_step("$S/x", undef)]],
+ ['a reference as argument', [['zfs', 'get', []]]],
+ ['a relative write', [write_step('x', 1)]],
+ ['a relative key path', [{ key => ['x'] }]],
+ ['an empty key step', [{ key => [] }]],
+ ['two key steps', [{ key => ['/a'] }, { key => ['/b'] }]],
+ ['bash', [['bash', '-c', 'true']]],
+ ['sh', [['sh', '-c', 'true']]],
+ ['perl', [['perl', '-e', '1']]],
+ ['an absolute command', [['/bin/rm', '/a']]],
+ ['an empty command', [[]]],
+ ['a write with extra keys', [{ write => '/a', value => 1, mode => 1 }]],
+ ['an unknown step', [{ run => '/a' }]],
+ ['a string step', ['mkdir /a']],
+ ['no steps', []],
+ ['a string', 'mkdir /a'],
+ ) {
+ eval { nv('_nvmet_render', $case->[1]) };
+ is($@, "internal error: invalid NVMe target step\n", "rejects $case->[0]");
+ }
+};
+
+subtest 'the rendered chains on a configfs stand-in' => sub {
+ my $dir = tempdir(CLEANUP => 1);
+ my $root = "$dir/nvmet";
+ mkdir($_) or die "mkdir $_: $!\n" for $root, map { "$root/$_" } qw(hosts ports subsystems);
+ my $device = "$dir/device";
+ symlink('/dev/null', $device) or die "symlink: $!\n";
+ my $box = sub($path) { $path =~ s{\A\Q$ROOT\E(?=/|\z)}{$root}r };
+ my $kind = sub($path) {
+ my $rel = substr($path, length($root) + 1);
+ return 'subsystem' if $rel =~ m{\Asubsystems/[^/]+\z};
+ return 'namespace' if $rel =~ m{\Asubsystems/[^/]+/namespaces/[0-9]+\z};
+ return 'port' if $rel =~ m{\Aports/[0-9]+\z};
+ return 'host' if $rel =~ m{\Ahosts/[^/]+\z};
+ die "unexpected directory $path\n";
+ };
+ my %attrs = (
+ subsystem => {
+ attr_model => 'Linux',
+ attr_serial => '0123456789abcdef',
+ attr_allow_any_host => 0,
+ },
+ namespace => {
+ enable => 0,
+ device_path => '(null)',
+ device_uuid => $U{9},
+ buffered_io => 0,
+ },
+ port => { addr_trtype => '', addr_adrfam => '', addr_traddr => '', addr_trsvcid => '' },
+ host => { dhchap_key => '', dhchap_ctrl_key => '' },
+ );
+ my %groups = (subsystem => ['namespaces', 'allowed_hosts'], port => ['subsystems']);
+ # configfs creates attributes and default groups with each directory and
+ # removes them with it; the stand-in does both with the same commands.
+ my $shim = sub($steps) {
+ my @out;
+ for my $step ($steps->@*) {
+ if (ref($step) eq 'HASH' && exists($step->{write})) {
+ push @out, write_step($box->($step->{write}), $step->{value});
+ } elsif (ref($step) eq 'HASH') {
+ push @out, { key => [map { $box->($_) } $step->{key}->@*] };
+ } elsif ($step->[0] eq 'test' && $step->[1] eq '-b') {
+ push @out, ['test', '-L', $device];
+ } elsif ($step->[0] eq 'mkdir') {
+ for my $path (map { $box->($_) } $step->@[1 .. $step->$#*]) {
+ my $type = $kind->($path);
+ push @out, ['mkdir', $path, map { "$path/$_" } ($groups{$type} // [])->@*];
+ push @out, map { write_step("$path/$_", $attrs{$type}->{$_}) }
+ sort keys $attrs{$type}->%*;
+ }
+ } elsif ($step->[0] eq 'rmdir') {
+ for my $path (map { $box->($_) } $step->@[1 .. $step->$#*]) {
+ my $type = $kind->($path);
+ push @out, ['rm', map { "$path/$_" } sort keys $attrs{$type}->%*];
+ push @out, ['rmdir', map { "$path/$_" } $groups{$type}->@*]
+ if $groups{$type};
+ push @out, ['rmdir', $path];
+ }
+ } else {
+ push @out, [map { $box->($_) } $step->@*];
+ }
+ }
+ return \@out;
+ };
+ my $run = sub($steps, $input = undef) {
+ my ($rc, undef, $err) = sh(nv('_nvmet_render', $shim->($steps)), $input);
+ return ($rc, $err);
+ };
+
+ my $capture = FakeTarget->new(pools => ['tank']);
+ flow($capture, $ACT{activate});
+ my ($find) = grep { step_is($_, 'env') } $capture->{calls}->[0]->{steps}->@*;
+ my $read = sub () {
+ my ($rc, $out, $err) = sh(nv('_nvmet_render', $shim->([$find])));
+ die "configfs read failed: $err\n" if $rc;
+ $out =~ s{\Q$root\E}{$ROOT}g;
+ return nv('_nvmet_parse_configfs', $out);
+ };
+ my $inv = inventory(@POOL, @ONE);
+ my $conf = { nqn => $NQN, portals => $PORTALS, hostnqns => [@HOSTS], keysha => $KEY_SHA };
+ my $plan = nv('_nvmet_plan_activation', $inv, $read->(), $conf);
+ my ($rc, $err) = $run->([map { $_->@* } $plan->{prepublish}->@*], "$KEY\n");
+ is($rc, 0, 'the whole configuration runs as one chain') or diag($err);
+ my $cfs = $read->();
+ is_deeply(
+ nv('_nvmet_plan_activation', $inv, $cfs, $conf)->{prepublish},
+ [],
+ 'and converges',
+ );
+ is_deeply(
+ [map { $cfs->{hosts}->{$_}->{key_sha256} } @HOSTS],
+ [$KEY_SHA, $KEY_SHA],
+ 'the digests read back equal sha256 of the key and a newline',
+ );
+ is_deeply(
+ [map { (stat("$root/hosts/$_/dhchap_key"))[2] & 07777 } @HOSTS],
+ [0600, 0600],
+ 'and the key attributes are readable by their owner only',
+ );
+
+ # Only the kernel's own groups are skipped: the ACL of another tool's
+ # subsystem named like one of them is read and protects the key.
+ my $other = "$root/subsystems/referrals";
+ mkdir($_) or die "mkdir $_: $!\n" for $other, "$other/allowed_hosts", "$other/namespaces";
+ for my $attr (keys $attrs{subsystem}->%*) {
+ open(my $fh, '>', "$other/$attr") or die "open: $!\n";
+ print {$fh} "$attrs{subsystem}->{$attr}\n";
+ close($fh);
+ }
+ symlink("$root/hosts/$HOSTS[0]", "$other/allowed_hosts/$HOSTS[0]") or die "symlink: $!\n";
+ mkdir($_)
+ or die "mkdir $_: $!\n"
+ for "$root/ports/1/referrals", "$root/ports/1/referrals/r";
+ my (undef, $raw) = sh(nv('_nvmet_render', $shim->([$find])));
+ ok(
+ $read->()->{subsystems}->{referrals}->{acl}->{ $HOSTS[0] },
+ 'a subsystem named referrals',
+ );
+ unlike($raw, qr{/ports/1/referrals}, 'while the referrals of a port are skipped');
+ unlink("$other/allowed_hosts/$HOSTS[0]", map { "$other/$_" } keys $attrs{subsystem}->%*);
+ rmdir($_)
+ or die "rmdir $_: $!\n"
+ for "$other/allowed_hosts", "$other/namespaces", $other, "$root/ports/1/referrals/r",
+ "$root/ports/1/referrals";
+
+ for my $unit (nv('_nvmet_plan_publish', $cfs, $NQN, $plan->{port_ids}, [@HOSTS])->@*) {
+ ($rc) = $run->($unit->{steps});
+ is($rc, 0, "the guarded link to port $unit->{port}");
+ }
+ is_deeply(nv('_nvmet_plan_publish', $read->(), $NQN, [1, 2], [@HOSTS]), [], 'publishes');
+
+ unlink("$root/ports/1/subsystems/$NQN", "$root/subsystems/$NQN/allowed_hosts/$HOSTS[1]");
+ my ($unit) = nv('_nvmet_plan_publish', $read->(), $NQN, [1], [@HOSTS])->@*;
+ ($rc) = $run->($unit->{steps});
+ ok($rc && !-l "$root/ports/1/subsystems/$NQN", 'the guard blocks a link without every ACL');
+ symlink("$root/hosts/$HOSTS[1]", "$root/subsystems/$NQN/allowed_hosts/$HOSTS[1]") or die;
+ ($rc) = $run->([write_step("$ROOT/subsystems/$NQN/attr_allow_any_host", 1)]);
+ ($rc) = $run->($unit->{steps});
+ ok($rc && !-l "$root/ports/1/subsystems/$NQN", 'and while any host may connect');
+ $run->([write_step("$ROOT/subsystems/$NQN/attr_allow_any_host", 0)]);
+ ($rc) = $run->($unit->{steps});
+ ok(!$rc && -l "$root/ports/1/subsystems/$NQN", 'but links once both hold');
+
+ my ($units) = nv('_nvmet_plan_unexport', $read->(), $NQN, $U{1});
+ ($rc) = $run->([map { $_->@* } $units->@*]);
+ ok(!$rc && !-e "$root/subsystems/$NQN/namespaces/1", 'the unexport chain removes it');
+ my ($teardown, $candidates) = nv(
+ '_nvmet_plan_delete_target', inventory(@POOL), $read->(), $NQN, [@HOSTS],
+ );
+ ($rc) = $run->([map { $_->@* } $teardown->@*]);
+ ok(!$rc && !-e "$root/subsystems/$NQN", 'the teardown chain removes the subsystem');
+ ($rc) = $run->([map { $_->@* } nv('_nvmet_plan_orphan_hosts', $read->(), $candidates)->@*]);
+ ok(!$rc && !-e "$root/hosts/$HOSTS[0]" && !-e "$root/hosts/$HOSTS[1]", 'and the hosts');
+ ok(-d "$root/ports/1" && -d "$root/ports/2", 'ports stay');
+};
+
+# Last: every command rendered during this test run, and every protocol
+# violation recorded (by a fake target: a key on a command line or in output,
+# a change without the lock; or a local command).
+subtest 'every rendered command is a POSIX command chain' => sub {
+ is_deeply(\@VIOLATIONS, [], 'no flow violated the target protocol');
+ my %shapes;
+ for my $command (keys %CORPUS) {
+ (my $shape = $command) =~ s/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/U/gi;
+ $shape =~ s/[0-9]+/N/g;
+ $shapes{$shape} //= $command;
+ }
+ ok(keys(%shapes) >= 40, 'the corpus covers ' . keys(%shapes) . ' command shapes');
+ my $meta = qr/[;&|<>`\$(){}\\*?\[\]~#!"]/;
+ my @bad;
+ for my $command (sort values %shapes) {
+ push @bad, "sh -n: $command" if system('/bin/sh', '-n', '-c', $command) != 0;
+ push @bad, "bash-ism: $command"
+ if $command =~ /\[\[|\$\(\(|<<<|\$'|pipefail|(?:\A|&& )(?:function|source|\.) /;
+ (my $bare = $command) =~ s/'[^']*'|\\'//g;
+ for my $segment (split / && /, $bare) {
+ next
+ if $segment =~ m{\Add\ ibs=4096\ obs=8192\ 2>/dev/null\ \|\ tee(?:\ /[^\s;&|<>]+)+
+ \ >/dev/null\z}x;
+ if ($segment =~ /\Aprintf +(\S*) +> (\S+)\z/) {
+ push @bad, "write: $segment" if "$1$2" =~ $meta;
+ next;
+ }
+ push @bad, "shell syntax: $segment" if $segment =~ $meta;
+ }
+ }
+ is_deeply(\@bad, [], 'every command is a plain POSIX command chain');
+};
+
+done_testing();
diff --git a/src/test/zfsnvme_test.pm b/src/test/zfsnvme_test.pm
new file mode 100644
index 00000000..3b311bfa
--- /dev/null
+++ b/src/test/zfsnvme_test.pm
@@ -0,0 +1,2353 @@
+package PVE::Storage::TestZFSNVMe;
+
+# Storage API and local NVMe host side of the zfsnvme plugin. The target side
+# is covered by zfsnvme_target_test.pm. Nothing here opens a connection or
+# changes the host outside a temporary directory: every probe of the local
+# host is mocked, and the children that the plugin forks for its connect and
+# delete steps 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::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, the ssh command of the runner
+# by $COMMAND; sysfs and key files are read from %FILES and listed from %DIRS,
+# block devices are %BLOCK and symbolic links %LINKS. The children of the
+# bounded host steps run inline and record their bound in @FORKS. Waits
+# advance $NOW. The host side runs no external command: only the runner
+# tests, which set $COMMAND, may reach run_command.
+# ---------------------------------------------------------------------------
+
+our ($TARGET, $COMMAND, $NOW);
+our (%FILES, %DIRS, %CONFIG, %BLOCK, %LINKS, @TARGET_CALLS, @WARNINGS, @WRITES);
+our (@SYSFS_WRITES, @GLOBS, @CONNECTS, @ACTIVATIONS, @UNLINKED, @RESTRICTED, @DELETED, @FORKS);
+our (%REFUSE, %CONNECT_STATE); # address => the connect is refused, the new controller's 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);
+ },
+);
+# A command is also recorded, in case the caller handles the error; the last
+# test checks that there was 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(_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 });
+
+# The connect child: creates a controller of the portal named in the options.
+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);
+# The deletion child: the controllers disappear from sysfs.
+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);
+my $fork_inline = sub($timeout, $code, $opts = undef) {
+ push @FORKS, $timeout;
+ my $res = $code->();
+ return wantarray ? ($res, 0) : $res;
+};
+$tools_mock->redefine(run_fork_with_timeout => $fork_inline);
+$file_mock->redefine(
+ dir_glob_foreach => sub($dir, $regex, $func) {
+ push @GLOBS, [$dir, $regex];
+ 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} } });
+
+# A local controller of $NQN, as nvme-core shows it in sysfs.
+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 = @GLOBS = ();
+ @RESTRICTED = @UNLINKED = @DELETED = @FORKS = ();
+ $NOW += 61; # a new minute: no storage is in its slow-path backoff
+ return;
+}
+
+# ---------------------------------------------------------------------------
+# Volume names and features (same formats as the other ZFS plugins)
+# ---------------------------------------------------------------------------
+
+# [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', ['images', 'vm-100-disk-0', 100, undef, undef, '', 'raw']],
+ ['base-100-disk-0', ['images', 'base-100-disk-0', 100, undef, undef, 1, 'raw']],
+ ['subvol-100-disk-0', ['images', 'subvol-100-disk-0', 100, undef, undef, '', 'subvol']],
+ ['basevol-100-disk-0', ['images', 'basevol-100-disk-0', 100, undef, undef, 1, 'subvol']],
+ [
+ 'base-100-disk-0/vm-200-disk-0',
+ ['images', 'vm-200-disk-0', 200, 'base-100-disk-0', 100, '', 'raw'],
+ ],
+ [
+ 'basevol-100-disk-0/subvol-200-disk-0',
+ ['images', '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");
+}
+
+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");
+}
+
+# ---------------------------------------------------------------------------
+# Configuration
+# ---------------------------------------------------------------------------
+
+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',
+);
+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');
+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->('::ffff: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:<hash>:<base64 of the key and its little-endian CRC-32>:
+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');
+
+# ---------------------------------------------------------------------------
+# Storage hooks and secrets
+# ---------------------------------------------------------------------------
+
+{
+ 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: storages on 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');
+}
+
+# Adding and updating a storage check its listeners; 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');
+}
+
+# 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');
+}
+
+# ---------------------------------------------------------------------------
+# Volumes through the target runner
+# ---------------------------------------------------------------------------
+
+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');
+}
+
+# ---------------------------------------------------------------------------
+# The runner: one ssh argv, no Perl, no shell on the local side
+# ---------------------------------------------------------------------------
+
+{
+ 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');
+}
+
+# ---------------------------------------------------------------------------
+# The shared storage lock
+# ---------------------------------------------------------------------------
+
+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');
+};
+
+# ---------------------------------------------------------------------------
+# Local NVMe host side
+# ---------------------------------------------------------------------------
+
+# The connect options of a controller: one write to the fabrics device.
+{
+ my $portal = { address => '192.0.2.22', port => 4420, host_iface => 'ens21' };
+ my $options = sub($scfg) {
+ return nv(
+ '_fabrics_options', $scfg, $portal, $hostnqn_a, $UUID, $KEY,
+ );
+ };
+ my ($string, $names) = $options->({ subsysnqn => $NQN });
+ is(
+ $string,
+ "transport=tcp,traddr=192.0.2.22,trsvcid=4420,host_iface=ens21,nqn=$NQN,"
+ . "hostnqn=$hostnqn_a,hostid=$UUID,dhchap_secret=$KEY,keep_alive_tmo=5,"
+ . 'reconnect_delay=2,ctrl_loss_tmo=600',
+ 'the portal, the identities, the key and the default timeouts',
+ );
+ is_deeply(
+ $names,
+ [
+ qw(transport traddr trsvcid host_iface nqn hostnqn hostid dhchap_secret),
+ qw(keep_alive_tmo reconnect_delay ctrl_loss_tmo),
+ ],
+ 'with the names of the options',
+ );
+ my $tuned = {
+ subsysnqn => $NQN,
+ 'nvme-keep-alive-tmo' => 10,
+ 'nvme-reconnect-delay' => 5,
+ 'nvme-ctrl-loss-tmo' => 60,
+ 'nvme-fast-io-fail-tmo' => 15,
+ 'nvme-nr-io-queues' => 4,
+ };
+ ($string, $names) = $options->($tuned);
+ my $tail = 'keep_alive_tmo=10,reconnect_delay=5,ctrl_loss_tmo=60,'
+ . 'fast_io_fail_tmo=15,nr_io_queues=4';
+ like($string, qr/,\Q$tail\E\z/, 'the configured timeouts and queues');
+ is_deeply([$names->@[-2, -1]], ['fast_io_fail_tmo', 'nr_io_queues'], 'are named too');
+ ($string) = $options->({ $tuned->%*, 'nvme-fast-io-fail-tmo' => 0 });
+ like($string, qr/,fast_io_fail_tmo=0,/, 'a fast I/O fail timeout of 0 is a real value');
+ ($string) = $options->({ $tuned->%*, 'nvme-ctrl-loss-tmo' => -1 });
+ like($string, qr/,ctrl_loss_tmo=-1,/, 'an infinite loss timeout');
+
+ for my $value ('6 0', '60,duplicate_connect', "60\x00", '') {
+ eval { $options->({ $tuned->%*, 'nvme-ctrl-loss-tmo' => $value }) };
+ is(
+ $@,
+ "internal error: invalid NVMe connect option 'ctrl_loss_tmo'\n",
+ 'a value that would end the option early is refused without echoing it',
+ );
+ }
+}
+
+# The connect runs in a child bounded by 10 seconds. Its result and errors
+# pass through; a stopped task and a timeout have their own message.
+{
+ my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+ my $connect = sub($child) {
+ local @FORKS = ();
+ $nvme_mock->redefine(_fabrics_connect => $child);
+ my $res = eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY); };
+ my $error = $@;
+ $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+ return ($res, $error, [@FORKS]);
+ };
+ my ($res, $error, $forks) = $connect->(sub($options, $names) { return 7 });
+ is($res, 7, 'returns the instance of the new controller');
+ is_deeply($forks, [10], 'from a child bounded by 10 seconds');
+ for my $exception ("received interrupt\n", "interrupted by unexpected signal\n") {
+ (undef, $error) = $connect->(sub(@args) {
+ die $exception;
+ });
+ is($error, "received interrupt\n", 'a stopped task dies with the task marker');
+ }
+ my @warnings;
+ local $SIG{__WARN__} = sub($warning) { push @warnings, $warning };
+ $tools_mock->redefine(
+ run_fork_with_timeout => sub($timeout, $code, $opts = undef) { return (undef, 1) },
+ );
+ (undef, $error) = $connect->(sub(@args) {
+ return 7;
+ });
+ is($error, "NVMe/TCP connect did not complete within 10 seconds\n", 'a timeout');
+ $tools_mock->redefine(
+ run_fork_with_timeout => sub($timeout, $code, $opts = undef) {
+ warn "malformed JSON string\n"; # what a child that died without a result leaves
+ return (undef, 0);
+ },
+ );
+ (undef, $error) = $connect->(sub(@args) {
+ return 7;
+ });
+ is($error, "NVMe/TCP connect left no result\n", 'a child without a result');
+ is_deeply(\@warnings, [], 'without the warning of run_fork_with_timeout in the task log');
+ $tools_mock->redefine(run_fork_with_timeout => $fork_inline);
+}
+
+# The signals a stopped task can bring that are blocked while a child runs.
+my %signal = (HUP => SIGHUP, INT => SIGINT, QUIT => SIGQUIT, TERM => SIGTERM, ALRM => SIGALRM);
+
+sub blocked_signals() {
+ my $mask = POSIX::SigSet->new();
+ sigprocmask(SIG_BLOCK, POSIX::SigSet->new(), $mask) or die "sigprocmask: $!\n";
+ return join(',', grep { $mask->ismember($signal{$_}) } sort keys %signal);
+}
+
+# The child itself: a real fork under the real run_fork_with_timeout.
+subtest 'the connect child' => sub {
+ $tools_mock->unmock('run_fork_with_timeout');
+ my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+ my $connect = sub() {
+ my $res = eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY); };
+ return ($res, $@);
+ };
+ $nvme_mock->redefine(_fabrics_connect => sub(@args) { return 7 });
+ my ($res, $error) = $connect->();
+ is($res, 7, 'the result of the child reaches the parent');
+ is(blocked_signals(), '', 'and the signal mask is restored');
+ $nvme_mock->redefine(
+ _fabrics_connect => sub(@args) { die "connect failed: Connection refused\n" },
+ );
+ (undef, $error) = $connect->();
+ is($error, "connect failed: Connection refused\n", 'and so does its error');
+ is(blocked_signals(), '', 'with the signal mask restored');
+
+ # The warnings of the child go to the standard error of the task.
+ my $dir = tempdir(CLEANUP => 1);
+ $nvme_mock->redefine(_fabrics_connect => sub(@args) { warn "child warning\n"; return 7 });
+ open(my $saved, '>&', \*STDERR) or die "cannot save STDERR: $!\n";
+ open(STDERR, '>', "$dir/stderr") or die "cannot redirect STDERR: $!\n";
+ ($res, $error) = $connect->();
+ open(STDERR, '>&', $saved) or die "cannot restore STDERR: $!\n";
+ is($res, 7, 'a child that warns');
+ open(my $fh, '<', "$dir/stderr") or die "cannot read '$dir/stderr': $!\n";
+ is(join('', <$fh>), "child warning\n", 'is heard');
+ close($fh);
+
+ # A stopped task: the signal stays pending while the child runs and, once
+ # the child is reaped, the handler of the worker dies with the task marker.
+ for my $name (qw(TERM QUIT INT)) {
+ pipe(my $from_child, my $to_parent) or die "pipe: $!\n";
+ $nvme_mock->redefine(
+ _fabrics_connect => sub(@args) {
+ kill($name, getppid()) or die "kill: $!\n";
+ print {$to_parent} "$$ " . blocked_signals() . "\n";
+ close($to_parent);
+ return 7;
+ },
+ );
+ my $seen;
+ local $SIG{$name} = sub { # as in a PVE worker
+ chomp(my $report = <$from_child> // '');
+ my ($pid, $blocked) = split(/ /, $report, 2);
+ $seen = { blocked => $blocked, reaped => $pid && waitpid($pid, WNOHANG) == -1 };
+ die "received interrupt\n";
+ };
+ ($res, $error) = $connect->();
+ close($to_parent);
+ close($from_child);
+ is($error, "received interrupt\n", "$name stops the task with the task marker");
+ is(
+ $seen->{blocked},
+ 'HUP,INT,QUIT,TERM',
+ 'once the child, with the inherited mask, is done',
+ );
+ ok($seen->{reaped}, 'and reaped');
+ is(blocked_signals(), '', 'and the signal mask is restored');
+ }
+ $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+ $tools_mock->redefine(run_fork_with_timeout => $fork_inline);
+};
+
+# The body of the connect child, inline. A pseudoterminal stands in for the
+# fabrics device: a character device that answers reads with the lines the
+# test writes to the master, and passes writes to the master.
+subtest 'the connect child body' => sub {
+ my $body = $nvme_mock->original('_fabrics_connect');
+ my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+ my ($options, $names) = nv('_fabrics_options', scfg(), $portal, $hostnqn_a, $UUID, $KEY);
+ my $tokens = sub(@names) {
+ return join(',', map { "$_=%s" } @names) . "\n";
+ };
+ # a body that waits for a line the test did not write must not hang the suite
+ local $SIG{ALRM} = sub { die "the child body did not finish\n" };
+ my $run = sub() {
+ @RESTRICTED = ();
+ alarm(30);
+ my $res = eval { $body->($options, $names) };
+ alarm(0);
+ return ($res, $@);
+ };
+ my $dir = tempdir(CLEANUP => 1);
+ my $file = "$dir/file";
+ open(my $fh, '>', $file) or die "cannot create '$file': $!\n";
+ close($fh);
+ for my $case (
+ [
+ 'a missing device',
+ "$dir/missing",
+ qr/\A'\Q$dir\E\/missing' does not exist; load the nvme-tcp kernel module\n\z/,
+ ],
+ ['a regular file', $file, qr/\A'\Q$file\E' is not a character device\n\z/],
+ [
+ 'a device without the option list',
+ '/dev/null',
+ qr/\Athe running kernel does not support the NVMe connect option 'transport'\n\z/,
+ ],
+ ) {
+ my ($name, $device, $expected) = $case->@*;
+ $nvme_mock->redefine(_fabrics_device => sub () { return $device });
+ my (undef, $error) = $run->();
+ like($error, $expected, "$name is refused");
+ unlike($error, qr/\Q$KEY\E/, 'without the key in the error');
+ }
+ is(-s $file, 0, 'and nothing is written before the device is checked');
+
+ my $pty = sub() {
+ # TIOCSPTLCK and TIOCGPTN are only known for these architectures
+ return if $Config{archname} !~ m/\A(?:x86_64|i[3-6]86|aarch64|arm|riscv64)-linux/;
+ sysopen(my $master, '/dev/ptmx', O_RDWR | O_NOCTTY) or return;
+ my $zero = pack('i', 0);
+ ioctl($master, 0x40045431, $zero) or return;
+ my $number = pack('i', 0);
+ ioctl($master, 0x80045430, $number) or return;
+ my $slave = '/dev/pts/' . unpack('i', $number);
+ # keeps the line discipline: canonical reads, no echo, no translation
+ sysopen(my $keep, $slave, O_RDWR | O_NOCTTY) or return;
+ my $termios = POSIX::Termios->new();
+ $termios->getattr(fileno($keep)) or die "tcgetattr: $!\n";
+ $termios->setlflag(($termios->getlflag() & ~(ECHO | ECHONL)) | ICANON);
+ $termios->setoflag($termios->getoflag() & ~OPOST);
+ $termios->setattr(fileno($keep), TCSANOW) or die "tcsetattr: $!\n";
+ return ($master, $slave, $keep);
+ };
+ my $received = sub($master) {
+ my $readable = '';
+ vec($readable, fileno($master), 1) = 1;
+ return '' if !select($readable, undef, undef, 0.1);
+ sysread($master, my $buffer, 65536) // die "cannot read the pseudoterminal: $!\n";
+ return $buffer;
+ };
+ my ($master, $slave, $keep) = $pty->();
+ SKIP: {
+ skip 'no pseudoterminal available', 25 if !$master;
+ $nvme_mock->redefine(_fabrics_device => sub () { return $slave });
+
+ my ($res, $error);
+ for my $instance (3, 12) {
+ syswrite($master, $tokens->($names->@*, 'tls'));
+ syswrite($master, "instance=$instance,cntlid=1\n");
+ ($res, $error) = $run->();
+ is($error, '', "a connect (instance $instance)");
+ is($res, $instance, 'returns the instance of the controller');
+ is($received->($master), $options, 'after exactly one write of the options');
+ my $attrs = "/sys/class/nvme/nvme$instance";
+ is_deeply(
+ \@RESTRICTED,
+ ["$attrs/dhchap_secret", "$attrs/dhchap_ctrl_secret"],
+ 'and restricts the secret attributes of that controller',
+ );
+ }
+
+ for my $missing (qw(host_iface nqn)) {
+ syswrite($master,
+ $tokens->(map { $_ eq $missing ? "${_}_suffix" : $_ } $names->@*));
+ ($res, $error) = $run->();
+ is(
+ $error,
+ "the running kernel does not support the NVMe connect option '$missing'\n",
+ "an option the kernel does not list ($missing)",
+ );
+ is($received->($master), '', 'is found before anything is written');
+ }
+
+ for my $result ("garbage\n", "instance=3,cntlid=1,garbage\n") {
+ syswrite($master, $tokens->($names->@*));
+ syswrite($master, $result);
+ ($res, $error) = $run->();
+ is($error, "unexpected connect result\n", 'an unexpected result is refused');
+ is($received->($master), $options, 'after the one write');
+ is_deeply(\@RESTRICTED, [], 'and nothing is restricted');
+ }
+
+ symlink($slave, "$dir/link") or die "symlink: $!\n";
+ $nvme_mock->redefine(_fabrics_device => sub () { return "$dir/link" });
+ ($res, $error) = $run->();
+ is(
+ $error,
+ "cannot open '$dir/link': Too many levels of symbolic links\n",
+ 'a symbolic link to the device is not followed',
+ );
+ $nvme_mock->redefine(_fabrics_device => sub () { return $slave });
+
+ # A failed write: the error has the errno text and never the options.
+ my $writes = 0;
+ $nvme_mock->redefine(
+ _fabrics_write => sub($fh, $data) { $writes++; $! = ECONNREFUSED; return undef },
+ );
+ syswrite($master, $tokens->($names->@*));
+ ($res, $error) = $run->();
+ is(
+ $error,
+ "connect failed: Connection refused\n",
+ 'a refused connect has the errno text',
+ );
+ is($writes, 1, 'after one write, which is not repeated');
+ is_deeply(\@RESTRICTED, [], 'and nothing is restricted');
+ $writes = 0;
+ $nvme_mock->redefine(
+ _fabrics_write => sub($fh, $data) { $writes++; return length($data) - 1 });
+ syswrite($master, $tokens->($names->@*));
+ syswrite($master, "instance=3,cntlid=1\n"); # never read: a short write ends the connect
+ ($res, $error) = $run->();
+ is($error, "connect failed: short write\n", 'a short write');
+ is($writes, 1, 'is not completed');
+ is_deeply(\@RESTRICTED, [], 'and restricts nothing');
+ $nvme_mock->unmock('_fabrics_write');
+ }
+ $nvme_mock->unmock('_fabrics_device');
+};
+
+# Deactivation deletes the controllers of the subsystem in one bounded child.
+{
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ add_controller('nvme3', '192.0.2.23', 4420, 'ens21', 'live', $OTHER_NQN);
+ $nvme_mock->redefine(
+ _namespace_openers =>
+ sub($nqn) { return ['qemu-system-x86_64 (PID 123, /dev/nvme0n1)'] },
+ );
+ eval { $PLUGIN->deactivate_storage('nvmetest', scfg()) };
+ like(
+ $@,
+ qr/refusing to disconnect.*namespace in use by qemu-system-x86_64/s,
+ 'deactivation refuses a namespace opened by a VM',
+ );
+ is_deeply(\@DELETED, [], 'and deletes nothing');
+ $nvme_mock->redefine(_namespace_openers => sub($nqn) { return [] });
+ is($PLUGIN->deactivate_storage('nvmetest', scfg()), 1, 'an unused storage is deactivated');
+ is_deeply(\@DELETED, ['nvme1', 'nvme2'], 'by deleting the controllers of its subsystem');
+ is_deeply(\@FORKS, [15], 'in one child bounded by 15 seconds');
+ is_deeply($DIRS{'/sys/class/nvme'}, ['nvme3'], 'the controllers of other subsystems stay');
+ is($PLUGIN->deactivate_storage('nvmetest', scfg()), 1, 'a storage without controllers');
+ is_deeply(\@FORKS, [15], 'needs no child');
+ $nvme_mock->unmock('_namespace_openers');
+
+ my $delete = $nvme_mock->original('_delete_controllers');
+ @SYSFS_WRITES = ();
+ is($delete->([{ name => 'nvme1' }, { name => 'nvme2' }]), 2, 'the child deletes each one');
+ is_deeply(
+ \@SYSFS_WRITES,
+ [map { ["/sys/class/nvme/$_/delete_controller", '1'] } qw(nvme1 nvme2)],
+ 'through sysfs',
+ );
+ # The stock file_write on files that fail: a failed write warns, with the
+ # errno text, and a failed open does not.
+ my $file_write = $sysfs_mock->original('file_write');
+ my $dir = tempdir(CLEANUP => 1);
+ my @warnings;
+ local $SIG{__WARN__} = sub($warning) { push @warnings, $warning };
+ for my $case (['/dev/full', 'No space left on device'], [$dir, 'Is a directory']) {
+ my ($path, $reason) = $case->@*;
+ $sysfs_mock->redefine(file_write => sub($file, @args) { $file_write->($path, @args) });
+ eval { $delete->([{ name => 'nvme1' }, { name => 'nvme2' }]) };
+ is(
+ $@,
+ "cannot delete NVMe controller 'nvme1': $reason\n",
+ "a failed delete names the controller and the errno text ($reason)",
+ );
+ }
+ $sysfs_mock->redefine(file_write => sub($file, @args) { $file_write->("$dir/a/b", @args) });
+ is(
+ $delete->([{ name => 'nvme1' }, { name => 'nvme2' }]),
+ 2,
+ 'a controller that went away since it was listed counts as deleted',
+ );
+ $sysfs_mock->redefine(
+ file_write => sub($path, $data, @rest) {
+ warn "error writing '$data' to '$path': Device or resource busy\n";
+ $! = 0;
+ return 0;
+ },
+ );
+ eval { $delete->([{ name => 'nvme1' }]) };
+ is(
+ $@,
+ "cannot delete NVMe controller 'nvme1': Device or resource busy\n",
+ 'the errno text of a failed write is the one of the warning',
+ );
+ is_deeply(\@warnings, [], 'which is not passed on');
+ $sysfs_mock->redefine(file_write => $sysfs_write);
+}
+
+# The users of the namespaces: file descriptors on a namespace or one of its
+# partitions, and kernel holders such as device-mapper.
+{
+ reset_host();
+ $DIRS{'/sys/class/nvme-subsystem/nvme-subsys7'} = ['nvme7n1', 'nvme7c1n1'];
+ $DIRS{'/sys/class/block/nvme7n1'} = ['nvme7n1p1', 'nvme7n1p2', 'holders'];
+ is_deeply(nv('_namespace_openers', $NQN), [], 'no device, no users');
+ my ($scan) = grep { $_->[0] eq '/sys/class/block/nvme7n1' } @GLOBS;
+ ok($scan, 'the partitions of the namespace are listed');
+ ok($scan && 'nvme7n1p1' =~ /^($scan->[1])$/ && 'nvme7n1' !~ /^($scan->[1])$/, 'only those');
+ ok(!grep({ $_->[0] eq '/sys/class/block/nvme7c1n1' } @GLOBS), 'not the path devices');
+
+ %BLOCK = map { ("/dev/$_" => 1) } qw(nvme7n1 nvme7n1p1 nvme7n1p2);
+ $DIRS{'/proc'} = [qw(100 200 300 self)];
+ $DIRS{'/proc/100/fd'} = [0, 1, 7];
+ $DIRS{'/proc/200/fd'} = [3];
+ $DIRS{'/proc/300/fd'} = [4];
+ %LINKS = (
+ '/proc/100/fd/0' => '/dev/null',
+ '/proc/100/fd/7' => '/dev/nvme7n1',
+ '/proc/200/fd/3' => '/dev/nvme7n1p1',
+ '/proc/300/fd/4' => '/dev/nvme8n1',
+ );
+ $FILES{'/proc/100/comm'} = 'qemu-system-x86';
+ $FILES{'/proc/200/comm'} = 'mkfs.ext4';
+ $DIRS{'/sys/class/block/nvme7n1p2/holders'} = ['dm-0'];
+ is_deeply(
+ nv('_namespace_openers', $NQN),
+ [
+ '/dev/nvme7n1p2 held by dm-0',
+ 'mkfs.ext4 (PID 200, /dev/nvme7n1p1)',
+ 'qemu-system-x86 (PID 100, /dev/nvme7n1)',
+ ],
+ 'open namespaces and partitions and their holders are users, other devices are not',
+ );
+}
+
+# The local device behind a namespace link must be that namespace.
+{
+ my $link = "/dev/disk/by-id/nvme-uuid.$UUID";
+ my $check = sub($target, %files) {
+ local %LINKS = (defined($target) ? ($link => $target) : ());
+ local %FILES = (
+ '/sys/block/nvme3n1/uuid' => uc($UUID),
+ '/sys/block/nvme3n1/nsid' => '7',
+ '/sys/block/nvme3n1/device/subsysnqn' => $NQN,
+ %files,
+ );
+ my $ok = nv('_nvmet_local_namespace_ok', $link, $NQN, 7, $UUID);
+ return $ok ? 1 : 0;
+ };
+ my $device = '../../nvme3n1';
+ is($check->($device), 1, 'accepts the namespace of the subsystem, whatever the UUID case');
+ is($check->($device, '/sys/block/nvme3n1/nsid' => '8'), 0, 'refuses another NSID');
+ is(
+ $check->($device, '/sys/block/nvme3n1/device/subsysnqn' => $OTHER_NQN),
+ 0,
+ 'another subsystem',
+ );
+ is(
+ $check->($device, '/sys/block/nvme3n1/uuid' => '22345678-1234-1234-1234-123456789abc'),
+ 0,
+ 'another UUID',
+ );
+ is($check->($device, '/sys/block/nvme3n1/uuid' => undef), 0, 'an unreadable device');
+ is($check->(undef), 0, 'a missing link');
+
+ for my $target ('../../nvme3c1n1', '../../nvme3n1p1', '../../sda') {
+ is($check->($target), 0, "a link to $target");
+ }
+
+ my $dir = tempdir(CLEANUP => 1);
+ symlink('../../nvme3n1', "$dir/link") or die "symlink: $!\n";
+ is($nvme_mock->original('_link_target')->("$dir/link"), '../../nvme3n1', 'read, not followed');
+}
+
+# Storage activation. Everything on the local host is mocked.
+my $activate = sub($storeid, $scfg, $cache = undef) {
+ local $FILES{"/etc/pve/priv/storage/$storeid.nvme-dhchap"} = $KEY;
+ local %CONFIG = (%CONFIG, $storeid => $scfg);
+ @ACTIVATIONS = ();
+ $nvme_mock->redefine(
+ _nvmet_activate_target => sub(@args) { push @ACTIVATIONS, [@args]; return },
+ );
+ my $res = eval { $PLUGIN->activate_storage($storeid, $scfg, $cache) };
+ my $error = $@;
+ $nvme_mock->unmock('_nvmet_activate_target');
+ return ($res, $error);
+};
+my $forced = sub($storeid) { return { 'zfsnvme-force-reconcile' => { $storeid => 1 } } };
+
+subtest 'activation preconditions' => sub {
+ my $file = sub($path, $value) {
+ return sub() { $FILES{$path} = $value }
+ };
+ my $missing_iface = sub() {
+ $nvme_mock->redefine(_local_iface_exists => sub($iface) { return $iface ne 'ens20' });
+ };
+ my $other_storage = sub(%override) {
+ return sub() { $CONFIG{other} = scfg(subsysnqn => $OTHER_NQN, %override) };
+ };
+ my $fabrics_injection = 'traddr=198.51.100.9';
+ for my $case (
+ [
+ 'NVMe kernel modules that are not loaded',
+ $file->('/sys/module/nvme_core/parameters/multipath', undef),
+ qr/the NVMe kernel modules are not loaded; load the nvme-tcp kernel module/,
+ ],
+ [
+ 'multipath disabled',
+ $file->('/sys/module/nvme_core/parameters/multipath', 'N'),
+ qr/native NVMe multipath is disabled/,
+ ],
+ [
+ 'no host NQN',
+ $file->('/etc/nvme/hostnqn', undef),
+ qr/missing \/etc\/nvme\/hostnqn; the nvme-cli package generates it/,
+ ],
+ [
+ 'a host that is not allowed',
+ $file->(
+ '/etc/nvme/hostnqn',
+ 'nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-00000000dead',
+ ),
+ qr/local NVMe host NQN .* is missing from nvme-host-nqns/,
+ ],
+ [
+ 'no host ID',
+ $file->('/etc/nvme/hostid', undef),
+ qr/missing \/etc\/nvme\/hostid; the nvme-cli package generates it/,
+ ],
+ [
+ 'the zero host ID',
+ $file->('/etc/nvme/hostid', '00000000-0000-0000-0000-000000000000'),
+ qr/invalid NVMe host ID/,
+ ],
+ [
+ 'a host ID with a connect option',
+ $file->('/etc/nvme/hostid', "$UUID,$fabrics_injection"),
+ qr/invalid NVMe host ID/,
+ ],
+ [
+ 'a host ID with a newline',
+ $file->('/etc/nvme/hostid', "$UUID\n"),
+ qr/invalid NVMe host ID/,
+ ],
+ [
+ 'a connection parameter that is not a number',
+ sub() { },
+ qr/invalid NVMe connection parameter 'reconnect-delay'/,
+ 'nvme-reconnect-delay' => "2,$fabrics_injection",
+ ],
+ [
+ 'a missing local interface',
+ $missing_iface,
+ qr/interface 'ens20' does not exist on this node/,
+ ],
+ [
+ 'a pool shared with another storage',
+ $other_storage->('nvme-portals' => '192.0.2.31,192.0.2.32'),
+ qr/ZFS pool 'tank' on '192\.0\.2\.10' is already used by storage 'other'/,
+ ],
+ [
+ 'a listener shared with another storage',
+ $other_storage->(pool => 'data', 'nvme-portals' => '192.0.2.31,192.0.2.22'),
+ qr/portal '192\.0\.2\.22' port 4420 is already used by storage 'other'/,
+ ],
+ ) {
+ my ($name, $setup, $error, %override) = $case->@*;
+ reset_host();
+ local %CONFIG = ();
+ $nvme_mock->redefine(_local_iface_exists => sub($iface) { return 1 });
+ $setup->();
+ my (undef, $got) = $activate->('zfsnvme-unit-s', scfg(%override));
+ like($got, $error, "refuses $name");
+ is_deeply([@ACTIVATIONS, @CONNECTS, @SYSFS_WRITES], [], 'and does nothing');
+ }
+ $nvme_mock->redefine(_local_iface_exists => sub($iface) { return 1 });
+};
+
+subtest 'a stopped task ends the activation at the connect' => sub {
+ for my $case (
+ ["received interrupt\n", 1],
+ ["interrupted by unexpected signal\n", 1],
+ ["connect failed: Connection refused\n", 0],
+ ["NVMe/TCP connect did not complete within 10 seconds\n", 0],
+ ) {
+ my ($exception, $cancelled) = $case->@*;
+ reset_host();
+ my $calls = 0;
+ $nvme_mock->redefine(
+ _fabrics_connect => sub($options, $names) {
+ my %option = map { split(/=/, $_, 2) } split(/,/, $options);
+ ++$calls;
+ # cancellation must escape even if the write created a live path
+ add_controller("nvme$calls", $option{traddr}, 4420, $option{host_iface})
+ if $cancelled || $calls > 1;
+ die $exception if $calls == 1;
+ return $calls;
+ },
+ );
+ my ($res, $err) = $activate->('zfsnvme-cancel', scfg());
+ is($err, $cancelled ? "received interrupt\n" : '', 'only a stopped task escapes');
+ is($res, $cancelled ? undef : 1, 'an ordinary failure still permits a degraded path');
+ is($calls, $cancelled ? 1 : 2, 'a stopped task never attempts the next portal');
+ unlike($err . join('', @WARNINGS), qr/\Q$KEY\E/, 'errors and warnings hide the key');
+ }
+ $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+
+ reset_host();
+ no warnings 'redefine';
+ local *PVE::Storage::ZFSNVMePlugin::_restrict_attr =
+ sub($path) { die "received interrupt\n" };
+ my ($res, $err) = $activate->('zfsnvme-cancel-scan', scfg());
+ is($err, "received interrupt\n",
+ 'cancellation in the post-connect permission scan escapes');
+ is(scalar(@CONNECTS), 1, 'no next portal after a cancelled permission scan');
+};
+
+# Deleting a controller runs in a bounded child: 5 seconds for a dead path
+# during an activation, which goes on, and 15 seconds for a deactivation,
+# which fails. Only a stopped task escapes an activation.
+subtest 'deleting a controller is bounded and keeps a stopped task' => sub {
+ my $interrupt = "received interrupt\n";
+ my $failed = "cannot delete NVMe controller 'nvme1'\n";
+ # [label, what the child does, activation error, deactivation error]
+ for my $case (
+ ['a stopped task', $interrupt, $interrupt, $interrupt],
+ ['a signalled child', "interrupted by unexpected signal\n", $interrupt, $interrupt],
+ ['a failed deletion', $failed, '', $failed],
+ [
+ 'a timeout',
+ undef,
+ '',
+ "disconnecting NVMe subsystem '$NQN' did not complete within 15 seconds\n",
+ ],
+ ) {
+ my ($label, $exception, $activation_error, $deactivation_error) = $case->@*;
+ $tools_mock->redefine(
+ run_fork_with_timeout => sub($seconds, $code, $opts = undef) {
+ push @FORKS, $seconds;
+ # without an exception, the deletion times out
+ return (undef, 1) if !defined($exception) && $seconds != 10;
+ return ($code->(), 0);
+ },
+ );
+ $nvme_mock->redefine(_delete_controllers => sub($controllers) { die $exception })
+ if defined($exception);
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+ my ($res, $err) = $activate->('zfsnvme-delete', scfg());
+ is($err, $activation_error, "$label while a dead path is deleted");
+ is($FORKS[0], 5, 'in a child bounded by 5 seconds');
+ is(scalar(@CONNECTS), $activation_error ? 0 : 2, 'only a failure goes on to connect');
+ my $warned = $exception
+ // "deleting NVMe controller 'nvme1' did not complete within 5 seconds\n";
+ like(join("\n", @WARNINGS), qr/\Q$warned\E/, 'and is warned about')
+ if !$activation_error;
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ eval { $PLUGIN->deactivate_storage('zfsnvme-delete', scfg()) };
+ is($@, $deactivation_error, "$label fails the deactivation");
+ is_deeply(\@FORKS, [15], 'in a child bounded by 15 seconds');
+ $nvme_mock->redefine(_delete_controllers => $delete_mock);
+ }
+ $tools_mock->redefine(run_fork_with_timeout => $fork_inline);
+};
+
+subtest 'storage deletion preserves task cancellation at each catch boundary' => sub {
+ for my $case (
+ ['deactivate', "received interrupt\n", 1, 0],
+ ['deactivate', "ordinary disconnect failure\n", 0, 1],
+ [
+ 'deactivate',
+ "disconnecting NVMe subsystem '$NQN' did not complete within 15 seconds\n",
+ 0,
+ 1,
+ ],
+ ['target', "received interrupt\n", 1, 1],
+ ['target', "ordinary target failure\n", 0, 1],
+ ) {
+ my ($phase, $exception, $cancelled, $expected_target_calls) = $case->@*;
+ reset_host();
+ my $target_calls = 0;
+ no warnings 'redefine';
+ local *PVE::Storage::ZFSNVMePlugin::deactivate_storage = sub(@args) {
+ die $exception if $phase eq 'deactivate';
+ return 1;
+ };
+ local *PVE::Storage::ZFSNVMePlugin::_nvmet_delete_target = sub(@args) {
+ ++$target_calls;
+ die $exception if $phase eq 'target';
+ return;
+ };
+ eval { $PLUGIN->on_delete_hook('zfsnvme-delete-cancel', scfg()) };
+ is(
+ $@,
+ $cancelled ? "received interrupt\n" : '',
+ "$phase preserves only task cancellation",
+ );
+ is($target_calls, $expected_target_calls, 'no target deletion after a cancellation');
+ is_deeply(
+ \@UNLINKED,
+ ['/etc/pve/priv/storage/zfsnvme-delete-cancel.nvme-dhchap'],
+ 'the key file is removed first',
+ );
+ chomp(my $message = $exception);
+ like(
+ join("\n", @WARNINGS),
+ qr/not disconnecting NVMe storage 'zfsnvme-delete-cancel': \Q$message\E/,
+ 'an ordinary deactivation failure only warns',
+ ) if $phase eq 'deactivate' && !$cancelled;
+ }
+};
+
+subtest 'slow-path backoff' => sub {
+ reset_host();
+ local %REFUSE = ('192.0.2.22' => 1);
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ my $scfg = scfg();
+ my ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is($error, '', 'a degraded storage activates');
+ is(scalar(@ACTIVATIONS), 1, 'through the target');
+ is_deeply(
+ [$ACTIVATIONS[0]->@[0, 2 .. 4]],
+ [
+ 'zfsnvme-unit-a',
+ [
+ map { {
+ family => 'ipv4',
+ address => "192.0.2.2$_",
+ port => 4420,
+ host_iface => 'ens' . (18 + $_),
+ } } 1,
+ 2,
+ ],
+ [$hostnqn_a, $hostnqn_b],
+ $KEY,
+ ],
+ 'with the storage, its parsed portals, hosts and key',
+ );
+ like(
+ join("\n", @WARNINGS),
+ qr/storage 'zfsnvme-unit-a' is degraded: 1\/2 paths live/,
+ 'and warns',
+ );
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is($error, '', 'within a minute, a live path takes the fast path');
+ is(scalar(@ACTIVATIONS), 0, 'without a target call');
+ {
+ local $NOW = $NOW + 61;
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is(scalar(@ACTIVATIONS), 1, 'a minute later the target is tried again');
+ }
+ my $cache = $forced->('zfsnvme-unit-a');
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg, $cache);
+ is(scalar(@ACTIVATIONS), 1, 'a forced activation always reaches the target');
+ ok(!$cache->{'zfsnvme-force-reconcile'}->{'zfsnvme-unit-a'}, 'and consumes the request');
+ $FILES{'/sys/class/nvme/nvme1/state'} = 'dead';
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is(
+ $error,
+ "no live NVMe/TCP path for storage 'zfsnvme-unit-a'\n",
+ 'within a minute, without a live path the activation fails at once',
+ );
+ is_deeply([@ACTIVATIONS, @DELETED], [], 'without a target call or a reconnect');
+ {
+ local $NOW = $NOW + 61;
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is(scalar(@ACTIVATIONS), 1, 'a minute later the target is tried');
+ is_deeply(\@DELETED, ['nvme1'], 'and the dead path is reconnected');
+ }
+
+ reset_host();
+ local %REFUSE = ('192.0.2.22' => 1);
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ local $NOW = 30; # the monotonic clock shortly after boot
+ ($res, $error) = $activate->('zfsnvme-unit-b', $scfg);
+ is(scalar(@ACTIVATIONS), 1, 'a storage that was never activated is not in its backoff');
+
+ # A storage without any path waits for one once per backoff period, not
+ # on every status update.
+ reset_host();
+ local %REFUSE = ('192.0.2.21' => 1, '192.0.2.22' => 1);
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+ is($error, "no live NVMe/TCP path for storage 'zfsnvme-unit-d'\n", 'no path, no storage');
+ is_deeply(
+ [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+ [1, 2],
+ 'after the target and each portal',
+ );
+ @CONNECTS = ();
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+ is(
+ $error,
+ "no live NVMe/TCP path for storage 'zfsnvme-unit-d'\n",
+ 'within a minute it fails',
+ );
+ is_deeply([@ACTIVATIONS, @CONNECTS], [], 'at once, without a target call or a connect');
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg, $forced->('zfsnvme-unit-d'));
+ is_deeply(
+ [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+ [1, 2],
+ 'a forced activation tries again',
+ );
+ {
+ local $NOW = $NOW + 61;
+ @CONNECTS = ();
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+ is_deeply(
+ [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+ [1, 2],
+ 'so does one a minute later',
+ );
+ }
+
+ # A slow path whose target call fails starts the backoff as well.
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ local $FILES{'/etc/pve/priv/storage/zfsnvme-unit-t.nvme-dhchap'} = $KEY;
+ local %CONFIG = ('zfsnvme-unit-t' => $scfg);
+ my $calls = 0;
+ $nvme_mock->redefine(
+ _nvmet_activate_target => sub(@args) {
+ $calls++;
+ die "NVMe target '192.0.2.10' is unreachable: timeout\n";
+ },
+ );
+ eval { $PLUGIN->activate_storage('zfsnvme-unit-t', $scfg) };
+ like($@, qr/is unreachable/, 'an unreachable target fails the slow path');
+ eval { $PLUGIN->activate_storage('zfsnvme-unit-t', $scfg) };
+ is($@, '', 'within a minute the live path takes the fast path');
+ is($calls, 1, 'without another target call');
+ $nvme_mock->unmock('_nvmet_activate_target');
+};
+
+subtest 'connecting the paths' => sub {
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ $network_mock->redefine(
+ tcp_ping => sub($host, $port, $timeout = undef) { return $host ne '192.0.2.22' },
+ );
+ my (undef, $error) = $activate->('zfsnvme-unit-v', scfg(), $forced->('zfsnvme-unit-v'));
+ is_deeply(\@CONNECTS, [], 'an unreachable portal is not connected');
+ like(join("\n", @WARNINGS), qr/'192\.0\.2\.22:4420' is unreachable/, 'but warned about');
+ $network_mock->redefine(tcp_ping => sub($host, $port, $timeout = undef) { return 1 });
+
+ # After a target restart, the kernel reconnects its controllers itself.
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'connecting');
+ local %REFUSE = ('192.0.2.22' => 1);
+ my $sleeps = 0;
+ $nvme_mock->redefine(
+ _sleep => sub($seconds) {
+ $NOW += $seconds;
+ $FILES{'/sys/class/nvme/nvme1/state'} = 'live' if ++$sleeps == 3;
+ return;
+ },
+ );
+ (undef, $error) = $activate->('zfsnvme-unit-w', scfg());
+ is($error, '', 'an activation waits for a controller that reconnects');
+ is($sleeps, 3, 'until it is live');
+ $nvme_mock->redefine(_sleep => sub($seconds) { $NOW += $seconds; return });
+};
+
+subtest 'moving a path to its configured interface' => sub {
+ my $single = scfg('nvme-portals' => '192.0.2.21', 'nvme-host-ifaces' => 'ens19');
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+ my ($res, $error) = $activate->('zfsnvme-unit-c', scfg());
+ is($error, '', 'a storage whose only live path uses another interface');
+ is_deeply(\@CONNECTS, ['192.0.2.21@ens19', '192.0.2.22@ens20'], 'connects both paths');
+ is_deeply(\@DELETED, ['nvme1'], 'and then disconnects the old one');
+ is_deeply(\@WARNINGS, [], 'the storage is healthy');
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+ local %CONNECT_STATE = ('192.0.2.21' => 'connecting');
+ my $start = $NOW;
+ ($res, $error) = $activate->('zfsnvme-unit-g', $single);
+ is($error, '', 'a new path that does not become live');
+ is_deeply(\@DELETED, [], 'keeps the old path');
+ like(
+ join("\n", @WARNINGS),
+ qr/'192\.0\.2\.21:4420' is not live on 'ens19' yet; keeping its path on another interface/,
+ 'and warns',
+ );
+ like(join("\n", @WARNINGS), qr/is degraded: 0\/1 paths live/, 'the storage is degraded');
+ is($NOW - $start, 10, 'after waiting 10 seconds for the new path');
+ ($res, $error) = $activate->('zfsnvme-unit-g', $single);
+ ok(!$error && !@ACTIVATIONS, 'within a minute, the old path takes the fast path');
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+ local %REFUSE = ('192.0.2.21' => 1);
+ ($res, $error) = $activate->('zfsnvme-unit-h', $single);
+ is($error, '', 'a new path that cannot connect');
+ is_deeply(\@DELETED, [], 'keeps the old path too');
+ like(
+ join("\n", @WARNINGS),
+ qr/192\.0\.2\.21:4420: connect failed: Connection refused/,
+ 'and warns',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+ my $connect = $PLUGIN->can('_connect_portal');
+ {
+ no warnings 'redefine';
+ local %REFUSE = ();
+ local *PVE::Storage::ZFSNVMePlugin::_connect_portal = sub($scfg, $portal, @ids) {
+ $connect->($scfg, $portal, @ids);
+ die "connection failed after creation\n";
+ };
+ ($res, $error) = $activate->('zfsnvme-unit-h-partial', $single);
+ }
+ ok(!$error && $res == 1, 'a partially successful connect leaves the storage usable');
+ is($FILES{'/sys/class/nvme/nvme71/state'}, 'live', 'a live replacement was created');
+ is_deeply(\@DELETED, [], 'the connect error still preserves the old interface path');
+ like(
+ join("\n", @WARNINGS),
+ qr/192\.0\.2\.21:4420: connection failed after creation/,
+ 'and preserves the original connect warning',
+ );
+};
+
+subtest 'reconnect timeouts reach connected controllers' => sub {
+ my $sysfs = sub () {
+ return [
+ map { [$_->[0] =~ s{\A/sys/class/nvme/}{}r, $_->[1] =~ s/\n\z//r] }
+ grep { $_->[0] =~ m{\A/sys/class/nvme/} } @SYSFS_WRITES
+ ];
+ };
+ my $case = sub($storeid, $scfg, %current) {
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ for my $name (qw(nvme1 nvme2)) {
+ $FILES{"/sys/class/nvme/$name/$_"} = $current{$_} for keys %current;
+ }
+ my ($res, $error) = $activate->($storeid, $scfg, $forced->($storeid));
+ is($error, '', "activation of $storeid");
+ return $sysfs->();
+ };
+ my $timeouts = scfg(
+ 'nvme-reconnect-delay' => 5,
+ 'nvme-ctrl-loss-tmo' => 60,
+ 'nvme-fast-io-fail-tmo' => 10,
+ );
+ my $written = [
+ map { (
+ ["$_/reconnect_delay", 5], ["$_/ctrl_loss_tmo", 60], ["$_/fast_io_fail_tmo", 10],
+ ) } qw(nvme1 nvme2)
+ ];
+ is_deeply($case->('zfsnvme-unit-i', $timeouts), $written, 'changes reach every controller');
+ is_deeply(
+ [grep { $_->[0] =~ /iopolicy/ } @SYSFS_WRITES],
+ [['/sys/class/nvme-subsystem/nvme-subsys7/iopolicy', "round-robin\n"]],
+ 'with the multipath policy',
+ );
+ my %current = (reconnect_delay => '5', ctrl_loss_tmo => '60', fast_io_fail_tmo => '10');
+ is_deeply(
+ $case->('zfsnvme-unit-j', $timeouts, %current),
+ [],
+ 'unchanged ones are not written',
+ );
+ is_deeply(
+ $case->('zfsnvme-unit-k', scfg('nvme-ctrl-loss-tmo' => -1)),
+ [map { ["$_/ctrl_loss_tmo", -1] } qw(nvme1 nvme2)],
+ 'an infinite loss timeout',
+ );
+ is_deeply(
+ $case->('zfsnvme-unit-l', scfg('nvme-ctrl-loss-tmo' => 7), ctrl_loss_tmo => '8'),
+ [],
+ 'the loss timeout the kernel rounds up to the reconnect delay',
+ );
+ is_deeply(
+ $case->('zfsnvme-unit-m', scfg(), fast_io_fail_tmo => '5'),
+ [map { ["$_/fast_io_fail_tmo", -1] } qw(nvme1 nvme2)],
+ 'an unset fast I/O fail timeout is turned off',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ my ($res, $error) = $activate->('zfsnvme-unit-n', $timeouts);
+ ok(!$error && $res == 1, 'a healthy storage activates on the fast path');
+ is(scalar(@ACTIVATIONS) + scalar(@CONNECTS), 0, 'without a target call or connect');
+ is_deeply($sysfs->(), $written, 'which also writes changed timeouts');
+ is_deeply(
+ [grep { $_->[0] =~ /iopolicy/ } @SYSFS_WRITES],
+ [['/sys/class/nvme-subsystem/nvme-subsys7/iopolicy', "round-robin\n"]],
+ 'and the multipath policy',
+ );
+ delete $FILES{'/etc/pve/priv/storage/zfsnvme-unit-n.nvme-dhchap'};
+ $res = eval {
+ local %CONFIG = ('zfsnvme-unit-n' => $timeouts);
+ $PLUGIN->activate_storage('zfsnvme-unit-n', $timeouts);
+ };
+ is($@, "missing NVMe DH-HMAC-CHAP key\n", 'the fast path needs the key file');
+
+ # file_write warns about a failed write, and is silent about a failed open,
+ # leaving its errno in $!
+ my @perl_warnings;
+ local $SIG{__WARN__} = sub($warning) { push @perl_warnings, $warning };
+ my $failing = sub($pattern, $errno, $warn) {
+ $sysfs_mock->redefine(
+ file_write => sub($path, $data, @rest) {
+ return $sysfs_write->($path, $data) if $path !~ $pattern;
+ $! = $errno;
+ return undef if !$warn;
+ warn "error writing '$data' to '$path': $!\n";
+ $! = ENOENT; # not the reason: file_write closed the file since
+ return 0;
+ },
+ );
+ };
+ my $reason = sub($errno) { local $! = $errno; return "$!" };
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $failing->(qr{/nvme1/ctrl_loss_tmo\z}, EINVAL, 1);
+ ($res, $error) = $activate->('zfsnvme-unit-e', $timeouts);
+ is($error, '', 'a timeout that cannot be written does not fail the activation');
+ my $einval = $reason->(EINVAL);
+ is_deeply(
+ [@WARNINGS, @perl_warnings],
+ ["cannot set ctrl_loss_tmo of NVMe controller 'nvme1': $einval"],
+ 'and is reported once, as a task warning with the reason',
+ );
+ reset_host();
+ @perl_warnings = ();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $failing->(qr{/nvme2/ctrl_loss_tmo\z}, EACCES, 0);
+ ($res, $error) = $activate->('zfsnvme-unit-tmo-open', $timeouts);
+ is($error, '', 'a timeout that cannot be opened does not fail the activation');
+ is_deeply(
+ [@WARNINGS, @perl_warnings],
+ ["cannot set ctrl_loss_tmo of NVMe controller 'nvme2': " . $reason->(EACCES)],
+ 'and is reported once, with the reason',
+ );
+ reset_host();
+ @perl_warnings = ();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $failing->(qr{/iopolicy\z}, EACCES, 0);
+ ($res, $error) = $activate->('zfsnvme-unit-f', $timeouts);
+ is(
+ $error,
+ 'unable to set NVMe multipath policy: ' . $reason->(EACCES) . "\n",
+ 'a policy that cannot be set fails the activation',
+ );
+ is_deeply([@WARNINGS, @perl_warnings], [], 'with the reason in the error only');
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $failing->(qr{/iopolicy\z}, EINVAL, 1);
+ ($res, $error) = $activate->('zfsnvme-unit-policy-write', $timeouts);
+ is(
+ $error,
+ "unable to set NVMe multipath policy: $einval\n",
+ 'a policy that cannot be written fails the activation',
+ );
+ is_deeply([@WARNINGS, @perl_warnings], [],
+ 'and the warning of file_write is not passed on');
+
+ # The stock file_write on an attribute that does not exist: unlike a
+ # deletion or a rescan, setting a timeout or the policy treats the failed
+ # open (ENOENT) as a failure like any other.
+ my $file_write = $sysfs_mock->original('file_write');
+ my $missing = tempdir(CLEANUP => 1) . '/a/b';
+ my $absent = sub($pattern) {
+ $sysfs_mock->redefine(
+ file_write => sub($path, $data, @rest) {
+ return $sysfs_write->($path, $data) if $path !~ $pattern;
+ return $file_write->($missing, $data, @rest);
+ },
+ );
+ };
+ my $enoent = $reason->(ENOENT);
+ reset_host();
+ @perl_warnings = ();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $absent->(qr{/nvme1/reconnect_delay\z});
+ ($res, $error) = $activate->('zfsnvme-unit-tmo-missing', $timeouts);
+ is($error, '', 'a missing timeout attribute does not fail the activation');
+ is_deeply(
+ [@WARNINGS, @perl_warnings],
+ ["cannot set reconnect_delay of NVMe controller 'nvme1': $enoent"],
+ 'but is reported once, as a task warning with the reason',
+ );
+ reset_host();
+ @perl_warnings = ();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $absent->(qr{/iopolicy\z});
+ ($res, $error) = $activate->('zfsnvme-unit-policy-missing', $timeouts);
+ is(
+ $error,
+ "unable to set NVMe multipath policy: $enoent\n",
+ 'a missing policy attribute fails the activation',
+ );
+ is_deeply([@WARNINGS, @perl_warnings], [], 'with the reason in the error only');
+ $sysfs_mock->redefine(file_write => $sysfs_write);
+};
+
+subtest 'the key attributes of the controllers are private' => sub {
+ my $attrs = sub(@names) {
+ my @attrs = qw(dhchap_secret dhchap_ctrl_secret);
+ return [
+ map {
+ my $name = $_;
+ map { "/sys/class/nvme/$name/$_" } @attrs
+ } @names
+ ];
+ };
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ add_controller('nvme3', '192.0.2.23', 4420, 'ens21', 'live', $OTHER_NQN);
+ my ($res, $error) = $activate->('zfsnvme-unit-o', scfg());
+ is($error, '', 'a healthy storage');
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme1', 'nvme2'),
+ 'restricts its controllers on the fast path',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ ($res, $error) = $activate->('zfsnvme-unit-p', scfg(), $forced->('zfsnvme-unit-p'));
+ is($error, '', 'a forced activation');
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme1', 'nvme1', 'nvme71'),
+ 'restricts those of the existing controllers first, then those of new ones',
+ );
+
+ reset_host();
+ local %CONNECT_STATE = map { ($_ => 'connecting') } '192.0.2.21', '192.0.2.22';
+ ($res, $error) = $activate->('zfsnvme-unit-q', scfg());
+ is(
+ $error,
+ "no live NVMe/TCP path for storage 'zfsnvme-unit-q'\n",
+ 'an activation that fails',
+ );
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme71', 'nvme71', 'nvme72'),
+ 'each one after its connect',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'connecting');
+ $nvme_mock->redefine(_nvmet_activate_target => sub(@args) { die "unreachable\n" });
+ $res = eval {
+ local $FILES{'/etc/pve/priv/storage/zfsnvme-unit-x.nvme-dhchap'} = $KEY;
+ local %CONFIG = ('zfsnvme-unit-x' => scfg());
+ $PLUGIN->activate_storage('zfsnvme-unit-x', scfg());
+ };
+ is($@, "unreachable\n", 'a slow path that fails at the target');
+ is_deeply(\@RESTRICTED, $attrs->('nvme1'), 'still restricts the existing controllers');
+ $nvme_mock->unmock('_nvmet_activate_target');
+
+ # The first connect fails after it created a live controller; the scan of
+ # the permissions after it fails too in the second case.
+ my $connect = $PLUGIN->can('_connect_portal');
+ my $connect_error = "connection failed after creation\n";
+ for my $scan_error (0, 1) {
+ reset_host();
+ my $scan_failed = 0;
+ {
+ no warnings 'redefine';
+ local *PVE::Storage::ZFSNVMePlugin::_connect_portal = sub($scfg, $portal, @ids) {
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme71'),
+ 'a failed connect restricts both attributes before the next connect',
+ ) if @CONNECTS == 1 && !$scan_error;
+ $connect->($scfg, $portal, @ids);
+ die $connect_error if @CONNECTS == 1;
+ };
+ local *PVE::Storage::ZFSNVMePlugin::_restrict_attr = sub($path) {
+ push @RESTRICTED, $path;
+ eval { 1 }; # A permission helper must not erase the saved connect error.
+ die "permission scan failed\n" if $scan_error && !$scan_failed++;
+ return;
+ };
+ ($res, $error) = $activate->("zfsnvme-unit-secret-failure-$scan_error", scfg());
+ }
+ is($error, '', 'a connect error does not discard its live controller');
+ ok(
+ scalar(grep { $_ eq "192.0.2.21:4420: $connect_error" } @WARNINGS),
+ 'and warns about it',
+ );
+ if ($scan_error) {
+ ok(
+ scalar(
+ grep { $_ eq "cannot restrict NVMe controller attributes for '$NQN'" }
+ @WARNINGS
+ ),
+ 'the scan failure has its own warning',
+ );
+ unlike(join("\n", @WARNINGS), qr/permission scan failed/, 'without its exception');
+ } else {
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme71', 'nvme71', 'nvme72'),
+ 'each attempt restricts the controllers, including a failed last connect',
+ );
+ }
+ }
+
+ my $dir = tempdir(CLEANUP => 1);
+ my $restrict = $nvme_mock->original('_restrict_attr');
+ for my $mode (0644, 0640, 0600, 0400) {
+ my $file = sprintf('%s/attr-%o', $dir, $mode);
+ open(my $fh, '>', $file) or die "open: $!\n";
+ close($fh);
+ chmod($mode, $file);
+ $restrict->($file);
+ is(
+ (stat($file))[2] & 07777,
+ $mode & 077 ? 0600 : $mode,
+ sprintf('an attribute with mode %o', $mode),
+ );
+ }
+ @WARNINGS = ();
+ $restrict->("$dir/missing");
+ is_deeply(\@WARNINGS, [], 'a missing attribute is skipped');
+ my $not_directory = "$dir/attr-600/child";
+ $restrict->($not_directory);
+ like(join("\n", @WARNINGS), qr/\Q$not_directory\E/, 'another stat failure warns');
+};
+
+subtest 'controllers match IPv6 portals in any spelling' => sub {
+ reset_host();
+ add_controller('nvme1', '2001:db8:0:0::11', 4420, 'ens19');
+ add_controller('nvme2', '2001:DB8::12', 4420, 'ens20');
+ my $scfg = scfg('nvme-portals' => '[2001:db8::11],[2001:db8::0:12]');
+ my ($res, $error) = $activate->('zfsnvme-unit-r', $scfg);
+ is($error, '', 'both paths are live');
+ is(scalar(@ACTIVATIONS) + scalar(@CONNECTS), 0, 'without a target call or connect');
+};
+
+is_deeply(\@COMMANDS, [], 'the host side ran no command');
+
+done_testing();
+
+1;
^ permalink raw reply related [relevance 10%]
* [PATCH storage v3 1/4] zfsnvme: add ZFS over NVMe/TCP storage plugin
2026-10-05 0:26 14% [PATCH storage v3 0/4] add ZFS over NVMe/TCP storage plugin Joaquin Varela
@ 2026-10-05 0:26 16% ` Joaquin Varela
2026-10-05 0:26 10% ` [PATCH storage v3 2/4] test: add zfsnvme plugin tests Joaquin Varela
` (2 subsequent siblings)
3 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-10-05 0:26 UTC (permalink / raw)
To: pve-devel
Add the shared storage type 'zfsnvme': ZFS zvols on a remote Linux
target, exported with the kernel NVMe target (nvmet, configured through
configfs) over NVMe/TCP, and consumed by the cluster nodes with native
NVMe multipath and DH-HMAC-CHAP authentication.
The ZFS dataset is the source of truth for a namespace: the subsystem
NQN, NSID and UUID of every volume are stored in the ZFS user properties
'proxmox:nvme-subsys', 'proxmox:nvme-nsid' and 'proxmox:nvme-uuid', and
the pool keeps the highest NSID handed out in 'proxmox:nvme-last-nsid'.
The nodes find a namespace by its UUID. Everything else on the target
(nvmet_tcp module, configfs mount, subsystem, namespaces, ports, host
ACLs) is derived state that an activation rebuilds after a target
restart.
All parsing, validation and planning happen locally. The target state
is read with one 'zfs get' and one 'find' over configfs; other reads
are 'zfs get' and 'zfs list', 'test -b' while a new zvol appears, and
'cat /proc/mounts' to decide whether configfs needs to be mounted. The
target runs quoted simple commands over SSH, joined with '&&' where a
step depends on the previous one: an export starts with 'test -b' on
its zvol, and each publish link repeats two read-only checks right
before it links the subsystem to a port. There are no scripts, loops
or variables on the target. As with ZFS over iSCSI, the SSH key is
/etc/pve/priv/zfs/<server>_id_rsa. Target changes are serialized
cluster-wide by a pmxcfs domain lock per target server, and an
operation whose SSH connection broke is reported as unknown and
repaired by the next activation rather than compensated from a read
that could overtake it.
Each storage needs its own NVMe/TCP listener (address family, address
and port) on the target. nvmet answers a connect to a listener that
does not publish the subsystem yet with DNR, and the host then deletes
the controller whatever its loss timeout, so after a target restart the
storage published second on a shared listener would lose its paths.
Adding, updating and activating a storage therefore refuse a portal
whose listener another zfsnvme storage uses, disabled ones included,
and a target address that another storage reaches through a different
'server' value, since that value names the target lock. A data address
thus identifies one target for all zfsnvme storages of the cluster.
The DH-HMAC-CHAP key is a sensitive property, stored like the other
storage secrets in /etc/pve/priv/storage/<storeid>.nvme-dhchap. It
reaches the target through stdin, and the plugin restricts the
dhchap_key and dhchap_ctrl_key attributes there to 0600 whenever it
writes the key. On the nodes, controllers are created with exactly one
write to /dev/nvme-fabrics in a bounded child (run_fork_with_timeout),
so the key never appears on a command line, and the secret attributes of
a new controller are restricted before the child returns. Rescans and
disconnects are sysfs writes; nvme-cli is not run.
Keep-alive, reconnect delay, controller loss and optional fast I/O
failure timeouts are configurable, with defaults that prefer waiting for
the target over failing guest I/O (ctrl_loss_tmo 600, fast_io_fail_tmo
unset).
Outside the plugin: register the type in PVE::Storage and the Makefile,
add it to @SHARED_STORAGE in PVE::Storage::Plugin, let 'pvesm add' and
'pvesm set' read --dhchap-key from a file, and depend on nvme-cli, which
creates /etc/nvme/hostnqn and /etc/nvme/hostid and remains the
administration tool, like the client packages of the other shared types.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
debian/control | 1 +
src/PVE/CLI/pvesm.pm | 21 +-
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/ZFSNVMePlugin.pm | 3177 ++++++++++++++++++++++++++++++
6 files changed, 3201 insertions(+), 3 deletions(-)
create mode 100644 src/PVE/Storage/ZFSNVMePlugin.pm
diff --git a/debian/control b/debian/control
index 850cd57c..ab46e6b6 100644
--- a/debian/control
+++ b/debian/control
@@ -43,6 +43,7 @@ Depends: bzip2,
lvm2,
lzop,
nfs-common,
+ nvme-cli,
proxmox-backup-client (>= 2.1.10~),
proxmox-backup-file-restore,
pve-cluster (>= 5.0-32),
diff --git a/src/PVE/CLI/pvesm.pm b/src/PVE/CLI/pvesm.pm
index 1aaa9f3c..3c68ffb5 100755
--- a/src/PVE/CLI/pvesm.pm
+++ b/src/PVE/CLI/pvesm.pm
@@ -78,12 +78,29 @@ sub param_mapping {
},
};
+ my $dhchap_key_map = {
+ name => 'dhchap-key',
+ desc => 'a file containing the NVMe DH-HMAC-CHAP key',
+ func => sub {
+ my ($value) = @_;
+ # never repeat a key passed in place of the file name
+ die "dhchap-key expects the path of a file containing the key\n"
+ if $value =~ /^DHHC-1:/i || -d $value;
+ my ($key) = split(/\n/, PVE::Tools::file_get_contents($value), 2);
+ $key = PVE::Tools::trim($key // '');
+ die "DH-HMAC-CHAP key file '$value' is empty\n" if $key eq '';
+ return $key;
+ },
+ };
+
my $mapping = {
'cifsscan' => [$password_map],
'cifs' => [$password_map],
'pbs' => [$password_map],
- 'create' => [$password_map, $enc_key_map, $master_key_map, $keyring_map],
- 'update' => [$password_map, $enc_key_map, $master_key_map, $keyring_map],
+ 'create' =>
+ [$password_map, $enc_key_map, $master_key_map, $keyring_map, $dhchap_key_map],
+ 'update' =>
+ [$password_map, $enc_key_map, $master_key_map, $keyring_map, $dhchap_key_map],
};
return $mapping->{$name};
}
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index fc3db812..2e5a8031 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -36,6 +36,7 @@ use PVE::Storage::CephFSPlugin;
use PVE::Storage::ISCSIDirectPlugin;
use PVE::Storage::ZFSPoolPlugin;
use PVE::Storage::ZFSPlugin;
+use PVE::Storage::ZFSNVMePlugin;
use PVE::Storage::PBSPlugin;
use PVE::Storage::BTRFSPlugin;
use PVE::Storage::ESXiPlugin;
@@ -61,6 +62,7 @@ PVE::Storage::CephFSPlugin->register();
PVE::Storage::ISCSIDirectPlugin->register();
PVE::Storage::ZFSPoolPlugin->register();
PVE::Storage::ZFSPlugin->register();
+PVE::Storage::ZFSNVMePlugin->register();
PVE::Storage::PBSPlugin->register();
PVE::Storage::BTRFSPlugin->register();
PVE::Storage::ESXiPlugin->register();
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index a67dc25f..d1cbfe29 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -11,6 +11,7 @@ SOURCES= \
ISCSIDirectPlugin.pm \
ZFSPoolPlugin.pm \
ZFSPlugin.pm \
+ ZFSNVMePlugin.pm \
PBSPlugin.pm \
BTRFSPlugin.pm \
LvmThinPlugin.pm \
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index a9e17513..a5aedc2b 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -35,7 +35,7 @@ our @COMMON_TAR_FLAGS = qw(
);
our @SHARED_STORAGE = (
- 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs',
+ 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'zfsnvme', 'drbd', 'pbs',
);
our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/ZFSNVMePlugin.pm b/src/PVE/Storage/ZFSNVMePlugin.pm
new file mode 100644
index 00000000..127680fb
--- /dev/null
+++ b/src/PVE/Storage/ZFSNVMePlugin.pm
@@ -0,0 +1,3177 @@
+package PVE::Storage::ZFSNVMePlugin;
+
+use v5.36;
+
+use Compress::Zlib qw(crc32);
+use Digest::SHA qw(sha256_hex);
+use Errno qw(ENOENT);
+use Fcntl qw(O_NOFOLLOW O_RDONLY O_RDWR S_ISCHR);
+use File::Path qw(make_path);
+use List::Util qw(max);
+use MIME::Base64 qw(decode_base64);
+use POSIX qw(SIG_BLOCK SIG_SETMASK SIGHUP SIGINT SIGQUIT SIGTERM sigprocmask);
+use Socket qw(AF_INET6 inet_ntop inet_pton);
+use Time::HiRes;
+
+use PVE::Cluster;
+use PVE::File;
+use PVE::JSONSchema;
+use PVE::Network;
+use PVE::RESTEnvironment qw(log_warn);
+use PVE::RPCEnvironment;
+use PVE::SysFSTools;
+use PVE::Tools qw(file_read_firstline file_set_contents run_command trim);
+
+use base qw(PVE::Storage::Plugin);
+
+# ZFS zvols on a remote Linux target, exported through the kernel NVMe target
+# (nvmet, configured through configfs) over NVMe/TCP and consumed with native
+# NVMe multipath.
+#
+# The ZFS dataset is the source of truth for a namespace: its owner NQN, NSID
+# and UUID are ZFS user properties. Everything else on the target is derived
+# state that the plugin rebuilds after a target restart.
+#
+# Storage parsing, validation and planning happen locally. SSH carries quoted
+# commands, sometimes joined with `&&`, to read or change ZFS/configfs state.
+# A pmxcfs domain lock per target serializes the changes within the cluster,
+# held like the storage lock of the other shared storage types.
+
+# ---------------------------------------------------------------------------
+# Constants and regular expressions
+# ---------------------------------------------------------------------------
+
+# LogLevel=ERROR keeps a login banner out of the first stderr line, which is
+# the error text of a failed call.
+my @ssh_cmd = (
+ '/usr/bin/ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'LogLevel=ERROR',
+);
+my $id_rsa_path = '/etc/pve/priv/zfs';
+my $secret_dir = '/etc/pve/priv/storage';
+my $max_paths = 16;
+my $max_hosts = 64;
+my $slow_path_backoff = 60;
+
+my $nvmet_root = '/sys/kernel/config/nvmet';
+my $nvmet_model = 'Proxmox ZFS NVMe';
+my $nvmet_marker = 'ZFSNVME-CONFIGFS';
+my $nvmet_max_nsid = 0xfffffffe;
+my $nvmet_max_command = 65536;
+# Seconds to wait for the target lock while another node changes the target;
+# a destroy or rollback can hold it for several seconds.
+my $nvmet_lock_wait = 30;
+# On the pool dataset: the highest NSID handed out for a volume of the pool.
+my $nvmet_last_nsid = 'proxmox:nvme-last-nsid';
+
+my @nvmet_zfs_props =
+ ('type', 'proxmox:nvme-subsys', 'proxmox:nvme-nsid', 'proxmox:nvme-uuid', $nvmet_last_nsid);
+my %nvmet_zfs_keys = (
+ type => 'type',
+ 'proxmox:nvme-subsys' => 'nqn',
+ 'proxmox:nvme-nsid' => 'nsid',
+ 'proxmox:nvme-uuid' => 'uuid',
+ $nvmet_last_nsid => 'last_nsid',
+);
+my @nvmet_cfs_attrs = qw(
+ enable device_path device_uuid buffered_io
+ attr_model attr_serial attr_allow_any_host
+ addr_trtype addr_adrfam addr_traddr addr_trsvcid
+);
+# Every command the plugin runs on the target, besides the `dd | tee` pipe of
+# a key write. The configfs read runs find through env to set its locale.
+my %nvmet_commands = map { $_ => 1 } qw(
+ cat chmod env grep ln mkdir modprobe mount printf rm rmdir test zfs
+);
+
+my $RE_NQN = qr{
+ \A
+ nqn \.
+ [A-Za-z0-9] [A-Za-z0-9.-]*
+ :
+ [A-Za-z0-9] [A-Za-z0-9._:-]*
+ \z
+}nxx;
+my $RE_IPV4_PORTAL = qr{
+ \A
+ (?<address> [^:]+)
+ (?: : (?<port> [0-9]+))?
+ \z
+}nxx;
+my $RE_IPV6_PORTAL = qr{
+ \A
+ \[ (?<address> [^\]]+) \]
+ (?: : (?<port> [0-9]+))?
+ \z
+}nxx;
+# A canonical IPv4-mapped IPv6 address.
+my $RE_IPV4_MAPPED = qr{\A ::ffff: (?<address> [0-9.]+) \z}nxx;
+my $RE_HOST_IFACE = qr{\A [A-Za-z0-9_.-]+ \z}nxx;
+my $RE_DHCHAP_KEY = qr{
+ \A DHHC-1 : (?<hash> 0[0-3]) : (?<secret> [A-Za-z0-9+/]+ ={0,2}) : \z
+}nxx;
+# A stopped PVE task: the worker's signal handler dies with the first text,
+# run_command adds the command context, and run_fork_with_timeout reports
+# the signal in its own words.
+my $RE_TASK_INTERRUPT = qr{
+ \A (?: (?: command \x20 ' .* ' \x20 failed: \x20 )? received \x20 interrupt
+ | interrupted \x20 by \x20 unexpected \x20 signal ) \n \z
+}nsxx;
+my $RE_COMMAND_TIMEOUT = qr{
+ \A (?: command \x20 ' .* ' \x20 failed: \x20 )? got \x20 timeout \n \z
+}nsxx;
+my $RE_COMMAND_EXIT =
+ qr{\A command \x20 ' .* ' \x20 failed: \x20 exit \x20 code \x20 (?<code> [0-9]+) \n \z}nsxx;
+my $RE_FABRICS_VALUE = qr{\A [^\s,\x00]+ \z}nxx;
+my $RE_FABRICS_RESULT = qr{\A instance=(?<instance> [0-9]+) ,cntlid= [0-9]+ \n \z}nxx;
+my $RE_ZERO_UUID = qr{\A 0{8} (?: -0{4}){3} -0{12} \z}nxx;
+my $RE_CONFIG_INT = qr{\A -?[0-9]+ \z}nxx;
+my $RE_NVME_CONTROLLER = qr{\A nvme [0-9]+ \z}nxx;
+my $RE_NVME_SUBSYSTEM = qr{\A nvme-subsys [0-9]+ \z}nxx;
+my $RE_NVME_NAMESPACE = qr{\A nvme [0-9]+ n [0-9]+ \z}nxx;
+my $RE_NVME_PARTITION = qr{\A nvme [0-9]+ n [0-9]+ p [0-9]+ \z}nxx;
+my $RE_TRADDR = qr{(?: \A | ,) traddr=(?<value>[^,]+)}nxx;
+my $RE_TRSVCID = qr{(?: \A | ,) trsvcid=(?<value>[^,]+)}nxx;
+my $RE_HOST_IFACE_ADDRESS = qr{(?: \A | ,) host_iface=(?<value>[^,]+)}nxx;
+my $RE_ZVOL_OWNER = qr{^ (?:vm|base|subvol|basevol)- (?<owner>\d+) - \S+ $}nxx;
+my $RE_VOLNAME = qr{
+ ^
+ (?: (?<base> (?:base|basevol)- (?<base_vmid>\d+) - \S+) /)?
+ (?<name> (?<type>base|basevol|vm|subvol)- (?<vmid>\d+) - \S+)
+ $
+}nxx;
+my $RE_BASE_SNAPSHOT = qr{^ (?<base>\S+) \@__base__ $}nxx;
+my $RE_UNSIGNED_INTEGER = qr{^ (?<value>\d+) $}nxx;
+
+my $RE_NVMET_UUID = qr{\A [0-9a-fA-F]{8} (?: - [0-9a-fA-F]{4}){3} - [0-9a-fA-F]{12} \z}nxx;
+my $RE_NVMET_NSID = qr{\A [1-9] [0-9]* \z}nxx;
+my $RE_NVMET_POOL = qr{\A [A-Za-z0-9] [A-Za-z0-9_.:/-]* \z}nxx;
+my $RE_NVMET_DATASET_NAME = qr{\A [A-Za-z0-9] [A-Za-z0-9_.:-]* \z}nxx;
+my $RE_NVMET_SNAPSHOT = qr{\A [A-Za-z0-9_.:-]+ \z}nxx;
+my $RE_NVMET_TEMPLATE_ZVOL = qr{/ (?<type> vm | base) - (?<suffix> [^/]+) \z}nxx;
+my $RE_NVMET_INHERITED = qr{\A inherited \x20 from \x20 (?<source> .+) \z}nxx;
+# Errors after which the target state is not known: an interrupted task, or a
+# change whose command may still be running on the target.
+my $RE_NVMET_ABANDONED = qr{
+ (?: \A received \x20 interrupt | ; \x20 the \x20 target \x20 state \x20 is \x20 unknown) \n \z
+}nxx;
+
+# Lines of the configfs read (nvmet_configfs_step below): `D <dir>`,
+# `L <link>`, `<file>:<value>` from grep, and `<sha256> <file>` from
+# sha256sum. Attribute names anchor the split, so an NQN containing ':' is
+# never ambiguous.
+my $cfs_root = quotemeta($nvmet_root);
+my $RE_CFS_TOP = qr{\A D \x20 $cfs_root (?: / (?<top> hosts | ports | subsystems))? \z}nxx;
+my $RE_CFS_SUBSYS_DIR = qr{\A D \x20 $cfs_root /subsystems/ (?<nqn> [^/]+) \z}nxx;
+my $RE_CFS_SUBSYS_GROUP = qr{
+ \A D \x20 $cfs_root /subsystems/ [^/]+ / (?: namespaces | allowed_hosts) \z
+}nxx;
+my $RE_CFS_NS_DIR = qr{
+ \A D \x20 $cfs_root /subsystems/ (?<nqn> [^/]+) /namespaces/ (?<nsid> [0-9]+) \z
+}nxx;
+my $RE_CFS_PORT_DIR = qr{\A D \x20 $cfs_root /ports/ (?<port> [0-9]+) \z}nxx;
+my $RE_CFS_PORT_GROUP = qr{\A D \x20 $cfs_root /ports/ [0-9]+ /subsystems \z}nxx;
+my $RE_CFS_HOST_DIR = qr{\A D \x20 $cfs_root /hosts/ (?<host> [^/]+) \z}nxx;
+my $RE_CFS_PORT_LINK = qr{
+ \A L \x20 $cfs_root /ports/ (?<port> [0-9]+) /subsystems/ (?<nqn> [^/]+) \z
+}nxx;
+my $RE_CFS_ACL_LINK = qr{
+ \A L \x20 $cfs_root /subsystems/ (?<nqn> [^/]+) /allowed_hosts/ (?<host> [^/]+) \z
+}nxx;
+my $RE_CFS_OTHER_ENTRY = qr{\A [DL] \x20 $cfs_root /}nxx;
+my $RE_CFS_NS_ATTR = qr{
+ \A $cfs_root /subsystems/ (?<nqn> [^/]+) /namespaces/ (?<nsid> [0-9]+)
+ / (?<attr> enable | device_path | device_uuid | buffered_io) : (?<value> .*) \z
+}nxx;
+my $RE_CFS_SUBSYS_ATTR = qr{
+ \A $cfs_root /subsystems/ (?<nqn> [^/]+)
+ / (?<attr> attr_model | attr_serial | attr_allow_any_host) : (?<value> .*) \z
+}nxx;
+my $RE_CFS_PORT_ATTR = qr{
+ \A $cfs_root /ports/ (?<port> [0-9]+)
+ / (?<attr> addr_trtype | addr_adrfam | addr_traddr | addr_trsvcid) : (?<value> .*) \z
+}nxx;
+my $RE_CFS_KEY_DIGEST = qr{
+ \A (?<sha> [0-9a-f]{64}) \x20 [\x20*] $cfs_root /hosts/ (?<host> [^/]+) /dhchap_key \z
+}nxx;
+my $RE_CFS_OTHER_ATTR = qr{\A $cfs_root /}nxx;
+
+# ---------------------------------------------------------------------------
+# Target addressing and validated names
+# ---------------------------------------------------------------------------
+
+my sub nvmet_server($scfg) {
+ return $scfg->{server};
+}
+
+my sub nvmet_ssh_key($scfg) {
+ return "$id_rsa_path/" . nvmet_server($scfg) . '_id_rsa';
+}
+
+my sub nvmet_lock_id($scfg) {
+ my $server = nvmet_server($scfg) // '';
+ return 'zfsnvme-' . ($server =~ s/[^A-Za-z0-9.-]/_/gr);
+}
+
+my sub secret_path($storeid) {
+ return "$secret_dir/$storeid.nvme-dhchap";
+}
+
+my sub nvmet_nqn($scfg) {
+ my $nqn = $scfg->{subsysnqn};
+ die "invalid NVMe subsystem NQN\n" if !defined($nqn) || !verify_nvme_nqn($nqn, 1);
+ return $nqn;
+}
+
+my sub nvmet_pool($scfg) {
+ my $pool = $scfg->{pool};
+ die "invalid ZFS pool name\n" if !defined($pool) || $pool !~ $RE_NVMET_POOL;
+ return $pool;
+}
+
+my sub nvmet_dataset($scfg, $name) {
+ die "invalid ZFS volume name\n" if !defined($name) || $name !~ $RE_NVMET_DATASET_NAME;
+ return nvmet_pool($scfg) . "/$name";
+}
+
+# zfs destroy reads '%' and ',' in a snapshot name as a range and a list.
+my sub nvmet_snapshot($scfg, $name, $snap) {
+ die "invalid snapshot name\n" if !defined($snap) || $snap !~ $RE_NVMET_SNAPSHOT;
+ return nvmet_dataset($scfg, $name) . "\@$snap";
+}
+
+my sub nvmet_valid_nsid($value) {
+ return defined($value) && $value =~ $RE_NVMET_NSID && $value <= $nvmet_max_nsid;
+}
+
+# IPv6 addresses have many spellings; compare and store only the canonical one.
+my sub nvmet_canonical_address($address) {
+ return $address if !defined($address) || index($address, ':') < 0;
+ my $packed = inet_pton(AF_INET6, $address) // return $address;
+ return inet_ntop(AF_INET6, $packed);
+}
+
+# The address family and address that a portal of parse_nvme_portals reaches:
+# an IPv4-mapped IPv6 address reaches the IPv4 address.
+my sub nvmet_listener_address($portal) {
+ return ('ipv4', $+{address})
+ if $portal->{family} eq 'ipv6' && $portal->{address} =~ $RE_IPV4_MAPPED;
+ return $portal->@{qw(family address)};
+}
+
+# Target-provided names only appear in messages when they are well-formed.
+my sub nvmet_label($name) {
+ return $name =~ $RE_NQN ? " '$name'" : '';
+}
+
+# The other name of a zvol that a template conversion renames: vm-* and base-*.
+my sub nvmet_template_twin($name) {
+ return '' if $name !~ $RE_NVMET_TEMPLATE_ZVOL;
+ my $twin = ($+{type} eq 'vm' ? 'base' : 'vm') . "-$+{suffix}";
+ return substr($name, 0, $-[0]) . "/$twin";
+}
+
+# The timeout of a call that changes ZFS: ZFS waits for transaction groups,
+# which a busy pool can take minutes to sync.
+my sub nvmet_long_timeout() {
+ return PVE::RPCEnvironment->is_worker() ? 60 * 60 : 60;
+}
+
+# ---------------------------------------------------------------------------
+# Remote steps
+#
+# A step is an argv array, a write `{ write => $path, value => $value }` or a
+# key write `{ key => [$path, ...] }` fed from stdin. A unit is a list of steps
+# that must stay in one call.
+# ---------------------------------------------------------------------------
+
+my sub nvmet_subsys_path($nqn) {
+ return "$nvmet_root/subsystems/$nqn";
+}
+
+my sub nvmet_ns_path($nqn, $nsid) {
+ return "$nvmet_root/subsystems/$nqn/namespaces/$nsid";
+}
+
+my sub nvmet_port_path($id) {
+ return "$nvmet_root/ports/$id";
+}
+
+my sub nvmet_host_path($hostnqn) {
+ return "$nvmet_root/hosts/$hostnqn";
+}
+
+my sub nvmet_write($path, $value) {
+ return { write => $path, value => $value };
+}
+
+# Parts of a parsed configfs state; missing parts read as empty.
+my sub nvmet_namespaces($cfs, $nqn) {
+ my $subsys = $cfs->{subsystems}->{$nqn};
+ return ($subsys ? $subsys->{namespaces} : undef) // {};
+}
+
+my sub nvmet_port_linked($cfs, $id, $nqn) {
+ my $port = $cfs->{ports}->{$id};
+ return $port && ($port->{links} // {})->{$nqn};
+}
+
+my sub nvmet_linked_hosts($cfs) {
+ my %linked;
+ for my $subsys (values $cfs->{subsystems}->%*) {
+ $linked{$_} = 1 for keys(($subsys->{acl} // {})->%*);
+ }
+ return \%linked;
+}
+
+# A subsystem whose creation by this plugin stopped after its model was
+# written, before its serial: nobody else writes our model, and it exports,
+# allows and publishes nothing, so completing it takes nothing from anybody.
+# A subsystem with the kernel's default model may belong to another tool.
+my sub nvmet_unfinished_subsystem($cfs, $nqn) {
+ my $subsys = $cfs->{subsystems}->{$nqn};
+ return 0 if !$subsys;
+ return
+ $subsys->{attr_model} eq $nvmet_model
+ && !($subsys->{namespaces} // {})->%*
+ && !($subsys->{acl} // {})->%*
+ && !grep { nvmet_port_linked($cfs, $_, $nqn) } keys $cfs->{ports}->%*;
+}
+
+# Same write order as the kernel requires: the device before enabling it.
+my sub nvmet_build_unit($nqn, $nsid, $uuid, $dev) {
+ my $ns = nvmet_ns_path($nqn, $nsid);
+ return [
+ ['test', '-b', $dev],
+ ['mkdir', $ns],
+ nvmet_write("$ns/device_path", $dev),
+ nvmet_write("$ns/device_uuid", $uuid),
+ nvmet_write("$ns/buffered_io", 0),
+ nvmet_write("$ns/enable", 1),
+ ];
+}
+
+my sub nvmet_enable_unit($nqn, $nsid, $dev) {
+ return [['test', '-b', $dev], nvmet_write(nvmet_ns_path($nqn, $nsid) . '/enable', 1)];
+}
+
+my sub nvmet_unexport_unit($nqn, $nsid, $enabled) {
+ my $ns = nvmet_ns_path($nqn, $nsid);
+ return [($enabled ? (nvmet_write("$ns/enable", 0)) : ()), ['rmdir', $ns]];
+}
+
+my sub nvmet_identity($nqn, $nsid, $uuid) {
+ return ("proxmox:nvme-subsys=$nqn", "proxmox:nvme-nsid=$nsid", "proxmox:nvme-uuid=$uuid");
+}
+
+# The pool and its direct children with their identity properties.
+my sub nvmet_zfs_inventory_step($pool) {
+ return [
+ 'zfs',
+ 'get',
+ '-H',
+ '-p',
+ '-d',
+ '1',
+ '-t',
+ 'filesystem,volume',
+ '-o',
+ 'name,property,value,source',
+ join(',', @nvmet_zfs_props),
+ $pool,
+ ];
+}
+
+# Every configfs object the plugin uses, in one traversal. Keys are never
+# read back; with host NQNs, only their sha256 digests are returned. Only the
+# kernel's own groups of objects the plugin does not use are skipped, so an
+# object of another tool with one of their names is still listed.
+my sub nvmet_configfs_step($hostnqns) {
+ my @names = map { ('-o', '-name', $_) } @nvmet_cfs_attrs;
+ shift @names;
+ my @keys = map { ('-o', '-path', nvmet_host_path($_) . '/dhchap_key') } $hostnqns->@*;
+ shift @keys;
+ return [
+ 'env',
+ 'LC_ALL=C',
+ 'find',
+ $nvmet_root,
+ '(',
+ '-path',
+ "$nvmet_root/subsystems/*/passthru",
+ '-o',
+ '-path',
+ "$nvmet_root/ports/*/ana_groups",
+ '-o',
+ '-path',
+ "$nvmet_root/ports/*/referrals",
+ ')',
+ '-type',
+ 'd',
+ '-prune',
+ '-o',
+ '-type',
+ 'd',
+ '-exec',
+ 'printf',
+ 'D %s\n',
+ '{}',
+ '+',
+ '-o',
+ '-type',
+ 'l',
+ '-exec',
+ 'printf',
+ 'L %s\n',
+ '{}',
+ '+',
+ '-o',
+ '-type',
+ 'f',
+ '(',
+ @names,
+ ')',
+ '-exec',
+ 'grep',
+ '',
+ '/dev/null',
+ '{}',
+ '+',
+ (@keys ? ('-o', '-type', 'f', '(', @keys, ')', '-exec', 'sha256sum', '{}', '+') : ()),
+ ];
+}
+
+# The whole target state: the ZFS inventory, a marker and configfs. Only a
+# locked read loads nvmet first (modprobe).
+my sub nvmet_state_steps($pool, $hostnqns, $modprobe) {
+ return [
+ ($modprobe ? (['modprobe', 'nvmet_tcp']) : ()),
+ nvmet_zfs_inventory_step($pool),
+ ['printf', '%s\n', $nvmet_marker],
+ nvmet_configfs_step($hostnqns),
+ ];
+}
+
+# ---------------------------------------------------------------------------
+# Renderer and runner
+# ---------------------------------------------------------------------------
+
+my sub nvmet_valid_word($word) {
+ return defined($word) && !ref($word) && $word !~ /[\0\r\n]/;
+}
+
+my sub nvmet_valid_path($path) {
+ return nvmet_valid_word($path) && $path =~ m{\A/};
+}
+
+my sub nvmet_quote($word) {
+ return PVE::Tools::shellquote($word);
+}
+
+# Renders steps into one POSIX shell command line: simple commands joined with
+# `&&`, plus `>` for configfs writes and one `dd | tee` pipe for a key read from
+# stdin. There are no loops, variables, conditionals or substitutions. Every
+# word is quoted; all operands are built from validated configuration.
+sub _nvmet_render($steps) {
+ my $invalid = "internal error: invalid NVMe target step\n";
+ die $invalid if ref($steps) ne 'ARRAY' || !$steps->@*;
+
+ my $keys = 0;
+ my @commands;
+ for my $step ($steps->@*) {
+ if (ref($step) eq 'ARRAY') {
+ die $invalid if !$step->@* || grep { !nvmet_valid_word($_) } $step->@*;
+ die $invalid if !$nvmet_commands{ $step->[0] };
+ push @commands, join(' ', map { nvmet_quote($_) } $step->@*);
+ } elsif (ref($step) eq 'HASH' && exists($step->{write})) {
+ die $invalid
+ if keys($step->%*) != 2
+ || !nvmet_valid_path($step->{write})
+ || !nvmet_valid_word($step->{value});
+ push @commands,
+ q{printf '%s\n' }
+ . nvmet_quote($step->{value}) . ' > '
+ . nvmet_quote($step->{write});
+ } elsif (ref($step) eq 'HASH' && exists($step->{key})) {
+ my $paths = $step->{key};
+ die $invalid
+ if keys($step->%*) != 1
+ || ref($paths) ne 'ARRAY'
+ || !$paths->@*
+ || grep { !nvmet_valid_path($_) } $paths->@*;
+ $keys++;
+ die $invalid if $keys > 1;
+ # configfs needs the whole key in one write(2). dd collects its
+ # input into one output block: GNU dd without bs=, busybox dd only
+ # when ibs and obs differ. tee writes it to every host object.
+ push @commands,
+ 'dd ibs=4096 obs=8192 2>/dev/null | tee '
+ . join(' ', map { nvmet_quote($_) } $paths->@*)
+ . ' >/dev/null';
+ } else {
+ die $invalid;
+ }
+ }
+ return join(' && ', @commands);
+}
+
+# Packs whole units into calls of at most $max bytes of rendered command, the
+# single argument sshd runs, below its limit. A rendered command is ASCII
+# (every operand is validated), so its length is its size in bytes.
+sub _nvmet_chunk($units, $max = $nvmet_max_command) {
+ my (@chunks, @current);
+ for my $unit ($units->@*) {
+ my @next = (@current, $unit->@*);
+ if (length(_nvmet_render(\@next)) > $max) {
+ die "internal error: NVMe target command too long\n"
+ if !@current || length(_nvmet_render($unit)) > $max;
+ push @chunks, [@current];
+ @next = $unit->@*;
+ }
+ @current = @next;
+ }
+ push @chunks, [@current] if @current;
+ return \@chunks;
+}
+
+# Never propagate the context run_command adds to the task marker: it quotes
+# the command line.
+my sub rethrow_task_interrupt($error) {
+ die "received interrupt\n" if $error =~ $RE_TASK_INTERRUPT;
+}
+
+# The only code that runs anything on the target. Returns
+# { rc => exit code, or -1 when ssh did not run to its end, out => [lines],
+# err => text } and never dies on a failing command; a stopped task dies with
+# the task marker. %opts: op (label, required), timeout and input (stdin,
+# used for keys).
+sub _nvmet_run($scfg, $steps, %opts) {
+ die "internal error: NVMe target call without label\n" if !defined($opts{op});
+ my $command = _nvmet_render($steps);
+ die "internal error: NVMe target command too long\n" if length($command) > $nvmet_max_command;
+ my $cmd = [@ssh_cmd, '-i', nvmet_ssh_key($scfg), 'root@' . nvmet_server($scfg), $command];
+ my (@out, $err);
+ my $rc = 0;
+ # Not noerr: run_command would then also swallow the interrupt of a stopped
+ # task, which must end the call. The exit code is taken from the exception.
+ eval {
+ run_command(
+ $cmd,
+ timeout => $opts{timeout} // 15,
+ outfunc => sub($line) { push @out, $line },
+ errfunc => sub($line) { $err = $line if !defined($err) && $line ne '' },
+ (defined($opts{input}) ? (input => $opts{input}) : ()),
+ );
+ };
+ if (my $error = $@) {
+ rethrow_task_interrupt($error);
+ return { rc => -1, out => [], err => 'timeout' } if $error =~ $RE_COMMAND_TIMEOUT;
+ return { rc => -1, out => [], err => 'ssh failed' } if $error !~ $RE_COMMAND_EXIT;
+ $rc = $+{code};
+ }
+ return { rc => $rc, out => \@out, err => $err // ($rc ? "exit code $rc" : '') };
+}
+
+# Monotonic clock for the activation backoff and local waits (a test seam).
+sub _now() {
+ return Time::HiRes::clock_gettime(Time::HiRes::CLOCK_MONOTONIC());
+}
+
+# Every local wait of the plugin (a test seam).
+sub _sleep($seconds) {
+ Time::HiRes::sleep($seconds);
+ return;
+}
+
+# ---------------------------------------------------------------------------
+# Parsers (pure)
+# ---------------------------------------------------------------------------
+
+sub _nvmet_split_state($text) {
+ my @parts = split /^\Q$nvmet_marker\E\n/m, $text, -1;
+ die "malformed NVMe target state\n" if @parts != 2;
+ return @parts;
+}
+
+sub _nvmet_property_value($value, $source) {
+ die "malformed ZFS property value\n"
+ if !defined($value)
+ || !defined($source)
+ || $value eq ''
+ || $source eq ''
+ || $value =~ /[\r\n\t]/
+ || $source =~ /[\r\n\t]/;
+ return $value if $source eq 'local' || $source eq 'received';
+ return '-' if $value eq '-' && $source eq '-';
+ if ($source =~ $RE_NVMET_INHERITED) {
+ die "invalid ZFS pool name\n" if $+{source} !~ $RE_NVMET_POOL;
+ return '-';
+ }
+ die "invalid ZFS property source\n";
+}
+
+# Parses the ZFS inventory into { types => { dataset => type }, volumes =>
+# { dataset => { nqn, nsid, uuid } }, last_nsid => highest NSID handed out }.
+# The inventory must be complete: the pool rows and all rows of every
+# dataset, or the read fails. Children whose names PVE never uses (for
+# example with a space) are kept as datasets but never count as owned.
+sub _nvmet_parse_zfs_inventory($text, $pool) {
+ die "invalid ZFS pool name\n" if $pool !~ $RE_NVMET_POOL;
+
+ my (%rows, %foreign);
+ for my $line (split /\n/, $text) {
+ my @fields = split /\t/, $line, -1;
+ die "malformed ZFS inventory row\n" if @fields != 4 || $line =~ /\r/;
+ my ($dataset, $property, $value, $source) = @fields;
+ if ($dataset ne $pool) {
+ die "ZFS dataset is outside configured pool\n" if index($dataset, "$pool/") != 0;
+ my $child = substr($dataset, length($pool) + 1);
+ die "ZFS dataset is outside configured pool\n"
+ if $child eq '' || index($child, '/') >= 0;
+ $foreign{$dataset} = 1 if $child !~ $RE_NVMET_DATASET_NAME;
+ }
+ my $on = $foreign{$dataset} ? '' : " on '$dataset'";
+ my $key = $nvmet_zfs_keys{$property} // die "unexpected ZFS property$on\n";
+ die "duplicate ZFS property '$property'$on\n" if exists($rows{$dataset}->{$key});
+ if ($key eq 'type') {
+ die "invalid ZFS dataset type$on\n"
+ if ($value ne 'filesystem' && $value ne 'volume') || $source ne '-';
+ $rows{$dataset}->{type} = $value;
+ } else {
+ $rows{$dataset}->{$key} = _nvmet_property_value($value, $source);
+ }
+ }
+ die "ZFS dataset inventory is missing the configured pool\n" if !$rows{$pool};
+
+ my (%types, %volumes);
+ for my $dataset (keys %rows) {
+ my $row = $rows{$dataset};
+ die "incomplete ZFS properties" . ($foreign{$dataset} ? '' : " on '$dataset'") . "\n"
+ if keys($row->%*) != scalar(@nvmet_zfs_props);
+ $types{$dataset} = $row->{type};
+ next if $row->{type} ne 'volume';
+ # nvmet shows device_uuid and udev names the by-id link in lower case,
+ # so identities are compared in lower case.
+ $volumes{$dataset} =
+ $foreign{$dataset}
+ ? { nqn => '-', nsid => '-', uuid => '-' }
+ : { nqn => $row->{nqn}, nsid => $row->{nsid}, uuid => lc($row->{uuid}) };
+ }
+ my $last_nsid = $rows{$pool}->{last_nsid};
+ return {
+ types => \%types,
+ volumes => \%volumes,
+ last_nsid => nvmet_valid_nsid($last_nsid) ? $last_nsid : 0,
+ };
+}
+
+# Parses the configfs read into
+# { subsystems => { nqn => { attr_model, attr_serial, attr_allow_any_host,
+# acl => { hostnqn => 1 }, namespaces => { nsid => { enable, device_path,
+# device_uuid, buffered_io } } } },
+# ports => { id => { addr_trtype, addr_adrfam, addr_traddr, addr_trsvcid,
+# links => { nqn => 1 } } },
+# hosts => { hostnqn => { key_sha256 => hex or undef } } }
+# Every object must be complete; unknown objects of newer kernels are ignored.
+sub _nvmet_parse_configfs($text) {
+ my $state = { subsystems => {}, ports => {}, hosts => {} };
+ my (%top, %dir);
+
+ my $subsystem = sub($nqn) {
+ return $state->{subsystems}->{$nqn} //= { acl => {}, namespaces => {} };
+ };
+ my $namespace = sub($nqn, $nsid) {
+ return $subsystem->($nqn)->{namespaces}->{$nsid} //= {};
+ };
+ my $port = sub($id) { return $state->{ports}->{$id} //= { links => {} } };
+ my $host = sub($hostnqn) { return $state->{hosts}->{$hostnqn} //= { key_sha256 => undef } };
+ my $set = sub($object, $attr, $value) {
+ die "duplicate NVMe target configfs attribute\n" if exists($object->{$attr});
+ $object->{$attr} = $value;
+ };
+
+ for my $line (split /\n/, $text) {
+ if ($line =~ $RE_CFS_TOP) {
+ $top{ $+{top} // 'root' } = 1;
+ } elsif ($line =~ $RE_CFS_SUBSYS_DIR) {
+ my $nqn = $+{nqn};
+ $subsystem->($nqn);
+ $dir{"subsystem $nqn"} = 1;
+ } elsif ($line =~ $RE_CFS_SUBSYS_GROUP || $line =~ $RE_CFS_PORT_GROUP) {
+ # default groups, always present with their parent
+ } elsif ($line =~ $RE_CFS_NS_DIR) {
+ my ($nqn, $nsid) = @+{qw(nqn nsid)};
+ $namespace->($nqn, $nsid);
+ $dir{"namespace $nqn/$nsid"} = 1;
+ } elsif ($line =~ $RE_CFS_PORT_DIR) {
+ my $id = $+{port};
+ $port->($id);
+ $dir{"port $id"} = 1;
+ } elsif ($line =~ $RE_CFS_HOST_DIR) {
+ my $hostnqn = $+{host};
+ $host->($hostnqn);
+ $dir{"host $hostnqn"} = 1;
+ } elsif ($line =~ $RE_CFS_PORT_LINK) {
+ my ($id, $nqn) = @+{qw(port nqn)};
+ $port->($id)->{links}->{$nqn} = 1;
+ } elsif ($line =~ $RE_CFS_ACL_LINK) {
+ my ($nqn, $hostnqn) = @+{qw(nqn host)};
+ $subsystem->($nqn)->{acl}->{$hostnqn} = 1;
+ } elsif ($line =~ $RE_CFS_OTHER_ENTRY) {
+ # objects of a shape the plugin does not use
+ } elsif ($line =~ $RE_CFS_NS_ATTR) {
+ my ($nqn, $nsid, $attr, $value) = @+{qw(nqn nsid attr value)};
+ $set->($namespace->($nqn, $nsid), $attr, $value);
+ } elsif ($line =~ $RE_CFS_SUBSYS_ATTR) {
+ my ($nqn, $attr, $value) = @+{qw(nqn attr value)};
+ $set->($subsystem->($nqn), $attr, $value);
+ } elsif ($line =~ $RE_CFS_PORT_ATTR) {
+ my ($id, $attr, $value) = @+{qw(port attr value)};
+ $set->($port->($id), $attr, $value);
+ } elsif ($line =~ $RE_CFS_KEY_DIGEST) {
+ my ($sha, $hostnqn) = @+{qw(sha host)};
+ my $object = $host->($hostnqn);
+ die "duplicate DH-HMAC-CHAP key digest" . nvmet_label($hostnqn) . "\n"
+ if defined($object->{key_sha256});
+ $object->{key_sha256} = $sha;
+ } elsif ($line =~ $RE_CFS_OTHER_ATTR) {
+ # attribute of an object shape the plugin does not use
+ } else {
+ die "unexpected NVMe target configfs line\n";
+ }
+ }
+
+ for my $name (qw(root hosts ports subsystems)) {
+ die "NVMe target configfs is unavailable\n" if !$top{$name};
+ }
+ for my $nqn (keys $state->{subsystems}->%*) {
+ my $subsys = $state->{subsystems}->{$nqn};
+ die "incomplete NVMe subsystem" . nvmet_label($nqn) . "\n"
+ if !$dir{"subsystem $nqn"}
+ || grep { !defined($subsys->{$_}) } qw(attr_model attr_serial attr_allow_any_host);
+ for my $nsid (keys $subsys->{namespaces}->%*) {
+ my $ns = $subsys->{namespaces}->{$nsid};
+ die "incomplete NVMe namespace '$nsid' of subsystem" . nvmet_label($nqn) . "\n"
+ if !$dir{"namespace $nqn/$nsid"}
+ || grep { !defined($ns->{$_}) } qw(enable device_path device_uuid buffered_io);
+ }
+ }
+ for my $id (keys $state->{ports}->%*) {
+ my $object = $state->{ports}->{$id};
+ my @attrs = qw(addr_trtype addr_adrfam addr_traddr addr_trsvcid);
+ die "incomplete NVMe port '$id'\n"
+ if !$dir{"port $id"} || grep { !defined($object->{$_}) } @attrs;
+ }
+ for my $hostnqn (keys $state->{hosts}->%*) {
+ die "DH-HMAC-CHAP key digest for unknown NVMe host" . nvmet_label($hostnqn) . "\n"
+ if !$dir{"host $hostnqn"};
+ }
+ return $state;
+}
+
+sub _nvmet_parse_mounts($text) {
+ for my $line (split /\n/, $text) {
+ my (undef, $mountpoint, $type) = split / /, $line;
+ return 1 if ($mountpoint // '') eq '/sys/kernel/config' && ($type // '') eq 'configfs';
+ }
+ return 0;
+}
+
+# ---------------------------------------------------------------------------
+# Planners (pure)
+# ---------------------------------------------------------------------------
+
+sub _nvmet_serial($nqn) {
+ return 'PVEZFS' . substr(sha256_hex($nqn), 0, 14);
+}
+
+sub _nvmet_template_name($dataset) {
+ die "only VM zvols can become templates\n"
+ if $dataset !~ $RE_NVMET_TEMPLATE_ZVOL || $+{type} ne 'vm';
+ return nvmet_template_twin($dataset);
+}
+
+# The durable identity (NSID, UUID) of a volume owned by $nqn. Refuses a
+# volume that another owned volume duplicates anywhere in the pool.
+sub _nvmet_owned_identity($inv, $nqn, $dataset) {
+ my $type = $inv->{types}->{$dataset} // die "ZFS volume '$dataset' does not exist\n";
+ die "'$dataset' is not a ZFS volume\n" if $type ne 'volume';
+ my $row = $inv->{volumes}->{$dataset};
+ die "ZFS volume '$dataset' is not owned by NVMe subsystem '$nqn'\n" if $row->{nqn} ne $nqn;
+ die "invalid NSID on '$dataset'\n" if !nvmet_valid_nsid($row->{nsid});
+ die "invalid namespace UUID on '$dataset'\n" if $row->{uuid} !~ $RE_NVMET_UUID;
+ for my $other (keys $inv->{volumes}->%*) {
+ next if $other eq $dataset;
+ my $identity = $inv->{volumes}->{$other};
+ next if $identity->{nqn} ne $nqn;
+ die "duplicate NVMe identity on '$dataset'\n"
+ if $identity->{nsid} eq $row->{nsid} || $identity->{uuid} eq $row->{uuid};
+ }
+ return ($row->{nsid}, $row->{uuid});
+}
+
+# { nsid => [uuid, device] } for every volume owned by $nqn, after validating
+# all of them, so a bad identity refuses the whole plan before any change.
+sub _nvmet_desired_namespaces($inv, $nqn) {
+ my (%desired, %uuids);
+ for my $dataset (sort keys $inv->{volumes}->%*) {
+ my $row = $inv->{volumes}->{$dataset};
+ next if $row->{nqn} ne $nqn;
+ die "invalid NSID on '$dataset'\n" if !nvmet_valid_nsid($row->{nsid});
+ die "invalid namespace UUID on '$dataset'\n" if $row->{uuid} !~ $RE_NVMET_UUID;
+ die "duplicate NSID '$row->{nsid}'\n" if $desired{ $row->{nsid} };
+ die "duplicate namespace UUID '$row->{uuid}'\n" if $uuids{ lc($row->{uuid}) }++;
+ $desired{ $row->{nsid} } = [$row->{uuid}, "/dev/zvol/$dataset"];
+ }
+ return \%desired;
+}
+
+# NSIDs grow monotonically, also past the last NSID handed out in the pool,
+# so a host that missed a namespace removal never sees a new volume at an old
+# NSID. Only after the last NSID is used does the allocation fall back to the
+# lowest free one.
+sub _nvmet_allocate_nsid($inv, $cfs, $nqn) {
+ my %used;
+ for my $row (values $inv->{volumes}->%*) {
+ $used{ $row->{nsid} } = 1 if $row->{nqn} eq $nqn && nvmet_valid_nsid($row->{nsid});
+ }
+ $used{$_} = 1 for keys nvmet_namespaces($cfs, $nqn)->%*;
+
+ my $highest = max(0, $inv->{last_nsid} // 0, keys %used);
+ return $highest + 1 if $highest < $nvmet_max_nsid;
+ my $nsid = 1;
+ $nsid++ while $used{$nsid};
+ die "no free namespace ID\n" if $nsid > $nvmet_max_nsid;
+ return $nsid;
+}
+
+# Export state of (NSID, UUID, device) in the subsystem: present, disabled,
+# absent, incomplete (a disabled namespace with another identity, for example
+# one being built), stale (enabled on the other template name of the zvol) or
+# nosubsys. Dies on a conflict.
+sub _nvmet_export_state($cfs, $nqn, $nsid, $uuid, $dev) {
+ return 'nosubsys' if !$cfs->{subsystems}->{$nqn};
+ my $namespaces = nvmet_namespaces($cfs, $nqn);
+ for my $id (keys $namespaces->%*) {
+ next if $id eq $nsid;
+ die "namespace UUID '$uuid' is already in use\n"
+ if $namespaces->{$id}->{device_uuid} eq $uuid;
+ }
+ my $ns = $namespaces->{$nsid} // return 'absent';
+ if ($ns->{device_uuid} eq $uuid && $ns->{device_path} eq $dev) {
+ return $ns->{enable} eq '1' ? 'present' : 'disabled';
+ }
+ # A template conversion or its undo that ssh gave up on can rename the
+ # zvol on the target after an activation exported it under its old name.
+ my $twin = nvmet_template_twin($dev);
+ return 'stale'
+ if $ns->{enable} eq '1'
+ && $ns->{device_uuid} eq $uuid
+ && $twin ne ''
+ && $ns->{device_path} eq $twin;
+ die "NVMe namespace ID '$nsid' has a different identity; refusing to replace it\n"
+ if $ns->{enable} ne '0';
+ return 'incomplete';
+}
+
+# Units that export (NSID, UUID, device) and the state they start from:
+# absent, present, disabled, reclaim or stale. A disabled namespace with
+# another identity, or a stale one, is rebuilt, which is only correct under
+# the target lock. A stale namespace belongs to a template, or to a volume
+# whose template conversion failed, so no guest uses it.
+sub _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev) {
+ die "NVMe subsystem does not exist\n" if !$cfs->{subsystems}->{$nqn};
+ my $state = _nvmet_export_state($cfs, $nqn, $nsid, $uuid, $dev);
+ return ([nvmet_build_unit($nqn, $nsid, $uuid, $dev)], 'absent') if $state eq 'absent';
+ return ([], 'present') if $state eq 'present';
+ return ([nvmet_enable_unit($nqn, $nsid, $dev)], 'disabled') if $state eq 'disabled';
+ my $unexport = nvmet_unexport_unit($nqn, $nsid, $state eq 'stale');
+ my $build = nvmet_build_unit($nqn, $nsid, $uuid, $dev);
+ return ([[$unexport->@*, $build->@*]], $state eq 'stale' ? 'stale' : 'reclaim');
+}
+
+# Units that remove the namespace exporting $uuid, and its previous state.
+sub _nvmet_plan_unexport($cfs, $nqn, $uuid) {
+ my $namespaces = nvmet_namespaces($cfs, $nqn);
+ my @matches = grep { $namespaces->{$_}->{device_uuid} eq $uuid }
+ sort { $a <=> $b } keys $namespaces->%*;
+ die "duplicate namespace UUID '$uuid'\n" if @matches > 1;
+ return ([], undef) if !@matches;
+ my $enabled = $namespaces->{ $matches[0] }->{enable} eq '1';
+ return (
+ [nvmet_unexport_unit($nqn, $matches[0], $enabled)],
+ { nsid => $matches[0], enabled => $enabled },
+ );
+}
+
+# The port serving a portal ({ family, address, port } of parse_nvme_portals).
+# Among complete, matching ports, the one already linked to $nqn wins, then
+# the lowest id. Incomplete ports never match.
+sub _nvmet_find_port($cfs, $nqn, $portal) {
+ my $wanted = nvmet_canonical_address($portal->{address});
+ my @matches = grep {
+ my $port = $cfs->{ports}->{$_};
+ $port->{addr_trtype} eq 'tcp'
+ && $port->{addr_adrfam} eq $portal->{family}
+ && $port->{addr_traddr} ne ''
+ && $port->{addr_trsvcid} eq "$portal->{port}"
+ && nvmet_canonical_address($port->{addr_traddr}) eq $wanted
+ } sort {
+ $a <=> $b
+ } keys $cfs->{ports}->%*;
+ my @linked = grep { nvmet_port_linked($cfs, $_, $nqn) } @matches;
+ return $linked[0] // $matches[0];
+}
+
+# Units that bring the target to the configured state, except publishing:
+# objects (subsystem, ports, hosts), keys, ACLs, namespaces in NSID order,
+# then removal of undesired namespaces.
+# $conf: { nqn, portals (of parse_nvme_portals), hostnqns, keysha }
+sub _nvmet_plan_activation($inv, $cfs, $conf) {
+ my ($nqn, $keysha) = $conf->@{qw(nqn keysha)};
+ my $desired = _nvmet_desired_namespaces($inv, $nqn); # refuse before any unit
+ my $subsys_path = nvmet_subsys_path($nqn);
+ my $subsys = $cfs->{subsystems}->{$nqn};
+ my (@objects, @key_hosts, @acls, @namespaces, %port_ids);
+
+ if (!$subsys) {
+ push @objects,
+ [
+ ['mkdir', $subsys_path],
+ nvmet_write("$subsys_path/attr_model", $nvmet_model),
+ nvmet_write("$subsys_path/attr_serial", _nvmet_serial($nqn)),
+ nvmet_write("$subsys_path/attr_allow_any_host", 0),
+ ];
+ } else {
+ my $serial = _nvmet_serial($nqn);
+ my @attrs;
+ if ($subsys->{attr_model} ne $nvmet_model || $subsys->{attr_serial} ne $serial) {
+ die "refusing to take over existing NVMe subsystem '$nqn': it was not created by"
+ . " Proxmox VE; remove it on the target or use another NQN\n"
+ if !nvmet_unfinished_subsystem($cfs, $nqn);
+ push @attrs, nvmet_write("$subsys_path/attr_serial", $serial);
+ }
+ push @attrs, nvmet_write("$subsys_path/attr_allow_any_host", 0)
+ if $subsys->{attr_allow_any_host} ne '0';
+ push @objects, [@attrs] if @attrs;
+ }
+
+ my %taken = map { $_ => 1 } keys $cfs->{ports}->%*;
+ for my $portal ($conf->{portals}->@*) {
+ my $id = _nvmet_find_port($cfs, $nqn, $portal);
+ if (!defined($id)) {
+ $id = 1;
+ $id++ while $taken{$id};
+ $taken{$id} = 1;
+ my $port_path = nvmet_port_path($id);
+ push @objects,
+ [
+ ['mkdir', $port_path],
+ nvmet_write("$port_path/addr_trtype", 'tcp'),
+ nvmet_write("$port_path/addr_adrfam", $portal->{family}),
+ nvmet_write("$port_path/addr_traddr", $portal->{address}),
+ nvmet_write("$port_path/addr_trsvcid", $portal->{port}),
+ ];
+ }
+ $port_ids{$id} = 1;
+ }
+
+ # nvmet keeps the key on the global host object. A key that differs from
+ # ours is only replaced while no subsystem links the host.
+ my $linked = nvmet_linked_hosts($cfs);
+ for my $hostnqn ($conf->{hostnqns}->@*) {
+ my $host_path = nvmet_host_path($hostnqn);
+ if (my $host = $cfs->{hosts}->{$hostnqn}) {
+ my $sha = $host->{key_sha256}
+ // die "NVMe target does not expose a DH-HMAC-CHAP key for host '$hostnqn'\n";
+ if ($sha ne $keysha) {
+ die "refusing to replace an in-use DH-HMAC-CHAP key for '$hostnqn'\n"
+ if $linked->{$hostnqn};
+ push @key_hosts, $host_path;
+ }
+ } else {
+ push @objects, [['mkdir', $host_path]];
+ push @key_hosts, $host_path;
+ }
+ push @acls, [['ln', '-s', $host_path, "$subsys_path/allowed_hosts/$hostnqn"]]
+ if !$subsys || !($subsys->{acl} // {})->{$hostnqn};
+ }
+ # nvmet creates the key attributes world-readable. The chmod before the
+ # write keeps every later open from reading the key; a descriptor opened
+ # while an attribute was still world-readable is not affected by it.
+ my @keys;
+ if (@key_hosts) {
+ my @attrs = map { ("$_/dhchap_key", "$_/dhchap_ctrl_key") } @key_hosts;
+ @keys = ([['chmod', '0600', @attrs], { key => [map { "$_/dhchap_key" } @key_hosts] }]);
+ }
+
+ my $current = { subsystems => { $nqn => $subsys // { acl => {}, namespaces => {} } } };
+ for my $nsid (sort { $a <=> $b } keys $desired->%*) {
+ my ($units) = _nvmet_plan_export($current, $nqn, $nsid, $desired->{$nsid}->@*);
+ push @namespaces, $units->@*;
+ }
+ my $existing = nvmet_namespaces($cfs, $nqn);
+ for my $nsid (sort { $a <=> $b } keys $existing->%*) {
+ next if $desired->{$nsid};
+ push @namespaces, nvmet_unexport_unit($nqn, $nsid, $existing->{$nsid}->{enable} eq '1');
+ }
+
+ return {
+ prepublish => [@objects, @keys, @acls, @namespaces],
+ port_ids => [sort { $a <=> $b } keys %port_ids],
+ };
+}
+
+# One call per port: each link repeats the guards, so it only succeeds while
+# the subsystem denies unknown hosts and every configured host has its ACL.
+# Under the target lock, only a manager of the target outside this cluster
+# can change that after the verify read; the guards stop the publish then.
+# Links to ports that are no longer configured are removed.
+# Returns [{ port => $id, action => 'link' | 'unlink', steps => [...] }, ...].
+sub _nvmet_plan_publish($cfs, $nqn, $port_ids, $hostnqns) {
+ my $subsys_path = nvmet_subsys_path($nqn);
+ my %wanted = map { $_ => 1 } $port_ids->@*;
+ my @guards = (
+ ['grep', '-qx', '0', "$subsys_path/attr_allow_any_host"],
+ map { ['test', '-L', "$subsys_path/allowed_hosts/$_"] } $hostnqns->@*,
+ );
+
+ my @units;
+ for my $id ($port_ids->@*) {
+ next if nvmet_port_linked($cfs, $id, $nqn);
+ my $link = ['ln', '-s', $subsys_path, nvmet_port_path($id) . "/subsystems/$nqn"];
+ push @units, { port => $id, action => 'link', steps => [@guards, $link] };
+ }
+ for my $id (sort { $a <=> $b } keys $cfs->{ports}->%*) {
+ next if $wanted{$id} || !nvmet_port_linked($cfs, $id, $nqn);
+ my $unlink = ['rm', nvmet_port_path($id) . "/subsystems/$nqn"];
+ push @units, { port => $id, action => 'unlink', steps => [$unlink] };
+ }
+ return \@units;
+}
+
+# Teardown units for the subsystem and the hosts that may become orphans.
+sub _nvmet_plan_delete_target($inv, $cfs, $nqn, $hostnqns) {
+ for my $dataset (sort keys $inv->{volumes}->%*) {
+ die "refusing to delete NVMe subsystem '$nqn': owned ZFS volume '$dataset' exists\n"
+ if $inv->{volumes}->{$dataset}->{nqn} eq $nqn;
+ }
+ my $subsys = $cfs->{subsystems}->{$nqn} // return ([], [$hostnqns->@*]);
+ die "refusing to delete foreign NVMe subsystem '$nqn'\n"
+ if $subsys->{attr_model} ne $nvmet_model || $subsys->{attr_serial} ne _nvmet_serial($nqn);
+ die "refusing to delete NVMe subsystem '$nqn': namespaces remain\n"
+ if nvmet_namespaces($cfs, $nqn)->%*;
+
+ my $subsys_path = nvmet_subsys_path($nqn);
+ my @acl = sort keys(($subsys->{acl} // {})->%*);
+ die "refusing to delete NVMe subsystem '$nqn': it allows a malformed host name\n"
+ if grep { $_ !~ $RE_NQN } @acl;
+ my @links = (
+ (
+ map { nvmet_port_path($_) . "/subsystems/$nqn" }
+ grep { nvmet_port_linked($cfs, $_, $nqn) }
+ sort { $a <=> $b } keys $cfs->{ports}->%*
+ ),
+ (map { "$subsys_path/allowed_hosts/$_" } @acl),
+ );
+ # A retry after a teardown that failed at its rmdir finds no ACL left, so
+ # the configured hosts are candidates as well.
+ my %candidates = map { $_ => 1 } @acl, $hostnqns->@*;
+ return (
+ [[(@links ? (['rm', @links]) : ()), ['rmdir', $subsys_path]]], [sort keys %candidates],
+ );
+}
+
+# Candidate hosts that exist and that no subsystem links any more.
+sub _nvmet_plan_orphan_hosts($cfs, $candidates) {
+ my $linked = nvmet_linked_hosts($cfs);
+ my %seen;
+ my @orphans = map { nvmet_host_path($_) }
+ grep { !$seen{$_}++ && $_ =~ $RE_NQN && $cfs->{hosts}->{$_} && !$linked->{$_} }
+ sort $candidates->@*;
+ return @orphans ? [[['rmdir', @orphans]]] : [];
+}
+
+# ---------------------------------------------------------------------------
+# Target lock and remote execution
+# ---------------------------------------------------------------------------
+
+my %nvmet_lock_owner; # lock id => pid of the process holding the domain lock
+
+# Runs $code under the pmxcfs domain lock of the target. Like the pmxcfs
+# lock itself, it is not re-entrant, and a child forked inside is not the
+# owner.
+my sub nvmet_locked($scfg, $code) {
+ my $id = nvmet_lock_id($scfg);
+ die "cluster not quorate - refusing NVMe target changes\n"
+ if !PVE::Cluster::check_cfs_quorum(1);
+ my $res = PVE::Cluster::cfs_lock_domain(
+ $id,
+ $nvmet_lock_wait,
+ sub {
+ local $nvmet_lock_owner{$id} = $$;
+ return $code->();
+ },
+ );
+ die $@ if $@;
+ return $res;
+}
+
+# Runs steps on the target. %opts: op, timeout, input, change (the steps
+# change the target, which needs the lock).
+#
+# ssh does not stop a command on the target when it gives up on it: a change
+# whose connection broke (exit code 255), any call under the lock that ssh
+# did not run to its end (-1: its timeout, or ssh was killed), and a call
+# during which the task was stopped (it dies with the task marker) may still
+# be running there. Its outcome is unknown, so it is never compensated from a
+# read that could come before the rest of it. The next activation repairs
+# from the target state.
+my sub nvmet_exec($scfg, $steps, %opts) {
+ my $locked = ($nvmet_lock_owner{ nvmet_lock_id($scfg) } // 0) == $$;
+ die "internal error: NVMe target change without target lock\n"
+ if $opts{change} && !$locked;
+ my $res = _nvmet_run(
+ $scfg, $steps,
+ op => $opts{op},
+ timeout => $opts{timeout} // 15,
+ (defined($opts{input}) ? (input => $opts{input}) : ()),
+ );
+ die "NVMe target operation '$opts{op}' did not complete ($res->{err});"
+ . " the target state is unknown\n"
+ if ($locked && $res->{rc} == -1)
+ || ($opts{change} && $res->{rc} == 255);
+ return $res;
+}
+
+# An abandoned operation is passed on instead of being compensated.
+my sub nvmet_rethrow_abandoned($error) {
+ die $error if $error =~ $RE_NVMET_ABANDONED;
+}
+
+my sub nvmet_unreachable($res) {
+ return $res->{rc} == 255 || $res->{rc} == -1;
+}
+
+my sub nvmet_check($res, $op) {
+ die "NVMe target operation '$op' failed: $res->{err}\n" if $res->{rc};
+}
+
+my sub nvmet_read_failed($scfg, $res) {
+ die "NVMe target '" . nvmet_server($scfg) . "' is unreachable: $res->{err}\n"
+ if nvmet_unreachable($res);
+ die "cannot read NVMe target state: $res->{err}\n";
+}
+
+my sub nvmet_output($res) {
+ return join('', map { "$_\n" } $res->{out}->@*);
+}
+
+# A read, retried twice after 200 ms unless the target is unreachable: a read
+# without the lock can meet a configfs object that another node removes
+# while find lists it, which makes find fail once.
+my sub nvmet_read_call($scfg, $steps, %opts) {
+ my $res;
+ for my $attempt (0 .. 2) {
+ _sleep(0.2) if $attempt;
+ $res = nvmet_exec($scfg, $steps, %opts, timeout => 15);
+ last if !$res->{rc} || nvmet_unreachable($res);
+ }
+ return $res;
+}
+
+# Reads the target state and returns (ZFS inventory, configfs state).
+# keys => [hostnqns] adds the digests of their keys. modprobe => 1, for locked
+# reads only, loads nvmet first and mounts configfs if that is what failed.
+# With tolerant => 1, a failed or unparsable read returns an empty list,
+# unless the target is unreachable.
+my sub nvmet_read($scfg, %opts) {
+ my $pool = nvmet_pool($scfg);
+ my $hostnqns = $opts{keys} // [];
+ # loading a module that may still be loading is harmless
+ my @modprobe = $opts{modprobe} ? (change => 1) : ();
+ my $read = sub () {
+ return nvmet_read_call(
+ $scfg,
+ nvmet_state_steps($pool, $hostnqns, $opts{modprobe}),
+ op => 'read target state',
+ @modprobe,
+ );
+ };
+ my $res = $read->();
+ if ($res->{rc} && $opts{modprobe} && !nvmet_unreachable($res)) {
+ my $mounts = nvmet_exec($scfg, [['cat', '/proc/mounts']], op => 'read mounts');
+ nvmet_check($mounts, 'read mounts');
+ if (!_nvmet_parse_mounts(nvmet_output($mounts))) {
+ my $mount = ['mount', '-t', 'configfs', 'none', '/sys/kernel/config'];
+ my $mounted = nvmet_exec($scfg, [$mount], op => 'mount configfs', change => 1);
+ nvmet_check($mounted, 'mount configfs');
+ $res = $read->();
+ }
+ }
+ if ($res->{rc}) {
+ return () if $opts{tolerant} && !nvmet_unreachable($res);
+ nvmet_read_failed($scfg, $res);
+ }
+ my @state = eval {
+ my ($zfs, $configfs) = _nvmet_split_state(nvmet_output($res));
+ (_nvmet_parse_zfs_inventory($zfs, $pool), _nvmet_parse_configfs($configfs));
+ };
+ if (my $error = $@) {
+ return () if $opts{tolerant};
+ die $error;
+ }
+ return @state;
+}
+
+my sub nvmet_read_zfs($scfg) {
+ my $pool = nvmet_pool($scfg);
+ my $res = nvmet_read_call($scfg, [nvmet_zfs_inventory_step($pool)], op => 'read ZFS inventory');
+ nvmet_read_failed($scfg, $res) if $res->{rc};
+ return _nvmet_parse_zfs_inventory(nvmet_output($res), $pool);
+}
+
+# Applies units in as few calls as possible and stops at the first failing
+# call, whose result it returns. A chain only saves SSH round trips: every
+# decision was taken locally before, and `&&` only stops at the first
+# failing command. Only the call with the key step gets stdin. The default
+# timeout suits configfs chains; ZFS changes pass their own.
+my sub nvmet_apply($scfg, $units, %opts) {
+ my $input = delete $opts{input};
+ $opts{timeout} //= 30;
+ for my $chunk (_nvmet_chunk($units)->@*) {
+ my $with_key = grep { ref($_) eq 'HASH' && exists($_->{key}) } $chunk->@*;
+ my @input = $with_key ? (input => $input) : ();
+ my $res = nvmet_exec($scfg, $chunk, %opts, @input, change => 1);
+ return $res if $res->{rc};
+ }
+ return { rc => 0, out => [], err => '' };
+}
+
+my sub nvmet_change($scfg, $units, %opts) {
+ nvmet_check(nvmet_apply($scfg, $units, %opts), $opts{op});
+}
+
+my sub nvmet_wait_device($scfg, $dev) {
+ my $deadline = _now() + 10;
+ while (1) {
+ my $res = nvmet_exec($scfg, [['test', '-b', $dev]], op => 'wait for zvol');
+ return if !$res->{rc};
+ nvmet_read_failed($scfg, $res) if nvmet_unreachable($res);
+ last if _now() >= $deadline;
+ _sleep(0.25);
+ }
+ die "zvol '$dev' is not a block device after 10 seconds\n";
+}
+
+my sub nvmet_new_uuid($inv, $cfs) {
+ my %used = map { lc($_->{uuid}) => 1 } values $inv->{volumes}->%*;
+ for my $subsys (values $cfs->{subsystems}->%*) {
+ $used{ lc($_->{device_uuid}) } = 1 for values(($subsys->{namespaces} // {})->%*);
+ }
+ for (1 .. 10) {
+ my $uuid = lc(file_read_firstline('/proc/sys/kernel/random/uuid') // '');
+ return $uuid if $uuid =~ $RE_NVMET_UUID && !$used{$uuid};
+ }
+ die "cannot generate an unused namespace UUID\n";
+}
+
+my sub nvmet_has_identity($row, $nqn, $nsid, $uuid) {
+ return $row && $row->{nqn} eq $nqn && $row->{nsid} eq "$nsid" && $row->{uuid} eq $uuid;
+}
+
+# The configfs state after a successful unexport of namespace $pre->{nsid}.
+my sub nvmet_without_namespace($cfs, $nqn, $pre) {
+ return $cfs if !$pre;
+ my $subsys = $cfs->{subsystems}->{$nqn};
+ my %namespaces = $subsys->{namespaces}->%*;
+ delete $namespaces{ $pre->{nsid} };
+ my $changed = { $subsys->%*, namespaces => \%namespaces };
+ return { $cfs->%*, subsystems => { $cfs->{subsystems}->%*, $nqn => $changed } };
+}
+
+# Links the subsystem to each desired port separately. One port that cannot
+# be bound (for example, its address is missing on the target) only warns
+# while another desired port serves the subsystem.
+my sub nvmet_publish($scfg, $cfs, $nqn, $port_ids, $hostnqns) {
+ my @failed;
+ for my $unit (_nvmet_plan_publish($cfs, $nqn, $port_ids, $hostnqns)->@*) {
+ my $op = "$unit->{action} NVMe subsystem on port $unit->{port}";
+ my $res = nvmet_apply($scfg, [$unit->{steps}], op => $op);
+ push @failed, { $unit->%*, err => $res->{err} } if $res->{rc};
+ }
+ return if !@failed;
+
+ my (undef, $fresh) = eval { nvmet_read($scfg) };
+ nvmet_rethrow_abandoned($@) if $@;
+ my $published = $fresh && grep { nvmet_port_linked($fresh, $_, $nqn) } $port_ids->@*;
+ my ($first) = grep { $_->{action} eq 'link' } @failed;
+ $first //= $failed[0];
+ die "cannot publish NVMe subsystem '$nqn': $first->{err}\n" if !$published;
+ for my $failure (@failed) {
+ my $what = $failure->{action} eq 'link' ? 'publish' : 'unpublish';
+ log_warn("cannot $what NVMe subsystem '$nqn' on port $failure->{port}: $failure->{err}");
+ }
+}
+
+# ---------------------------------------------------------------------------
+# Target flows
+# ---------------------------------------------------------------------------
+
+# Brings the target to the configured state and publishes the subsystem.
+# A converged target costs one read and no lock. Otherwise, under the lock:
+# read, apply, verify with a fresh read, and publish only once the verify
+# read plans nothing more. $portals and $hostnqns are the parsed and validated
+# storage configuration.
+sub _nvmet_activate_target($storeid, $scfg, $portals, $hostnqns, $key) {
+ my $nqn = nvmet_nqn($scfg);
+ my $conf = {
+ nqn => $nqn,
+ portals => $portals,
+ hostnqns => $hostnqns,
+ keysha => sha256_hex("$key\n"),
+ };
+ my $converged = sub($inv, $cfs) {
+ my $plan = _nvmet_plan_activation($inv, $cfs, $conf);
+ return !$plan->{prepublish}->@*
+ && !_nvmet_plan_publish($cfs, $nqn, $plan->{port_ids}, $hostnqns)->@*;
+ };
+
+ # Without the lock, a refusal or failed read only means "take the lock".
+ my @state = nvmet_read($scfg, keys => $hostnqns, tolerant => 1);
+ return if @state && eval { $converged->(@state) };
+
+ nvmet_locked(
+ $scfg,
+ sub {
+ # Removing the storage deletes its key before it removes the target
+ # configuration, so an activation that waited for the lock meanwhile
+ # does not restore it.
+ die "storage '$storeid' is being removed or its key changed\n"
+ if (file_read_firstline(secret_path($storeid)) // '') ne $key;
+ my ($inv, $cfs) = nvmet_read($scfg, keys => $hostnqns, modprobe => 1);
+ my $plan = _nvmet_plan_activation($inv, $cfs, $conf);
+ my $error;
+ for my $round (1 .. 2) {
+ last if !$plan->{prepublish}->@*;
+ my $apply = nvmet_apply(
+ $scfg, $plan->{prepublish},
+ op => 'configure NVMe target',
+ input => "$key\n",
+ );
+ $error //= $apply->{err} if $apply->{rc};
+ ($inv, $cfs) = nvmet_read($scfg, keys => $hostnqns);
+ $plan = _nvmet_plan_activation($inv, $cfs, $conf);
+ }
+ die "NVMe target did not converge: " . ($error // 'state mismatch') . "\n"
+ if $plan->{prepublish}->@*;
+ nvmet_publish($scfg, $cfs, $nqn, $plan->{port_ids}, $hostnqns);
+ },
+ );
+ return;
+}
+
+# The namespace UUID of an owned volume, from one read-only ZFS query.
+sub _nvmet_volume_uuid($scfg, $name) {
+ my $dataset = nvmet_dataset($scfg, $name);
+ my $inv = nvmet_read_zfs($scfg);
+ my (undef, $uuid) = _nvmet_owned_identity($inv, nvmet_nqn($scfg), $dataset);
+ return $uuid;
+}
+
+# Creates (size => KiB) or clones (origin => pool/base@snap) a zvol with its
+# identity set at creation, then exports it. A failure removes only what this
+# call created, decided from a fresh read.
+my sub nvmet_create_volume($scfg, $name, %opts) {
+ my $nqn = nvmet_nqn($scfg);
+ my $dataset = nvmet_dataset($scfg, $name);
+ my $dev = "/dev/zvol/$dataset";
+ die "internal error: invalid zvol creation request\n"
+ if defined($opts{size}) == defined($opts{origin})
+ || (defined($opts{size}) && $opts{size} !~ $RE_UNSIGNED_INTEGER);
+
+ return nvmet_locked(
+ $scfg,
+ sub {
+ my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1);
+ die "zvol '$dataset' already exists\n" if exists($inv->{types}->{$dataset});
+ die "NVMe subsystem does not exist; activate the storage first\n"
+ if !$cfs->{subsystems}->{$nqn};
+ my $nsid = _nvmet_allocate_nsid($inv, $cfs, $nqn);
+ my $uuid = nvmet_new_uuid($inv, $cfs);
+ my (undef, $state) = _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev);
+ die "internal error: namespace ID '$nsid' is in use\n" if $state ne 'absent';
+
+ # Record the NSID on the pool before the zvol exists: a creation that
+ # completes on the target only after this call gave up on it must
+ # never share its NSID with a later volume.
+ my $timeout = nvmet_long_timeout();
+ if ($nsid > $inv->{last_nsid}) {
+ my $reserve = ['zfs', 'set', "$nvmet_last_nsid=$nsid", nvmet_pool($scfg)];
+ nvmet_change(
+ $scfg, [[$reserve]],
+ op => 'reserve namespace ID',
+ timeout => $timeout,
+ );
+ }
+
+ my @identity = map { ('-o', $_) } nvmet_identity($nqn, $nsid, $uuid);
+ my @create_opts = (
+ ($scfg->{sparse} ? ('-s') : ()),
+ ($scfg->{blocksize} ? ('-b', $scfg->{blocksize}) : ()),
+ );
+ my $create =
+ defined($opts{origin})
+ ? ['zfs', 'clone', @identity, $opts{origin}, $dataset]
+ : ['zfs', 'create', @create_opts, @identity, '-V', "$opts{size}k", $dataset];
+ my $res = nvmet_apply(
+ $scfg, [[$create]],
+ op => 'create zvol',
+ timeout => $timeout,
+ );
+ if ($res->{rc}) {
+ # A definite command failure may still have created the zvol.
+ # Only a zvol with this call's identity counts. Ambiguous SSH
+ # outcomes have already aborted the transaction in nvmet_exec.
+ my $check = eval { nvmet_read_zfs($scfg) };
+ nvmet_rethrow_abandoned($@) if $@;
+ my $row = $check ? $check->{volumes}->{$dataset} : undef;
+ die "NVMe target operation 'create zvol' failed: $res->{err}\n"
+ if !nvmet_has_identity($row, $nqn, $nsid, $uuid);
+ }
+
+ my $verified;
+ eval {
+ nvmet_wait_device($scfg, $dev);
+ my $build_unit = nvmet_build_unit($nqn, $nsid, $uuid, $dev);
+ my $build = nvmet_apply($scfg, [$build_unit], op => 'export namespace');
+ $verified = [nvmet_read($scfg)];
+ my ($vinv, $vcfs) = $verified->@*;
+ my ($vnsid, $vuuid) = _nvmet_owned_identity($vinv, $nqn, $dataset);
+ die "NVMe identity of zvol '$dataset' changed\n"
+ if $vnsid ne $nsid || $vuuid ne $uuid;
+ if (_nvmet_export_state($vcfs, $nqn, $nsid, $uuid, $dev) ne 'present') {
+ nvmet_check($build, 'export namespace');
+ die "NVMe namespace '$nsid' was not exported\n";
+ }
+ };
+ my $error = $@ or return $uuid;
+ nvmet_rethrow_abandoned($error);
+
+ eval {
+ my ($cinv, $ccfs) = $verified ? $verified->@* : nvmet_read($scfg);
+ my $namespaces = nvmet_namespaces($ccfs, $nqn);
+ # The build writes the UUID before it enables the namespace, so an
+ # enabled namespace without our UUID was not built by this call.
+ my @unexport =
+ map { nvmet_unexport_unit($nqn, $_, $namespaces->{$_}->{enable} eq '1') }
+ grep {
+ my $ns = $namespaces->{$_};
+ $ns->{device_uuid} eq $uuid
+ || ($ns->{enable} ne '1' && $ns->{device_path} eq $dev)
+ } sort {
+ $a <=> $b
+ } keys $namespaces->%*;
+ nvmet_change($scfg, \@unexport, op => 'remove namespace') if @unexport;
+ # -o at creation proves that this call created the zvol
+ if (nvmet_has_identity($cinv->{volumes}->{$dataset}, $nqn, $nsid, $uuid)) {
+ my $destroy = ['zfs', 'destroy', '-r', $dataset];
+ nvmet_change(
+ $scfg, [[$destroy]],
+ op => 'destroy zvol',
+ timeout => $timeout,
+ );
+ }
+ };
+ log_warn("failed to clean up zvol '$name': $@") if $@;
+ die $error;
+ },
+ );
+}
+
+# Unexports and destroys an owned zvol. A missing zvol is already destroyed.
+my sub nvmet_destroy_volume($scfg, $name) {
+ my $nqn = nvmet_nqn($scfg);
+ my $dataset = nvmet_dataset($scfg, $name);
+ my $dev = "/dev/zvol/$dataset";
+ my $destroy = ['zfs', 'destroy', '-r', $dataset];
+ my $timeout = nvmet_long_timeout();
+
+ nvmet_locked(
+ $scfg,
+ sub {
+ my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1);
+ return if !exists($inv->{types}->{$dataset});
+ my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset);
+ my ($unexport, $pre) = ([], undef);
+ if ($cfs->{subsystems}->{$nqn}) {
+ _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev); # refusals only
+ ($unexport, $pre) = _nvmet_plan_unexport($cfs, $nqn, $uuid);
+ }
+ my $units = [$unexport->@*, [$destroy]];
+ my $res = nvmet_apply($scfg, $units, op => 'destroy zvol', timeout => $timeout);
+ return if !$res->{rc};
+ my $error = $res->{err};
+
+ # Decide from a fresh read what the failed call changed.
+ my ($finv, $fcfs) = eval { nvmet_read($scfg) };
+ if (my $read_error = $@) {
+ nvmet_rethrow_abandoned($read_error);
+ die "failed to destroy '$dataset': $error\n";
+ }
+ return if !exists($finv->{types}->{$dataset});
+ my $namespaces = nvmet_namespaces($fcfs, $nqn);
+ my ($current) =
+ grep { $namespaces->{$_}->{device_uuid} eq $uuid } keys $namespaces->%*;
+ if (defined($current)) {
+ die "cannot disable namespace '$current': $error\n"
+ if $namespaces->{$current}->{enable} eq '1';
+ die "cannot remove namespace '$current': $error\n" if !$pre || !$pre->{enabled};
+ my $enable = [nvmet_enable_unit($nqn, $current, $dev)];
+ my $restore = nvmet_apply($scfg, $enable, op => 'enable namespace');
+ die "cannot remove namespace '$current': $error"
+ . ($restore->{rc} ? "; cannot restore namespace: $restore->{err}" : '') . "\n";
+ }
+
+ # The namespace is gone and the zvol is still there, typically busy.
+ for my $attempt (1 .. 5) {
+ _sleep(1);
+ my $retry =
+ nvmet_apply($scfg, [[$destroy]], op => 'destroy zvol', timeout => $timeout);
+ return if !$retry->{rc};
+ $error = $retry->{err};
+ }
+ die "failed to destroy '$dataset': $error\n" if !$pre;
+ eval {
+ my (undef, $rcfs) = nvmet_read($scfg);
+ my ($units) = _nvmet_plan_export($rcfs, $nqn, $nsid, $uuid, $dev);
+ nvmet_change($scfg, $units, op => 'restore namespace');
+ };
+ die "failed to destroy '$dataset': $error; namespace restoration also failed: $@"
+ if $@;
+ die "failed to destroy '$dataset': $error; namespace restored\n";
+ },
+ );
+ return;
+}
+
+# Rolls an owned zvol back and always exports it again with the same identity.
+my sub nvmet_rollback_volume($scfg, $name, $snap) {
+ my $snapshot = nvmet_snapshot($scfg, $name, $snap);
+ my $nqn = nvmet_nqn($scfg);
+ my $dataset = nvmet_dataset($scfg, $name);
+ my $dev = "/dev/zvol/$dataset";
+
+ my $timeout = nvmet_long_timeout();
+
+ nvmet_locked(
+ $scfg,
+ sub {
+ my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1);
+ my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset);
+ die "NVMe subsystem does not exist\n" if !$cfs->{subsystems}->{$nqn};
+ _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev); # refusals only
+ my ($unexport, $pre) = _nvmet_plan_unexport($cfs, $nqn, $uuid);
+ my $set_identity = ['zfs', 'set', nvmet_identity($nqn, $nsid, $uuid), $dataset];
+ my $rollback = ['zfs', 'rollback', $snapshot];
+ my $res = nvmet_apply(
+ $scfg, [$unexport->@*, [$rollback], [$set_identity]],
+ op => 'rollback zvol',
+ timeout => $timeout,
+ );
+ my $error;
+ $error = "NVMe target operation 'rollback zvol' failed: $res->{err}" if $res->{rc};
+
+ # Always export the volume again, from a fresh read if anything failed.
+ eval {
+ my ($rinv, $rcfs) =
+ $error ? nvmet_read($scfg) : ($inv, nvmet_without_namespace($cfs, $nqn, $pre));
+ nvmet_wait_device($scfg, $dev);
+ my @units;
+ push @units, [$set_identity]
+ if !nvmet_has_identity($rinv->{volumes}->{$dataset}, $nqn, $nsid, $uuid);
+ my ($export) = _nvmet_plan_export($rcfs, $nqn, $nsid, $uuid, $dev);
+ push @units, $export->@*;
+ nvmet_change($scfg, \@units, op => 'restore namespace', timeout => $timeout);
+ };
+ chomp(my $restore_error = $@);
+
+ die "rollback failed: $error; namespace restoration failed: $restore_error\n"
+ if defined($error) && $restore_error;
+ die "namespace restoration failed after rollback: $restore_error\n"
+ if $restore_error;
+ die "$error\n" if defined($error);
+ },
+ );
+ return;
+}
+
+# Renames vm-* to base-*, exports it under the same identity and takes the
+# __base__ snapshot. A failed conversion is undone from a fresh read.
+my sub nvmet_template_volume($scfg, $name) {
+ my $nqn = nvmet_nqn($scfg);
+ my $old = nvmet_dataset($scfg, $name);
+ my $new = _nvmet_template_name($old);
+ my ($old_dev, $new_dev) = ("/dev/zvol/$old", "/dev/zvol/$new");
+ my $timeout = nvmet_long_timeout();
+
+ nvmet_locked(
+ $scfg,
+ sub {
+ my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1);
+ my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $old);
+ die "template zvol '$new' already exists\n" if exists($inv->{types}->{$new});
+ die "NVMe subsystem does not exist\n" if !$cfs->{subsystems}->{$nqn};
+ _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $old_dev); # refusals only
+ my ($unexport) = _nvmet_plan_unexport($cfs, $nqn, $uuid);
+
+ eval {
+ my $rename = [$unexport->@*, [['zfs', 'rename', $old, $new]]];
+ nvmet_change($scfg, $rename, op => 'rename zvol', timeout => $timeout);
+ nvmet_wait_device($scfg, $new_dev);
+ my $build = nvmet_build_unit($nqn, $nsid, $uuid, $new_dev);
+ my $template = [$build, [['zfs', 'snapshot', "$new\@__base__"]]];
+ nvmet_change($scfg, $template, op => 'create template', timeout => $timeout);
+ };
+ my $error = $@ or return;
+ nvmet_rethrow_abandoned($error);
+ chomp($error);
+
+ eval {
+ my ($rinv, $rcfs) = nvmet_read($scfg);
+ if (exists($rinv->{types}->{$new})) {
+ my ($units) = _nvmet_plan_unexport($rcfs, $nqn, $uuid);
+ my $back = [$units->@*, [['zfs', 'rename', $new, $old]]];
+ nvmet_change($scfg, $back, op => 'rename zvol back', timeout => $timeout);
+ (undef, $rcfs) = nvmet_read($scfg);
+ } elsif (!exists($rinv->{types}->{$old})) {
+ die "zvol '$old' does not exist\n";
+ }
+ nvmet_wait_device($scfg, $old_dev);
+ my ($units) = _nvmet_plan_export($rcfs, $nqn, $nsid, $uuid, $old_dev);
+ nvmet_change($scfg, $units, op => 'restore namespace');
+ };
+ die "template conversion failed: $error; restoration failed: $@" if $@;
+ die "template conversion failed: $error\n";
+ },
+ );
+ return;
+}
+
+# Grows an owned zvol and lets an exported namespace pick up the new size.
+my sub nvmet_resize_volume($scfg, $name, $size) {
+ my $nqn = nvmet_nqn($scfg);
+ my $dataset = nvmet_dataset($scfg, $name);
+ die "internal error: invalid zvol size\n" if $size !~ $RE_UNSIGNED_INTEGER;
+
+ # The volume is checked before it changes; under the lock, the namespace
+ # read here is still the one to revalidate after the resize. It is
+ # revalidated in the same call, so whenever the zvol grows, also after a
+ # lost reply, the hosts see the new size. A namespace that is not enabled
+ # reads the new size when it is enabled.
+ nvmet_locked(
+ $scfg,
+ sub {
+ my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1);
+ my (undef, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset);
+ my $namespaces = nvmet_namespaces($cfs, $nqn);
+ my @matches =
+ grep { $namespaces->{$_}->{device_uuid} eq $uuid } keys $namespaces->%*;
+ die "duplicate namespace UUID '$uuid'\n" if @matches > 1;
+ my @resize = (['zfs', 'set', "volsize=${size}k", $dataset]);
+ push @resize, nvmet_write(nvmet_ns_path($nqn, $matches[0]) . '/revalidate_size', 1)
+ if @matches && $namespaces->{ $matches[0] }->{enable} eq '1';
+ nvmet_change(
+ $scfg, [\@resize],
+ op => 'resize zvol',
+ timeout => nvmet_long_timeout(),
+ );
+ },
+ );
+ return;
+}
+
+# Removes the subsystem once it has no volumes and namespaces, then the hosts
+# that no subsystem links any more. Ports are never removed.
+sub _nvmet_delete_target($scfg) {
+ my $nqn = nvmet_nqn($scfg);
+ my $hostnqns = parse_nvme_host_nqns($scfg->{'nvme-host-nqns'}, 1) // [];
+
+ nvmet_locked(
+ $scfg,
+ sub {
+ my ($inv, $cfs) = nvmet_read($scfg, modprobe => 1);
+ my ($units, $candidates) = _nvmet_plan_delete_target($inv, $cfs, $nqn, $hostnqns);
+ my $fresh = $cfs;
+ if ($units->@*) {
+ my $res = nvmet_apply($scfg, $units, op => 'remove NVMe subsystem');
+ (undef, $fresh) = eval { nvmet_read($scfg) };
+ my $read_error = $@;
+ nvmet_rethrow_abandoned($read_error) if $read_error;
+ die "cannot remove NVMe subsystem '$nqn': $res->{err}\n"
+ if $res->{rc} && (!$fresh || $fresh->{subsystems}->{$nqn});
+ die $read_error if !$fresh;
+ }
+ my $orphans = _nvmet_plan_orphan_hosts($fresh, $candidates);
+ return if !$orphans->@*;
+ my $res = nvmet_apply($scfg, $orphans, op => 'remove orphan NVMe hosts');
+ log_warn("could not remove orphan NVMe host(s): $res->{err}") if $res->{rc};
+ },
+ );
+ return;
+}
+
+# ---------------------------------------------------------------------------
+# Configuration
+# ---------------------------------------------------------------------------
+
+sub verify_nvme_nqn($value, $noerr = undef) {
+
+ if (
+ length($value) > 223
+ || $value !~ $RE_NQN
+ ) {
+ return undef if $noerr;
+ die "value is not a valid NVMe qualified name\n";
+ }
+
+ return $value;
+}
+
+sub parse_nvme_portals($value, $noerr = undef) {
+ my $result = [];
+ my $seen = {};
+
+ for my $entry (split(/,/, $value // '')) {
+ $entry = trim($entry);
+ my ($address, $port, $family);
+ if ($entry =~ $RE_IPV6_PORTAL) {
+ ($address, $port, $family) = ($+{address}, $+{port} // 4420, 'ipv6');
+ } elsif ($entry =~ $RE_IPV4_PORTAL) {
+ ($address, $port, $family) = ($+{address}, $+{port} // 4420, 'ipv4');
+ } else {
+ return undef if $noerr;
+ die "invalid NVMe/TCP portal '$entry'\n";
+ }
+
+ if (
+ !PVE::JSONSchema::pve_verify_ip($address, 1)
+ || ($family eq 'ipv4' && index($address, ':') >= 0)
+ || ($family eq 'ipv6' && index($address, ':') < 0)
+ || $port < 1
+ || $port > 65535
+ ) {
+ return undef if $noerr;
+ die "invalid NVMe/TCP portal '$entry'\n";
+ }
+ $address = nvmet_canonical_address($address) if $family eq 'ipv6';
+ # one listener: compare like _assert_unique_target
+ my $id = join(
+ "\0",
+ nvmet_listener_address({ family => $family, address => $address }),
+ int($port),
+ );
+ if ($seen->{$id}++) {
+ return undef if $noerr;
+ die "duplicate NVMe/TCP portal '$entry'\n";
+ }
+ push $result->@*,
+ {
+ address => $address,
+ port => int($port),
+ family => $family,
+ };
+ if (scalar($result->@*) > $max_paths) {
+ return undef if $noerr;
+ die "at most $max_paths NVMe/TCP portals are supported\n";
+ }
+ }
+
+ if (!$result->@*) {
+ return undef if $noerr;
+ die "at least one NVMe/TCP portal is required\n";
+ }
+
+ return $result;
+}
+
+my sub verify_nvme_portals($value, $noerr = undef) {
+ return undef if !parse_nvme_portals($value, $noerr);
+ return $value;
+}
+
+sub parse_nvme_host_ifaces($value, $noerr = undef) {
+ my $result = [];
+
+ for my $iface (split(/,/, $value // '')) {
+ $iface = trim($iface);
+ # the kernel never names an interface '.' or '..'
+ if (
+ length($iface) < 1
+ || length($iface) > 15
+ || $iface !~ $RE_HOST_IFACE
+ || $iface eq '.'
+ || $iface eq '..'
+ ) {
+ return undef if $noerr;
+ die "invalid NVMe/TCP host interface '$iface'\n";
+ }
+ push $result->@*, $iface;
+ }
+
+ if (!$result->@*) {
+ return undef if $noerr;
+ die "at least one NVMe/TCP host interface is required\n";
+ }
+
+ return $result;
+}
+
+sub parse_nvme_host_nqns($value, $noerr = undef) {
+ my $result = [];
+ my $seen = {};
+
+ for my $hostnqn (split(/,/, $value // '')) {
+ $hostnqn = trim($hostnqn);
+ if (!verify_nvme_nqn($hostnqn, 1) || $seen->{$hostnqn}++) {
+ return undef if $noerr;
+ die "invalid or duplicate NVMe host NQN '$hostnqn'\n";
+ }
+ push $result->@*, $hostnqn;
+ if (scalar($result->@*) > $max_hosts) {
+ return undef if $noerr;
+ die "at most $max_hosts NVMe host NQNs are supported\n";
+ }
+ }
+
+ if (!$result->@*) {
+ return undef if $noerr;
+ die "at least one NVMe host NQN is required\n";
+ }
+
+ return $result;
+}
+
+my sub verify_nvme_host_ifaces($value, $noerr = undef) {
+ return undef if !parse_nvme_host_ifaces($value, $noerr);
+ return $value;
+}
+
+my sub verify_nvme_host_nqns($value, $noerr = undef) {
+ return undef if !parse_nvme_host_nqns($value, $noerr);
+ return $value;
+}
+
+sub _configured_portals($scfg) {
+ my $portals = parse_nvme_portals($scfg->{'nvme-portals'});
+ my $ifaces = parse_nvme_host_ifaces($scfg->{'nvme-host-ifaces'});
+ die "nvme-host-ifaces must contain one interface for each nvme-portals entry\n"
+ if scalar($ifaces->@*) != scalar($portals->@*);
+
+ for (my $i = 0; $i < scalar($portals->@*); $i++) {
+ $portals->[$i]->{host_iface} = $ifaces->[$i];
+ }
+ return $portals;
+}
+
+sub _local_iface_exists($iface) {
+ return -d "/sys/class/net/$iface";
+}
+
+sub _validate_local_ifaces($portals) {
+ for my $portal ($portals->@*) {
+ my $iface = $portal->{host_iface};
+ die "NVMe/TCP host interface '$iface' does not exist on this node\n"
+ if !_local_iface_exists($iface);
+ }
+}
+
+PVE::JSONSchema::register_format('pve-storage-nvme-nqn', \&verify_nvme_nqn);
+PVE::JSONSchema::register_format('pve-storage-nvme-portals', \&verify_nvme_portals);
+PVE::JSONSchema::register_format('pve-storage-nvme-host-ifaces', \&verify_nvme_host_ifaces);
+PVE::JSONSchema::register_format('pve-storage-nvme-host-nqns', \&verify_nvme_host_nqns);
+
+sub type($class) {
+ return 'zfsnvme';
+}
+
+sub plugindata($class) {
+ return {
+ content => [{ images => 1 }, { images => 1 }],
+ 'sensitive-properties' => { 'dhchap-key' => 1 },
+ };
+}
+
+sub properties($class) {
+ return {
+ subsysnqn => {
+ description => "NVMe subsystem qualified name.",
+ type => 'string',
+ format => 'pve-storage-nvme-nqn',
+ },
+ 'nvme-portals' => {
+ description =>
+ "Comma-separated NVMe/TCP target IP addresses, at most 16. Put IPv6 addresses in"
+ . " brackets. The default TCP port is 4420.",
+ type => 'string',
+ format => 'pve-storage-nvme-portals',
+ maxLength => 2048,
+ },
+ 'nvme-host-ifaces' => {
+ description =>
+ "Comma-separated local interfaces, in portal order. Interface names must be"
+ . " identical on every cluster node.",
+ type => 'string',
+ format => 'pve-storage-nvme-host-ifaces',
+ maxLength => 512,
+ },
+ 'nvme-host-nqns' => {
+ description =>
+ "Comma-separated /etc/nvme/hostnqn values for every cluster node allowed to use"
+ . " this storage, at most 64. Host NQNs can only be added.",
+ type => 'string',
+ format => 'pve-storage-nvme-host-nqns',
+ maxLength => 8192,
+ },
+ 'dhchap-key' => {
+ description =>
+ "NVMe DH-HMAC-CHAP key in secret representation format (DHHC-1). Required when the"
+ . " storage is created; it cannot be changed.",
+ type => 'string',
+ maxLength => 256,
+ },
+ 'nvme-iopolicy' => {
+ description => "Native NVMe multipath I/O policy.",
+ type => 'string',
+ enum => ['numa', 'round-robin', 'queue-depth'],
+ default => 'round-robin',
+ },
+ 'nvme-keep-alive-tmo' => {
+ description => "NVMe keep-alive timeout in seconds.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 120,
+ default => 5,
+ },
+ 'nvme-reconnect-delay' => {
+ description => "Delay between NVMe reconnect attempts in seconds.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 120,
+ default => 2,
+ },
+ 'nvme-ctrl-loss-tmo' => {
+ description => "Time to keep retrying a lost NVMe controller in seconds.",
+ type => 'integer',
+ minimum => -1,
+ maximum => 86400,
+ default => 600,
+ },
+ 'nvme-fast-io-fail-tmo' => {
+ description =>
+ "Optional time before failing I/O on a reconnecting NVMe controller. Unset queues"
+ . " I/O until controller loss timeout.",
+ type => 'integer',
+ minimum => 0,
+ maximum => 86400,
+ optional => 1,
+ },
+ 'nvme-nr-io-queues' => {
+ description => "Number of NVMe/TCP I/O queues per controller.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 1024,
+ optional => 1,
+ },
+ };
+}
+
+sub options($class) {
+ return {
+ server => { fixed => 1 },
+ subsysnqn => { fixed => 1 },
+ 'nvme-portals' => { fixed => 1 },
+ 'nvme-host-ifaces' => {},
+ 'nvme-host-nqns' => {},
+ pool => { fixed => 1 },
+ blocksize => { fixed => 1 },
+ sparse => { optional => 1 },
+ 'dhchap-key' => { optional => 1 },
+ 'nvme-iopolicy' => { optional => 1 },
+ 'nvme-keep-alive-tmo' => { optional => 1 },
+ 'nvme-reconnect-delay' => { optional => 1 },
+ 'nvme-ctrl-loss-tmo' => { optional => 1 },
+ 'nvme-fast-io-fail-tmo' => { optional => 1 },
+ 'nvme-nr-io-queues' => { optional => 1 },
+ nodes => { optional => 1 },
+ disable => { optional => 1 },
+ content => { optional => 1 },
+ bwlimit => { optional => 1 },
+ };
+}
+
+sub _validate_fail_fast_timeout($config, $default_ctrl_loss_tmo = undef) {
+ my $fast = $config->{'nvme-fast-io-fail-tmo'};
+ return if !defined($fast);
+
+ my $ctrl = $config->{'nvme-ctrl-loss-tmo'};
+ $ctrl = $default_ctrl_loss_tmo if !defined($ctrl);
+ return if !defined($ctrl) || $ctrl < 0;
+
+ die "nvme-fast-io-fail-tmo must not exceed nvme-ctrl-loss-tmo\n"
+ if $fast > $ctrl;
+}
+
+# Defaults are not injected here: this also runs when storage.cfg is parsed.
+# Every use site applies the schema default itself.
+sub check_config($class, $section_id, $config, $create, $skip_schema_check = undef) {
+ nvmet_pool($config) if defined($config->{pool});
+ verify_nvme_nqn($config->{subsysnqn}) if defined($config->{subsysnqn});
+ parse_nvme_portals($config->{'nvme-portals'}) if defined($config->{'nvme-portals'});
+ if (defined($config->{'nvme-host-ifaces'}) && defined($config->{'nvme-portals'})) {
+ _configured_portals($config);
+ } elsif (defined($config->{'nvme-host-ifaces'})) {
+ parse_nvme_host_ifaces($config->{'nvme-host-ifaces'});
+ }
+ parse_nvme_host_nqns($config->{'nvme-host-nqns'})
+ if defined($config->{'nvme-host-nqns'});
+ _validate_fail_fast_timeout($config, $create ? 600 : undef);
+ return $class->SUPER::check_config($section_id, $config, $create, $skip_schema_check);
+}
+
+# ---------------------------------------------------------------------------
+# ZFS helpers (same formats as the other ZFS plugins)
+# ---------------------------------------------------------------------------
+
+my sub zfs_request($scfg, $timeout, $method, @args) {
+ $timeout = PVE::RPCEnvironment->is_worker() ? 60 * 60 : 10 if !$timeout;
+ my $change = $method ne 'get' && $method ne 'list';
+ my $res = nvmet_exec(
+ $scfg, [['zfs', $method, @args]],
+ op => "zfs $method",
+ timeout => $timeout,
+ change => $change,
+ );
+ die "zfs error on '" . nvmet_server($scfg) . "': $res->{err}\n" if $res->{rc};
+ return nvmet_output($res);
+}
+
+# The direct children of the pool with PVE volume names. The plugin creates
+# and owns zvols only; a filesystem child holds its name.
+my sub zfs_parse_zvol_list($text, $pool) {
+ my $list = [];
+ for my $line (split /\n/, $text // '') {
+ my ($dataset, $size, $origin, $type) = split(/\s+/, $line);
+ next if !defined($type) || ($type ne 'volume' && $type ne 'filesystem');
+ my @parts = split /\//, $dataset;
+ next if @parts < 2;
+ my $name = pop @parts;
+ next if join('/', @parts) ne $pool;
+ next if $name !~ $RE_ZVOL_OWNER;
+ push $list->@*,
+ {
+ name => $name,
+ owner => $+{owner},
+ type => $type,
+ ($type eq 'volume' ? (size => $size + 0) : ()),
+ ($origin ne '-' ? (origin => $origin) : ()),
+ };
+ }
+ return $list;
+}
+
+# The pool's direct children with PVE volume names, so that a name is never
+# handed out twice; with $owned_only, the zvols owned by this storage's NVMe
+# subsystem.
+my sub zfs_list_zvol($scfg, $owned_only) {
+ my $pool = nvmet_pool($scfg);
+ my $text = zfs_request(
+ $scfg,
+ 10,
+ 'list',
+ '-o',
+ 'name,volsize,origin,type',
+ '-t',
+ 'volume,filesystem',
+ '-d1',
+ '-Hp',
+ $pool,
+ );
+ my $list = {};
+ my $prefix = "$pool/";
+ for my $zvol (zfs_parse_zvol_list($text, $pool)->@*) {
+ next if $owned_only && $zvol->{type} ne 'volume';
+ my $parent = $zvol->{origin};
+ # an origin in the pool is named relative to it, like the ZFS plugins do
+ $parent = substr($parent, length($prefix)) if $parent && index($parent, $prefix) == 0;
+ $list->{ $zvol->{name} } = {
+ name => $zvol->{name},
+ size => $zvol->{size},
+ parent => $parent,
+ format => 'raw',
+ vmid => $zvol->{owner},
+ };
+ }
+ return $list if !$owned_only;
+
+ my $properties = zfs_request(
+ $scfg,
+ 10,
+ 'get',
+ '-H',
+ '-d',
+ '1',
+ '-o',
+ 'name,value,source',
+ 'proxmox:nvme-subsys',
+ $pool,
+ );
+ my $owned = {};
+ for my $line (split(/\n/, $properties)) {
+ my ($dataset, $nqn, $source) = split(/\t/, $line, 3);
+ next if !defined($source) || ($source ne 'local' && $source ne 'received');
+ next if !defined($nqn) || $nqn ne $scfg->{subsysnqn};
+ next if index($dataset, $prefix) != 0;
+ $owned->{ substr($dataset, length($prefix)) } = 1;
+ }
+ for my $name (keys $list->%*) {
+ delete $list->{$name} if !$owned->{$name};
+ }
+ return $list;
+}
+
+my sub zfs_get_properties($scfg, $properties, $dataset, $timeout = undef) {
+ my $text = zfs_request($scfg, $timeout, 'get', '-o', 'value', '-Hp', $properties, $dataset);
+ my @values = split /\n/, $text;
+ return wantarray ? @values : $values[0];
+}
+
+my sub zfs_get_sorted_snapshot_list($scfg, $name, $sort_params) {
+ return [
+ map { s/^.*\@//r } split /\n/,
+ zfs_request(
+ $scfg,
+ undef,
+ 'list',
+ '-H',
+ '-r',
+ '-t',
+ 'snapshot',
+ '-o',
+ 'name',
+ $sort_params->@*,
+ nvmet_dataset($scfg, $name),
+ ),
+ ];
+}
+
+# ---------------------------------------------------------------------------
+# Storage API: volumes
+# ---------------------------------------------------------------------------
+
+sub parse_volname($class, $volname) {
+ if ($volname =~ $RE_VOLNAME) {
+ my $format = ($+{type} eq 'subvol' || $+{type} eq 'basevol') ? 'subvol' : 'raw';
+ my $is_base = $+{type} eq 'base' || $+{type} eq 'basevol';
+ return ('images', $+{name}, $+{vmid}, $+{base}, $+{base_vmid}, $is_base, $format);
+ }
+ die "unable to parse zfs volume name '$volname'\n";
+}
+
+sub list_images($class, $storeid, $scfg, $vmid = undef, $vollist = undef, $cache = undef) {
+ my $res = [];
+ for my $info (values zfs_list_zvol($scfg, 1)->%*) {
+ my $volname =
+ $info->{parent} && $info->{parent} =~ $RE_BASE_SNAPSHOT
+ ? "$storeid:$+{base}/$info->{name}"
+ : "$storeid:$info->{name}";
+ next
+ if $vollist
+ ? !grep { $_ eq $volname } $vollist->@*
+ : defined($vmid) && $info->{vmid} ne $vmid;
+ $info->{volid} = $volname;
+ push $res->@*, $info;
+ }
+ return $res;
+}
+
+# Names are allocated against every direct child of the pool, owned or not, so
+# a leftover zvol that list_images hides is never handed out again.
+sub find_free_diskname($class, $storeid, $scfg, $vmid, $fmt = undef, $add_fmt_suffix = undef) {
+ my $disk_list = [map { "$storeid:$_" } sort keys zfs_list_zvol($scfg, 0)->%*];
+ return PVE::Storage::Plugin::get_next_vm_diskname(
+ $disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix,
+ );
+}
+
+sub status($class, $storeid, $scfg, $cache = undef) {
+ my ($available, $used) =
+ eval { zfs_get_properties($scfg, 'available,used', nvmet_pool($scfg)) };
+ if (my $err = $@) {
+ warn "storage '$storeid': $err";
+ return (0, 0, 0, 0);
+ }
+ if (
+ !defined($available)
+ || !defined($used)
+ || $available !~ $RE_UNSIGNED_INTEGER
+ || $used !~ $RE_UNSIGNED_INTEGER
+ ) {
+ warn "unexpected ZFS pool usage for storage '$storeid'\n";
+ return (0, 0, 0, 0);
+ }
+ return ($available + $used, $available, $used, 1);
+}
+
+sub volume_size_info($class, $scfg, $storeid, $volname, $timeout = undef) {
+ my (undef, $name, undef, $parent, undef, undef, $format) = $class->parse_volname($volname);
+ die "volume_size_info requires a ZFS volume\n" if $format ne 'raw';
+ my ($size, $used) = zfs_get_properties(
+ $scfg, 'volsize,usedbydataset', nvmet_dataset($scfg, $name), $timeout,
+ );
+ die "Could not get zfs volume size\n" if !defined($size) || $size !~ $RE_UNSIGNED_INTEGER;
+ $used = defined($used) && $used =~ $RE_UNSIGNED_INTEGER ? $used + 0 : 0;
+ return wantarray ? ($size + 0, 'raw', $used, $parent) : $size + 0;
+}
+
+sub volume_snapshot($class, $scfg, $storeid, $volname, $snap) {
+ my (undef, $name, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
+ die "volume_snapshot requires a ZFS volume\n" if $format ne 'raw';
+ my $snapshot = nvmet_snapshot($scfg, $name, $snap);
+ nvmet_locked($scfg, sub { zfs_request($scfg, undef, 'snapshot', $snapshot) });
+ return;
+}
+
+sub volume_snapshot_delete($class, $scfg, $storeid, $volname, $snap, $running = undef) {
+ my $name = ($class->parse_volname($volname))[1];
+ my $snapshot = nvmet_snapshot($scfg, $name, $snap);
+ nvmet_locked($scfg, sub { zfs_request($scfg, undef, 'destroy', $snapshot) });
+ return;
+}
+
+sub volume_rollback_is_possible($class, $scfg, $storeid, $volname, $snap, $blockers = undef) {
+ my $name = ($class->parse_volname($volname))[1];
+ nvmet_snapshot($scfg, $name, $snap); # validation only
+ my $found;
+ $blockers //= [];
+ for my $snapshot (zfs_get_sorted_snapshot_list($scfg, $name, ['-s', 'creation'])->@*) {
+ $found = 1 if $snapshot eq $snap;
+ push $blockers->@*, $snapshot if $found && $snapshot ne $snap;
+ }
+ die "can't rollback, snapshot '$snap' does not exist on '${storeid}:${volname}'\n" if !$found;
+ die "can't rollback, '$snap' is not most recent snapshot on '${storeid}:${volname}'\n"
+ if $blockers->@*;
+ return 1;
+}
+
+sub volume_snapshot_rollback($class, $scfg, $storeid, $volname, $snap) {
+ my (undef, $name, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
+ die "snapshot rollback requires a ZFS volume\n" if $format ne 'raw';
+ nvmet_rollback_volume($scfg, $name, $snap);
+}
+
+sub volume_snapshot_info($class, $scfg, $storeid, $volname) {
+ my $name = ($class->parse_volname($volname))[1];
+ my $info = {};
+ my $text = zfs_request(
+ $scfg,
+ undef,
+ 'list',
+ '-Hp',
+ '-r',
+ '-t',
+ 'snapshot',
+ '-o',
+ 'name,guid,creation',
+ nvmet_dataset($scfg, $name),
+ );
+ for my $line (split /\n/, $text) {
+ my ($snapshot, $guid, $creation) = split /\s+/, $line;
+ $snapshot =~ s/^.*\@//;
+ $info->{$snapshot} = { id => $guid, timestamp => $creation };
+ }
+ return $info;
+}
+
+sub free_image($class, $storeid, $scfg, $volname, $is_base = undef, $format = undef) {
+ my (undef, $name, undef, undef, undef, undef, $volformat) = $class->parse_volname($volname);
+ die "free_image requires a ZFS volume\n" if $volformat ne 'raw';
+ nvmet_destroy_volume($scfg, $name);
+ return undef;
+}
+
+sub create_base($class, $storeid, $scfg, $volname) {
+ my (undef, $name, undef, $basename, undef, $is_base, $format) = $class->parse_volname($volname);
+ die "create_base not possible with base image\n" if $is_base;
+ die "create_base requires a ZFS volume\n" if $format ne 'raw';
+ my $newname = $name =~ s/^vm-/base-/r;
+ nvmet_template_volume($scfg, $name);
+ return $basename ? "$basename/$newname" : $newname;
+}
+
+sub clone_image($class, $scfg, $storeid, $volname, $vmid, $snap = undef) {
+ $snap ||= '__base__';
+ my (undef, $basename, undef, undef, undef, $is_base, $format) = $class->parse_volname($volname);
+ die "clone_image only works on base images\n" if !$is_base;
+ die "clone_image requires a ZFS volume\n" if $format ne 'raw';
+ my $origin = nvmet_snapshot($scfg, $basename, $snap);
+ my $name = $class->find_free_diskname($storeid, $scfg, $vmid, $format);
+ nvmet_create_volume($scfg, $name, origin => $origin);
+ return "$basename/$name";
+}
+
+sub alloc_image($class, $storeid, $scfg, $vmid, $fmt, $name, $size) {
+ die "unsupported format '$fmt'" if $fmt ne 'raw';
+ die "illegal name '$name' - should be 'vm-$vmid-*'\n"
+ if $name && index($name, "vm-$vmid-") != 0;
+ my $volname = $name || $class->find_free_diskname($storeid, $scfg, $vmid, $fmt);
+ $size += (1024 - $size % 1024) % 1024;
+ nvmet_create_volume($scfg, $volname, size => $size);
+ return $volname;
+}
+
+sub volume_resize($class, $scfg, $storeid, $volname, $size, $running = undef, $snapname = undef) {
+ # QEMU can resize a host_device once the device itself has grown, but the
+ # plugin cannot yet wait for the local NVMe namespace to report the new
+ # size. Until it can, refuse online resize before changing the zvol, so a
+ # running VM never sees a size different from its configuration.
+ die "online resize is not supported for NVMe/TCP block devices; stop the VM first\n"
+ if $running;
+ die "resizing a snapshot is not supported for $class\n" if $snapname;
+ my $new_size = int($size / 1024);
+ $new_size += (1024 - $new_size % 1024) % 1024;
+ my $name = ($class->parse_volname($volname))[1];
+ nvmet_resize_volume($scfg, $name, $new_size);
+ return $new_size;
+}
+
+sub volume_has_feature(
+ $class, $scfg, $feature, $storeid, $volname,
+ $snapname = undef,
+ $running = undef,
+ $opts = undef,
+) {
+ my $features = {
+ snapshot => { current => 1, snap => 1 },
+ clone => { base => 1 },
+ template => { current => 1 },
+ copy => { base => 1, current => 1 },
+ };
+ my $is_base = ($class->parse_volname($volname))[5];
+ my $key = $snapname ? 'snap' : $is_base ? 'base' : 'current';
+ return $features->{$feature}->{$key};
+}
+
+# No stream transfers or renames; the storage has no path, so the base class
+# offers no export or import format either.
+sub volume_export($class, @args) {
+ die "ZFS stream export is not supported for NVMe/TCP storage\n";
+}
+
+sub volume_import($class, @args) {
+ die "ZFS stream import is not supported for NVMe/TCP storage\n";
+}
+
+sub rename_volume($class, @args) {
+ die "renaming volumes is not supported for NVMe/TCP storage\n";
+}
+
+sub rename_snapshot($class, @args) {
+ die "rename_snapshot is not supported for $class";
+}
+
+# ---------------------------------------------------------------------------
+# Secrets and configuration hooks
+# ---------------------------------------------------------------------------
+
+# Each storage needs its own NVMe/TCP listener (address family, address and
+# port), and a disabled storage keeps its listener. nvmet answers a connect to
+# a listener that does not publish the subsystem yet with DNR, and the host
+# then deletes the controller whatever its loss timeout: after a target
+# restart, the storage published second would lose its paths. Storages that
+# reach the same data address must spell the server alike, as it names the
+# target lock.
+sub _assert_unique_target($storeid, $scfg, $cfg = undef) {
+ $cfg //= PVE::Storage::config();
+ my (%listeners, %addresses);
+ for my $portal (parse_nvme_portals($scfg->{'nvme-portals'})->@*) {
+ my $address = join("\0", nvmet_listener_address($portal));
+ $listeners{"$address\0$portal->{port}"} = 1;
+ $addresses{$address} = 1;
+ }
+ my $ids = $cfg->{ids} // {};
+ for my $other_id (sort keys $ids->%*) {
+ next if $other_id eq $storeid;
+ my $other = $ids->{$other_id};
+ next if ($other->{type} // '') ne 'zfsnvme';
+
+ die "NVMe subsystem NQN is already used by storage '$other_id'\n"
+ if ($other->{subsysnqn} // '') eq $scfg->{subsysnqn};
+ my $other_server = $other->{server} // '';
+ # a storage whose portals do not parse cannot be activated
+ for my $portal ((parse_nvme_portals($other->{'nvme-portals'}, 1) // [])->@*) {
+ my $address = join("\0", nvmet_listener_address($portal));
+ die "NVMe/TCP portal '$portal->{address}' port $portal->{port} is already used by"
+ . " storage '$other_id'; give each storage its own address or port\n"
+ if $listeners{"$address\0$portal->{port}"};
+ die "storage '$other_id' reaches target address '$portal->{address}' through server"
+ . " '$other_server'; use the same server value for both storages\n"
+ if $addresses{$address} && $other_server ne $scfg->{server};
+ }
+ next if $other_server ne $scfg->{server};
+ my ($pool, $other_pool) = ($scfg->{pool}, $other->{pool} // '');
+ die "ZFS pool '$pool' on '$scfg->{server}' is already used by storage '$other_id'\n"
+ if $other_pool eq $pool;
+ die "ZFS pool '$pool' on '$scfg->{server}' overlaps the pool of storage '$other_id'\n"
+ if index("$other_pool/", "$pool/") == 0 || index("$pool/", "$other_pool/") == 0;
+ }
+}
+
+# nvmet keeps one DH-HMAC-CHAP key per host NQN, so storages on the same target
+# whose host NQNs overlap must use the same key.
+sub _assert_shared_host_key($storeid, $scfg, $key, $cfg = undef) {
+ $cfg //= PVE::Storage::config();
+ my %hosts = map { $_ => 1 } (parse_nvme_host_nqns($scfg->{'nvme-host-nqns'}, 1) // [])->@*;
+ my $ids = $cfg->{ids} // {};
+ for my $other_id (sort keys $ids->%*) {
+ next if $other_id eq $storeid;
+ my $other = $ids->{$other_id};
+ next if ($other->{type} // '') ne 'zfsnvme';
+ next if ($other->{server} // '') ne ($scfg->{server} // '');
+ my $other_hosts = parse_nvme_host_nqns($other->{'nvme-host-nqns'}, 1) // [];
+ next if !grep { $hosts{$_} } $other_hosts->@*;
+ my $other_key = file_read_firstline(secret_path($other_id));
+ die "storage '$other_id' uses a different DH-HMAC-CHAP key for the same NVMe host NQNs"
+ . " on '$scfg->{server}'\n"
+ if defined($other_key) && $other_key ne $key;
+ }
+}
+
+# DHHC-1:<hash>:<base64 of key and its little-endian CRC-32>: as generated by
+# `nvme gen-dhchap-key`. Messages never contain the key.
+sub _validate_secret($key) {
+ die "missing NVMe DH-HMAC-CHAP key\n" if !defined($key) || $key eq '';
+ my $invalid = "invalid NVMe DH-HMAC-CHAP key representation\n";
+ die $invalid if $key !~ $RE_DHCHAP_KEY;
+ my ($hash, $encoded) = @+{qw(hash secret)};
+ die $invalid if length($encoded) % 4;
+ my $decoded = decode_base64($encoded);
+ my $length = length($decoded) - 4;
+ my %lengths = ('00' => [32, 48, 64], '01' => [32], '02' => [48], '03' => [64]);
+ die $invalid if !grep { $_ == $length } $lengths{$hash}->@*;
+ die $invalid if pack('V', crc32(substr($decoded, 0, $length))) ne substr($decoded, $length);
+ return $key;
+}
+
+my sub set_secret($storeid, $key) {
+ _validate_secret($key);
+ make_path($secret_dir, { mode => 0700 });
+ file_set_contents(secret_path($storeid), "$key\n", 0600);
+}
+
+my sub get_secret($storeid) {
+ my $key = file_read_firstline(secret_path($storeid));
+ return _validate_secret($key);
+}
+
+# Removes the key file of a storage (a test seam).
+sub _unlink_file($path) {
+ return unlink($path);
+}
+
+my sub delete_secret($storeid) {
+ _unlink_file(secret_path($storeid));
+}
+
+sub on_add_hook($class, $storeid, $scfg, %sensitive) {
+ _configured_portals($scfg);
+ parse_nvme_host_nqns($scfg->{'nvme-host-nqns'});
+ _assert_unique_target($storeid, $scfg);
+ my $key = _validate_secret($sensitive{'dhchap-key'});
+ _assert_shared_host_key($storeid, $scfg, $key);
+ set_secret($storeid, $key);
+ return;
+}
+
+sub on_update_hook_full($class, $storeid, $scfg, $update, $delete = undef, $sensitive = undef) {
+ $sensitive //= {};
+ my %prospective = ($scfg->%*, $update->%*);
+ delete @prospective{ $delete->@* } if $delete;
+ verify_nvme_nqn($prospective{subsysnqn});
+ _configured_portals(\%prospective);
+ my $new_hostnqns = parse_nvme_host_nqns($prospective{'nvme-host-nqns'});
+ my %new_hosts = map { $_ => 1 } $new_hostnqns->@*;
+ for my $old_hostnqn (parse_nvme_host_nqns($scfg->{'nvme-host-nqns'})->@*) {
+ die "removing NVMe host NQN '$old_hostnqn' is not supported; move every volume off"
+ . " the storage and recreate it with a new subsystem NQN and a new DH-HMAC-CHAP"
+ . " key\n"
+ if !$new_hosts{$old_hostnqn};
+ }
+ _validate_fail_fast_timeout(\%prospective, 600);
+ _assert_unique_target($storeid, \%prospective);
+
+ my $old_key = file_read_firstline(secret_path($storeid));
+ my $key = exists($sensitive->{'dhchap-key'}) ? $sensitive->{'dhchap-key'} : $old_key;
+ _validate_secret($key);
+
+ # nvmet stores authentication on the global Host NQN object, which can be
+ # shared by multiple subsystems. Replacing an active key in place can make
+ # unrelated storages unrecoverable on their next reconnect. Until PVE can
+ # coordinate a rolling rotation on every node, fail before mutating the
+ # cluster-wide secret.
+ die "NVMe DH-HMAC-CHAP key rotation is not supported; create a new storage with a new"
+ . " subsystem NQN\n"
+ if defined($old_key) && $key ne $old_key;
+ _assert_shared_host_key($storeid, \%prospective, $key);
+
+ set_secret($storeid, $key) if exists($sensitive->{'dhchap-key'});
+ return;
+}
+
+# ---------------------------------------------------------------------------
+# Local NVMe host side
+# ---------------------------------------------------------------------------
+
+my %slow_path_last; # storeid => time of the last slow-path activation
+
+# Probes of the local host (test seams).
+sub _block_device($path) {
+ return -b $path;
+}
+
+sub _link_target($path) {
+ return readlink($path);
+}
+
+sub _fabrics_device() {
+ return '/dev/nvme-fabrics';
+}
+
+# Runs $code in a child and gives up on it after $timeout seconds. Returns the
+# child's result; the child's errors pass through as exceptions, a timeout
+# becomes one. The bound is not hard: as with PVE::Tools::run_command, a
+# child stuck in the kernel (a write or delete in D state) is only reaped
+# once the kernel returns, and a timeout does not mean that the operation did
+# not happen.
+#
+# A stopped task (TERM, also HUP, INT and QUIT) stays pending in the parent
+# while the child runs, and the child inherits the mask: a connect that ends
+# before PVE escalates the stop to KILL, 5 seconds after the TERM, creates
+# the controller and restricts its secret attributes without interruption,
+# and run_fork_with_timeout, whose own handlers would consume the signal when
+# the child delivers a result, never sees it. Once the child is reaped and the
+# mask is restored, the handler of the worker dies with the task marker, also
+# over a result or an error of the child. ALRM, the timeout, is not blocked.
+# The KILL ends the parent and the child together; a controller that the
+# child had created but not restricted yet keeps its secret attributes
+# world-readable until the next activation restricts them.
+#
+# run_fork_with_timeout is called in list context on purpose: only there does
+# run_with_timeout report a timeout as its second return value; in scalar
+# context the timeout would be a warning and an undef result.
+my sub run_bounded($timeout, $what, $code) {
+ my $previous = POSIX::SigSet->new();
+ sigprocmask(SIG_BLOCK, POSIX::SigSet->new(SIGHUP, SIGINT, SIGQUIT, SIGTERM), $previous)
+ or die "cannot block signals: $!\n";
+ my $outer_warn = $SIG{__WARN__};
+ my ($res, $timed_out) = eval {
+ # Only a child that leaves no result makes run_fork_with_timeout warn
+ # in the parent; that case is an exception below. The child keeps the
+ # handler of the caller, so its own warnings reach the task log.
+ local $SIG{__WARN__} = sub($message) { };
+ PVE::Tools::run_fork_with_timeout(
+ $timeout,
+ sub {
+ local $SIG{__WARN__} = $outer_warn;
+ return $code->();
+ },
+ );
+ };
+ my $error = $@;
+ sigprocmask(SIG_SETMASK, $previous) or die "cannot restore signals: $!\n";
+ if ($error) {
+ rethrow_task_interrupt($error);
+ die $error;
+ }
+ die "$what did not complete within $timeout seconds\n" if $timed_out;
+ die "$what left no result\n" if !defined($res);
+ return $res;
+}
+
+# The connect options of one controller, as the fabrics device takes them,
+# and their names. The values are validated configuration and host identities
+# checked by the caller; the kernel reads each one up to the next ','.
+sub _fabrics_options($scfg, $portal, $hostnqn, $hostid, $key) {
+ my @options = (
+ [transport => 'tcp'],
+ [traddr => $portal->{address}],
+ [trsvcid => $portal->{port}],
+ [host_iface => $portal->{host_iface}],
+ [nqn => $scfg->{subsysnqn}],
+ [hostnqn => $hostnqn],
+ [hostid => $hostid],
+ [dhchap_secret => $key],
+ [keep_alive_tmo => $scfg->{'nvme-keep-alive-tmo'} // 5],
+ [reconnect_delay => $scfg->{'nvme-reconnect-delay'} // 2],
+ [ctrl_loss_tmo => $scfg->{'nvme-ctrl-loss-tmo'} // 600],
+ );
+ # unlike unset, which leaves fast I/O failure off, 0 is a real timeout
+ push @options, [fast_io_fail_tmo => $scfg->{'nvme-fast-io-fail-tmo'}]
+ if defined($scfg->{'nvme-fast-io-fail-tmo'});
+ push @options, [nr_io_queues => $scfg->{'nvme-nr-io-queues'}]
+ if defined($scfg->{'nvme-nr-io-queues'});
+ for my $option (@options) {
+ die "internal error: invalid NVMe connect option '$option->[0]'\n"
+ if !defined($option->[1]) || $option->[1] !~ $RE_FABRICS_VALUE;
+ }
+ return (join(',', map { "$_->[0]=$_->[1]" } @options), [map { $_->[0] } @options]);
+}
+
+# The child of a connect (a test seam): creates exactly one controller with
+# one write of $options to the fabrics device and returns its instance. The
+# write is never repeated, because the kernel may have created the controller
+# even when it reports an error. Errors carry the errno text of the failed
+# operation and never the options, which hold the key.
+sub _fabrics_connect($options, $names) {
+ my $device = _fabrics_device();
+ my $probe;
+ if (!sysopen($probe, $device, O_RDONLY | O_NOFOLLOW)) {
+ die "'$device' does not exist; load the nvme-tcp kernel module\n" if $! == ENOENT;
+ die "cannot open '$device': $!\n";
+ }
+ my @stat = stat($probe);
+ die "'$device' is not a character device\n" if !@stat || !S_ISCHR($stat[2]);
+ # without a controller, a read lists the supported options as patterns
+ my $supported = '';
+ sysread($probe, $supported, 4096) // die "cannot read '$device': $!\n";
+ close($probe);
+ my %supported = map { s/=.*//r => 1 } split(/,/, $supported =~ s/\n\z//r);
+ for my $name ($names->@*) {
+ die "the running kernel does not support the NVMe connect option '$name'\n"
+ if !$supported{$name};
+ }
+
+ # Not PVE::SysFSTools::file_write: the kernel returns the instance of the
+ # new controller on a read of the file descriptor that wrote the options.
+ sysopen(my $fh, $device, O_RDWR | O_NOFOLLOW) or die "cannot open '$device': $!\n";
+ my $written = _fabrics_write($fh, $options);
+ die "connect failed: $!\n" if !defined($written);
+ die "connect failed: short write\n" if $written != length($options);
+ my $result = '';
+ sysread($fh, $result, 128) // die "cannot read the connect result: $!\n";
+ die "unexpected connect result\n" if $result !~ $RE_FABRICS_RESULT;
+ my $instance = int($+{instance});
+ # The kernel creates the secret attributes of a controller world-readable;
+ # the caller keeps a stopped task from interrupting before this, short of
+ # a KILL.
+ _restrict_attr("/sys/class/nvme/nvme$instance/$_") for qw(dhchap_secret dhchap_ctrl_secret);
+ close($fh);
+ return $instance;
+}
+
+# The write that creates a controller (a test seam).
+sub _fabrics_write($fh, $options) {
+ return syswrite($fh, $options);
+}
+
+# Writes a sysfs attribute and returns the errno text of a failure, or undef.
+# PVE::SysFSTools::file_write returns undef without a warning when the open
+# fails, leaving its errno in $!, and 0 after warning "error writing ...:
+# <errno text>" when the write fails; that warning is not passed on. With
+# $missing_ok, an attribute that does not exist, because its controller went
+# away, is not a failure.
+my sub write_attribute($path, $value, $missing_ok = 0) {
+ my $warning;
+ my $written = do {
+ local $SIG{__WARN__} = sub($message) { $warning = $message };
+ PVE::SysFSTools::file_write($path, $value);
+ };
+ return if $written;
+ return if !defined($warning) && $missing_ok && $! == ENOENT;
+ return "$!" if !defined($warning);
+ return $warning =~ s/\A.*: //sr =~ s/\n\z//r;
+}
+
+# Deletes controllers (the body of a child, a test seam): the deletion can
+# block in the kernel. The error names the controller and the errno text; a
+# controller that is already gone counts as deleted.
+sub _delete_controllers($controllers) {
+ for my $controller ($controllers->@*) {
+ my $path = "/sys/class/nvme/$controller->{name}/delete_controller";
+ my $error = write_attribute($path, '1', 1) // next;
+ die "cannot delete NVMe controller '$controller->{name}': $error\n";
+ }
+ return scalar($controllers->@*);
+}
+
+# Every local controller of the subsystem.
+my sub nvme_controllers($nqn) {
+ my $controllers = [];
+ PVE::File::dir_glob_foreach(
+ '/sys/class/nvme',
+ $RE_NVME_CONTROLLER,
+ sub($entry) {
+ my $base = "/sys/class/nvme/$entry";
+ my $subsys = file_read_firstline("$base/subsysnqn");
+ return if !defined($subsys) || $subsys ne $nqn;
+ my $address = file_read_firstline("$base/address") // '';
+ my $traddr = $address =~ $RE_TRADDR ? $+{value} : undef;
+ my $trsvcid = $address =~ $RE_TRSVCID ? $+{value} : undef;
+ my $host_iface = $address =~ $RE_HOST_IFACE_ADDRESS ? $+{value} : undef;
+ push $controllers->@*,
+ {
+ name => $entry,
+ state => file_read_firstline("$base/state") // 'unknown',
+ traddr => nvmet_canonical_address($traddr),
+ trsvcid => $trsvcid,
+ host_iface => $host_iface,
+ };
+ },
+ );
+ return $controllers;
+}
+
+# Controllers by "address:port", with canonical IPv6 addresses. A portal has
+# more than one controller while its path moves to another interface.
+my sub controller_states($nqn) {
+ my $states = {};
+ for my $controller (nvme_controllers($nqn)->@*) {
+ next if !defined($controller->{traddr}) || !defined($controller->{trsvcid});
+ push $states->{"$controller->{traddr}:$controller->{trsvcid}"}->@*, $controller;
+ }
+ return $states;
+}
+
+# The multipath namespace devices of the subsystem and their partitions. One
+# dir_glob_foreach per directory level, because PVE::File::dir_glob_regex
+# returns only the first match.
+my sub namespace_devices($nqn) {
+ my $devices = {};
+
+ PVE::File::dir_glob_foreach(
+ '/sys/class/nvme-subsystem',
+ $RE_NVME_SUBSYSTEM,
+ sub($entry) {
+ my $base = "/sys/class/nvme-subsystem/$entry";
+ my $subsys = file_read_firstline("$base/subsysnqn");
+ return if !defined($subsys) || $subsys ne $nqn;
+
+ PVE::File::dir_glob_foreach(
+ $base,
+ $RE_NVME_NAMESPACE,
+ sub($device) {
+ $devices->{"/dev/$device"} = $device if _block_device("/dev/$device");
+ PVE::File::dir_glob_foreach(
+ "/sys/class/block/$device",
+ $RE_NVME_PARTITION,
+ sub($partition) {
+ $devices->{"/dev/$partition"} = $partition
+ if _block_device("/dev/$partition");
+ },
+ );
+ },
+ );
+ },
+ );
+ return $devices;
+}
+
+sub _namespace_openers($nqn) {
+ my $devices = namespace_devices($nqn);
+ return [] if !$devices->%*;
+
+ my %openers;
+ PVE::File::dir_glob_foreach(
+ '/proc',
+ '[0-9]+',
+ sub($pid) {
+ PVE::File::dir_glob_foreach(
+ "/proc/$pid/fd",
+ '[0-9]+',
+ sub($fd) {
+ my $target = _link_target("/proc/$pid/fd/$fd");
+ return if !defined($target) || !exists($devices->{$target});
+ my $comm = eval { file_read_firstline("/proc/$pid/comm") } // 'unknown';
+ $openers{"$pid:$target"} = "$comm (PID $pid, $target)";
+ },
+ );
+ },
+ );
+
+ # Kernel consumers such as device-mapper do not necessarily keep a userspace
+ # file descriptor open, but expose their dependency in the holders directory.
+ for my $path (keys $devices->%*) {
+ my $device = $devices->{$path};
+ my $holders = "/sys/class/block/$device/holders";
+ PVE::File::dir_glob_foreach(
+ $holders,
+ '[^\\.].*',
+ sub($holder) {
+ $openers{"holder:$device:$holder"} = "$path held by $holder";
+ },
+ );
+ }
+
+ return [sort values %openers];
+}
+
+my sub portal_reachable($portal) {
+ return PVE::Network::tcp_ping($portal->{address}, $portal->{port}, 2) // 0;
+}
+
+# The number of portals with a live controller on their configured interface,
+# or, with $any_iface, on any interface: such a path carries I/O, even while
+# it waits to be moved to its configured interface.
+sub _live_portal_count($states, $portals, $any_iface = 0) {
+ my $live = 0;
+ for my $portal ($portals->@*) {
+ my $id = "$portal->{address}:$portal->{port}";
+ $live++ if grep {
+ $_->{state} eq 'live'
+ && ($any_iface || ($_->{host_iface} // '') eq $portal->{host_iface})
+ } ($states->{$id} // [])->@*;
+ }
+ return $live;
+}
+
+# Creates the controller of a portal in a child, giving up after 10 seconds.
+sub _connect_portal($scfg, $portal, $hostnqn, $hostid, $key) {
+ my ($options, $names) = _fabrics_options($scfg, $portal, $hostnqn, $hostid, $key);
+ return run_bounded(10, 'NVMe/TCP connect', sub { return _fabrics_connect($options, $names) });
+}
+
+my sub set_iopolicy($nqn, $policy) {
+ PVE::File::dir_glob_foreach(
+ '/sys/class/nvme-subsystem',
+ $RE_NVME_SUBSYSTEM,
+ sub($entry) {
+ my $base = "/sys/class/nvme-subsystem/$entry";
+ my $subsys = file_read_firstline("$base/subsysnqn");
+ return if !defined($subsys) || $subsys ne $nqn;
+ my $error = write_attribute("$base/iopolicy", "$policy\n");
+ die "unable to set NVMe multipath policy: $error\n" if defined($error);
+ },
+ );
+}
+
+# Applies the reconnect timeouts to connected controllers, which otherwise
+# keep the values of their connect. sysfs shows "off" for -1, and shows the
+# loss timeout rounded up to a multiple of the reconnect delay.
+my sub set_tunables($scfg) {
+ my $delay = $scfg->{'nvme-reconnect-delay'} // 2;
+ my $loss = $scfg->{'nvme-ctrl-loss-tmo'} // 600;
+ my $fast = $scfg->{'nvme-fast-io-fail-tmo'};
+ my $shown_loss = $loss < 0 ? 'off' : int(($loss + $delay - 1) / $delay) * $delay;
+ my $shown_fast = defined($fast) && $fast >= 0 ? $fast : 'off';
+
+ for my $controller (nvme_controllers($scfg->{subsysnqn})->@*) {
+ my $base = "/sys/class/nvme/$controller->{name}";
+ my $current_delay = file_read_firstline("$base/reconnect_delay") // next;
+ my $write = sub($attr, $value) {
+ my $error = write_attribute("$base/$attr", "$value\n") // return;
+ log_warn("cannot set $attr of NVMe controller '$controller->{name}': $error");
+ };
+ my $delay_changed = $current_delay ne "$delay";
+ $write->('reconnect_delay', $delay) if $delay_changed;
+ # the loss timeout is stored as a number of reconnects of the delay
+ $write->('ctrl_loss_tmo', $loss < 0 ? -1 : $loss)
+ if $delay_changed
+ || (file_read_firstline("$base/ctrl_loss_tmo") // '') ne "$shown_loss";
+ $write->('fast_io_fail_tmo', $shown_fast eq 'off' ? -1 : $fast)
+ if (file_read_firstline("$base/fast_io_fail_tmo") // '') ne "$shown_fast";
+ }
+}
+
+# Attempts to make a controller attribute readable by root only (a test seam).
+sub _restrict_attr($path) {
+ my @stat = stat($path);
+ if (!@stat) {
+ log_warn("cannot stat NVMe controller attribute '$path': $!") if $! != ENOENT;
+ return;
+ }
+ return if !($stat[2] & 077);
+ chmod(0600, $path) or log_warn("cannot restrict permissions of '$path': $!");
+}
+
+# The kernel creates the DH-HMAC-CHAP secret attributes world-readable.
+my sub restrict_secret_attrs($nqn) {
+ for my $controller (nvme_controllers($nqn)->@*) {
+ _restrict_attr("/sys/class/nvme/$controller->{name}/$_")
+ for qw(dhchap_secret dhchap_ctrl_secret);
+ }
+}
+
+# Best effort: a controller that went away since it was listed needs no scan,
+# and one that cannot be rescanned is a warning.
+my sub rescan_namespaces($nqn) {
+ for my $controller (nvme_controllers($nqn)->@*) {
+ next if $controller->{state} ne 'live';
+ my $path = "/sys/class/nvme/$controller->{name}/rescan_controller";
+ my $error = write_attribute($path, "1\n", 1) // next;
+ log_warn("cannot rescan NVMe controller '$controller->{name}': $error");
+ }
+}
+
+# Deletes a controller that is dead or that moved to another interface. The
+# activation reconnects or keeps the path either way, so this only warns.
+my sub disconnect_controller($controller) {
+ my $name = $controller->{name};
+ eval {
+ run_bounded(
+ 5,
+ "deleting NVMe controller '$name'",
+ sub { return _delete_controllers([$controller]) },
+ );
+ };
+ if (my $error = $@) {
+ rethrow_task_interrupt($error);
+ log_warn($error);
+ }
+}
+
+# Waits up to 10 seconds for a live controller of the portal on its
+# configured interface.
+my sub wait_for_live_path($nqn, $portal) {
+ for (my $attempt = 0; $attempt < 40; $attempt++) {
+ return 1 if _live_portal_count(controller_states($nqn), [$portal]);
+ _sleep(0.25);
+ }
+ return 0;
+}
+
+# Connects every missing or dead path on its configured interface. A path
+# that is connected on another interface moves make-before-break: its old
+# controller is only disconnected once the new one is live, so changing an
+# interface mapping never takes away a path that carries I/O.
+my sub connect_portals($scfg, $portals, $hostnqn, $hostid, $key) {
+ my $nqn = $scfg->{subsysnqn};
+ for my $portal ($portals->@*) {
+ my $id = "$portal->{address}:$portal->{port}";
+ my $iface = $portal->{host_iface};
+ my @controllers = (controller_states($nqn)->{$id} // [])->@*;
+ my ($configured) = grep { ($_->{host_iface} // '') eq $iface } @controllers;
+ my @moved = grep { ($_->{host_iface} // '') ne $iface } @controllers;
+
+ if (!$configured || $configured->{state} eq 'dead') {
+ disconnect_controller($configured) if $configured;
+ if (!portal_reachable($portal)) {
+ log_warn("NVMe/TCP portal '$id' is unreachable");
+ next;
+ }
+ eval { _connect_portal($scfg, $portal, $hostnqn, $hostid, $key) };
+ my $connect_error = $@;
+ # A failed or timed-out connect can still have created a controller.
+ eval { restrict_secret_attrs($nqn); 1 };
+ if (my $error = $@) {
+ rethrow_task_interrupt($error);
+ log_warn("cannot restrict NVMe controller attributes for '$nqn'");
+ }
+ rethrow_task_interrupt($connect_error) if $connect_error;
+ if ($connect_error) {
+ log_warn("$id: $connect_error");
+ next;
+ }
+ }
+ next if !@moved;
+ if (!wait_for_live_path($nqn, $portal)) {
+ log_warn("NVMe/TCP portal '$id' is not live on '$iface' yet; keeping its path on"
+ . " another interface");
+ next;
+ }
+ disconnect_controller($_) for @moved;
+ }
+}
+
+sub activate_storage($class, $storeid, $scfg, $cache = undef) {
+ $cache //= {};
+ my $nqn = $scfg->{subsysnqn};
+ # First, whatever the rest of the activation does, also for controllers
+ # connected by hand. Also try after each connect attempt below, including
+ # failures that may have created a controller.
+ restrict_secret_attrs($nqn);
+
+ my $multipath = file_read_firstline('/sys/module/nvme_core/parameters/multipath')
+ // die "the NVMe kernel modules are not loaded; load the nvme-tcp kernel module\n";
+ die "native NVMe multipath is disabled in the running kernel\n" if $multipath ne 'Y';
+
+ my $portals = _configured_portals($scfg);
+ verify_nvme_nqn($nqn);
+ _validate_local_ifaces($portals);
+ _assert_unique_target($storeid, $scfg);
+ my $hostnqn = file_read_firstline('/etc/nvme/hostnqn')
+ // die "missing /etc/nvme/hostnqn; the nvme-cli package generates it\n";
+ verify_nvme_nqn($hostnqn);
+ my $hostnqns = parse_nvme_host_nqns($scfg->{'nvme-host-nqns'});
+ die "local NVMe host NQN '$hostnqn' is missing from nvme-host-nqns\n"
+ if !grep { $_ eq $hostnqn } $hostnqns->@*;
+ my $policy = $scfg->{'nvme-iopolicy'} // 'round-robin';
+ my $force_reconcile = delete($cache->{'zfsnvme-force-reconcile'}->{$storeid}) // 0;
+ my $states = controller_states($nqn);
+ my $healthy = _live_portal_count($states, $portals);
+ my $usable = _live_portal_count($states, $portals, 1);
+ my $last = $slow_path_last{$storeid};
+ my $recent = defined($last) && _now() - $last < $slow_path_backoff;
+
+ # This method is called by the periodic storage status loop. Once every
+ # configured path is live, lifecycle operations keep the target converged,
+ # so no remote call is needed. A degraded storage retries the target at
+ # most once a minute: in between, one with a live path (also one waiting
+ # to move to its configured interface) is usable, and one without fails
+ # at once instead of waiting for a path again. Missing namespaces
+ # explicitly force the slow path from activate_volume().
+ if (!$force_reconcile && ($healthy == scalar($portals->@*) || $recent)) {
+ die "no live NVMe/TCP path for storage '$storeid'\n" if !$usable;
+ die "missing NVMe DH-HMAC-CHAP key\n"
+ if (file_read_firstline(secret_path($storeid)) // '') eq '';
+ set_iopolicy($nqn, $policy);
+ set_tunables($scfg);
+ return 1;
+ }
+
+ $slow_path_last{$storeid} = _now();
+ my $hostid = file_read_firstline('/etc/nvme/hostid')
+ // die "missing /etc/nvme/hostid; the nvme-cli package generates it\n";
+ die "invalid NVMe host ID\n"
+ if $hostid !~ $RE_NVMET_UUID || $hostid =~ $RE_ZERO_UUID;
+ my $key = get_secret($storeid);
+ for my $name (qw(keep-alive-tmo reconnect-delay ctrl-loss-tmo fast-io-fail-tmo nr-io-queues)) {
+ my $value = $scfg->{"nvme-$name"};
+ die "invalid NVMe connection parameter '$name'\n"
+ if defined($value) && $value !~ $RE_CONFIG_INT;
+ }
+ _nvmet_activate_target($storeid, $scfg, $portals, $hostnqns, $key);
+ connect_portals($scfg, $portals, $hostnqn, $hostid, $key);
+
+ # Existing controllers can be in the middle of their kernel reconnect delay
+ # after a target restart. Do not create duplicates, but give that recovery
+ # cycle enough time to complete before declaring the storage unavailable.
+ for (my $attempt = 0; $attempt < 60; $attempt++) {
+ $states = controller_states($nqn);
+ last if _live_portal_count($states, $portals, 1);
+ _sleep(0.25);
+ }
+ die "no live NVMe/TCP path for storage '$storeid'\n"
+ if !_live_portal_count($states, $portals, 1);
+ $healthy = _live_portal_count($states, $portals);
+ log_warn("storage '$storeid' is degraded: $healthy/" . scalar($portals->@*) . " paths live")
+ if $healthy < scalar($portals->@*);
+
+ set_iopolicy($nqn, $policy);
+ set_tunables($scfg);
+ return 1;
+}
+
+sub deactivate_storage($class, $storeid, $scfg, $cache = undef) {
+ my $nqn = $scfg->{subsysnqn};
+ my $openers = _namespace_openers($nqn);
+ die "refusing to disconnect NVMe storage '$storeid': namespace in use by "
+ . join(', ', $openers->@*) . "\n"
+ if $openers->@*;
+
+ # One child deletes every controller, bounded by 15 seconds in all. When it
+ # gives up, the controllers that are left stay connected and the
+ # deactivation fails.
+ my $controllers = nvme_controllers($nqn);
+ run_bounded(
+ 15,
+ "disconnecting NVMe subsystem '$nqn'",
+ sub { return _delete_controllers($controllers) },
+ ) if $controllers->@*;
+ return 1;
+}
+
+# Removing a storage definition never destroys data and never depends on the
+# target, like for every other storage type. Target cleanup is best effort
+# and only happens once the storage owns no volume. Other nodes keep their
+# connections until they are disconnected there.
+sub on_delete_hook($class, $storeid, $scfg) {
+ # First: an activation elsewhere that waits for the target lock then
+ # refuses instead of restoring what is removed below.
+ delete_secret($storeid);
+ eval { $class->deactivate_storage($storeid, $scfg) };
+ if (my $err = $@) {
+ rethrow_task_interrupt($err);
+ chomp($err);
+ log_warn("not disconnecting NVMe storage '$storeid': $err");
+ }
+ eval { _nvmet_delete_target($scfg) };
+ if (my $err = $@) {
+ rethrow_task_interrupt($err);
+ chomp($err);
+ log_warn("keeping the NVMe target configuration of storage '$storeid': $err");
+ }
+ return;
+}
+
+sub path($class, $scfg, $volname, $storeid, $snapname = undef) {
+ die "direct access to snapshots not implemented\n" if defined($snapname);
+ my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+ my $uuid = _nvmet_volume_uuid($scfg, $name);
+ my $path = "/dev/disk/by-id/nvme-uuid.$uuid";
+ return ($path, $vmid, $vtype);
+}
+
+sub qemu_blockdev_options(
+ $class, $scfg, $storeid, $volname,
+ $machine_version = undef,
+ $options = undef,
+) {
+ die "direct access to snapshots not implemented\n" if $options->{'snapshot-name'};
+ my ($path) = $class->path($scfg, $volname, $storeid);
+ return { driver => 'host_device', filename => $path };
+}
+
+# Whether the local device behind a namespace link is the namespace (NSID,
+# UUID) of this subsystem, so a UUID claimed by another subsystem is never
+# handed to a guest.
+sub _nvmet_local_namespace_ok($path, $nqn, $nsid, $uuid) {
+ my $link = _link_target($path) // return 0;
+ my $device = (split m{/}, $link)[-1];
+ return 0 if !defined($device) || $device !~ $RE_NVME_NAMESPACE;
+ my $sys = "/sys/block/$device";
+ return 0 if lc(file_read_firstline("$sys/uuid") // '') ne lc($uuid);
+ return 0 if (file_read_firstline("$sys/nsid") // '') ne "$nsid";
+ return 0 if (file_read_firstline("$sys/device/subsysnqn") // '') ne $nqn;
+ return 1;
+}
+
+sub activate_volume(
+ $class, $storeid, $scfg, $volname,
+ $snapname = undef,
+ $cache = undef,
+ $hints = undef,
+) {
+ die "unable to activate snapshot from remote zfs storage\n" if $snapname;
+ my (undef, $name) = $class->parse_volname($volname);
+ my $nqn = nvmet_nqn($scfg);
+ my $dataset = nvmet_dataset($scfg, $name);
+
+ my ($inv, $cfs) = nvmet_read($scfg);
+ my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset);
+ my $state = _nvmet_export_state($cfs, $nqn, $nsid, $uuid, "/dev/zvol/$dataset");
+ my $path = "/dev/disk/by-id/nvme-uuid.$uuid";
+ my $ok = sub {
+ return _block_device($path) && _nvmet_local_namespace_ok($path, $nqn, $nsid, $uuid);
+ };
+ return 1 if $state eq 'present' && $ok->();
+
+ $cache //= {};
+ $cache->{'zfsnvme-force-reconcile'}->{$storeid} = 1;
+ $class->activate_storage($storeid, $scfg, $cache);
+ for (my $attempt = 0; $attempt < 40 && !_block_device($path); $attempt++) {
+ # a host can miss the change notice; rescanning is harmless
+ rescan_namespaces($nqn) if $attempt % 8 == 0;
+ _sleep(0.25);
+ }
+ die "NVMe namespace for '$volname' did not appear\n" if !_block_device($path);
+ die "NVMe namespace for '$volname' has an unexpected identity\n" if !$ok->();
+ return 1;
+}
+
+sub deactivate_volume(
+ $class, $storeid, $scfg, $volname, $snapname = undef, $cache = undef,
+) {
+ die "unable to deactivate snapshot from remote zfs storage\n" if $snapname;
+ return 1;
+}
+
+1;
^ permalink raw reply related [relevance 16%]
* Re: [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend
2026-10-05 0:27 15% ` Joaquin Varela
@ 2026-10-21 8:06 6% ` Max R. Carrara
0 siblings, 0 replies; 43+ results
From: Max R. Carrara @ 2026-10-21 8:06 UTC (permalink / raw)
To: Joaquin Varela; +Cc: pve-devel
On Mon Oct 5, 2026 at 2:27 AM CEST, Joaquin Varela wrote:
> Hi Max,
>
> thank you very much for the detailed review, and sorry that it took a
> few days. I have just sent v3 ("[PATCH storage v3 0/4] add ZFS over
> NVMe/TCP storage plugin"), together with the docs and manager patches.
> It addresses all three points and the helper suggestions: the plugin
> inherits from PVE::Storage::Plugin, LunCmd::NVMET is gone, ZFS/configfs
> parsing and operation planning are local. In patch 1/4 the target runs
> quoted simple commands,
> sometimes joined with '&&', plus one pipe that writes the key, and the
> PVE helpers replace the builtins.
> Instead of dir_glob_regex, which returns only the first match, the
> sysfs walks nest dir_glob_foreach.
>
> Two parts are questions for you, explained in the cover letter: an
> optional patch that guards transaction commands on the target against a
> delayed command of an abandoned operation, which adds target-side
> validation and a small sh guard with the only shell control flow on the
> target, and a longer default
> wait for the shared storage lock. Both are separate patches, so either
> can be dropped without touching the other storage patches (dropping
> the guard also drops one sentence and one paragraph of the docs
> patch). If the size of the series gets in the way, I can split the
> backend patch and split or trim the tests.
>
> The contribution is limited to the storage backend and its integration
> with PVE. It does not implement target high availability, pool takeover
> or target fencing. The optional guard protects control-plane operations
> on a single target too; it is not host or guest-I/O fencing. Multi-head
> target compatibility remains conditional and has not been qualified.
>
> The v3 cover Message-ID is:
> <20261005002609.571-1-joaquinvarela@neatech.ar>
>
> v3 also refuses storages that share an NVMe/TCP listener on the
> target, because after a target restart they could lose their
> controllers. The cover letter has the details.
>
> Kind regards,
> Joaquin Varela
Hi Joaquin!
Thank you very much for refreshing the series! I will do a re-review at
my earliest convenience. 🫡
- Max
^ permalink raw reply [relevance 6%]
* [PATCH v3 proxmox,proxmox-perl-rs,cluster,storage,docs,manager 00/76] SAN: cluster-wide multipath, SAN views and a guided storage setup
@ 2026-11-05 23:30 6% Thomas Lamprecht
2026-11-05 23:31 7% ` [PATCH v3 storage 41/76] api: disks: guard SAN wipes with stable identities and storage checks Thomas Lamprecht
0 siblings, 1 reply; 43+ results
From: Thomas Lamprecht @ 2026-11-05 23:30 UTC (permalink / raw)
To: pve-devel
This v3 combines the cluster-wide multipath series [0][1] with
Dietmar's RFC for guided remote storage setup and SAN visibility [2].
What it adds:
- cluster-wide dm-multipath management through /etc/pve/multipath.cfg:
iSCSI storages with the new 'multipath' option supply their LUNs;
explicit entries cover individual LUNs, for example Fibre Channel.
pvestatd applies the configuration on each node without removing
allow-list entries added by hand or for boot from SAN. Array-specific
settings go in /etc/pve/multipath-overrides.conf.
- SAN views: Datacenter > SAN shows node status and initiator names
for target access rules. Its Multipath view groups path health per
LUN, including expected paths, report age, and unresolved identities.
Node > SAN lists LUNs, paths, usage, and iSCSI targets and sessions,
with actions to enable multipath or wipe a LUN as root@pam.
- guided setup for NFS, SMB/CIFS, iSCSI, Fibre Channel, and ZFS over
iSCSI. For shared LVM over iSCSI, it creates or reuses the connection
storage, waits for LUN discovery, and creates a volume group on the
selected LUN, using its map when multipath is enabled. Partial setups
retain their settings and retry only missing steps; unanswered
requests are checked before retrying.
- guards for destructive actions: SAN wipes and volume-group creation
check cluster storage references, local users, and device identities.
Before a wipe, the web UI also asks the other nodes for users of the
LUN. Wipes keep the checked device references and recheck identities
between writes. Inconclusive checks refuse the operation. Session
logout is refused if it would remove the last usable path of a LUN in
use. Cluster locks do not cover hosts outside the cluster.
Patches 04-11 are independent fixes and could go in first, with their
documentation and pvestatd parts in patches 43 and 46: status-only
activation and bounded LVM queries, shared VGs missed by LVM hints,
per-target rescans, LUNs listed per iSCSI session, validation before
volume-group creation, and a target check that refuses composite
devices. The smaller fixes for SCSI padding, iSCSI discovery errors,
iSER and offload sessions, LVM base volumes and the iSCSI edit dialog
are already applied.
Changes since v2:
- combined with Dietmar's RFC; multipath is an iSCSI storage option
rather than a separate per-LUN storage type
- Node > SAN offers Enable Multipath; the datacenter view uses one
row per LUN with expandable node details, not a column per node
(Dominik)
- addressed Dominik's API and code remarks: add_wwid accepts alias and
settings, alias changes use the update endpoint, config helpers are
renamed, group_by_tpg is available, and the overrides example is
fixed
- preserved existing allow-list entries, addressing Maximiliano's
migration concern without a warning on first use
- added expected path counts, stalled-node detection, withdrawn LUN
status, unresolved identities, and duplicate-PV hints for clones
- added LVM and wipe guards, bounded status commands, the node iSCSI
API, and pvenode commands
- added an admin guide chapter, including removal, growth, and clone
procedures tested on real hardware
- moved the parsing of multipathd map status and the health derivation
to a new proxmox-multipath crate, used through pve-rs bindings
Testing used a five-node nested cluster attached to a NetApp AFF A20
through two independent paths over iSCSI and NVMe/TCP, plus host-side
Linux LIO and nvmet targets. Scenarios covered path, LIF, and
whole-array outages with guests running; LUN unmapping with queued I/O;
revoked node access; online growth; snapshot clones; reboot; and adding
30 LUNs at once. Wizard and wipe tests covered lost responses, stuck
tasks, denied logins, and LVM metadata written by other nodes. The
screens were also reviewed from four user perspectives. The bounded
status commands and the wizard's LUN identity check also have focused
regression tests. Fibre Channel and offload iSCSI initiators, which can
run several sessions on one SCSI host, were not tested on hardware.
Open points:
- path-redundancy loss is visible in the web UI and API but sends no
notification (can be more easily done once Lukas' notification
matcher rework has landed)
- an optimal LUN is marked incomplete while its state on an expected
node is unknown, but there is no count of the current reports per LUN
- LUN removal is documented, not guided - can be added later.
- if thin_check takes longer than the shared status-command budget,
that status pass reports no LVM or LVM-thin status. Later passes
retry the activation; starting a guest activates the pool without
this budget
- pvcreate and vgcreate receive a checked, identity-bearing by-id name,
but resolve it themselves, leaving a short race after the final check
- integration with the per-node target and portal mapping work [3][4]
Apply in patch order. The pve-rs bindings need the proxmox-multipath
crate packaged first. pve-storage needs pve-cluster with the multipath
configuration files registered and libpve-rs-perl with the bindings.
pve-manager needs the matching pve-storage APIs and status-command
helper, plus the pve-docs and pve-doc-generator changes.
Feature-specific dependency bumps are deferred until the providing
package versions are known and must be added before shipping. This
includes a Breaks of libpve-storage-perl on older pve-manager, whose
Ceph OSD creation would accept the iSCSI LUNs that the disk list now
includes (patch 45).
[0]: https://lore.proxmox.com/pve-devel/20260626121000.2095591-1-t.lamprecht@proxmox.com/
[1]: https://lore.proxmox.com/pve-devel/20260703124707.1172980-2-t.lamprecht@proxmox.com/
[2]: https://lore.proxmox.com/pve-devel/20260731102156.3947857-1-dietmar@proxmox.com/
[3]: https://lore.proxmox.com/pve-devel/20260430173220.441001-1-m.limbeck@proxmox.com/
[4]: https://lore.proxmox.com/pve-devel/20260804090819.2136483-1-dietmar@proxmox.com/
proxmox:
Thomas Lamprecht (1):
add proxmox-multipath crate
Cargo.toml | 2 +
proxmox-multipath/Cargo.toml | 17 ++
proxmox-multipath/debian/changelog | 7 +
proxmox-multipath/debian/control | 38 +++
proxmox-multipath/debian/copyright | 18 ++
proxmox-multipath/debian/debcargo.toml | 7 +
proxmox-multipath/src/lib.rs | 531 +++++++++++++++++++++++++++++++++
7 files changed, 620 insertions(+)
proxmox-perl-rs:
Thomas Lamprecht (1):
pve-rs: add PVE::RS::Multipath bindings for multipathd status parsing
pve-rs/Cargo.toml | 1 +
pve-rs/Makefile | 2 ++
pve-rs/debian/control | 1 +
pve-rs/src/bindings/mod.rs | 3 ++
pve-rs/src/bindings/multipath.rs | 40 ++++++++++++++++++++++
pve-rs/test/Makefile | 1 +
pve-rs/test/multipath.pl | 74 ++++++++++++++++++++++++++++++++++++++++
7 files changed, 122 insertions(+)
pve-cluster:
Thomas Lamprecht (1):
cfs: observe the multipath configuration files
src/PVE/Cluster.pm | 2 ++
src/pmxcfs/status.c | 2 ++
2 files changed, 4 insertions(+)
pve-storage:
Dietmar Maurer (12):
diskmanage: collect disk transport type from lsblk
diskmanage: add helper to list multipath devices
diskmanage: qualify NVMe over fabrics transport
disks: list: add include-remote parameter
diskmanage: include iSCSI session devices in disk enumeration
diskmanage: link multipath member disks to their map device
iscsi: factor out session device map from device list
api: scan: add a SAN LUN inventory
pvesm: expose the SAN LUN inventory
diskmanage: collect native NVMe multipath path state
api: scan: san-luns: report path state
api: add node-level iSCSI status and maintenance
Thomas Lamprecht (27):
storage: distinguish status-only activation in plugins
lvm: find a shared volume group created by another node
storage: bound LVM status commands
iscsi: rate-limit session rescans per target
iscsi: list the LUNs of each session, not of its SCSI host
lvm: refuse to create a volume group on a device that holds data
lvm: refuse a base volume of a target that serves disk images
iscsi: refuse virtual devices other than multipath maps as volumes
disks: lvm: allow volume groups on SAN LUNs and multipath maps
multipath: add a library around multipathd
diskmanage: collect local block device users
api: iscsi: add session logout with last-path protection
multipath: add a cluster-wide configuration
iscsi: add an option to manage storage LUNs with multipath
lvm: activate a missing base volume before using the volume group
multipath: apply the configuration on every node
iscsi: share the initiator identity reader
multipath: publish per-node status
api: add endpoints for the cluster-wide multipath configuration
api: multipath: add the cluster-wide health status
multipath: collect identities of non-iSCSI SCSI paths
api: scan: san-luns: report the multipath state of each LUN
api: scan: flag duplicate physical volumes on distinct LUNs
api: disks: recheck local users and retain wipe device references
iscsi: name plain LUNs after their identity link
api: disks: guard SAN wipes with stable identities and storage checks
api: scan: refresh SAN usage with bounded probes
ApiChangeLog | 24 +
debian/control | 2 +
src/PVE/API2/Disks.pm | 76 +-
src/PVE/API2/Disks/LVM.pm | 74 +-
src/PVE/API2/ISCSI.pm | 423 +++++++
src/PVE/API2/Makefile | 2 +
src/PVE/API2/Multipath.pm | 689 +++++++++++
src/PVE/API2/Storage/Scan.pm | 247 ++++
src/PVE/CLI/pvesm.pm | 13 +
src/PVE/Diskmanage.pm | 1007 +++++++++++++++-
src/PVE/Makefile | 6 +
src/PVE/Multipath.pm | 375 ++++++
src/PVE/Multipath/ClusterConfig.pm | 64 +
src/PVE/Multipath/Config.pm | 451 +++++++
src/PVE/Multipath/Generator.pm | 314 +++++
src/PVE/Multipath/Identity.pm | 402 +++++++
src/PVE/Multipath/Status.pm | 486 ++++++++
src/PVE/Storage.pm | 272 ++++-
src/PVE/Storage/ISCSIPlugin.pm | 695 +++++++++--
src/PVE/Storage/LVMPlugin.pm | 323 ++++-
src/PVE/Storage/LvmThinPlugin.pm | 39 +-
src/PVE/Storage/Makefile | 4 +-
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SANScan.pm | 429 +++++++
src/PVE/Storage/StatusCommand.pm | 241 ++++
src/test/Makefile | 61 +-
src/test/disk_api_test.pm | 194 +++
src/test/disk_tests/iscsi/disklist | 1 +
src/test/disk_tests/iscsi/disklist_expected.json | 19 +
src/test/disk_tests/iscsi/lsblk | 5 +
src/test/disk_tests/iscsi/sda/device/model | 1 +
src/test/disk_tests/iscsi/sda/device/vendor | 1 +
src/test/disk_tests/iscsi/sda/queue/rotational | 1 +
src/test/disk_tests/iscsi/sda/size | 1 +
src/test/disk_tests/iscsi/sda_udevadm | 21 +
src/test/disk_tests/multipath/disklist | 11 +
.../disk_tests/multipath/disklist_expected.json | 111 ++
src/test/disk_tests/multipath/dm-0/dm/name | 1 +
src/test/disk_tests/multipath/dm-0/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-0/size | 1 +
src/test/disk_tests/multipath/dm-0_slaves | 4 +
src/test/disk_tests/multipath/dm-1/dm/name | 1 +
src/test/disk_tests/multipath/dm-1/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-1/size | 1 +
src/test/disk_tests/multipath/dm-1_slaves | 4 +
src/test/disk_tests/multipath/dm-2/dm/name | 1 +
src/test/disk_tests/multipath/dm-2/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-2/size | 1 +
src/test/disk_tests/multipath/dm-2_slaves | 1 +
src/test/disk_tests/multipath/dm-3/dm/name | 1 +
src/test/disk_tests/multipath/dm-3/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-3/size | 1 +
src/test/disk_tests/multipath/dm-3_slaves | 1 +
src/test/disk_tests/multipath/dm-4/dm/name | 1 +
src/test/disk_tests/multipath/dm-4/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-4/size | 1 +
src/test/disk_tests/multipath/dm-4_slaves | 1 +
src/test/disk_tests/multipath/lsblk | 77 ++
src/test/disk_tests/multipath/lvs | 0
src/test/disk_tests/multipath/mounts | 1 +
.../disk_tests/multipath/multipath_expected.json | 59 +
src/test/disk_tests/multipath/multipathd | 124 ++
.../multipath/multipathd_status_expected.json | 42 +
.../nvme-subsystem/nvme-subsys0/nvme3/address | 1 +
.../nvme-subsys0/nvme3/nvme2c3n1/ana_state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme3/state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme4/address | 1 +
.../nvme-subsys0/nvme4/nvme2c4n1/ana_state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme4/state | 1 +
.../nvme-subsystem/nvme-subsys1/nvme0/address | 1 +
.../nvme-subsystem/nvme-subsys1/nvme0/state | 1 +
src/test/disk_tests/multipath/nvme8n1/device/model | 1 +
.../disk_tests/multipath/nvme8n1/device/transport | 1 +
.../disk_tests/multipath/nvme8n1/queue/rotational | 1 +
src/test/disk_tests/multipath/nvme8n1/size | 1 +
src/test/disk_tests/multipath/nvme8n1_udevadm | 14 +
src/test/disk_tests/multipath/nvme9n1/device/model | 1 +
.../disk_tests/multipath/nvme9n1/device/transport | 1 +
.../disk_tests/multipath/nvme9n1/device/vendor | 1 +
.../disk_tests/multipath/nvme9n1/queue/rotational | 1 +
src/test/disk_tests/multipath/nvme9n1/size | 1 +
src/test/disk_tests/multipath/nvme9n1_udevadm | 12 +
.../multipath/nvme_path_status_expected.json | 19 +
src/test/disk_tests/multipath/partlist | 0
src/test/disk_tests/multipath/pvs | 1 +
src/test/disk_tests/multipath/sda/device/model | 1 +
src/test/disk_tests/multipath/sda/device/vendor | 1 +
src/test/disk_tests/multipath/sda/holders/holder | 1 +
src/test/disk_tests/multipath/sda/queue/rotational | 1 +
src/test/disk_tests/multipath/sda/size | 1 +
src/test/disk_tests/multipath/sda_udevadm | 18 +
src/test/disk_tests/multipath/sdb/device/model | 1 +
src/test/disk_tests/multipath/sdb/device/vendor | 1 +
src/test/disk_tests/multipath/sdb/holders/holder | 1 +
src/test/disk_tests/multipath/sdb/queue/rotational | 1 +
src/test/disk_tests/multipath/sdb/size | 1 +
src/test/disk_tests/multipath/sdb_udevadm | 18 +
src/test/disk_tests/multipath/sdc/device/model | 1 +
src/test/disk_tests/multipath/sdc/device/vendor | 1 +
src/test/disk_tests/multipath/sdc/holders/holder | 1 +
src/test/disk_tests/multipath/sdc/queue/rotational | 1 +
src/test/disk_tests/multipath/sdc/size | 1 +
src/test/disk_tests/multipath/sdc_udevadm | 18 +
src/test/disk_tests/multipath/sdd/device/model | 1 +
src/test/disk_tests/multipath/sdd/device/vendor | 1 +
src/test/disk_tests/multipath/sdd/holders/holder | 1 +
src/test/disk_tests/multipath/sdd/queue/rotational | 1 +
src/test/disk_tests/multipath/sdd/size | 1 +
src/test/disk_tests/multipath/sdd_udevadm | 18 +
src/test/disk_tests/multipath/zpool | 1 +
src/test/disk_tests/sas/disklist_expected.json | 1 +
src/test/disk_tests/sas/lsblk | 5 +
src/test/disklist_test.pm | 117 +-
src/test/lvm-fixtures/README.md | 20 +
.../lvm-fixtures/lab1-nomda-orphan-derived.colon | 2 +
src/test/lvm-fixtures/lab1-nomda-orphan.txt | 23 +
src/test/run_block_device_users_tests.pl | 172 +++
src/test/run_disk_api_tests.pl | 11 +
src/test/run_iscsi_activation_tests.pl | 171 +++
src/test/run_iscsi_device_list_tests.pl | 78 ++
src/test/run_iscsi_logout_tests.pl | 271 +++++
src/test/run_iscsi_rescan_tests.pl | 109 ++
src/test/run_iscsi_session_tests.pl | 15 +-
src/test/run_iscsi_volume_tests.pl | 81 +-
src/test/run_lun_identity_tests.pl | 1262 ++++++++++++++++++++
src/test/run_multipath_api_tests.pl | 693 +++++++++++
src/test/run_multipath_tests.pl | 1240 +++++++++++++++++++
src/test/run_san_api_tests.pl | 180 +++
src/test/run_san_library_tests.pl | 77 ++
src/test/run_san_lun_scan_tests.pl | 945 +++++++++++++++
src/test/run_san_lvm_create_tests.pl | 611 ++++++++++
src/test/run_san_taint_tests.pl | 80 ++
src/test/run_san_wipe_tests.pl | 673 +++++++++++
src/test/run_status_command_contention_tests.pl | 520 ++++++++
src/test/run_status_command_tests.pl | 189 +++
src/test/run_test_lvm_base_activation.pl | 130 ++
src/test/run_test_lvm_base_conflicts.pl | 62 +
src/test/run_test_lvm_base_volume.pl | 8 +-
src/test/run_test_lvm_create.pl | 243 ++++
src/test/run_test_lvm_hints.pl | 110 ++
src/test/run_test_lvm_status.pl | 220 ++++
src/test/run_wipe_partition_tests.pl | 387 ++++++
src/test/run_wipe_readiness_tests.pl | 138 +++
src/test/run_wipe_reference_tests.pl | 243 ++++
src/test/run_wipedisk_tests.pl | 110 ++
145 files changed, 16554 insertions(+), 215 deletions(-)
pve-docs:
Thomas Lamprecht (2):
storage: lvm: note the rescan after extending a shared volume group
storage: document the cluster-wide multipath management
pve-storage-iscsi.adoc | 13 +-
pve-storage-lvm.adoc | 9 +
pve-storage-multipath.adoc | 527 +++++++++++++++++++++++++++++++++++++++++++++
pvesm.adoc | 13 +-
4 files changed, 554 insertions(+), 8 deletions(-)
pve-manager:
Dietmar Maurer (10):
ui: storage: allow changing the node for NFS/CIFS scans
ui: storage: add guided remote storage wizard with NFS support
ui: storage wizard: add SMB/CIFS support
ui: storage wizard: add ZFS over iSCSI support
ui: dc: storage: add remote storage wizard entry to the add menu
ui: node: add SAN LUNs panel
ui: san luns: show multipath path state
api: nodes: expose iSCSI status and maintenance
pvenode: add iscsi commands
ui: node: san: add iSCSI target and session management
Thomas Lamprecht (22):
api: ceph: osd: keep iSCSI LUNs out of OSD creation
pvestatd: track pending storage status commands across re-exec
ui: storage: factor out the scan picker error mask
ui: storage: nfs: show scan errors and empty results
ui: storage wizard: preserve settings after partial setup
ui: storage wizard: add Fibre Channel shared LVM setup
ui: storage wizard: reconcile unanswered storage creation
pvestatd: apply the multipath configuration and report the node status
api: cluster: add the multipath endpoints
ui: dc: add a cluster-wide multipath view
ui: storage: iscsi: add the multipath option
ui: san luns: show multipath state and manage LUN entries
ui: storage wizard: add iSCSI support
ui: storage wizard: iscsi: show cluster initiator names
ui: storage wizard: iscsi: enable multipath for shared LVM
ui: node: san: wipe a LUN that no storage uses
ui: storage wizard: iscsi: reuse existing target connections
ui: storage wizard: fibre channel: enable multipath for a LUN
ui: storage wizard: let root@pam wipe a LUN with data
ui: storage wizard: do not offer LUNs in use for a new volume group
ui: san: show the local users of a LUN in its usage tooltip
ui: san: check the other nodes for users before wiping a LUN
PVE/API2/Ceph/OSD.pm | 3 +
PVE/API2/Cluster.pm | 7 +
PVE/API2/Nodes.pm | 7 +
PVE/CLI/pvenode.pm | 48 ++
PVE/Service/pvestatd.pm | 34 +
debian/control | 1 +
test/Makefile | 10 +
test/SANUtils_test.js | 204 +++++
test/StorageWizard_test.js | 128 +++
www/manager6/Makefile | 21 +
www/manager6/SANUtils.js | 579 +++++++++++++
www/manager6/Utils.js | 47 ++
www/manager6/dc/Config.js | 28 +-
www/manager6/dc/Multipath.js | 535 ++++++++++++
www/manager6/dc/MultipathWwidEdit.js | 233 ++++++
www/manager6/dc/SAN.js | 326 ++++++++
www/manager6/dc/StorageView.js | 13 +-
www/manager6/node/Config.js | 24 +
www/manager6/node/ISCSITargets.js | 615 ++++++++++++++
www/manager6/node/SANLuns.js | 771 ++++++++++++++++++
www/manager6/panel/SANNotice.js | 26 +
www/manager6/storage/CIFSEdit.js | 29 +-
www/manager6/storage/IScsiEdit.js | 38 +
www/manager6/storage/NFSEdit.js | 13 +
www/manager6/storage/wizard/CIFS.js | 118 +++
www/manager6/storage/wizard/CommonSettings.js | 75 ++
www/manager6/storage/wizard/FCRecovery.js | 242 ++++++
www/manager6/storage/wizard/FibreChannel.js | 1083 +++++++++++++++++++++++++
www/manager6/storage/wizard/IScsi.js | 707 ++++++++++++++++
www/manager6/storage/wizard/LunPicker.js | 101 +++
www/manager6/storage/wizard/LunSelect.js | 485 +++++++++++
www/manager6/storage/wizard/NFS.js | 89 ++
www/manager6/storage/wizard/NodeIdentities.js | 123 +++
www/manager6/storage/wizard/SanLvm.js | 179 ++++
www/manager6/storage/wizard/WipeStatus.js | 34 +
www/manager6/storage/wizard/Wizard.js | 970 ++++++++++++++++++++++
www/manager6/storage/wizard/ZFSOverISCSI.js | 180 ++++
www/manager6/window/SANLunWipe.js | 331 ++++++++
38 files changed, 8432 insertions(+), 25 deletions(-)
^ permalink raw reply [relevance 6%]
* [PATCH v3 storage 41/76] api: disks: guard SAN wipes with stable identities and storage checks
2026-11-05 23:30 6% [PATCH v3 proxmox,proxmox-perl-rs,cluster,storage,docs,manager 00/76] SAN: cluster-wide multipath, SAN views and a guided storage setup Thomas Lamprecht
@ 2026-11-05 23:31 7% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-05 23:31 UTC (permalink / raw)
To: pve-devel
A SAN LUN without local users may still belong to storage used on
another node. Before wiping, check storage references and PV identities
under the cluster storage configuration lock. Read PV membership without
LVM hints; missing volume-group metadata does not prove a PV is
orphaned.
Retain SAN identities across worker delays, require usable paths before
probes, and wipe same-LUN partition maps before removing them. Expose
usage hints and verified device references in the scan, while keeping
the worker checks authoritative. Local wipes remain independent of
quorum.
A path without an identity, such as a local disk that multipathd
ignores, counts as a possible path of the LUN: the write is refused
unless the cached VPD page of the path shows another logical unit.
Apply the same identity, readiness, and ownership checks before each
SAN volume-group initialization write, through both the disk API and
storage-add. Accept only whole LUNs and reject raw guest disks and
LUNs on targets used by storage for disk images.
pvcreate and vgcreate cannot use an open descriptor. Give them a
checked, identity-bearing by-id name, but a race remains before LVM
resolves and opens it. Cluster locks do not serialize hosts outside the
cluster.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
src/PVE/API2/Disks.pm | 35 +-
src/PVE/API2/Disks/LVM.pm | 7 +
src/PVE/API2/Storage/Scan.pm | 24 +
src/PVE/Diskmanage.pm | 390 ++++++++++++-
src/PVE/Multipath/Identity.pm | 119 +++-
src/PVE/Storage.pm | 219 ++++++++
src/PVE/Storage/LVMPlugin.pm | 27 +-
src/PVE/Storage/SANScan.pm | 7 +
src/test/Makefile | 15 +-
src/test/disk_api_test.pm | 1 +
src/test/run_block_device_users_tests.pl | 11 +
src/test/run_lun_identity_tests.pl | 214 +++++++
src/test/run_san_lun_scan_tests.pl | 26 +
src/test/run_san_lvm_create_tests.pl | 453 +++++++++++++--
src/test/run_san_wipe_tests.pl | 673 +++++++++++++++++++++++
src/test/run_test_lvm_base_volume.pl | 8 +-
src/test/run_wipe_partition_tests.pl | 297 +++++++++-
src/test/run_wipe_readiness_tests.pl | 138 +++++
src/test/run_wipe_reference_tests.pl | 168 +++++-
src/test/run_wipedisk_tests.pl | 58 +-
20 files changed, 2743 insertions(+), 147 deletions(-)
create mode 100755 src/test/run_san_wipe_tests.pl
create mode 100755 src/test/run_wipe_readiness_tests.pl
diff --git a/src/PVE/API2/Disks.pm b/src/PVE/API2/Disks.pm
index ebc73103..37a2df31 100644
--- a/src/PVE/API2/Disks.pm
+++ b/src/PVE/API2/Disks.pm
@@ -321,7 +321,7 @@ __PACKAGE__->register_method({
disk => {
type => 'string',
description => "Block device name",
- pattern => '^/dev/[a-zA-Z0-9\/]+$',
+ pattern => '^/dev/[a-zA-Z0-9._:/-]+$',
},
},
},
@@ -333,18 +333,39 @@ __PACKAGE__->register_method({
my $expected = PVE::Diskmanage::block_device_reference($reference);
my $disk = $expected->{device};
- my $mounted = PVE::Diskmanage::is_mounted($disk);
- die "disk/partition '${mounted}' is mounted\n" if $mounted;
-
- my $held = PVE::Diskmanage::has_holder($disk);
- die "disk/partition '${held}' has a holder\n" if $held;
+ my $users = PVE::Diskmanage::block_device_users(
+ [basename($disk)],
+ { 'partition-maps' => 1, 'metadata-only' => 1 },
+ );
+ die "cannot wipe '$disk' - " . join(', ', $users->@*) . "\n" if $users->@*;
my $rpcenv = PVE::RPCEnvironment::get();
my $authuser = $rpcenv->get_user();
+ # A SAN LUN may be another storage's, which is checked against the cluster-wide storage
+ # configuration under its lock. A local disk is not, and its wipe must work without quorum.
+ my $is_san = sub {
+ my ($dev) = @_;
+ return PVE::Diskmanage::is_san_device($dev)
+ || PVE::Diskmanage::is_multipath_device($dev);
+ };
+ my $san = $is_san->($disk);
+
my $worker = sub {
PVE::Diskmanage::locked_disk_action(sub {
- PVE::Diskmanage::wipe_blockdev_checked($reference, $expected);
+ my $locked = $san ? \&PVE::Storage::lock_storage_config : sub { $_[0]->() };
+ $locked->(sub {
+ my $cfg = $san ? PVE::Storage::config() : undef;
+ my $check_storage = $san
+ ? sub {
+ my ($disk, $partitions) = @_;
+ PVE::Storage::assert_san_write_safe($cfg, $disk, $partitions);
+ }
+ : undef;
+ PVE::Diskmanage::wipe_blockdev_checked(
+ $reference, $expected, $check_storage,
+ );
+ });
});
};
diff --git a/src/PVE/API2/Disks/LVM.pm b/src/PVE/API2/Disks/LVM.pm
index e2cc8118..6129df56 100644
--- a/src/PVE/API2/Disks/LVM.pm
+++ b/src/PVE/API2/Disks/LVM.pm
@@ -160,6 +160,7 @@ __PACKAGE__->register_method({
|| PVE::Diskmanage::is_san_device($device);
};
my $san = $is_san->($dev);
+ PVE::Storage::LVMPlugin::assert_whole_lun($dev) if $san;
my $expected = $san ? PVE::Diskmanage::block_device_reference($reference) : undef;
$dev = $expected->{device} if $san;
@@ -189,6 +190,7 @@ __PACKAGE__->register_method({
my $create = sub {
if ($san) {
$dev = PVE::Diskmanage::verify_blockdev_path($reference);
+ PVE::Storage::LVMPlugin::assert_whole_lun($dev);
$dev = PVE::Diskmanage::block_device_reference($reference, $expected)
->{device};
}
@@ -208,6 +210,11 @@ __PACKAGE__->register_method({
san => $san,
expected => $expected,
};
+ if ($san) {
+ my $cfg = PVE::Storage::config();
+ $guard->{check_storage} =
+ sub { PVE::Storage::assert_san_write_safe($cfg, $_[0]) };
+ }
PVE::Storage::LVMPlugin::lvm_create_volume_group(
$guard->{reference},
$name,
diff --git a/src/PVE/API2/Storage/Scan.pm b/src/PVE/API2/Storage/Scan.pm
index f6263150..e7f6eba8 100644
--- a/src/PVE/API2/Storage/Scan.pm
+++ b/src/PVE/API2/Storage/Scan.pm
@@ -513,6 +513,30 @@ __PACKAGE__->register_method({
type => 'string',
optional => 1,
},
+ 'in-use' => {
+ description =>
+ "Local usage indicated by mounts and devices using this device,"
+ . " including its partitions and kpartx partition maps for the same LUN."
+ . " 'no' does not rule out open file descriptors, swap, or other uses"
+ . " checked before wiping. 'unknown' means the metadata check failed.",
+ type => 'string',
+ enum => ['yes', 'no', 'unknown'],
+ },
+ 'in-use-by' => {
+ description =>
+ "Local devices and mounts using this device, or why its usage"
+ . " could not be checked. Device mapper devices are identified by their"
+ . " map name when available.",
+ type => 'string',
+ },
+ 'by-id' => {
+ description =>
+ "A path under /dev/disk/by-id that encodes the device's identity"
+ . " and has been verified to resolve to this device. Absent when no such"
+ . " link could be verified.",
+ type => 'string',
+ optional => 1,
+ },
'duplicate-pv' => {
description =>
"Another listed LUN has the same LVM physical volume UUID, as"
diff --git a/src/PVE/Diskmanage.pm b/src/PVE/Diskmanage.pm
index d0e1dd0d..796d4eb4 100644
--- a/src/PVE/Diskmanage.pm
+++ b/src/PVE/Diskmanage.pm
@@ -70,6 +70,23 @@ sub block_device_number {
return PVE::Tools::dev_t_major($st[6]) . ':' . PVE::Tools::dev_t_minor($st[6]);
}
+# Canonical udev names that encode the kernel's LUN identity, unlike model/serial aliases.
+# Partition names carry the identity of the containing LUN as well as their partition number.
+sub block_identity_from_id {
+ my ($name) = @_;
+ if ($name =~ m/^dm-uuid-(?:part([1-9]\d*)-)?mpath-([a-zA-Z0-9_.:+-]+)$/) {
+ return { key => "scsi:$2", partition => $1 // '' };
+ }
+ if (
+ $name =~ m/^nvme-((?:eui\.(?:[0-9a-f]{16}|[0-9a-f]{32})
+ |uuid\.[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}
+ |nvme\.[0-9a-f]{4}-[0-9a-f]+-[0-9a-f]+-[0-9a-f]{8}))(?:-part([1-9]\d*))?$/x
+ ) {
+ return { key => "nvme:$1", partition => $2 // '' };
+ }
+ return undef;
+}
+
# The sysfs inode distinguishes device instances even when the kernel reuses a name and dev_t.
sub block_device_stamp {
my ($device, $sys) = @_;
@@ -82,15 +99,64 @@ sub block_device_stamp {
return "$ino:$number";
}
-# Retain the device instance before queueing a worker; kernel names can be reused while it waits.
+# Retain both the original reference and the identity it denotes before queueing a worker. Only
+# identities established from kernel metadata may survive renumbering while the worker waits.
sub block_device_reference {
my ($reference, $expected, $sys) = @_;
$sys //= '/sys';
my $device = verify_blockdev_path($reference);
my $stamp = block_device_stamp($device, $sys);
+ my $whole = is_partition($device) ? get_blockdev($device) : $device;
+ my $name = basename($whole);
+ my $dir = "$sys/class/block/$name";
+ my $partition =
+ $whole ne $device
+ ? file_read_firstline("$sys/class/block/" . basename($device) . '/partition')
+ : '';
+ my ($identity, $dm_uuid);
+
+ if ($name =~ m/^dm-\d+$/) {
+ my $uuid = file_read_firstline("$dir/dm/uuid")
+ // die "cannot use '$reference' - missing device mapper identity\n";
+ # passed on to dmsetup, the daemons run with taint checks
+ ($dm_uuid) = $uuid =~ m/^([\w.:+-]+)$/
+ or die "unable to identify '$device' - unexpected device mapper identity\n";
+ $identity = block_identity_from_id("dm-uuid-$uuid");
+ $identity //= { key => "dm:$uuid", partition => '' };
+ } elsif ($name =~ m/^nvme\d+n\d+$/) {
+ my $wwid = file_read_firstline("$dir/wwid")
+ // die "cannot use '$reference' - missing namespace identity\n";
+ $identity = { key => "nvme:$wwid", partition => $partition };
+ } elsif ($name =~ m/^sd[a-z]+$/) {
+ require PVE::Multipath::Identity;
+ my $ids = PVE::Multipath::Identity::collect(all => 1);
+ my $wwid = PVE::Multipath::Identity::path_wwid($ids, $name);
+ $identity = { key => "scsi:$wwid", partition => $partition } if defined($wwid);
+ }
+ $identity //= { key => "instance:$stamp", partition => $partition };
+ if ($reference =~ m{^/dev/disk/by-id/([^/]+)$}) {
+ my $id = $1;
+ my $encoded = block_identity_from_id($id);
+ if (!$encoded && $id =~ m/^scsi-(.+?)(?:-part([1-9]\d*))?$/) {
+ $encoded = { key => "scsi:$1", partition => $2 // '' };
+ } elsif (!$encoded && $id =~ m/^wwn-0x([0-9a-f]+)(?:-part([1-9]\d*))?$/) {
+ my ($wwn, $part) = ($1, $2 // '');
+ die "cannot use '$reference' - device identity does not match its by-id name\n"
+ if $identity->{key} !~ m/^scsi:[23]\Q$wwn\E$/;
+ $encoded = { key => $identity->{key}, partition => $part };
+ }
+ die "cannot use '$reference' - device identity does not match its by-id name\n"
+ if $encoded
+ && ($encoded->{key} ne $identity->{key}
+ || $encoded->{partition} ne $identity->{partition});
+ }
die "cannot use '$reference' - device identity changed\n"
- if $expected && $expected->{stamp} ne $stamp;
- return { device => $device, stamp => $stamp };
+ if $expected
+ && ($expected->{key} ne $identity->{key}
+ || $expected->{partition} ne $identity->{partition});
+ die "cannot use '$reference' - device changed while identifying it\n"
+ if block_device_stamp($device, $sys) ne $stamp;
+ return { %$identity, device => $device, stamp => $stamp, dm_uuid => $dm_uuid };
}
sub assert_block_device_instance {
@@ -102,6 +168,107 @@ sub assert_block_device_instance {
return;
}
+# A scan must not invent a stable name from a friendly mapper alias or an opaque serial string.
+# Return a canonical identity-bearing link only while it resolves to the device being reported.
+sub canonical_blockdev_link {
+ my ($device, $ids, $expected_wwid, $sys) = @_;
+ $sys //= '/sys';
+ return eval {
+ $device = verify_blockdev_path($device);
+ my $stamp = block_device_stamp($device, $sys);
+ my $whole = is_partition($device) ? get_blockdev($device) : $device;
+ my $name = basename($whole);
+ my $suffix = '';
+ if ($whole ne $device) {
+ my $part =
+ file_read_firstline("$sys/class/block/" . basename($device) . '/partition');
+ die "invalid partition number\n" if !defined($part) || $part !~ m/^[1-9]\d*$/;
+ $suffix = "-part$part";
+ }
+ my @links;
+ if ($name =~ m/^dm-\d+$/) {
+ my $uuid = file_read_firstline("$sys/class/block/$name/dm/uuid") // '';
+ if ($uuid =~ m/^(?:part[1-9]\d*-)?mpath-([a-zA-Z0-9_.:+-]+)$/) {
+ die "map identity changed\n" if defined($expected_wwid) && $1 ne $expected_wwid;
+ my $id = "dm-uuid-$uuid";
+ $id = "dm-uuid-part$1-$uuid" if $suffix =~ m/^-part([1-9]\d*)$/;
+ push @links, $id if block_identity_from_id($id);
+ }
+ } elsif ($name =~ m/^nvme\d+n\d+$/) {
+ my $wwid = file_read_firstline("$sys/class/block/$name/wwid") // '';
+ push @links, "nvme-$wwid$suffix" if block_identity_from_id("nvme-$wwid$suffix");
+ } elsif ($name =~ m/^sd[a-z]+$/) {
+ require PVE::Multipath::Identity;
+ $ids //= PVE::Multipath::Identity::collect(all => 1);
+ die "cannot inspect SAN identities\n" if $ids->{error};
+ my $wwid = PVE::Multipath::Identity::path_wwid($ids, $name);
+ if (defined($wwid) && $wwid =~ m/^[a-zA-Z0-9_.:+-]+$/) {
+ die "path identity changed\n"
+ if defined($expected_wwid) && $wwid ne $expected_wwid;
+ push @links, "scsi-$wwid$suffix";
+ push @links, "wwn-0x$1$suffix" if $wwid =~ m/^[23]([0-9a-f]+)$/;
+ }
+ }
+ my $link;
+ for my $id (@links) {
+ my ($path) = "/dev/disk/by-id/$id" =~ m{\A(/dev/disk/by-id/[a-zA-Z0-9_.:+-]+)\z};
+ next if !defined($path);
+ next if (eval { verify_blockdev_path($path) } // '') ne $device;
+ $link = $path;
+ last;
+ }
+ die "device changed\n" if block_device_stamp($device, $sys) ne $stamp;
+ $link;
+ };
+}
+
+# This is a metadata-only hint, not a certificate that the full destructive-operation checks pass.
+# With 'map-wwid', the device is the multipath map of that WWID and the users of its current paths
+# count as well, for example a logical volume that LVM activated on a path before the map existed.
+# A user found stays a user if a later check fails.
+sub block_device_usage_hint {
+ my ($device, $options) = @_;
+ my %options = (%{ $options // {} }, 'partition-maps' => 1, 'metadata-only' => 1);
+ my $wwid = delete $options{'map-wwid'};
+ my (@users, $error);
+ my $check = sub {
+ my ($code) = @_;
+ eval { $code->() };
+ chomp($error //= $@) if $@;
+ };
+ my $name;
+ $check->(sub {
+ $name = basename(verify_blockdev_path($device));
+ push @users, block_device_users([$name], \%options)->@*;
+ });
+ if (defined($wwid) && defined($name)) {
+ my $dir = ($options{sysfs} // '/sys') . "/class/block/$name";
+ my $topology = sub {
+ my $uuid = file_read_firstline("$dir/dm/uuid") // '';
+ die "'$name' is not the multipath map of '$wwid'\n" if $uuid ne "mpath-$wwid";
+ opendir(my $dh, "$dir/slaves") or die "unable to list '$dir/slaves' - $!\n";
+ my @paths = sort grep { $_ ne '.' && $_ ne '..' } readdir($dh);
+ closedir($dh);
+ return \@paths;
+ };
+ my %path_options = (
+ %options, 'ignore-holders' => { %{ $options{'ignore-holders'} // {} }, $name => 1 },
+ );
+ $check->(sub {
+ my $paths = $topology->();
+ # one path at a time, so that a failed check keeps the users of the others
+ for my $path ($paths->@*) {
+ $check->(sub { push @users, block_device_users([$path], \%path_options)->@* });
+ }
+ die "the paths of '$name' changed during the check\n"
+ if join(' ', $topology->()->@*) ne join(' ', $paths->@*);
+ });
+ }
+ return { 'in-use' => 'yes', 'in-use-by' => join(', ', @users) } if @users;
+ return { 'in-use' => 'unknown', 'in-use-by' => "check failed: $error" } if defined($error);
+ return { 'in-use' => 'no', 'in-use-by' => '' };
+}
+
# Retain the checked device instance even if its kernel name or udev alias is reused.
sub open_block_device {
my ($device, $stamp) = @_;
@@ -122,8 +289,9 @@ my sub block_entries {
return [map { m/^([\w.:+-]+)$/ ? $1 : die "unexpected entry '$_' in '$dir'\n" } @names];
}
+# Only exact same-LUN kpartx UUIDs make a holder a partition, not its name or its table type.
sub block_device_partitions {
- my ($name, $sys) = @_;
+ my ($name, $sys, $partition_maps) = @_;
$sys //= '/sys';
my $dir = "$sys/class/block/$name";
my @parts;
@@ -134,10 +302,22 @@ sub block_device_partitions {
if !defined($number) || $number !~ m/^[1-9]\d*$/;
push @parts, $part;
}
+ if ($partition_maps && $name =~ m/^dm-\d+$/) {
+ my $uuid = file_read_firstline("$dir/dm/uuid")
+ // die "unable to identify '$name' - missing device mapper identity\n";
+ if (my ($wwid) = $uuid =~ m/^(?:part[1-9]\d*-)?mpath-(\S+)$/) {
+ for my $holder (block_entries("$dir/holders")->@*) {
+ next if $holder !~ m/^dm-\d+$/;
+ my $child = file_read_firstline("$sys/class/block/$holder/dm/uuid")
+ // die "unable to identify holder '$holder'\n";
+ push @parts, $holder if $child =~ m/^part[1-9]\d*-mpath-\Q$wwid\E$/;
+ }
+ }
+ }
return \@parts;
}
-# Postorder keeps child partitions accessible until their signatures have been erased.
+# Postorder keeps nested partition maps accessible until their own signatures have been erased.
sub wipe_partitions {
my ($device, $sys) = @_;
$sys //= '/sys';
@@ -146,7 +326,7 @@ sub wipe_partitions {
$visit = sub {
my ($name) = @_;
die "cannot inspect '$device' - cyclic partition topology\n" if $seen{$name}++;
- for my $part (block_device_partitions($name, $sys)->@*) {
+ for my $part (block_device_partitions($name, $sys, 1)->@*) {
$visit->($part);
push @parts, $part;
}
@@ -156,6 +336,116 @@ sub wipe_partitions {
return \@parts;
}
+# Readiness is checked before signature probes: even read-only I/O can stall on a queueing map.
+# A map's direct member users matter too, including same-identity paths not yet added to the map.
+sub assert_block_device_ready {
+ my ($device, $options) = @_;
+ $options //= {};
+ my $sys = $options->{sysfs} // '/sys';
+ my $whole = is_partition($device) ? get_blockdev($device) : $device;
+ my $name = basename($whole);
+ my $dir = "$sys/class/block/$name";
+ my $size = file_read_firstline("$dir/size");
+ die "cannot use '$device' - device is unavailable\n"
+ if !defined($size) || $size !~ m/^\d+$/ || !$size;
+ my $uuid = $name =~ m/^dm-\d+$/ ? file_read_firstline("$dir/dm/uuid") : undef;
+ die "cannot use '$device' - missing device mapper identity\n"
+ if $name =~ m/^dm-\d+$/ && !defined($uuid);
+
+ if (defined($uuid) && $uuid =~ m/^part[1-9]\d*-mpath-/) {
+ my $parents = block_entries("$dir/slaves");
+ die "cannot use '$device' - cannot identify containing map\n" if @$parents != 1;
+ return assert_block_device_ready("/dev/$parents->[0]", $options);
+ }
+ if ($name =~ m/^nvme\d+n\d+$/) {
+ my $status = get_nvme_path_status()->{$name};
+ my $state = file_read_firstline("$dir/device/state") // '';
+ die "cannot use '$device' - namespace has no usable path\n"
+ if $status ? !$status->{active} : $state ne 'live';
+ my $id = file_read_firstline("$dir/wwid")
+ // die "cannot use '$device' - missing namespace identity\n";
+ for my $other (
+ grep { /^nvme\d+n\d+$/ && $_ ne $name }
+ block_entries("$sys/class/block")->@*
+ ) {
+ my $other_id = file_read_firstline("$sys/class/block/$other/wwid")
+ // die "cannot use '$device' - unresolved namespace '$other'\n";
+ die "cannot use '$device' - namespace has multiple devices without a selected map\n"
+ if $id eq $other_id;
+ }
+ return;
+ }
+
+ my ($wwid) = defined($uuid) ? $uuid =~ m/^mpath-(\S+)$/ : ();
+ my %members;
+ if (defined($wwid)) {
+ require PVE::Multipath;
+ %members = map { $_ => 1 } block_entries("$dir/slaves")->@*;
+ my ($map) = grep { ($_->{sysfs} // '') eq $name && ($_->{wwid} // '') eq $wwid }
+ PVE::Multipath::get_maps()->@*;
+ my $usable = 0;
+ if ($map) {
+ for my $path (map { $_->{paths}->@* } $map->{'path-groups'}->@*) {
+ $usable++
+ if $members{ $path->{dev} }
+ && ($path->{'dm-state'} // '') eq 'active'
+ && ($path->{'check-state'} // '') =~ m/^(?:ready|ghost)$/;
+ }
+ }
+ die "cannot use '$device' - multipath map has no usable path\n" if !$usable;
+ } elsif (!is_san_device($whole)) {
+ return;
+ }
+
+ require PVE::Multipath::Identity;
+ my $ids = PVE::Multipath::Identity::collect(all => 1);
+ die "cannot use '$device' - cannot inspect sibling paths: $ids->{error}\n" if $ids->{error};
+ $wwid //= PVE::Multipath::Identity::path_wwid($ids, $name)
+ // die "cannot use '$device' - unresolved LUN identity\n";
+ for my $path (sort keys $ids->{paths}->%*) {
+ my $id = PVE::Multipath::Identity::path_wwid($ids, $path);
+ if (!defined($id)) {
+ next if PVE::Multipath::Identity::path_is_other_lun($ids, $path, $wwid);
+ die "cannot use '$device' - cannot exclude '$path' as another path of this LUN because"
+ . " its identity could not be verified; check the path identity and multipathd"
+ . " configuration\n";
+ }
+ next if $id ne $wwid;
+ die "cannot use '$device' - LUN has multiple paths without a selected multipath map\n"
+ if !defined($uuid) && $path ne $name;
+ $members{$path} = 1 if defined($uuid);
+ }
+ if (defined($uuid)) {
+ my %namespace_ids;
+ for my $member (grep { /^nvme/ } keys %members) {
+ my $id = file_read_firstline("$sys/class/block/$member/wwid")
+ // die "cannot use '$device' - unresolved namespace '$member'\n";
+ $namespace_ids{$id} = 1;
+ }
+ if (%namespace_ids) {
+ for my $other (grep { /^nvme\d+n\d+$/ } block_entries("$sys/class/block")->@*) {
+ my $id = file_read_firstline("$sys/class/block/$other/wwid")
+ // die "cannot use '$device' - unresolved namespace '$other'\n";
+ $members{$other} = 1 if $namespace_ids{$id};
+ }
+ }
+ my $users = block_device_users(
+ [sort keys %members],
+ {
+ %$options,
+ 'ignore-holders' => { $name => 1 },
+ 'ignore-executables' =>
+ { '/sbin/multipathd' => 1, '/usr/sbin/multipathd' => 1 },
+ },
+ );
+ die "cannot use '$device' - " . join(', ', $users->@*) . "\n" if $users->@*;
+ } else {
+ my $state = file_read_firstline("$dir/device/state") // '';
+ die "cannot use '$device' - path is not running\n" if $state ne 'running';
+ }
+ return;
+}
+
# Never read device data. Probe failures are not evidence of non-use. Excluding a holder must not
# exclude direct users; multipathd can be exempted because its checkers keep member paths open.
sub block_device_users {
@@ -183,6 +473,11 @@ sub block_device_users {
die "unable to read '$file' - missing value\n" if !defined($value);
return $value;
};
+ my $display_name = sub {
+ my ($name) = @_;
+ return $name if $name !~ m/^dm-\d+$/;
+ return file_read_firstline("$sys/class/block/$name/dm/name") || $name;
+ };
my ($numbers, $seen, $users) = ({}, {}, []);
my $visit;
$visit = sub {
@@ -192,16 +487,15 @@ sub block_device_users {
my $dir = "$sys/class/block/$name";
my $dev = $read->("$dir/dev");
die "invalid device number for '$name'\n" if $dev !~ m/^\d+:\d+$/;
- $numbers->{$dev} = $name;
- for my $part ($entries->($dir)->@*) {
- next if !-e "$dir/$part/partition";
- my $number = $read->("$dir/$part/partition");
- die "invalid partition number for '$part'\n" if $number !~ m/^[1-9]\d*$/;
- $visit->($part);
- }
+ my $display = $display_name->($name);
+ $numbers->{$dev} = $display;
+ my $parts = block_device_partitions($name, $sys, $options->{'partition-maps'});
+ my %parts = map { $_ => 1 } $parts->@*;
+ $visit->($_) for $parts->@*;
+
for my $holder ($entries->("$dir/holders")->@*) {
- next if $ignore->{$holder};
- push $users->@*, "$name held by $holder";
+ next if $ignore->{$holder} || $parts{$holder};
+ push $users->@*, "$display held by " . $display_name->($holder);
$visit->($holder);
}
};
@@ -215,9 +509,12 @@ sub block_device_users {
my (undef, undef, $dev, undef, $target) = split(/\s+/, $line);
die "unable to check mounts - malformed mountinfo\n"
if !defined($target) || $dev !~ m/^\d+:\d+$/ || $line !~ m/ - /;
+ $target =~ s/\\([0-7]{3})/chr(oct($1))/ge;
push $users->@*, "$numbers->{$dev} mounted at $target" if defined($numbers->{$dev});
}
+ return $users if $options->{'metadata-only'};
+
my $by_path = sub {
my ($path, $what) = @_;
return if $path eq '';
@@ -331,6 +628,27 @@ sub parse_wipefs_signatures {
return $probe->{signatures};
}
+sub parse_pv_report {
+ my ($json) = @_;
+
+ my $report = decode_json($json);
+ die "Malformed pvs report\n"
+ if ref($report) ne 'HASH'
+ || ref($report->{report}) ne 'ARRAY'
+ || $report->{report}->@* != 1
+ || ref($report->{report}->[0]) ne 'HASH'
+ || ref($report->{report}->[0]->{pv}) ne 'ARRAY';
+ for my $pv ($report->{report}->[0]->{pv}->@*) {
+ die "Malformed PV in pvs report\n"
+ if ref($pv) ne 'HASH'
+ || grep { !defined($pv->{$_}) || ref($pv->{$_}) } qw(pv_name vg_name pv_in_use);
+ die "Invalid PV in pvs report\n"
+ if ($pv->{vg_name} ne '[unknown]' && $pv->{vg_name} !~ m/^[a-zA-Z0-9+_.-]*$/)
+ || $pv->{pv_in_use} !~ m/^(?:0|1|unknown|)$/;
+ }
+ return $report->{report}->[0]->{pv};
+}
+
# Read cached metadata only; never probe the device.
sub udev_properties {
my ($dev) = @_;
@@ -774,6 +1092,15 @@ sub dir_is_empty {
return 1;
}
+# Some controllers pad the NQN or derive it from padded serial/model fields; trim trailing space.
+sub read_subsysnqn {
+ my ($path) = @_;
+
+ my $nqn = file_read_firstline($path) // return undef;
+ $nqn =~ s/\s+$//;
+ return $nqn;
+}
+
# Returns the NVMe transport (pcie, fc, tcp, rdma, loop) of a namespace, either directly from
# its controller, or from any controller of its subsystem for native NVMe multipath setups.
sub get_nvme_transport {
@@ -1464,12 +1791,15 @@ sub change_parttype {
run_command(['sgdisk', "-t${partnum}:${parttype}", $blockdev], errmsg => $err);
}
-# Caller holds the disk lock through verification, wiping and the device trigger.
+# Caller holds the disk lock and, for SAN devices, the storage config lock. Without a storage
+# callback the device was classified local; a topology change must not bypass that lock.
sub wipe_blockdev_checked {
- my ($reference, $expected) = @_;
+ my ($reference, $expected, $check_storage) = @_;
my $current = block_device_reference($reference, $expected);
my $disk = $current->{device};
+ die "cannot wipe '$reference' - device topology changed\n"
+ if !$check_storage && (is_san_device($disk) || is_multipath_device($disk));
my $partitions = wipe_partitions($disk);
my $children = { map { $_ => block_device_reference("/dev/$_") } $partitions->@* };
my $verify = sub {
@@ -1481,18 +1811,17 @@ sub wipe_blockdev_checked {
die "cannot wipe '$reference' - partition topology changed\n"
if join(',', @remaining) ne join(',', $parts->@*);
for my $part (@remaining) {
- my $now = block_device_reference(
- "/dev/$part", $children->{$part},
- );
+ my $now = block_device_reference("/dev/$part", $children->{$part});
die "cannot wipe '$reference' - partition '$part' changed\n"
if $now->{stamp} ne $children->{$part}->{stamp};
}
};
+ assert_block_device_ready($disk);
$verify->();
my $handle = open_block_device($disk, $current->{stamp});
- my $users = block_device_users(
- [basename($disk)], {},
- );
+ $check_storage->($disk, $partitions) if $check_storage;
+ assert_block_device_ready($disk);
+ my $users = block_device_users([basename($disk)], { 'partition-maps' => 1 });
die "cannot wipe '$disk' - " . join(', ', $users->@*) . "\n" if $users->@*;
$verify->();
wipe_blockdev(
@@ -1519,7 +1848,7 @@ sub wipe_blockdev {
my $current = wipe_partitions($devpath);
die "cannot wipe '$devpath' - partition topology changed\n"
if join(',', $current->@*) ne join(',', $partitions->@*);
- my $users = block_device_users([basename($devpath)], {});
+ my $users = block_device_users([basename($devpath)], { 'partition-maps' => 1 });
die "cannot wipe '$devpath' - " . join(', ', $users->@*) . "\n" if $users->@*;
for my $part ($partitions->@*) {
$verify->();
@@ -1528,8 +1857,17 @@ sub wipe_blockdev {
my $path = $handle ? "/proc/$$/fd/" . fileno($handle) : "/dev/$part";
run_command(['wipefs', '--all', $path], errmsg => "error wiping '/dev/$part'");
close($handle) or die "error closing '/dev/$part' - $!\n" if $handle;
+ next if $part !~ m/^dm-\d+$/;
+ $verify->();
+ my @selector = $child ? ('--uuid', $child->{dm_uuid}) : ("/dev/$part");
+ # udev probes the wiped partition map right away and keeps it open meanwhile
+ run_command(
+ ['dmsetup', 'remove', '--retry', @selector],
+ errmsg => "error removing '/dev/$part'",
+ );
+ $removed->{$part} = 1;
}
- # New holders make the parent unsafe even after its child signatures have been erased.
+ # Recreated partition maps, new holders and new openers all make the parent unsafe.
$users = block_device_users([basename($devpath)], {});
die "cannot wipe '$devpath' - " . join(', ', $users->@*) . "\n" if $users->@*;
}
@@ -1591,7 +1929,7 @@ sub udevadm_trigger {
return if scalar(@devs) == 0;
- eval { run_command(['udevadm', 'trigger', @devs]); };
+ eval { run_command(['udevadm', 'trigger', '--settle', @devs]); };
warn $@ if $@;
}
diff --git a/src/PVE/Multipath/Identity.pm b/src/PVE/Multipath/Identity.pm
index 5fa6542d..ed02373e 100644
--- a/src/PVE/Multipath/Identity.pm
+++ b/src/PVE/Multipath/Identity.pm
@@ -81,7 +81,7 @@ sub resolve($disks, $daemon, $naa_ok) {
my $unresolved = !$daemon;
for my $name ($lun->{paths}->@*) {
my $disk = $disks->{$name};
- $held->{ $disk->{map} } = 1 if defined($disk->{map});
+ $held->{$_} = 1 for ($disk->{maps} // [$disk->{map} // ()])->@*;
my $line = $daemon ? $daemon->{$name} : undef;
if (line_identifies($disk, $line, $naa_ok)) {
$listed->{ $line->{wwid} } = 1;
@@ -178,13 +178,21 @@ my sub scsi_disks($sessions, $targets, $all) {
my $devt = sysfs_line("$dir/block/$name/dev") // return;
my $disk = { lun => int($lun), devt => $devt, hctl => $hctl, dir => $dir };
$disk->{target} = $target if defined($target);
- # Read the holder through the SCSI device, so neither name can refer to another device
- # meanwhile.
- my (undef, $holder) = dir_glob_regex("$SYSFS/$dir/block/$name/holders", '(dm-\d+)');
- if (defined($holder)) {
- my $uuid = sysfs_line("$dir/block/$name/holders/$holder/dm/uuid") // '';
- ($disk->{map}) = $uuid =~ m/^mpath-(\S+)$/;
- }
+ # Read the holders through the SCSI device, so neither name can refer to another device
+ # meanwhile. Check every holder, as a logical volume can hold a path next to its map.
+ my %maps;
+ dir_glob_foreach(
+ "$SYSFS/$dir/block/$name/holders",
+ 'dm-\d+',
+ sub($holder, @) {
+ my $uuid = sysfs_line("$dir/block/$name/holders/$holder/dm/uuid") // '';
+ $maps{$1} = 1 if $uuid =~ m/^mpath-(\S+)$/;
+ },
+ );
+ my @maps = sort keys %maps;
+ $disk->{map} = $maps[0] if @maps;
+ # several maps on one path leave its LUN unresolved
+ $disk->{maps} = \@maps if @maps > 1;
$res->{$name} = $disk;
},
);
@@ -237,10 +245,12 @@ sub collect(%param) {
for my $lun (values %$luns) {
for my $name ($lun->{paths}->@*) {
my $disk = $disks->{$name};
+ # claimed: a map or the daemon names an identity, even one that did not resolve
$paths->{$name} = {
$disk->%{qw(devt hctl)},
wwid => $lun->{wwid},
$lun->{unresolved} ? (unresolved => 1) : (),
+ defined($disk->{map}) || ($daemon && $daemon->{$name}) ? (claimed => 1) : (),
};
}
}
@@ -296,4 +306,97 @@ sub path_wwid($ids, $name) {
return $path->{wwid};
}
+my sub valid_naa($value) {
+ my $naa = length($value) ? ord($value) >> 4 : 0;
+ return length($value) == 16 ? $naa == 6 : length($value) == 8 && grep { $naa == $_ } 2, 3, 5;
+}
+
+# The VPD page 0x83 of the path $name of $ids, if the name denotes the collected device before and
+# after reading it.
+my sub current_page($ids, $name) {
+ my $path = $ids->{paths}->{$name} // return undef;
+ my $current = sub {
+ my $devt = sysfs_line("class/block/$name/dev");
+ my $device = abs_path("$SYSFS/class/block/$name/device");
+ return
+ defined($devt)
+ && defined($device)
+ && $devt eq $path->{devt}
+ && basename($device) eq $path->{hctl};
+ };
+ return undef if !$current->();
+ my $page = eval { file_get_contents("$SYSFS/class/block/$name/device/vpd_pg83") };
+ return undef if !$current->();
+ return $page;
+}
+
+# Return the binary NAA designators of the logical unit in VPD page 0x83, in hex, and the number of
+# its other designators. Return undef for a malformed page, and if any other logical unit designator
+# is malformed or of a kind that multipathd might turn into an NAA WWID ('3...'), for example a SCSI
+# name string 'naa.<hex>'.
+my sub unit_designators($page) {
+ my $designators = vpd_designators($page) // return undef;
+ my ($naa, $other) = ([], 0);
+ for my $designator ($designators->@*) {
+ my ($set, $association, $type, $value) = $designator->@*;
+ next if $association != 0; # target port and target device designators
+ if ($type == 3) {
+ return undef if $set != 1 || !valid_naa($value);
+ push $naa->@*, unpack('H*', $value);
+ next;
+ }
+ my $length = length($value);
+ # printable ASCII with at least one character, padded with spaces or NUL bytes
+ my $ascii = $value =~ m/\A[\x20-\x7e]*[\x21-\x7e][\x20-\x7e]*\0*\z/;
+ if ($type == 0) { # vendor specific
+ return undef if $set == 1 ? !$length : $set != 2 || !$ascii;
+ } elsif ($type == 1) { # T10 vendor identification
+ return undef if $set != 2 || $length < 8 || !$ascii;
+ } elsif ($type == 2) { # EUI-64 based
+ return undef if $set != 1 || ($length != 8 && $length != 12 && $length != 16);
+ } elsif ($type == 8) { # SCSI name string, only the ASCII forms of iSCSI and EUI names
+ my $name = $value =~ s/\0+\z//r;
+ return undef
+ if $set != 3
+ || ($name !~ m/\Aiqn\.[0-9]{4}-[0-9]{2}\.[a-zA-Z0-9.:_-]+\z/
+ && $name !~ m/\Aeui\.[0-9a-fA-F]{16}(?:[0-9a-fA-F]{8}){0,2}\z/);
+ } else {
+ return undef;
+ }
+ $other++;
+ }
+ return { naa => $naa, other => $other };
+}
+
+# Whether the path $name of $ids, which has no resolved identity, is not a path of the LUN with
+# the NAA WWID $wwid. Only a path that neither a map nor multipathd names, for example a local disk
+# that multipathd does not list, can qualify: an identity from the configured source that did not
+# resolve may still be this LUN. Its VPD page 0x83 must name the logical unit only with designators
+# that multipathd cannot turn into $wwid, and a current path of the LUN must have $wwid as a binary
+# NAA designator, as other sources, like a SCSI name string or a configured udev property, can
+# yield the same spelling. The kernel caches the page when it scans the device, as multipathd
+# caches its identity.
+sub path_is_other_lun($ids, $name, $wwid) {
+ my ($hex) = $wwid =~ m/^3((?:[0-9a-fA-F]{16}){1,2})$/ or return 0;
+ $hex = lc($hex);
+ my $path = $ids->{paths}->{$name} // return 0;
+ return 0 if $path->{claimed};
+ my $unit = unit_designators(current_page($ids, $name)) // return 0;
+ return 0 if !$unit->{other} && !$unit->{naa}->@*;
+ return 0 if grep { $_ eq $hex } $unit->{naa}->@*;
+ for my $member (sort keys $ids->{paths}->%*) {
+ next if (path_wwid($ids, $member) // '') ne $wwid;
+ my $designators = vpd_designators(current_page($ids, $member)) // next;
+ return 1 if grep {
+ my ($set, $association, $type, $value) = $_->@*;
+ $set == 1
+ && $association == 0
+ && $type == 3
+ && valid_naa($value)
+ && unpack('H*', $value) eq $hex
+ } $designators->@*;
+ }
+ return 0;
+}
+
1;
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index 8cbe9308..cb7a62f9 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -329,6 +329,225 @@ sub derived_multipath_wwids {
return $derived;
}
+# Compare whole LUN identities, not aliases or the spelling of a configured base volume. A
+# partition belongs to its containing LUN for storage-reference checks.
+sub san_device_identity {
+ my ($device, $ids, $sysfs, $allow_member) = @_;
+ $sysfs //= '/sys';
+
+ $device = PVE::Diskmanage::verify_blockdev_path($device);
+ $device = PVE::Diskmanage::get_blockdev($device) if PVE::Diskmanage::is_partition($device);
+ my $name = basename($device);
+ my $dir = "$sysfs/class/block/$name";
+ my $number = file_read_firstline("$dir/dev");
+ die "unable to identify '$device' - missing device number\n"
+ if !defined($number) || $number !~ m/^\d+:\d+$/;
+ opendir(my $dh, "$dir/holders") or die "unable to inspect '$device' - $!\n";
+ my @holders = grep { $_ ne '.' && $_ ne '..' } readdir($dh);
+ closedir($dh);
+ my $wwid;
+
+ for my $holder (@holders) {
+ next if $holder !~ m/^dm-\d+$/;
+ my $uuid = file_read_firstline("$sysfs/class/block/$holder/dm/uuid");
+ die "unable to identify holder '$holder'\n" if !defined($uuid);
+ if ($uuid =~ m/^mpath-(\S+)$/) {
+ die "cannot use '$device' - member path of multipath map '$holder'\n"
+ if !$allow_member;
+ $wwid = $1;
+ }
+ }
+
+ my $res = { key => "local:$number", targets => {} };
+ if ($name =~ m/^dm-\d+$/) {
+ my $uuid = file_read_firstline("$dir/dm/uuid")
+ // die "unable to identify '$device' - missing device mapper identity\n";
+ ($wwid) = $uuid =~ m/^(?:part\d+-)?mpath-(\S+)$/;
+ } elsif ($name =~ m/^nvme\d+n\d+$/) {
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$dir/device/subsysnqn")
+ // die "unable to identify '$device' - missing subsystem\n";
+ my $id = file_read_firstline("$dir/wwid")
+ // die "unable to identify '$device' - missing namespace identity\n";
+ die "unable to identify '$device' - empty namespace identity\n" if !$id;
+ $res->{key} = "nvme:$id";
+ $res->{subsystem} = $nqn;
+ } elsif (PVE::Diskmanage::is_san_device($device)) {
+ $ids = $ids->() if ref($ids) eq 'CODE';
+ $wwid = PVE::Multipath::Identity::path_wwid($ids, $name)
+ // die "unable to identify '$device' - unresolved LUN identity\n";
+ }
+ if (defined($wwid)) {
+ $ids = $ids->() if ref($ids) eq 'CODE';
+ $res->{key} = "scsi:$wwid";
+ my $observed = 0;
+ for my $lun (values $ids->{luns}->%*) {
+ $observed = 1 if ($lun->{wwid} // '') eq $wwid;
+ next if !defined($lun->{target});
+ if (!defined($lun->{wwid})) {
+ my @paths = sort(($lun->{paths} // [])->@*);
+ next
+ if @paths
+ && !grep { !PVE::Multipath::Identity::path_is_other_lun($ids, $_, $wwid) }
+ @paths;
+ die "unable to inspect target '$lun->{target}' - the identity of '"
+ . join(', ', @paths)
+ . "' could not be verified; check the path identity and multipathd"
+ . " configuration\n";
+ }
+ $res->{targets}->{ $lun->{target} } = 1 if $lun->{wwid} eq $wwid;
+ }
+ die "unable to inspect '$device' - no identified member paths\n" if !$observed;
+ }
+ return $res;
+}
+
+my sub normalized_pv_uuid {
+ my ($uuid) = @_;
+ die "unable to inspect physical volume - invalid PV UUID\n"
+ if !defined($uuid)
+ || ref($uuid)
+ || $uuid !~ m/^(?:[a-zA-Z0-9]{32}|[a-zA-Z0-9]{6}(?:-[a-zA-Z0-9]{4}){5}-[a-zA-Z0-9]{6})$/;
+ $uuid =~ s/-//g;
+ return $uuid;
+}
+
+# Called under the storage configuration lock before writing a SAN device. Scan attribution is
+# intentionally not used: it selects only one owner and can be stale.
+sub assert_san_write_safe {
+ my ($cfg, $device, $partitions) = @_;
+ $partitions //= PVE::Diskmanage::wipe_partitions($device);
+ PVE::Diskmanage::assert_block_device_ready($device);
+
+ my $collected;
+ my $ids = sub {
+ return $collected if $collected;
+ my $result = PVE::Multipath::Identity::collect(all => 1);
+ die "unable to inspect SAN identities - $result->{error}\n" if $result->{error};
+ if (-d "$PVE::Storage::ISCSIPlugin::SYSFS/class/iscsi_session") {
+ my $sessions = PVE::Storage::ISCSIPlugin::iscsi_session_device_map(1);
+ # san_device_identity() decides about devices without an identity
+ for my $name (keys %$sessions) {
+ $result->{luns}->{"$name\0strict"} = {
+ wwid => PVE::Multipath::Identity::path_wwid($result, $name),
+ target => $sessions->{$name}->{target},
+ paths => [$name],
+ };
+ }
+ }
+ return $collected = $result;
+ };
+ my $identity = san_device_identity($device, $ids);
+ for my $sid (sort keys $cfg->{ids}->%*) {
+ my $scfg = $cfg->{ids}->{$sid};
+ if (
+ $scfg->{content}->{images} || $scfg->{type} eq 'iscsidirect' || $scfg->{type} eq 'zfs'
+ ) {
+ die "cannot use '$device' - storage '$sid' serves disk images from this target\n"
+ if $scfg->{target} && $identity->{targets}->{ $scfg->{target} };
+ die "cannot use '$device' - storage '$sid' serves disk images from this subsystem\n"
+ if $scfg->{subsysnqn} && ($identity->{subsystem} // '') eq $scfg->{subsysnqn};
+ }
+ next if $scfg->{type} ne 'lvm' || !$scfg->{base};
+ my $base = eval {
+ my ($base_sid) = parse_volume_id($scfg->{base});
+ my (undef, $name) = parse_volname($cfg, $scfg->{base});
+ my $type = $cfg->{ids}->{$base_sid}->{type};
+ my $canonical =
+ $type eq 'iscsi' ? PVE::Diskmanage::block_identity_from_id($name) : undef;
+ $canonical
+ // san_device_identity(scalar(path($cfg, $scfg->{base})), $ids, undef, 1);
+ };
+ if (!$base) {
+ my $err = $@ // '';
+ chomp($err);
+ die "cannot use '$device' - cannot check storage '$sid', its base volume"
+ . " '$scfg->{base}' is not visible on this node\n"
+ if $err =~ m/not a valid block device|failed to get absolute path/ || !$err;
+ die "cannot use '$device' - cannot check base volume '$scfg->{base}' of storage '$sid'"
+ . " - $err\n";
+ }
+ die "cannot use '$device' - storage '$sid' uses this LUN as its base volume\n"
+ if $base->{key} eq $identity->{key};
+ }
+
+ # LVM can select a clone instead of the candidate when both have the same PV UUID. Probe
+ # every device being destroyed directly rather than relying on that selected device list.
+ my %candidate_pvs;
+ for my $candidate ($device, map { "/dev/$_" } $partitions->@*) {
+ my $output = '';
+ run_command(
+ ['wipefs', '--no-act', '--json', '--output', 'TYPE,UUID', $candidate],
+ timeout => 10,
+ outfunc => sub { $output .= "$_[0]\n" },
+ );
+ my $probe = eval { PVE::Diskmanage::parse_wipefs_signatures($output) };
+ if (my $err = $@) {
+ my $kind = $err eq "Malformed wipefs signature\n" ? 'signature' : 'output';
+ die "unable to probe '$candidate' - malformed wipefs $kind\n";
+ }
+ for my $signature ($probe->@*) {
+ next if $signature->{type} ne 'LVM2_member';
+ $candidate_pvs{ normalized_pv_uuid($signature->{uuid}) } = 1;
+ }
+ }
+
+ my $output = '';
+ run_command(
+ [
+ '/sbin/pvs',
+ '--nohints',
+ '--readonly',
+ '--binary',
+ '--reportformat',
+ 'json',
+ '--options',
+ 'pv_name,vg_name,pv_uuid,pv_in_use',
+ ],
+ timeout => 10,
+ outfunc => sub { $output .= "$_[0]\n" },
+ );
+ my $report = eval { PVE::Diskmanage::parse_pv_report($output) };
+ if (my $err = $@) {
+ my $kind = $err =~ m/^(?:Malformed|Invalid) PV in pvs report\n$/ ? 'PV' : 'pvs output';
+ die "unable to inspect volume groups - malformed $kind\n";
+ }
+ my %reported;
+ for my $pv ($report->@*) {
+ die "unable to inspect volume groups - malformed PV\n" if $pv->{pv_name} !~ m{^/dev/};
+ $reported{ normalized_pv_uuid($pv->{pv_uuid}) } = 1;
+ }
+ die "cannot use '$device' - LVM does not report its physical volume,"
+ . " so its volume group is unknown\n"
+ if grep { !$reported{$_} } keys %candidate_pvs;
+
+ for my $pv ($report->@*) {
+ my $uuid = normalized_pv_uuid($pv->{pv_uuid});
+ # The sentinel means missing metadata even if the use flag contradicts it. A matching UUID
+ # already proves membership; resolving an alias first could hide that proof if it vanished.
+ my $unknown_vg = $pv->{vg_name} eq '[unknown]'
+ || ($pv->{vg_name} eq '' && $pv->{pv_in_use} ne '0');
+ if ($unknown_vg) {
+ die "cannot use '$device' - physical volume belongs to a volume group"
+ . " whose metadata is not visible on this node\n"
+ if $candidate_pvs{$uuid}
+ || san_device_identity($pv->{pv_name}, $ids, undef, 1)->{key} eq $identity->{key};
+ next;
+ }
+ next if $pv->{vg_name} eq '';
+ my @storages = grep {
+ my $scfg = $cfg->{ids}->{$_};
+ ($scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin')
+ && ($scfg->{vgname} // '') eq $pv->{vg_name};
+ } sort keys $cfg->{ids}->%*;
+ next if !@storages;
+ die "cannot use '$device' - volume group '$pv->{vg_name}' is used by storage '"
+ . $storages[0] . "'\n"
+ if $candidate_pvs{$uuid}
+ || san_device_identity($pv->{pv_name}, $ids, undef, 1)->{key} eq $identity->{key};
+ }
+ return;
+}
+
# storage_can_replicate:
# return true if storage supports replication
# (volumes allocated with vdisk_alloc() has replication feature)
diff --git a/src/PVE/Storage/LVMPlugin.pm b/src/PVE/Storage/LVMPlugin.pm
index 5ba56519..0660529a 100644
--- a/src/PVE/Storage/LVMPlugin.pm
+++ b/src/PVE/Storage/LVMPlugin.pm
@@ -146,6 +146,15 @@ sub clear_first_sector {
}
}
+sub assert_whole_lun {
+ my ($device) = @_;
+
+ my $uuid = file_read_firstline('/sys/class/block/' . basename($device) . '/dm/uuid') // '';
+ die "cannot use '$device' - create the volume group on the whole LUN\n"
+ if PVE::Diskmanage::is_partition($device) || $uuid =~ m/^part[1-9]\d*-mpath-/;
+ return;
+}
+
sub lvm_create_volume_group {
my ($device, $vgname, $shared, $guard) = @_;
$guard = {%$guard} if $guard;
@@ -153,12 +162,15 @@ sub lvm_create_volume_group {
my $requested_device = $guard ? $guard->{reference} : $device;
$device = PVE::Diskmanage::verify_blockdev_path($requested_device);
my $san = $guard && $guard->{san};
+ my $stable_device;
if ($guard) {
if ($san) {
+ assert_whole_lun($device);
my $current = $guard->{current} = PVE::Diskmanage::block_device_reference(
$requested_device, $guard->{expected},
);
$device = $current->{device};
+ PVE::Diskmanage::assert_block_device_ready($device);
$guard->{handle} = PVE::Diskmanage::open_block_device($device, $current->{stamp});
$guard->{verify} = sub {
PVE::Diskmanage::assert_block_device_instance($requested_device, $current);
@@ -174,10 +186,12 @@ sub lvm_create_volume_group {
$guard->{verify}->();
}
}
- my $check_instance = sub { $guard->{verify}->() if $guard };
+ my $check_instance = sub { $guard->{verify}->($stable_device) if $guard };
my $check_safe = sub {
$check_instance->();
if ($san) {
+ $guard->{check_storage}->($device);
+ PVE::Diskmanage::assert_block_device_ready($device);
my $users = PVE::Diskmanage::block_device_users(
[basename($device)], { 'partition-maps' => 1 },
);
@@ -258,17 +272,21 @@ sub lvm_create_volume_group {
delete $signatures{LVM2_member} if $res && !$res->{vgname};
$refuse_data->(keys %signatures) if %signatures;
+ if ($san) {
+ $stable_device = PVE::Diskmanage::canonical_blockdev_link($device)
+ // die "cannot use '$device' - cannot verify a stable name under /dev/disk/by-id\n";
+ }
$check_safe->();
clear_first_sector($san ? '/proc/' . $$ . '/fd/' . fileno($guard->{handle}) : $device);
# we use --metadatasize 250k, which reseults in "pe_start = 512"
# so pe_start is aligned on a 128k boundary (advantage for SSDs)
- my $cmd = ['/sbin/pvcreate', '--metadatasize', '250k', $device];
+ my $cmd = ['/sbin/pvcreate', '--metadatasize', '250k', $stable_device // $device];
$check_safe->();
run_command($cmd, errmsg => "pvcreate '$device' error");
- $cmd = ['/sbin/vgcreate', $vgname, $device];
+ $cmd = ['/sbin/vgcreate', $vgname, $stable_device // $device];
# push @$cmd, '-c', 'y' if $shared; # we do not use this yet
$check_safe->();
@@ -1107,6 +1125,8 @@ sub on_add_hook {
# for the map to assemble before the VG is created on it
PVE::Storage::activate_volumes($cfg, [$base]);
+ assert_whole_lun(PVE::Diskmanage::verify_blockdev_path($path));
+
# a failing hook does not remove a volume group it created, so check the device first
assert_device_discard_supported($path)
if discard_on_remove_requested($scfg->{'on-volume-remove'});
@@ -1120,6 +1140,7 @@ sub on_add_hook {
{
reference => $path,
san => 1,
+ check_storage => sub { PVE::Storage::assert_san_write_safe($cfg, $_[0]) },
},
);
}
diff --git a/src/PVE/Storage/SANScan.pm b/src/PVE/Storage/SANScan.pm
index 4015361b..7efdbfd5 100644
--- a/src/PVE/Storage/SANScan.pm
+++ b/src/PVE/Storage/SANScan.pm
@@ -256,6 +256,13 @@ my sub build_lun_rows($cfg, $inventory) {
$entry->{multipath} = 'unmanaged';
}
}
+ my $hint = PVE::Diskmanage::block_device_usage_hint(
+ $disk->{devpath},
+ defined($disk->{slaves}) ? { 'map-wwid' => $disk->{wwn} } : undef,
+ );
+ $entry->@{qw(in-use in-use-by)} = $hint->@{qw(in-use in-use-by)};
+ my $link = PVE::Diskmanage::canonical_blockdev_link($disk->{devpath}, $ids, $wwid);
+ $entry->{'by-id'} = $link if defined($link);
push $records->@*,
{ row => $entry, disk => $disk, identity => lun_compare_key($entry, $disk) };
};
diff --git a/src/test/Makefile b/src/test/Makefile
index 3ae2639f..49f6413c 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_lvm_base_activation test_lvm_status test_status_command test_disklist test_disk_api test_bwlimit test_plugin test_ovf test_volume_access test_multipath test_iscsi test_lun_identity test_multipath_api test_san_lun_scan test_san_api test_san_libraries test_san_taint
+test: test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_lvm_base_activation test_lvm_status test_status_command test_disklist test_wipe test_disk_api test_bwlimit test_plugin test_ovf test_volume_access test_multipath test_iscsi test_lun_identity test_multipath_api test_san_lun_scan test_san_api test_san_libraries test_san_taint
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
@@ -37,11 +37,15 @@ test_disklist: run_disk_tests.pl run_block_device_users_tests.pl
./run_disk_tests.pl
./run_block_device_users_tests.pl
-test_disk_api: run_disk_api_tests.pl run_wipedisk_tests.pl run_wipe_reference_tests.pl run_wipe_partition_tests.pl
- ./run_disk_api_tests.pl
+test_wipe: run_wipedisk_tests.pl run_wipe_partition_tests.pl run_wipe_readiness_tests.pl run_wipe_reference_tests.pl
./run_wipedisk_tests.pl
- ./run_wipe_reference_tests.pl
./run_wipe_partition_tests.pl
+ ./run_wipe_readiness_tests.pl
+ ./run_wipe_reference_tests.pl
+
+test_disk_api: run_disk_api_tests.pl run_san_wipe_tests.pl
+ ./run_disk_api_tests.pl
+ ./run_san_wipe_tests.pl
test_bwlimit: run_bwlimit_tests.pl
./run_bwlimit_tests.pl
@@ -82,5 +86,6 @@ test_san_api: run_san_api_tests.pl
test_san_libraries: run_san_library_tests.pl
./run_san_library_tests.pl
-test_san_taint: run_san_taint_tests.pl
+test_san_taint: run_san_lvm_create_tests.pl run_san_taint_tests.pl
+ perl -T ./run_san_lvm_create_tests.pl
perl -T ./run_san_taint_tests.pl
diff --git a/src/test/disk_api_test.pm b/src/test/disk_api_test.pm
index 2371a953..2d30d2e5 100644
--- a/src/test/disk_api_test.pm
+++ b/src/test/disk_api_test.pm
@@ -132,6 +132,7 @@ subtest 'a volume group on a map is created under the storage configuration lock
$disk->mock(locked_disk_action => sub { $lock->('disk', $_[0]) });
$disk->mock(verify_blockdev_path => sub { $_[0] });
$disk->mock(block_device_reference => sub { { device => $_[0] } });
+ $storage->mock(config => sub { { ids => {} } });
$disk->mock(assert_disk_unused => sub { });
$disk->mock(is_partition => sub { 0 });
$disk->mock(udevadm_trigger => sub { });
diff --git a/src/test/run_block_device_users_tests.pl b/src/test/run_block_device_users_tests.pl
index 1c040f60..b041201f 100755
--- a/src/test/run_block_device_users_tests.pl
+++ b/src/test/run_block_device_users_tests.pl
@@ -16,6 +16,7 @@ my $options = { sysfs => "$root/sys", procfs => "$root/proc" };
my $disk = Test::MockModule->new('PVE::Diskmanage');
my %numbers = ('/dev/alias' => '8:1');
$disk->mock(
+ verify_blockdev_path => sub { $_[0] },
block_device_number => sub {
my ($path) = @_;
die "stat failed\n" if !exists($numbers{$path});
@@ -53,6 +54,11 @@ device('sda1', '8:1', 'sda');
is_deeply(users(), [], 'unused disk and partition');
write_file('/proc/self/mountinfo', "1 0 8:1 / /mnt rw - ext4 /dev/alias rw\n");
is_deeply(users(), ['sda1 mounted at /mnt'], 'mounts matched by number');
+is_deeply(
+ PVE::Diskmanage::block_device_usage_hint('/dev/sda', $options),
+ { 'in-use' => 'yes', 'in-use-by' => 'sda1 mounted at /mnt' },
+ 'metadata hint includes kernel partition mounts',
+);
write_file('/proc/self/mountinfo', "1 0 0:1 / / rw - rootfs rootfs rw\n");
write_file('/proc/swaps', "Filename\tType\tSize\tUsed\tPriority\n/dev/alias partition 1 0 -2\n");
is_deeply(users(), ['sda1 used as swap'], 'swap alias');
@@ -135,6 +141,11 @@ is_deeply(
unlink("$root/sys/class/block/sda1/dev") or die $!;
eval { users() };
like($@, qr/missing value/, 'missing partition identity fails closed');
+is(
+ PVE::Diskmanage::block_device_usage_hint('/dev/sda', $options)->{'in-use'},
+ 'unknown',
+ 'missing kernel partition identity gives unknown hint',
+);
write_file('/sys/class/block/sda1/dev', "8:1\n");
remove_tree("$root/sys/class/block/sda1/holders");
eval { users() };
diff --git a/src/test/run_lun_identity_tests.pl b/src/test/run_lun_identity_tests.pl
index a49f27c4..5a5fdced 100755
--- a/src/test/run_lun_identity_tests.pl
+++ b/src/test/run_lun_identity_tests.pl
@@ -538,6 +538,200 @@ for my $case ([$Q, '3WQ', 'sdg'], [$R, '3WR', 'sdh']) {
query_path_identities => sub { $queries++; die $reply if !ref($reply); return $reply });
}
+# --- paths without an identity that are provably another LUN ---
+
+{
+ my $W = '3600a09803832355367242f747a716b7a';
+ my sub page {
+ my $body =
+ join('', map { pack('C C x C', $_->[0], $_->[1], length($_->[2])) . $_->[2] } @_);
+ return pack('C C n', 0, 0x83, length($body)) . $body;
+ }
+ my sub naa { [0x01, 0x03, pack('H*', $_[0])] }
+ # a local QEMU disk, as lab nodes have it: one vendor specific ASCII designator
+ my $qemu = pack('H*', '0083000f0200000b64726976652d7363736930');
+ disk_device('0:0:0:0', 'sda', '8:0');
+ put('bus/scsi/devices/0:0:0:0/type', "0\n");
+ # the map's path names its NAA, the other path of the same LUN is not listed by the daemon
+ put('bus/scsi/devices/7:0:0:0/vpd_pg83', $vpd);
+ $reply = {};
+ my sub other {
+ my ($name, $wwid) = @_;
+ $ids = PVE::Multipath::Identity::collect(all => 1);
+ return PVE::Multipath::Identity::path_is_other_lun($ids, $name, $wwid // $W);
+ }
+ my sub sda_page { put('bus/scsi/devices/0:0:0:0/vpd_pg83', $_[0]) }
+
+ sda_page($qemu);
+ ok(other('sda'), 'other LUN: a local disk with a vendor specific designator only');
+ is($ids->{paths}->{sda}->{wwid}, undef, 'other LUN: and without an identity of its own');
+ ok(!other('sdc'), 'other LUN: not the unlisted path of the same LUN');
+ ok(!other('sda', '3OTHER'), 'other LUN: undecided for a WWID that is not an NAA');
+ ok(!other('sda', '2600a09803832355367242f747a716b7a'), 'other LUN: undecided for EUI-64');
+ ok(!other('sda', '3600a0980383235536724'), 'other LUN: undecided for a short NAA');
+
+ sda_page(page(naa('600a09803832355367242f747a716c30')));
+ ok(other('sda'), 'other LUN: a disk with the NAA of another LUN');
+ sda_page(page(naa('600a09803832355367242f747a716c30'), naa(substr($W, 1))));
+ ok(!other('sda'), 'other LUN: not with the NAA of the LUN after another one');
+ sda_page(page([0x01, 0x13, pack('H*', '600a098000000002ac16036a00000cbc')]));
+ ok(!other('sda'), 'other LUN: undecided with target port designators only');
+ sda_page(page());
+ ok(!other('sda'), 'other LUN: undecided with no designator');
+ sda_page(page([0x02, 0x03, '600a09803832355367242f747a716c30']));
+ ok(!other('sda'), 'other LUN: undecided with an NAA designator in ASCII');
+ sda_page(page(naa('600a0980383235536724')));
+ ok(!other('sda'), 'other LUN: undecided with an NAA designator of a wrong length');
+ sda_page(page(naa('500a09803832355367242f747a716c30')));
+ ok(!other('sda'), 'other LUN: undecided with an NAA type that does not fit its length');
+ sda_page(page([0x03, 0x08, 'naa.600A09803832355367242F747A716B7A']));
+ ok(!other('sda'), 'other LUN: undecided with a SCSI name string the daemon reads as an NAA');
+ sda_page(page([0x03, 0x08, 'iqn.2003-01.org.example:disk']));
+ ok(other('sda'), 'other LUN: a SCSI name string that is no NAA');
+ sda_page(substr($qemu, 0, 10));
+ ok(!other('sda'), 'other LUN: undecided with a truncated page');
+ unlink("$sys/bus/scsi/devices/0:0:0:0/vpd_pg83");
+ ok(!other('sda'), 'other LUN: undecided without a page');
+
+ for my $case (
+ [[0x00, 0x0f, 'x'], 'a designator of a reserved type'],
+ [[0x02, 0x00, ''], 'an empty vendor specific designator'],
+ [[0x03, 0x08, 'bad'], 'a SCSI name string without a known prefix'],
+ [[0x01, 0x07, pack('H*', '00' x 16)], 'an MD5 logical unit identifier'],
+ [[0x01, 0x02, pack('H*', '0123')], 'an EUI-64 designator of a wrong length'],
+ [[0x03, 0x08, "iqn.2003-01.org.example:\xff"], 'a SCSI name string that is not ASCII'],
+ [[0x03, 0x08, 'eui.x'], 'a SCSI name string with a malformed EUI'],
+ [[0x02, 0x00, "drive\xff"], 'a vendor specific designator that is not ASCII'],
+ [[0x02, 0x01, "QEMU \xff"], 'a T10 designator that is not ASCII'],
+ [[0x02, 0x00, "drive-scsi0\n"], 'a vendor specific designator ending in a newline'],
+ [[0x02, 0x01, "QEMU X\n"], 'a T10 designator ending in a newline'],
+ [[0x03, 0x08, "iqn.2003-01.org.example:disk\n"], 'an iSCSI name ending in a newline'],
+ [[0x03, 0x08, "eui.0123456789abcdef\n"], 'an EUI name ending in a newline'],
+ ) {
+ sda_page(page($case->[0]));
+ ok(!other('sda'), "other LUN: undecided with $case->[1]");
+ }
+ sda_page(page([0x01, 0x02, pack('H*', '0123456789abcdef')]));
+ ok(other('sda'), 'other LUN: a disk with an EUI-64 designator only');
+ sda_page(page([0x03, 0x08, "eui.0123456789ABCDEF\0\0\0\0"]));
+ ok(other('sda'), 'other LUN: a disk with an EUI name string only');
+ # the daemon names it, with an identity that its page does not confirm
+ $reply = { sda => { devt => '8:0', hctl => '0:0:0:0', init => 'ok', wwid => $W } };
+ ok(
+ !other('sda'),
+ 'other LUN: undecided if the daemon names the disk with an identity that did not resolve',
+ );
+ $reply = {};
+
+ sda_page($qemu);
+ $ids = PVE::Multipath::Identity::collect(all => 1);
+ put('bus/scsi/devices/0:0:0:0/block/sda/dev', "8:99\n");
+ ok(
+ !PVE::Multipath::Identity::path_is_other_lun($ids, 'sda', $W),
+ 'other LUN: undecided once the name denotes another device',
+ );
+ put('bus/scsi/devices/0:0:0:0/block/sda/dev', "8:0\n");
+ {
+ $ids = PVE::Multipath::Identity::collect(all => 1);
+ my $module = Test::MockModule->new('PVE::Multipath::Identity');
+ my $read = \&PVE::Multipath::Identity::file_get_contents;
+ my $change = 'sda';
+ $module->mock(
+ file_get_contents => sub {
+ my $page = $read->($_[0]);
+ put("bus/scsi/devices/$1/block/$change/dev", "8:99\n")
+ if $_[0] =~ m{/$change/device/vpd_pg83$}
+ && readlink("$sys/class/block/$change") =~ m{/devices/([^/]+)/block/};
+ return $page;
+ },
+ );
+ ok(
+ !PVE::Multipath::Identity::path_is_other_lun($ids, 'sda', $W),
+ 'other LUN: undecided if the device changes while its page is read',
+ );
+ put('bus/scsi/devices/0:0:0:0/block/sda/dev', "8:0\n");
+ $change = 'sdb';
+ $ids = PVE::Multipath::Identity::collect(all => 1);
+ ok(
+ !PVE::Multipath::Identity::path_is_other_lun($ids, 'sda', $W),
+ 'other LUN: undecided if the path of the LUN changes while its page is read',
+ );
+ put('bus/scsi/devices/7:0:0:0/block/sdb/dev', "8:16\n");
+ $module->unmock('file_get_contents');
+ $ids = PVE::Multipath::Identity::collect(all => 1);
+ ok(
+ PVE::Multipath::Identity::path_is_other_lun($ids, 'sda', $W),
+ 'other LUN: and decided again with both devices unchanged',
+ );
+ put('bus/scsi/devices/7:0:0:0/block/sdb/dev', "8:99\n");
+ ok(
+ !PVE::Multipath::Identity::path_is_other_lun($ids, 'sda', $W),
+ 'other LUN: undecided once the path of the LUN changed since an earlier answer',
+ );
+ put('bus/scsi/devices/7:0:0:0/block/sdb/dev', "8:16\n");
+ }
+ {
+ # a logical volume can hold a path next to its map
+ put('devices/virtual/block/dm-20/dm/uuid', "LVM-oldvg\n");
+ symlink(
+ "$sys/devices/virtual/block/dm-20",
+ "$sys/bus/scsi/devices/0:0:0:0/block/sda/holders/dm-20",
+ ) or die "$!\n";
+ hold('0:0:0:0', 'sda', 'dm-21', $W);
+ sda_page(page([0x01, 0x02, pack('H*', '0123456789abcdef')]));
+ $ids = PVE::Multipath::Identity::collect(all => 1);
+ is(
+ PVE::Multipath::Identity::path_wwid($ids, 'sda'),
+ $W,
+ 'holders: the map of a path that a logical volume holds as well',
+ );
+ # and in the other order, as the order of the holder links is the directory's
+ unlink("$sys/bus/scsi/devices/0:0:0:0/block/sda/holders/$_") for qw(dm-20 dm-21);
+ hold('0:0:0:0', 'sda', 'dm-21', $W);
+ symlink(
+ "$sys/devices/virtual/block/dm-20",
+ "$sys/bus/scsi/devices/0:0:0:0/block/sda/holders/dm-20",
+ ) or die "$!\n";
+ $ids = PVE::Multipath::Identity::collect(all => 1);
+ is(
+ PVE::Multipath::Identity::path_wwid($ids, 'sda'),
+ $W,
+ 'holders: the map of a path that a logical volume holds as well, linked the other way',
+ );
+ hold('0:0:0:0', 'sda', 'dm-22', '3600a09803832355367242f747a716c30');
+ $ids = PVE::Multipath::Identity::collect(all => 1);
+ is(PVE::Multipath::Identity::path_wwid($ids, 'sda'), undef, 'holders: none with two maps');
+ ok(
+ $ids->{paths}->{sda}->{claimed} && $ids->{paths}->{sda}->{unresolved},
+ 'holders: but claimed and unresolved',
+ );
+ ok(
+ !PVE::Multipath::Identity::path_is_other_lun($ids, 'sda', $W),
+ 'other LUN: undecided for a path that maps hold',
+ );
+ unlink("$sys/bus/scsi/devices/0:0:0:0/block/sda/holders/$_") for qw(dm-20 dm-21 dm-22);
+ }
+ {
+ # NAA format 5 has 8 bytes, so a 16-byte one cannot stand for the WWID
+ my $W5 = '35' . substr($W, 2);
+ hold('7:0:0:1', 'sdc', 'dm-9', $W5);
+ put('bus/scsi/devices/7:0:0:1/vpd_pg83', page(naa(substr($W5, 1))));
+ ok(!other('sda', $W5), 'other LUN: undecided if the NAA of the LUN is not a valid one');
+ unlink("$sys/bus/scsi/devices/7:0:0:1/block/sdc/holders/dm-9") or die "$!\n";
+ put('bus/scsi/devices/7:0:0:1/vpd_pg83', $vpd);
+ }
+
+ # only if a path of the LUN names its NAA in binary, as a name string can give the same WWID
+ unlink("$sys/bus/scsi/devices/7:0:0:0/vpd_pg83");
+ ok(!other('sda'), 'other LUN: undecided if no path of the LUN names its NAA');
+ put('bus/scsi/devices/7:0:0:0/vpd_pg83', page([0x03, 0x08, 'naa.' . uc(substr($W, 1))]));
+ ok(!other('sda'), 'other LUN: undecided if the LUN names its NAA as a SCSI name string only');
+
+ unlink("$sys/bus/scsi/devices/7:0:0:0/vpd_pg83");
+ remove_tree("$sys/bus/scsi/devices/0:0:0:0");
+ unlink("$sys/class/block/sda");
+}
+
# --- the iSCSI plugin ---
$ids = {
@@ -660,6 +854,26 @@ is_deeply(
is_deeply($list->(), ['0.0.3.scsi-3W3'], 'plain volumes: a LUN without aliases');
is($collected, 0, 'plain volumes: needs no identities');
+ my $device = {
+ map {
+ my $name = $_;
+ map { $_ => $name } $fixture->{$name}->[2]->@*
+ } keys %$fixture
+ };
+ my $diskmanage = Test::MockModule->new('PVE::Diskmanage');
+ $diskmanage->mock(
+ verify_blockdev_path => sub { '/dev/' . $device->{ $_[0] =~ s|^/dev/disk/by-id/||r } },
+ block_device_stamp => sub { '1:8:0' },
+ is_partition => sub { 0 },
+ );
+ for my $volname ($listed->@[0 .. 3]) {
+ my ($id) = $volname =~ m/^\d+\.\d+\.\d+\.(.+)$/;
+ eval { PVE::Diskmanage::block_device_reference("/dev/disk/by-id/$id") };
+ is($@, '', "plain volumes: $id passes the volume group creation identity check");
+ }
+ eval { PVE::Diskmanage::block_device_reference('/dev/disk/by-id/scsi-8naa.W0') };
+ like($@, qr/does not match its by-id name/, 'plain volumes: while an alias would not');
+
$iscsi->mock(
iscsi_session_device_map => $session_device_map,
load_stable_scsi_paths => sub { {} },
diff --git a/src/test/run_san_lun_scan_tests.pl b/src/test/run_san_lun_scan_tests.pl
index 1771a5c8..af8b4870 100755
--- a/src/test/run_san_lun_scan_tests.pl
+++ b/src/test/run_san_lun_scan_tests.pl
@@ -46,6 +46,9 @@ my sub sd {
# what the scan collects in which order
my @order;
my $diskmanage = Test::MockModule->new('PVE::Diskmanage');
+my $hint = { 'in-use' => 'no', 'in-use-by' => '' };
+my @hint_calls;
+my $by_id;
$diskmanage->mock(
get_disks => sub {
push @order, 'disks';
@@ -69,6 +72,8 @@ $diskmanage->mock(
};
},
get_nvme_path_status => sub { {} },
+ block_device_usage_hint => sub { push @hint_calls, [@_]; $hint },
+ canonical_blockdev_link => sub { $by_id },
udev_properties => sub {
my ($dev) = @_;
my $pv = $dev =~ m/^dm-(.+)$/ ? $maps->{$1}->{pv} : ($devices->{$dev} // {})->{pv};
@@ -196,7 +201,28 @@ my sub flagged {
{ '3W0' => { slaves => ['sdb', 'sdc'], pv => 'PV0' } },
);
is(scan()->{'3W0'}->{'paths-total'}, 2, 'map path count of the disk scan');
+@hint_calls = ();
my $res = scan();
+is($res->{sdd}->{'in-use'}, 'no', 'scan exposes metadata usage hint');
+is_deeply(
+ { map { $_->[0] => $_->[1] } @hint_calls },
+ {
+ '/dev/mapper/3W0' => { 'map-wwid' => '3W0' },
+ '/dev/sdd' => undef,
+ },
+ 'usage hint: a map also for its paths, a path without a map on its own',
+);
+ok(!exists($res->{sdd}->{'by-id'}), 'scan omits unverified by-id path');
+$hint = { 'in-use' => 'yes', 'in-use-by' => 'array held by vg-data' };
+$by_id = '/dev/disk/by-id/dm-uuid-mpath-3W0';
+my $busy = scan()->{'3W0'};
+is($busy->{'in-use'}, 'yes', 'scan propagates positive usage hint');
+is($busy->{'in-use-by'}, 'array held by vg-data', 'scan propagates user names');
+is($busy->{'by-id'}, $by_id, 'scan emits the verified canonical link');
+$hint = { 'in-use' => 'unknown', 'in-use-by' => 'check failed' };
+is(scan()->{sdd}->{'in-use'}, 'unknown', 'scan preserves failed-probe state');
+$hint = { 'in-use' => 'no', 'in-use-by' => '' };
+$by_id = undef;
is($res->{sdd}->{wwid}, '3W0', 'wwid: a path without a map has the identity of its LUN');
ok($derived_with && $derived_with == $collected, 'the storages derive from the same collection');
is_deeply([@order[0, 1]], ['identities', 'disks'], 'the identities are collected before the disks');
diff --git a/src/test/run_san_lvm_create_tests.pl b/src/test/run_san_lvm_create_tests.pl
index 8d6bbfdc..c41142da 100755
--- a/src/test/run_san_lvm_create_tests.pl
+++ b/src/test/run_san_lvm_create_tests.pl
@@ -7,7 +7,7 @@ use File::Basename qw(basename);
use File::Path qw(make_path);
use File::Temp qw(tempdir);
use JSON qw(encode_json);
-use Scalar::Util qw(weaken);
+use Scalar::Util qw(refaddr tainted weaken);
use Storable qw(dclone);
use Test::MockModule;
use Test::More;
@@ -16,20 +16,40 @@ use lib ('.', '..');
use PVE::API2::Disks::LVM;
use PVE::API2::Storage::Config;
+$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
+delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
+
+my sub command_boundary {
+ my ($cmd) = @_;
+
+ # Exercise exec's taint check without letting any device command reach a real device.
+ PVE::Tools::run_command(['/usr/bin/true', @$cmd]) if ${^TAINT};
+}
+
my $disk = Test::MockModule->new('PVE::Diskmanage');
my $storage = Test::MockModule->new('PVE::Storage');
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $mp = Test::MockModule->new('PVE::Multipath');
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
+my $iscsi = Test::MockModule->new('PVE::Storage::ISCSIPlugin');
my $rpc = Test::MockModule->new('PVE::RPCEnvironment');
-my $inotify = Test::MockModule->new('PVE::INotify');
my $tools = Test::MockModule->new('PVE::Tools');
-my $glob = \&PVE::Tools::dir_glob_foreach;
+my $inotify = Test::MockModule->new('PVE::INotify');
my $reference = \&PVE::Diskmanage::block_device_reference;
my $stamp = \&PVE::Diskmanage::block_device_stamp;
+my $ready = \&PVE::Diskmanage::assert_block_device_ready;
my $users = \&PVE::Diskmanage::block_device_users;
-my ($root, $resolved, $worker, $cfg, $handle, $local, $pv, $during_probe, $inventory_used);
-my (@locks, @writes);
+my $partitions = \&PVE::Diskmanage::wipe_partitions;
+my $san_identity = \&PVE::Storage::san_device_identity;
+my $storage_guard = \&PVE::Storage::assert_san_write_safe;
+my $canonical_link = \&PVE::Diskmanage::canonical_blockdev_link;
+my $glob = \&PVE::Tools::dir_glob_foreach;
+my ($root, $resolved, $worker, $cfg, $handle, $local, $partition, $pv, $during_probe, $after_write);
+my (@locks, @writes, @probes, $config_writes, $ids, $missing_links, $inventory_used);
+my ($config_reads, @guard_configs);
my $uuid = 'aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg';
-my $canonical = '/dev/mapper/lun';
+my $canonical = '/dev/disk/by-id/dm-uuid-mpath-test';
+my $nvme_id = 'eui.0123456789abcdef';
my sub put {
my ($path, $value) = @_;
my ($dir) = "$root/$path" =~ m{^(.*)/[^/]+$};
@@ -38,6 +58,13 @@ my sub put {
print $fh "$value\n";
close($fh) or die $!;
}
+my sub device {
+ my ($name, $number) = @_;
+ put("sys/class/block/$name/dev", $number);
+ put("sys/class/block/$name/size", '8192');
+ put("sys/class/block/$name/device/state", 'running');
+ make_path("$root/sys/class/block/$name/holders");
+}
my sub locked {
my ($name, $code) = @_;
push @locks, $name;
@@ -52,6 +79,7 @@ my sub written {
ok($handle && defined(fileno($handle)), 'production retains SAN handle through write')
if !$local;
push @writes, [$tool, $path];
+ $after_write->($tool) if $after_write;
}
{
@@ -63,10 +91,22 @@ my sub written {
$rpc->mock(get => sub { bless {}, 'SanLVMTestRPC' });
$inotify->mock(nodename => sub { 'n1' });
$disk->mock(
- verify_blockdev_path => sub { $_[0] =~ m{^/dev/mapper/} ? $resolved : $_[0] },
+ verify_blockdev_path => sub {
+ die "missing link\n" if $missing_links->{ $_[0] };
+ return '/dev/sda' if $_[0] eq '/dev/disk/by-id/scsi-test';
+ return $_[0] =~ m{^/dev/(?:disk|mapper)/} ? $resolved : $_[0];
+ },
+ canonical_blockdev_link => sub { $canonical_link->($_[0], $_[1], $_[2], "$root/sys") },
is_san_device => sub { !$local },
is_multipath_device => sub { !$local && $_[0] =~ /dm-/ },
- is_partition => sub { 0 },
+ is_partition => sub { $partition && $_[0] eq $resolved },
+ get_blockdev => sub { '/dev/sda' },
+ block_device_reference => sub { $reference->($_[0], $_[1], "$root/sys") },
+ block_device_stamp => sub { $stamp->($_[0], "$root/sys") },
+ assert_block_device_ready => sub {
+ push @probes, 'readiness';
+ $ready->($_[0], { sysfs => "$root/sys", procfs => "$root/proc" });
+ },
block_device_users => sub {
$users->($_[0], { %{ $_[1] // {} }, sysfs => "$root/sys", procfs => "$root/proc" });
},
@@ -75,9 +115,10 @@ $disk->mock(
return PVE::Tools::file_read_firstline(
"$root/sys/class/block/" . basename($path) . '/dev');
},
- block_device_reference => sub { $reference->($_[0], $_[1], "$root/sys") },
- block_device_stamp => sub { $stamp->($_[0], "$root/sys") },
+ wipe_partitions => sub { $partitions->($_[0], "$root/sys") },
open_block_device => sub {
+ push @probes, 'open';
+ is($_[1], $stamp->($_[0], "$root/sys"), 'open receives current instance stamp');
open(my $opened, '+<', "$root/handle") or die $!;
$handle = $opened;
weaken($handle);
@@ -85,9 +126,50 @@ $disk->mock(
},
is_mounted => sub { undef },
has_holder => sub { undef },
- assert_disk_unused => sub { die "device '$_[0]' is already in use\n" if $inventory_used },
+ assert_disk_unused => sub {
+ push @probes, 'inventory';
+ die "device '$_[0]' is already in use\n" if $inventory_used;
+ },
locked_disk_action => sub { locked('disk', $_[0]) },
+ get_partnum => sub { 1 },
+ get_disks => sub {
+ push @probes, 'disk';
+ return { sda => { gpt => 1 } };
+ },
+ run_command => sub {
+ my ($cmd) = @_;
+ command_boundary($cmd);
+ die "unexpected command @$cmd\n" if $cmd->[0] ne 'sgdisk';
+ written('parttype', $cmd->[-1]);
+ },
udevadm_trigger => sub { },
+ get_nvme_path_status => sub { { nvme900n1 => { active => 1 } } },
+);
+$tools->mock(
+ dir_glob_foreach => sub {
+ my $path = $_[0];
+ $path =~ s{^/sys}{$root/sys};
+ $glob->($path, $_[1], $_[2]);
+ },
+);
+$identity->mock(
+ collect => sub { push @probes, 'identity'; $ids },
+ path_wwid => sub { $_[0]->{paths}->{ $_[1] }->{wwid} },
+);
+$iscsi->mock(iscsi_session_device_map => sub { {} });
+$mp->mock(
+ get_maps => sub {
+ return [
+ map { {
+ sysfs => "dm-$_",
+ wwid => 'test',
+ 'path-groups' => [{
+ paths =>
+ [{ dev => 'sda', 'dm-state' => 'active', 'check-state' => 'ready' }],
+ }],
+ } } (900, 901)
+ ];
+ },
);
$storage->mock(
lock_storage_config => sub {
@@ -98,18 +180,45 @@ $storage->mock(
);
locked('storage', $_[0]);
},
- config =>
- sub { is($locks[-1], 'storage', 'configuration read under storage lock'); dclone($cfg) },
- write_config => sub { },
+ config => sub {
+ is($locks[-1], 'storage', 'configuration read under storage lock');
+ $config_reads++;
+ dclone($cfg);
+ },
+ assert_san_write_safe => sub {
+ push @guard_configs, refaddr($_[0]);
+ $storage_guard->(@_);
+ },
+ write_config => sub { $config_writes++ },
path => sub { $canonical },
activate_storage => sub { },
activate_volumes => sub { },
-);
-$tools->mock(
- dir_glob_foreach => sub {
- my $path = $_[0];
- $path =~ s{^/sys}{$root/sys};
- $glob->($path, $_[1], $_[2]);
+ san_device_identity => sub { $san_identity->($_[0], $_[1], "$root/sys", $_[3]) },
+ run_command => sub {
+ my ($cmd, %opt) = @_;
+ command_boundary($cmd);
+ push @probes, $cmd->[0];
+ if ($cmd->[0] eq 'wipefs') {
+ $opt{outfunc}->(encode_json({
+ signatures => $pv eq 'blank'
+ ? []
+ : [{ type => 'LVM2_member', uuid => $uuid }],
+ }));
+ } elsif ($cmd->[0] eq '/sbin/pvs') {
+ my $rows =
+ $pv eq 'blank'
+ ? []
+ : [{
+ pv_name => $resolved,
+ pv_uuid => $uuid,
+ vg_name => $pv eq 'same' ? 'vg' : '',
+ pv_in_use => $pv eq 'same' ? '1' : '0',
+ }];
+ $opt{outfunc}->(encode_json({ report => [{ pv => $rows }] }));
+ $during_probe->('storage') if $during_probe;
+ } else {
+ die "unexpected storage command @$cmd\n";
+ }
},
);
$lvm->mock(
@@ -120,18 +229,23 @@ $lvm->mock(
},
abs_path => sub { $_[0] },
clear_first_sector => sub { written('clear', $_[0]) },
- lvm_vgs => sub { $pv eq 'same' ? { vg => {} } : {} },
+ lvm_vgs => sub { push @probes, 'vgs'; $pv eq 'same' ? { vg => {} } : {} },
assert_discard_supported => sub { },
+ assert_device_discard_supported => sub { push @probes, 'discard' },
run_command => sub {
my ($cmd, %opt) = @_;
+ command_boundary($cmd);
if ($cmd->[0] eq 'wipefs') {
+ push @probes, 'wipefs';
$opt{outfunc}
->(encode_json({ signatures => $pv eq 'blank' ? [] : [{ type => 'LVM2_member' }] })
);
} elsif ($cmd->[0] eq '/usr/bin/file') {
+ push @probes, 'file';
$opt{outfunc}->("$cmd->[-1]: " . ($pv eq 'blank' ? 'data' : 'LVM2 PV'));
- $during_probe->() if $during_probe;
+ $during_probe->('lvm') if $during_probe;
} elsif ($cmd->[0] eq '/sbin/pvs') {
+ push @probes, 'pvs';
$opt{outfunc}->("$resolved:8192:"
. ($pv eq 'same' ? 'vg' : '')
. ":$uuid:"
@@ -144,29 +258,45 @@ $lvm->mock(
);
my sub reset_case {
$root = tempdir(CLEANUP => 1);
- for my $name ('dm-900', 'vdz') {
- put("sys/class/block/$name/dev", $name eq 'vdz' ? '252:0' : '253:900');
- put("sys/class/block/$name/size", '8192');
- make_path("$root/sys/class/block/$name/holders");
+ for my $n (900, 901, 902) {
+ device("dm-$n", "253:$n");
+ put("sys/class/block/dm-$n/dm/uuid", $n == 902 ? 'mpath-other' : 'mpath-test');
+ make_path("$root/sys/class/block/dm-$n/slaves");
+ symlink('../../sda', "$root/sys/class/block/dm-$n/slaves/sda") or die $!;
}
- put('sys/class/block/dm-900/dm/uuid', 'mpath-test');
- put('sys/class/block/dm-900/slaves/sda/device/state', 'running');
+ device('sda', '8:0');
+ device('sdb', '8:16');
+ device('vdz', '252:0');
+ device('nvme900n1', '259:900');
+ put('sys/class/block/nvme900n1/wwid', $nvme_id);
+ put('sys/class/block/nvme900n1/device/subsysnqn', 'nqn.test');
put('proc/self/mountinfo', '1 0 0:1 / / rw - rootfs rootfs rw');
put('proc/swaps', "Filename\tType\tSize\tUsed\tPriority");
put('handle', 'retained descriptor fixture');
- ($resolved, $local, $pv) = ('/dev/dm-900', 0, 'blank');
- ($during_probe, $worker, $handle) = (undef, undef, undef);
+ ($resolved, $local, $partition, $pv) = ('/dev/dm-900', 0, 0, 'blank');
+ ($during_probe, $after_write, $worker, $handle) = (undef, undef, undef, undef);
$cfg =
{ ids => { base => { type => 'iscsi', target => 'iqn.test', content => { none => 1 } } } };
+ $ids = {
+ paths => { sda => { wwid => 'test' }, sdb => { wwid => 'test' } },
+ luns => { lun => { wwid => 'test', target => 'iqn.test' } },
+ };
@writes = ();
+ @probes = ();
@locks = ();
+ $config_writes = 0;
+ $config_reads = 0;
+ @guard_configs = ();
+ $missing_links = {};
$inventory_used = 0;
+ $canonical = '/dev/disk/by-id/dm-uuid-mpath-test';
}
my sub queue {
- PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg', device => $_[0] // $canonical });
+ my ($path) = @_;
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg', device => $path // $canonical });
}
my sub run_route {
- my ($route) = @_;
+ my ($route, $options) = @_;
eval {
if ($route eq 'disk') {
queue();
@@ -176,27 +306,116 @@ my sub run_route {
type => 'lvm',
storage => 'new',
vgname => 'vg',
- base => 'base:0.0.1.lun',
+ %{ $options // {} },
+ base => 'base:0.0.1.dm-uuid-mpath-test',
});
}
};
return $@;
}
-for my $route ('disk', 'base') {
- reset_case();
+my sub raw_user {
+ my ($dev) = @_;
make_path("$root/proc/999999/fd");
- symlink('/dev/dm-900', "$root/proc/999999/fd/3") or die $!;
+ symlink("/dev/$dev", "$root/proc/999999/fd/3") or die $!;
put('proc/999999/comm', 'qemu');
- like(
- run_route($route),
- qr/cannot use.*qemu .* has dm-900 open/,
- "$route raw map opener refused",
- );
- is_deeply(\@writes, [], 'raw user receives no destructive command');
+}
+
+if (${^TAINT}) {
+ reset_case();
+ for my $attr ('dm-900/dm/uuid', 'nvme900n1/wwid') {
+ my $value = PVE::Tools::file_read_firstline("$root/sys/class/block/$attr");
+ ok(tainted($value), "$attr fixture retains taint from its file read");
+ eval { command_boundary(['/sbin/pvcreate', $value]) };
+ like($@, qr/Insecure dependency/, 'benign exec boundary rejects an uncaptured value');
+ }
+}
+
+for my $route ('disk', 'base') {
+ for my $transport ($route eq 'disk' ? ('iscsi', 'nvmeof') : ('iscsi')) {
+ for my $restriction ({}, { disable => 1 }, { nodes => { elsewhere => 1 } }) {
+ reset_case();
+ if ($transport eq 'nvmeof') {
+ $resolved = '/dev/nvme900n1';
+ $canonical = "/dev/disk/by-id/nvme-$nvme_id";
+ $cfg->{ids}->{base} =
+ { type => 'nvmeof', subsysnqn => 'nqn.test', content => { none => 1 } };
+ }
+ $cfg->{ids}->{images} =
+ { %{ $cfg->{ids}->{base} }, content => { images => 1 }, %$restriction };
+ my $kind = $transport eq 'nvmeof' ? 'subsystem' : 'target';
+ my $prefix = $route eq 'disk' ? "cannot use '$resolved' - " : '';
+ is(
+ run_route($route),
+ "${prefix}storage 'images' serves disk images from this $kind\n",
+ "$route $transport image owner refused",
+ );
+ is_deeply(\@writes, [], 'signatureless image volume receives no destructive command');
+ is($config_writes, 0, 'refusal does not publish storage');
+ $canonical = '/dev/disk/by-id/dm-uuid-mpath-test';
+ }
+ }
+ for my $dev ('dm-900', 'sda', 'sdb') {
+ reset_case();
+ raw_user($dev);
+ like(
+ run_route($route),
+ qr/cannot use.*qemu .* has $dev open/,
+ "$route raw map, member or same-identity sibling opener refused",
+ );
+ is_deeply(\@writes, [], 'raw user receives no destructive command');
+ }
reset_case();
unlink("$root/proc/swaps") or die $!;
like(run_route($route), qr{can't open '.*/proc/swaps'}, "$route inconclusive users refuse");
is_deeply(\@writes, [], 'inconclusive users receive no destructive command');
+ for my $dev ('sda', 'sdb') {
+ for my $probe_number (1 .. 3) {
+ reset_case();
+ my $probes = 0;
+ $during_probe = sub {
+ raw_user($dev) if $_[0] eq 'storage' && ++$probes == $probe_number;
+ };
+ like(
+ run_route($route),
+ qr/cannot use.*qemu .* has $dev open/,
+ "$route opener during storage probe $probe_number refuses the next write",
+ );
+ is(scalar(@writes), $probe_number - 1, 'only writes preceding the opener occurred');
+ is_deeply(\@writes, [], 'opener during first ownership probe causes zero writes')
+ if $probe_number == 1;
+ }
+ }
+ for my $probe ('lvm', 'storage') {
+ reset_case();
+ $during_probe = sub { $resolved = '/dev/dm-902' if $_[0] eq $probe };
+ like(
+ run_route($route),
+ qr/identity does not match/,
+ "$route replacement after $probe probe refused",
+ );
+ is_deeply(\@writes, [], 'replacement after probing receives no destructive command');
+ }
+ if ($route eq 'disk') {
+ reset_case();
+ $resolved = '/dev/nvme900n1';
+ $canonical = "/dev/disk/by-id/nvme-$nvme_id";
+ $cfg->{ids}->{base} =
+ { type => 'nvmeof', subsysnqn => 'nqn.test', content => { none => 1 } };
+ raw_user('nvme900n1');
+ like(
+ run_route($route),
+ qr/cannot use.*qemu .* has nvme900n1 open/,
+ "$route raw namespace refuses",
+ );
+ is_deeply(\@writes, [], 'raw namespace receives no destructive command');
+ unlink("$root/proc/999999/fd/3") or die $!;
+ is(run_route($route), '', "$route closed namespace permits initialization");
+ is(scalar(@writes), 3, 'closed namespace gets all initialization writes');
+ is($writes[1]->[1], $canonical, 'PV operand encodes namespace identity');
+ is($writes[2]->[1], $canonical, 'VG operand encodes namespace identity');
+ $canonical = '/dev/disk/by-id/dm-uuid-mpath-test';
+
+ }
for my $kind ('blank', 'orphan', 'same') {
reset_case();
@@ -224,8 +443,67 @@ for my $route ('disk', 'base') {
'only the base-route same-VG retry succeeds without writes',
);
}
+ if ($kind ne 'same') {
+ is(
+ $config_reads,
+ $route eq 'disk' ? 1 : 2,
+ 'guard uses one snapshot; base API retains its separate pre-hook config read',
+ );
+ is(scalar(@guard_configs), 3, 'ownership is checked before every write');
+ is_deeply(
+ \@guard_configs,
+ [($guard_configs[0]) x 3],
+ 'every guard check receives the same locked configuration snapshot',
+ );
+ }
+ ok(!defined($handle), 'production releases the retained handle after completion');
+ like($writes[0]->[1], qr{^/proc/\d+/fd/\d+$}, 'sector clear uses retained descriptor')
+ if @writes;
}
}
+
+reset_case();
+queue();
+$resolved = '/dev/dm-901';
+eval { $worker->() };
+is($@, '', 'identity-preserving queued renumbering succeeds');
+is($writes[1]->[1], $canonical, 'LVM uses the verified identity-encoding name after renumbering');
+is($writes[2]->[1], $canonical, 'VG creation also uses the verified stable name');
+for my $path ($canonical, '/dev/mapper/friendly', '/dev/dm-900') {
+ reset_case();
+ queue($path);
+ if ($path eq '/dev/dm-900') {
+ put('sys/class/block/dm-900/dm/uuid', 'mpath-other');
+ } else {
+ $resolved = '/dev/dm-902';
+ }
+ eval { $worker->() };
+ like(
+ $@,
+ qr/cannot use.*identity (?:changed|does not match)/,
+ 'moved by-id, rebound alias or recycled dm number refuses',
+ );
+ is_deeply(\@writes, [], 'queued identity replacement receives no destructive command');
+}
+for my $tool ('clear', '/sbin/pvcreate') {
+ reset_case();
+ $after_write = sub { $resolved = '/dev/dm-902' if $_[0] eq $tool };
+ like(
+ run_route('disk'),
+ qr/identity does not match/,
+ "replacement after $tool prevents next write",
+ );
+ is(
+ scalar(@writes),
+ $tool eq 'clear' ? 1 : 2,
+ 'only preceding writes to the checked instance occurred',
+ );
+}
+reset_case();
+$during_probe = sub { put('sys/class/block/dm-900/dev', '253:999') };
+like(run_route('disk'), qr/device topology changed/, 'instance change after probing refuses');
+is_deeply(\@writes, [], 'changed instance receives no destructive command');
+
reset_case();
$local = 1;
$resolved = '/dev/vdz';
@@ -241,20 +519,93 @@ eval { $worker->() };
like($@, qr/cannot use.*device topology changed/, 'queued local-to-SAN transition refuses');
is_deeply(\@writes, [], 'transition does not bypass storage lock');
+reset_case();
+$local = 1;
+$resolved = '/dev/sda1';
+$partition = 1;
+device('sda1', '8:1');
+put('sys/class/block/sda1/partition', '1');
+queue($resolved);
+eval { $worker->() };
+is($@, '', 'local partition initialization still works without quorum');
+is_deeply(
+ \@writes,
+ [
+ ['parttype', '/dev/sda'],
+ ['clear', $resolved],
+ ['/sbin/pvcreate', $resolved],
+ ['/sbin/vgcreate', $resolved],
+ ],
+ 'local partitions retain unguarded type changes and normal LVM operands',
+);
+
for my $route ('disk', 'base') {
reset_case();
- $during_probe = sub { put('sys/class/block/dm-900/dev', '253:999') };
- like(run_route($route), qr/device identity changed/, "$route changed instance refuses");
- is_deeply(\@writes, [], 'replacement after probing receives no destructive command');
+ $canonical = '/dev/mapper/friendly';
+ is(run_route($route), '', "$route converts friendly alias to canonical operand");
+ is($writes[1]->[1], '/dev/disk/by-id/dm-uuid-mpath-test',
+ 'PV operand encodes the map identity');
+ is($writes[2]->[1], '/dev/disk/by-id/dm-uuid-mpath-test',
+ 'VG operand encodes the map identity');
reset_case();
- is(run_route($route), '', "$route initializes unchanged instance");
- like($writes[0]->[1], qr{^/proc/\d+/fd/\d+$}, 'sector clear uses retained descriptor');
- ok(!defined($handle), 'production releases the retained handle after completion');
+ $canonical = '/dev/mapper/friendly';
+ $missing_links->{'/dev/disk/by-id/dm-uuid-mpath-test'} = 1;
+ is(
+ run_route($route),
+ "cannot use '/dev/dm-900' - cannot verify a stable name under /dev/disk/by-id\n",
+ "$route refuses missing canonical link",
+ );
+ is_deeply(\@writes, [], 'missing stable operand refuses before sector clearing');
}
+
+for my $route ('disk', 'base') {
+ for my $kind ($route eq 'disk' ? ('scsi', 'nvme', 'map') : ('scsi', 'map')) {
+ reset_case();
+ if ($kind eq 'map') {
+ device('dm-903', '253:903');
+ put('sys/class/block/dm-903/dm/uuid', 'part2-mpath-test');
+ $resolved = '/dev/dm-903';
+ $canonical = '/dev/mapper/friendly';
+ } else {
+ my $name = $kind eq 'scsi' ? 'sda1' : 'nvme900n1p1';
+ device($name, $kind eq 'scsi' ? '8:1' : '259:901');
+ put("sys/class/block/$name/partition", '1');
+ $resolved = "/dev/$name";
+ $partition = 1;
+ $canonical =
+ $kind eq 'scsi'
+ ? '/dev/disk/by-id/scsi-test-part1'
+ : "/dev/disk/by-id/nvme-$nvme_id-part1";
+ $cfg->{ids}->{base} =
+ { type => 'nvmeof', subsysnqn => 'nqn.test', content => { none => 1 } }
+ if $kind eq 'nvme';
+ }
+ is(
+ run_route($route, { 'on-volume-remove' => 'discard=1' }),
+ "cannot use '$resolved' - create the volume group on the whole LUN\n",
+ "$route refuses a $kind SAN partition",
+ );
+ is_deeply(
+ \@probes,
+ [],
+ 'partition refused before identity, readiness, inventory or content probes',
+ );
+ is_deeply(\@writes, [], 'partition refusal issues no destructive command');
+ is($config_writes, 0, 'partition refusal writes no storage configuration');
+ }
+}
+
reset_case();
queue();
-put('sys/class/block/dm-900/dev', '253:999');
+@probes = ();
+put('sys/class/block/dm-900/dm/uuid', 'part2-mpath-test');
eval { $worker->() };
-like($@, qr/device identity changed/, 'queued replacement refuses');
-is_deeply(\@writes, [], 'queued replacement receives no destructive command');
+is(
+ $@,
+ "cannot use '/dev/dm-900' - create the volume group on the whole LUN\n",
+ 'queued whole-LUN reference replaced by a partition refuses',
+);
+is_deeply(\@probes, [], 'queued partition refused before probes');
+is_deeply(\@writes, [], 'queued partition receives no destructive command');
+
done_testing();
diff --git a/src/test/run_san_wipe_tests.pl b/src/test/run_san_wipe_tests.pl
new file mode 100755
index 00000000..0779bc85
--- /dev/null
+++ b/src/test/run_san_wipe_tests.pl
@@ -0,0 +1,673 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use File::Path qw(make_path);
+use File::Temp qw(tempdir);
+use FindBin qw($Bin);
+use JSON;
+use Test::MockModule;
+use Test::More;
+
+use lib ('.', '..');
+use PVE::Storage;
+
+my $storage = Test::MockModule->new('PVE::Storage');
+my $disk = Test::MockModule->new('PVE::Diskmanage');
+my ($ready, $readiness_error);
+$disk->mock(
+ assert_block_device_ready => sub {
+ die "no usable path\n" if $readiness_error;
+ $ready = 1;
+ },
+);
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
+my $iscsi = Test::MockModule->new('PVE::Storage::ISCSIPlugin');
+$iscsi->mock(iscsi_session_device_map => sub { {} });
+$identity->mock(collect => sub { { luns => {} } });
+my ($report, $failure, $cfg, $key, $subsystem, $path, $signatures, $partitions, $pv_identities);
+my $pv_uuid = 'aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg';
+my (@probed, @resolved, @writes);
+$storage->mock(
+ san_device_identity => sub {
+ push @resolved, $_[0];
+ # a base path taken in list context would shift the arguments
+ die "san_device_identity called with " . scalar(@_) . " arguments\n" if @_ > 4;
+ # as verify_blockdev_path() does for a link that is not there
+ die "failed to get absolute path to $_[0]\n" if $_[0] eq '/dev/missing';
+ return {
+ key => $pv_identities->{ $_[0] } // ($_[0] eq '/dev/other' ? 'scsi:other' : $key),
+ targets => { 'iqn.test' => 1 },
+ subsystem => $subsystem,
+ };
+ },
+ # as the real one: path, owner and type in list context
+ path => sub { wantarray ? ($path, undef, 'images') : $path },
+ run_command => sub {
+ my ($cmd, %opt) = @_;
+ ok($ready, 'readiness precedes every device-reading probe');
+ is($opt{timeout}, 10, 'PV probe bounded');
+ if ($cmd->[0] eq 'wipefs') {
+ push @probed, $cmd->[-1];
+ die "wipefs failed\n" if $failure eq 'wipefs';
+ $opt{outfunc}->($signatures->{ $cmd->[-1] } // '{"signatures":[]}');
+ } elsif ($cmd->[0] eq '/sbin/pvs') {
+ is_deeply(
+ $cmd,
+ [
+ '/sbin/pvs',
+ '--nohints',
+ '--readonly',
+ '--binary',
+ '--reportformat',
+ 'json',
+ '--options',
+ 'pv_name,vg_name,pv_uuid,pv_in_use',
+ ],
+ 'full hint-free read-only PV report includes independent use flag',
+ );
+ die "pvs failed\n" if $failure;
+ $opt{outfunc}->($report);
+ } else {
+ push @writes, $cmd;
+ die "unexpected command @$cmd\n";
+ }
+ },
+);
+my sub reset_case {
+ $report = encode_json({ report => [{ pv => [] }] });
+ $cfg = { ids => {} };
+ $failure = 0;
+ $key = 'scsi:test';
+ $subsystem = undef;
+ $path = '/dev/alias';
+ $signatures = {};
+ $partitions = [];
+ $pv_identities = {};
+ @probed = ();
+ @resolved = ();
+ @writes = ();
+ ($ready, $readiness_error) = (0, 0);
+}
+my sub check {
+ eval { PVE::Storage::assert_san_write_safe($cfg, '/dev/dm-0', $partitions) };
+ return $@;
+}
+reset_case();
+is(check(), '', 'unreferenced LUN allowed');
+for my $type ('iscsi', 'iscsidirect', 'zfs', 'vendor') {
+ reset_case();
+ $cfg->{ids} = {
+ base => { type => 'iscsi', target => 'iqn.test', content => { none => 1 } },
+ images => {
+ type => $type,
+ target => 'iqn.test',
+ content => { images => 1 },
+ disable => 1,
+ nodes => { elsewhere => 1 },
+ },
+ };
+ like(check(), qr/storage 'images' serves disk images/, "$type conflicting reference found");
+}
+for my $base ('0.0.1.scsi-alias', '0.0.1.wwn-0x123-part1') {
+ reset_case();
+ $cfg->{ids}->{base} = { type => 'iscsi' };
+ $cfg->{ids}->{lvm} = { type => 'lvm', base => "base:$base", disable => 1 };
+ like(check(), qr/uses this LUN as its base volume/, "$base compared by resolved identity");
+ $path = '/dev/other';
+ is(check(), '', 'different LUN identity allowed');
+ $path = '/dev/missing';
+ like(
+ check(),
+ qr/cannot check storage 'lvm', its base volume 'base:\Q$base\E' is not visible/,
+ 'unresolvable alias refuses with storage context',
+ );
+}
+for my $case (
+ ['iscsi', '0.0.1.dm-uuid-mpath-test', 'scsi:test'],
+ ['iscsi', '0.0.1.dm-uuid-part2-mpath-test', 'scsi:test'],
+) {
+ reset_case();
+ my ($type, $base, $identity) = @$case;
+ $cfg->{ids}->{base} = { type => $type };
+ $cfg->{ids}->{lvm} = { type => 'lvm', base => "base:$base", disable => 1 };
+ $path = '/dev/missing';
+ $key = $identity;
+ like(check(), qr/uses this LUN as its base volume/, "$base matched without resolution");
+ $key = 'scsi:different';
+ is(check(), '', "$base: genuinely different invisible LUN allowed");
+}
+reset_case();
+$cfg->{ids}->{base} = { type => 'iscsi' };
+$cfg->{ids}->{lvm} = { type => 'lvm', base => 'base:dm-uuid-mpath-test' };
+like(
+ check(),
+ qr/cannot check base volume 'base:dm-uuid-mpath-test' of storage 'lvm'/,
+ 'plugin parser must accept the volume name',
+);
+for my $alias (
+ 'prefix-dm-uuid-mpath-test', 'nvme-eui.0123456789abcdef-extra', 'nvme-model_serial',
+) {
+ ok(!PVE::Diskmanage::block_identity_from_id($alias), "$alias is not a canonical identity");
+}
+reset_case();
+$cfg->{ids}->{lvm} = { type => 'lvm', vgname => 'vg', nodes => { elsewhere => 1 } };
+$report = encode_json({
+ report => [{
+ pv =>
+ [{ pv_name => '/dev/alias', vg_name => 'vg', pv_uuid => $pv_uuid, pv_in_use => '1' }],
+ }],
+});
+like(check(), qr/volume group 'vg' is used by storage 'lvm'/, 'VG referenced elsewhere refuses');
+$cfg = { ids => {} };
+is(check(), '', 'unreferenced old VG allowed');
+$failure = 1;
+like(check(), qr/pvs failed/, 'failed PV probe refuses');
+$failure = 0;
+$report = '{}';
+like(check(), qr/malformed pvs/, 'malformed PV report refuses');
+
+reset_case();
+$cfg->{ids}->{lvm} = { type => 'lvmthin', vgname => 'vg', disable => 1 };
+$report = encode_json({
+ report => [{
+ pv =>
+ [{ pv_name => '/dev/other', vg_name => 'vg', pv_uuid => $pv_uuid, pv_in_use => '1' }],
+ }],
+});
+is(check(), '', 'different LUN without a matching PV UUID allowed');
+
+for my $candidate ('/dev/dm-0', '/dev/dm-1', '/dev/sda1') {
+ $partitions = ['dm-1', 'sda1'];
+ $signatures = {
+ $candidate =>
+ encode_json({ signatures => [{ type => 'LVM2_member', uuid => $pv_uuid =~ s/-//gr }] }),
+ };
+ like(
+ check(),
+ qr/volume group 'vg' is used by storage 'lvm'/,
+ "$candidate duplicate UUID refuses even when LVM lists another LUN",
+ );
+}
+is_deeply(
+ [@probed[-3 .. -1]],
+ ['/dev/dm-0', '/dev/dm-1', '/dev/sda1'],
+ 'parent and every destroyed partition directly probed',
+);
+for my $bad (
+ '{}',
+ '{"signatures":[{}]}',
+ '{"signatures":[{"type":"LVM2_member"}]}',
+ '{"signatures":[{"type":"LVM2_member","uuid":"bad"}]}',
+) {
+ $signatures = { '/dev/dm-0' => $bad };
+ like(check(), qr/malformed wipefs|invalid PV UUID/, 'inconclusive direct probe refuses');
+}
+$signatures = {};
+$failure = 'wipefs';
+like(check(), qr/wipefs failed/, 'direct probe failure refuses');
+$failure = 0;
+$report = encode_json({
+ report => [{ pv => [{ pv_name => '/dev/other', vg_name => 'vg', pv_in_use => '1' }] }] });
+like(check(), qr/invalid PV UUID/, 'configured VG inventory requires PV UUIDs');
+
+reset_case();
+$signatures = {
+ '/dev/dm-0' => encode_json({ signatures => [{ type => 'LVM2_member', uuid => $pv_uuid }] }),
+};
+like(check(), qr/LVM does not report its physical volume/, 'missing candidate UUID refuses');
+my $candidate = { pv_name => '/dev/alias', vg_name => '', pv_uuid => $pv_uuid, pv_in_use => '0' };
+$report = encode_json({ report => [{ pv => [$candidate] }] });
+is(check(), '', 'positively unused orphan allowed');
+
+for my $used ('1', '', 'unknown') {
+ $candidate->{pv_in_use} = $used;
+ $report = encode_json({ report => [{ pv => [$candidate] }] });
+ like(
+ check(),
+ qr/belongs to a volume group whose metadata is not visible/,
+ "empty VG with use flag '$used' refuses missing or damaged metadata",
+ );
+}
+$candidate->{vg_name} = 'foreign';
+$candidate->{pv_in_use} = '1';
+$cfg->{ids}->{foreign} = { type => 'lvm', vgname => 'foreign', nodes => { elsewhere => 1 } };
+$report = encode_json({ report => [{ pv => [$candidate] }] });
+like(check(), qr/volume group 'foreign' is used by storage/, 'unhinted PV reference refuses');
+
+subtest 'malformed multi-record reports are refused' => sub {
+ reset_case();
+ $signatures->{'/dev/dm-0'} = encode_json({
+ signatures => [{ type => 'LVM2_member', uuid => 'bad' }, {}],
+ });
+ ok(check(), 'invalid UUID and malformed signature cannot pass');
+ is_deeply(\@writes, [], 'no writes after malformed signatures');
+
+ reset_case();
+ $report = encode_json({
+ report => [{
+ pv => [
+ { pv_name => '/dev/dm-0', vg_name => '', pv_uuid => 'bad', pv_in_use => '0' },
+ {},
+ ],
+ }],
+ });
+ ok(check(), 'invalid UUID and malformed PV cannot pass');
+ is_deeply(\@writes, [], 'no writes after malformed PV report');
+};
+
+subtest 'captured no-metadata PV and unrelated orphan' => sub {
+ my $capture = PVE::Tools::file_get_contents("$Bin/lvm-fixtures/lab1-nomda-orphan.txt");
+ my ($json) = $capture =~ m/\A== devices B,C\n(.*?)^== full nohints /ms;
+ die "missing captured JSON report\n" if !defined($json);
+ my $captured = decode_json($json);
+ is(scalar($captured->{log}->@*), 2, 'both captured log warnings remain in the report');
+ is($_->{log_type}, 'warn', 'captured log entry is a warning') for $captured->{log}->@*;
+ for my $pv ($captured->{report}->[0]->{pv}->@*) {
+ reset_case();
+ $report = $json;
+ $pv_identities =
+ { map { $_->{pv_name} => "scsi:$_->{pv_uuid}" } $captured->{report}->[0]->{pv}->@* };
+ $key = $pv_identities->{ $pv->{pv_name} };
+ $signatures->{'/dev/dm-0'} = encode_json({
+ signatures => [{ type => 'LVM2_member', uuid => $pv->{pv_uuid} }],
+ });
+ if ($pv->{vg_name} eq '[unknown]') {
+ like(
+ check(),
+ qr/physical volume belongs to a volume group whose metadata is not visible/,
+ 'captured no-metadata PV refused specifically, not as a malformed report',
+ );
+ is_deeply(
+ \@resolved,
+ ['/dev/dm-0'],
+ 'captured candidate UUID precedes alias resolution',
+ );
+ } else {
+ is(check(), '', 'captured orphan passes despite the unrelated no-metadata PV');
+ is(
+ scalar(@resolved),
+ 2,
+ 'unrelated no-metadata PV identity is checked before skipping',
+ );
+ }
+ is_deeply(\@writes, [], 'captured report guard performs no writes');
+ }
+};
+
+subtest 'unknown VG membership is isolated without orphan assumptions' => sub {
+ my $other_uuid = 'hhhhhh-iiii-jjjj-kkkk-llll-mmmm-nnnnnn';
+ for my $vg ('', '[unknown]') {
+ for my $flag ('1', '', 'unknown', $vg ? ('0') : ()) {
+ for my $alias ('/dev/alias', '/dev/other', '/dev/missing') {
+ reset_case();
+ $signatures->{'/dev/dm-0'} = encode_json({
+ signatures => [{ type => 'LVM2_member', uuid => $pv_uuid }],
+ });
+ $report = encode_json({
+ report => [{
+ pv => [{
+ pv_name => $alias,
+ vg_name => $vg,
+ pv_uuid => $pv_uuid,
+ pv_in_use => $flag,
+ }],
+ }],
+ });
+ like(
+ check(),
+ qr/physical volume belongs to a volume group whose metadata is not visible/,
+ "VG '$vg', flag '$flag', alias '$alias': UUID proves candidate membership",
+ );
+ is_deeply(\@resolved, ['/dev/dm-0'], 'matching UUID precedes alias resolution');
+ is_deeply(\@writes, [], 'refused candidate causes no writes');
+ }
+ }
+ }
+ for my $alias ('/dev/alias', '/dev/sda1', '/dev/other', '/dev/missing') {
+ reset_case();
+ $signatures->{'/dev/dm-0'} = encode_json({
+ signatures => [{ type => 'LVM2_member', uuid => $pv_uuid }],
+ });
+ $report = encode_json({
+ report => [{
+ pv => [
+ {
+ pv_name => '/dev/dm-0',
+ vg_name => '',
+ pv_uuid => $pv_uuid,
+ pv_in_use => '0',
+ },
+ {
+ pv_name => $alias,
+ vg_name => '[unknown]',
+ pv_uuid => $other_uuid,
+ pv_in_use => '1',
+ },
+ ],
+ }],
+ });
+ my $error = check();
+ if ($alias eq '/dev/other') {
+ is($error, '', 'unrelated unknown-membership PV does not block the orphan');
+ } elsif ($alias eq '/dev/missing') {
+ like(
+ $error,
+ qr/failed to get absolute path/,
+ 'unresolved different UUID fails closed',
+ );
+ } else {
+ like(
+ $error,
+ qr/metadata is not visible/,
+ 'different UUID can share whole-LUN identity',
+ );
+ }
+ is_deeply(
+ \@resolved,
+ ['/dev/dm-0', $alias],
+ 'different UUID still requires identity proof',
+ );
+ is_deeply(\@writes, [], 'guard performs no writes');
+ }
+
+ for my $flag (undef, [], {}, 'maybe') {
+ reset_case();
+ my $pv = {
+ pv_name => '/dev/other',
+ vg_name => '[unknown]',
+ pv_uuid => $pv_uuid,
+ };
+ $pv->{pv_in_use} = $flag if defined($flag);
+ $report = encode_json({ report => [{ pv => [$pv] }] });
+ like(
+ check(),
+ qr/malformed PV/,
+ 'sentinel does not excuse a malformed or missing use flag',
+ );
+ is_deeply(\@writes, [], 'malformed use flag causes no writes');
+ }
+ for my $vg ('[missing]', '[UNKNOWN]', 'bad/name') {
+ reset_case();
+ $report = encode_json({
+ report => [{
+ pv => [{
+ pv_name => '/dev/other',
+ vg_name => $vg,
+ pv_uuid => $pv_uuid,
+ pv_in_use => '0',
+ }],
+ }],
+ });
+ like(check(), qr/malformed PV/, "unrecognized VG '$vg' still fails closed");
+ }
+ reset_case();
+ $report = encode_json({
+ report => [{
+ pv => [{
+ pv_name => '[unknown]',
+ vg_name => '[unknown]',
+ pv_uuid => $pv_uuid,
+ pv_in_use => '1',
+ }],
+ }],
+ });
+ like(check(), qr/malformed PV/, 'missing-device spelling is not a supported VG sentinel');
+
+ reset_case();
+ $cfg->{ids}->{lvm} = { type => 'lvm', vgname => 'unknown' };
+ $signatures->{'/dev/dm-0'} = encode_json({
+ signatures => [{ type => 'LVM2_member', uuid => $pv_uuid }],
+ });
+ $report = encode_json({
+ report => [{
+ pv => [{
+ pv_name => '/dev/missing',
+ vg_name => 'unknown',
+ pv_uuid => $pv_uuid,
+ pv_in_use => '1',
+ }],
+ }],
+ });
+ like(
+ check(),
+ qr/volume group 'unknown' is used by storage 'lvm'/,
+ 'unknown is a valid VG name',
+ );
+ is_deeply(\@resolved, ['/dev/dm-0'], 'named VG UUID proof also precedes resolution');
+};
+
+reset_case();
+$readiness_error = 1;
+like(check(), qr/no usable path/, 'readiness refusal propagates');
+is_deeply(\@probed, [], 'no direct signature probe after path loss');
+ok(!$ready, 'pvs is not reached after path loss');
+
+$storage->unmock('san_device_identity');
+my $root = tempdir(CLEANUP => 1);
+my sub put {
+ my ($name, $file, $value) = @_;
+ my $dir = "$root/class/block/$name";
+ make_path("$dir/holders", "$dir/dm", "$dir/device");
+ open(my $fh, '>', "$dir/$file") or die $!;
+ print $fh "$value\n";
+ close($fh) or die $!;
+}
+put('dm-0', 'dev', '253:0');
+put('dm-0', 'dm/uuid', 'mpath-test');
+put('sda', 'dev', '8:0');
+$disk->mock(
+ verify_blockdev_path => sub { $_[0] },
+ is_partition => sub { 0 },
+ is_san_device => sub { 1 },
+);
+$identity->mock(path_wwid => sub { 'test' });
+my $ids = { luns => { one => { target => 'iqn.test', wwid => 'test' } } };
+is(
+ PVE::Storage::san_device_identity('/dev/dm-0', $ids, $root)->{key},
+ 'scsi:test',
+ 'map UUID identity',
+);
+is(
+ PVE::Storage::san_device_identity('/dev/sda', $ids, $root)->{key},
+ 'scsi:test',
+ 'single path identity',
+);
+symlink('../../dm-0', "$root/class/block/sda/holders/dm-0") or die $!;
+eval { PVE::Storage::san_device_identity('/dev/sda', $ids, $root) };
+like($@, qr/member path/, 'member cannot be wiped');
+is(
+ PVE::Storage::san_device_identity('/dev/sda', $ids, $root, 1)->{key},
+ 'scsi:test',
+ 'member-named reference resolves',
+);
+$disk->mock(is_partition => sub { $_[0] eq '/dev/sda1' }, get_blockdev => sub { '/dev/sda' });
+eval { PVE::Storage::san_device_identity('/dev/sda1', $ids, $root) };
+like($@, qr/member path/, 'partition of member cannot be wiped');
+$disk->mock(is_partition => sub { 0 });
+put('nvme0n1', 'dev', '259:0');
+put('nvme0n1', 'wwid', 'eui.test');
+# padded, as some controllers report it
+put('nvme0n1', 'device/subsysnqn', 'nqn.test ');
+my $ns =
+ PVE::Storage::san_device_identity('/dev/nvme0n1', sub { die 'unexpected SCSI probe' }, $root);
+is($ns->{key}, 'nvme:eui.test', 'native namespace identity');
+is($ns->{subsystem}, 'nqn.test', 'native subsystem attribution');
+
+# Offload initiators can run sessions to several targets on one SCSI host. Through the real
+# collectors, only the LUN of the target that serves disk images is refused, not its peer.
+{
+ my $sys = tempdir(CLEANUP => 1);
+ local $PVE::Multipath::Identity::SYSFS = $sys;
+ local $PVE::Storage::ISCSIPlugin::SYSFS = $sys;
+ my sub write_file {
+ my ($path, $value) = @_;
+ make_path("$sys/$path" =~ s|/[^/]+$||r);
+ open(my $fh, '>', "$sys/$path") or die $!;
+ print $fh "$value\n";
+ close($fh) or die $!;
+ }
+ my $lines = {};
+ for my $lun (
+ [1, 'iqn.images', '9:0:0:1', 'sdx', '8:240', '2EUIX'],
+ [2, 'iqn.other', '9:0:1:2', 'sdy', '65:0', '2EUIY'],
+ ) {
+ my ($sid, $target, $hctl, $name, $devt, $wwid) = @$lun;
+ my ($scsi_target) = $hctl =~ m/^(\d+:\d+:\d+):/;
+ my $session = "devices/platform/host9/session$sid";
+ my $dir = "$session/target$scsi_target/$hctl";
+ write_file("class/iscsi_session/session$sid/targetname", $target);
+ symlink("$sys/$session", "$sys/class/iscsi_session/session$sid/device") or die $!;
+ write_file("$dir/type", '0');
+ write_file("$dir/block/$name/dev", $devt);
+ make_path("$sys/$dir/block/$name/holders", "$sys/bus/scsi/devices", "$sys/class/block");
+ symlink("$sys/$dir", "$sys/bus/scsi/devices/$hctl") or die $!;
+ symlink("$sys/$dir", "$sys/$dir/block/$name/device") or die $!;
+ symlink("$sys/$dir/block/$name", "$sys/class/block/$name") or die $!;
+ $lines->{$name} =
+ { devt => $devt, hctl => $hctl, init => 'ok', target => $target, wwid => $wwid };
+ }
+ $readiness_error = 0;
+ $identity->unmock($_) for grep { $identity->is_mocked($_) } qw(collect path_wwid);
+ $iscsi->unmock('iscsi_session_device_map');
+ my $multipath = Test::MockModule->new('PVE::Multipath');
+ $multipath->mock(query_path_identities => sub { $lines });
+ $disk->mock(
+ verify_blockdev_path => sub { $_[0] },
+ is_partition => sub { 0 },
+ is_san_device => sub { 1 },
+ );
+ my $san_identity = \&PVE::Storage::san_device_identity;
+ $storage->mock(
+ san_device_identity => sub { $san_identity->($_[0], $_[1], $sys, $_[3]) },
+ run_command => sub {
+ my ($cmd, %opt) = @_;
+ $opt{outfunc}
+ ->($cmd->[0] eq 'wipefs' ? '{"signatures":[]}' : '{"report":[{"pv":[]}]}');
+ },
+ );
+ my $cfg = {
+ ids =>
+ { img => { type => 'iscsi', target => 'iqn.images', content => { images => 1 } } },
+ };
+ eval { PVE::Storage::assert_san_write_safe($cfg, '/dev/sdx', []) };
+ like(
+ $@,
+ qr/storage 'img' serves disk images from this target/,
+ 'shared host: the LUN of the image target is refused',
+ );
+ eval { PVE::Storage::assert_san_write_safe($cfg, '/dev/sdy', []) };
+ is($@, '', 'shared host: the LUN of the other target is not');
+}
+
+# A session device without an identity, for example of a LUN that multipathd is configured to
+# ignore, stops writes to another LUN unless its VPD page proves that it is another one.
+{
+ my $sys = tempdir(CLEANUP => 1);
+ local $PVE::Multipath::Identity::SYSFS = $sys;
+ local $PVE::Storage::ISCSIPlugin::SYSFS = $sys;
+ my sub write_file {
+ my ($path, $value) = @_;
+ make_path("$sys/$path" =~ s|/[^/]+$||r);
+ open(my $fh, '>', "$sys/$path") or die $!;
+ print $fh $value;
+ close($fh) or die $!;
+ }
+ my sub naa_page {
+ return pack('C C n', 0, 0x83, 20) . pack('C C x C', 1, 3, 16) . pack('H*', $_[0]);
+ }
+ my ($W, $V) = ('600a09803832355367242f747a716b7a', '600a09803832355367242f747a716c30');
+ my $lines = {};
+ for my $lun (
+ [1, 'iqn.data', '10:0:0:1', 'sdv', '65:16', "3$W"],
+ [2, 'iqn.ignored', '10:0:1:2', 'sdw', '65:32', undef],
+ ) {
+ my ($sid, $target, $hctl, $name, $devt, $wwid) = @$lun;
+ my ($scsi_target) = $hctl =~ m/^(\d+:\d+:\d+):/;
+ my $session = "devices/platform/host10/session$sid";
+ my $dir = "$session/target$scsi_target/$hctl";
+ write_file("class/iscsi_session/session$sid/targetname", "$target\n");
+ symlink("$sys/$session", "$sys/class/iscsi_session/session$sid/device") or die $!;
+ write_file("$dir/type", "0\n");
+ write_file("$dir/block/$name/dev", "$devt\n");
+ make_path("$sys/$dir/block/$name/holders", "$sys/bus/scsi/devices", "$sys/class/block");
+ symlink("$sys/$dir", "$sys/bus/scsi/devices/$hctl") or die $!;
+ symlink("$sys/$dir", "$sys/$dir/block/$name/device") or die $!;
+ symlink("$sys/$dir/block/$name", "$sys/class/block/$name") or die $!;
+ $lines->{$name} =
+ { devt => $devt, hctl => $hctl, init => 'ok', target => $target, wwid => $wwid }
+ if defined($wwid);
+ }
+ write_file('bus/scsi/devices/10:0:0:1/vpd_pg83', naa_page($W));
+ my $multipath = Test::MockModule->new('PVE::Multipath');
+ $multipath->mock(query_path_identities => sub { $lines });
+ my $san_identity = $storage->original('san_device_identity');
+ $storage->mock(
+ san_device_identity => sub { $san_identity->($_[0], $_[1], $sys, $_[3]) },
+ run_command => sub {
+ my ($cmd, %opt) = @_;
+ $opt{outfunc}
+ ->($cmd->[0] eq 'wipefs' ? '{"signatures":[]}' : '{"report":[{"pv":[]}]}');
+ },
+ );
+ my $write = sub {
+ eval { PVE::Storage::assert_san_write_safe({ ids => {} }, '/dev/sdv', []) };
+ return $@;
+ };
+ like(
+ $write->(),
+ qr/the identity of 'sdw' could not be verified/,
+ 'unidentified session device: refused without a VPD page',
+ );
+ write_file('bus/scsi/devices/10:0:1:2/vpd_pg83', naa_page($W));
+ like(
+ $write->(),
+ qr/the identity of 'sdw' could not be verified/,
+ 'unidentified session device: refused if it names the NAA of the LUN',
+ );
+ write_file('bus/scsi/devices/10:0:1:2/vpd_pg83', naa_page($V));
+ is($write->(), '', 'unidentified session device: not if it names the NAA of another LUN');
+ $lines->{sdv}->{wwid} = '2EUIV';
+ like(
+ $write->(),
+ qr/the identity of 'sdw' could not be verified/,
+ 'unidentified session device: refused for a LUN without an NAA WWID',
+ );
+ $lines->{sdv}->{wwid} = "3$W";
+ $lines->{sdw} = { devt => '65:32', hctl => '10:0:1:2', init => 'ok', wwid => "3$W" };
+ like(
+ $write->(),
+ qr/the identity of 'sdw' could not be verified/,
+ 'unidentified session device: refused if the daemon names it, with an identity that did not'
+ . ' resolve',
+ );
+ delete $lines->{sdw};
+
+ # a session device that only the strict walk of the sessions finds
+ my $collect = \&PVE::Multipath::Identity::collect;
+ $identity->mock(
+ collect => sub {
+ my $result = $collect->(@_);
+ delete $result->{paths}->{sdw};
+ for my $key (keys $result->{luns}->%*) {
+ delete $result->{luns}->{$key}
+ if grep { $_ eq 'sdw' } ($result->{luns}->{$key}->{paths} // [])->@*;
+ }
+ return $result;
+ },
+ );
+ like(
+ $write->(),
+ qr/the identity of 'sdw' could not be verified/,
+ 'unidentified session device: refused if only the strict session walk finds it',
+ );
+ $identity->unmock('collect');
+
+ delete $lines->{sdv};
+ like($write->(), qr/unresolved LUN identity/, 'unidentified device to write: refused');
+ eval { $san_identity->('/dev/sdv', $collect->(all => 1), $sys, 1) };
+ like($@, qr/unresolved LUN identity/, 'unidentified reference: refused as a member, too');
+}
+
+done_testing();
diff --git a/src/test/run_test_lvm_base_volume.pl b/src/test/run_test_lvm_base_volume.pl
index 208e7668..d16c0f70 100755
--- a/src/test/run_test_lvm_base_volume.pl
+++ b/src/test/run_test_lvm_base_volume.pl
@@ -28,8 +28,14 @@ $storage->mock(
},
);
+my $diskmanage = Test::MockModule->new('PVE::Diskmanage');
+$diskmanage->mock(verify_blockdev_path => sub { $_[0] });
+
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
-$lvm->mock(lvm_create_volume_group => sub { push @calls, 'lvm_create_volume_group' });
+$lvm->mock(
+ assert_whole_lun => sub { },
+ lvm_create_volume_group => sub { push @calls, 'lvm_create_volume_group' },
+);
my $scfg = { base => 'san:0.0.0.scsi-test', vgname => 'vg', shared => 1 };
diff --git a/src/test/run_wipe_partition_tests.pl b/src/test/run_wipe_partition_tests.pl
index 29ba74a2..3faa6032 100755
--- a/src/test/run_wipe_partition_tests.pl
+++ b/src/test/run_wipe_partition_tests.pl
@@ -16,7 +16,7 @@ my $disk = Test::MockModule->new('PVE::Diskmanage');
my $tools = Test::MockModule->new('PVE::Tools');
my $users = \&PVE::Diskmanage::block_device_users;
my $parts = \&PVE::Diskmanage::wipe_partitions;
-my (@commands, $drop_kernel);
+my (@commands, $remove_error, $new_holder, $new_opener, $drop_kernel);
my sub put {
my ($path, $value) = @_;
my ($dir) = "$root/$path" =~ m{^(.*)/[^/]+$};
@@ -33,45 +33,139 @@ my sub device {
}
my sub reset_case {
remove_tree("$root/sys", "$root/proc");
- device('sda', '8:0', '');
- device('sda1', '8:1', '');
- put('sys/class/block/sda1/partition', '1');
- symlink('../sda1', "$root/sys/class/block/sda/sda1") or die $!;
+ device('dm-0', '253:0', 'mpath-test');
+ device('dm-1', '253:1', 'part1-mpath-test');
+ symlink('../../dm-1', "$root/sys/class/block/dm-0/holders/dm-1") or die $!;
put('proc/self/mountinfo', '1 0 0:1 / / rw - rootfs rootfs rw');
put('proc/swaps', "Filename\tType\tSize\tUsed\tPriority");
@commands = ();
- $drop_kernel = 0;
+ ($remove_error, $new_holder, $new_opener, $drop_kernel) = (0, 0, 0, 0);
}
$disk->mock(
wipe_partitions => sub { $parts->($_[0], "$root/sys") },
block_device_users => sub {
$users->($_[0], { %{ $_[1] // {} }, sysfs => "$root/sys", procfs => "$root/proc" });
},
- block_device_number => sub { '8:1' },
+ block_device_number => sub {
+ my ($path) = @_;
+ my $target = -l $path ? readlink($path) : $path;
+ return $target eq '/dev/dm-0' ? '253:0' : '253:1';
+ },
is_partition => sub { 0 },
dir_glob_foreach => sub { },
run_command => sub {
my ($cmd) = @_;
push @commands, $cmd;
- if ($drop_kernel && $cmd->[0] eq 'wipefs' && $cmd->[-1] eq '/dev/sda') {
- unlink("$root/sys/class/block/sda/sda1") or die $!;
+ if ($drop_kernel && $cmd->[0] eq 'wipefs' && $cmd->[-1] eq '/dev/dm-0') {
+ unlink("$root/sys/class/block/dm-0/sda1") or die $!;
+ }
+ if ($cmd->[0] eq 'dmsetup') {
+ die "remove failed\n" if $remove_error;
+ unlink("$root/sys/class/block/dm-0/holders/dm-1") or die $!;
+ if ($new_holder) {
+ device('dm-2', '253:2', 'LVM-test');
+ symlink('../../dm-2', "$root/sys/class/block/dm-0/holders/dm-2") or die $!;
+ }
+ if ($new_opener) {
+ make_path("$root/proc/999998/fd");
+ symlink('/dev/dm-0', "$root/proc/999998/fd/3") or die $!;
+ put('proc/999998/comm', 'qemu');
+ }
}
},
);
$tools->mock(file_get_contents => sub { "8192\n" });
+my sub wipe {
+ eval {
+ PVE::Diskmanage::wipe_blockdev(
+ '/dev/dm-0',
+ PVE::Diskmanage::wipe_partitions('/dev/dm-0'),
+ );
+ };
+ return $@;
+}
reset_case();
+is_deeply(PVE::Diskmanage::wipe_partitions('/dev/dm-0'), ['dm-1'], 'exact kpartx child');
+is(wipe(), '', 'unused partition map can be wiped');
+is_deeply(
+ \@commands,
+ [
+ ['wipefs', '--all', '/dev/dm-1'],
+ ['dmsetup', 'remove', '--retry', '/dev/dm-1'],
+ ['wipefs', '--all', '/dev/dm-0'],
+ ['dd', 'if=/dev/zero', 'of=/dev/dm-0', 'bs=1M', 'conv=fdatasync', 'count=4'],
+ ],
+ 'child signatures erased while mapped, ordinary removal precedes parent writes',
+);
+for my $case (
+ [
+ 'mounted',
+ sub { put('proc/self/mountinfo', '1 0 253:1 / /mnt rw - ext4 /dev/dm-1 rw') },
+ qr/mounted/,
+ ],
+ [
+ 'open',
+ sub {
+ make_path("$root/proc/999999/fd");
+ symlink('/dev/dm-1', "$root/proc/999999/fd/3") or die $!;
+ put('proc/999999/comm', 'qemu');
+ },
+ qr/has dm-1 open/,
+ ],
+ [
+ 'foreign UUID',
+ sub { put('sys/class/block/dm-1/dm/uuid', 'part1-mpath-other') },
+ qr/held by/,
+ ],
+ ['opaque holder', sub { put('sys/class/block/dm-1/dm/uuid', 'LVM-test') }, qr/held by/],
+ [
+ 'missing UUID',
+ sub { unlink("$root/sys/class/block/dm-1/dm/uuid") or die $! },
+ qr/unable to identify/,
+ ],
+) {
+ reset_case();
+ $case->[1]->();
+ like(wipe(), $case->[2], "$case->[0] refuses");
+ is_deeply(\@commands, [], "$case->[0]: no writes");
+}
+reset_case();
+$remove_error = 1;
+like(wipe(), qr/remove failed/, 'failed child removal refuses');
+is(scalar(@commands), 2, 'parent untouched after failed removal');
+reset_case();
+$new_holder = 1;
+like(wipe(), qr/held by dm-2/, 'new holder refuses');
+is(scalar(@commands), 2, 'parent untouched after unexpected holder');
+reset_case();
+$new_opener = 1;
+like(wipe(), qr/has dm-0 open/, 'a process opening the parent meanwhile refuses');
+is(scalar(@commands), 2, 'parent untouched after a new opener');
+reset_case();
+device('dm-2', '253:2', 'part2-mpath-test');
+symlink('../../dm-2', "$root/sys/class/block/dm-1/holders/dm-2") or die $!;
+is_deeply(PVE::Diskmanage::wipe_partitions('/dev/dm-0'), ['dm-2', 'dm-1'], 'recursive postorder');
+put('proc/self/mountinfo', '1 0 253:2 / /nested rw - ext4 /dev/dm-2 rw');
+like(wipe(), qr/dm-2 mounted/, 'nested child mount refuses');
+is_deeply(\@commands, [], 'nested users checked before any write');
+
+reset_case();
+unlink("$root/sys/class/block/dm-0/holders/dm-1") or die $!;
+device('sda1', '8:1', '');
+put('sys/class/block/sda1/partition', '1');
+symlink('../sda1', "$root/sys/class/block/dm-0/sda1") or die $!;
$drop_kernel = 1;
my $removed_kernel;
eval {
PVE::Diskmanage::wipe_blockdev(
- '/dev/sda',
+ '/dev/dm-0',
['sda1'],
{
verify => sub {
$removed_kernel = $_[0]->{sda1};
my $expected = $removed_kernel ? [] : ['sda1'];
is_deeply(
- PVE::Diskmanage::wipe_partitions('/dev/sda'),
+ PVE::Diskmanage::wipe_partitions('/dev/dm-0'),
$expected,
'kernel partition topology matches deliberate removals',
);
@@ -97,11 +191,11 @@ $disk->mock(
);
my @verified;
PVE::Diskmanage::wipe_blockdev(
- '/dev/sda',
- ['sda1'],
+ '/dev/dm-0',
+ ['dm-1'],
{
handle => $parent,
- children => { 'sda1' => { stamp => 'test', dm_uuid => 'part1-mpath-test' } },
+ children => { 'dm-1' => { stamp => 'test', dm_uuid => 'part1-mpath-test' } },
verify => sub { push @verified, { %{ $_[0] } } },
},
);
@@ -112,11 +206,182 @@ is_deeply(
);
is_deeply(
$commands[1],
+ ['dmsetup', 'remove', '--retry', '--uuid', 'part1-mpath-test'],
+ 'remove selects verified UUID, not reusable dm name',
+);
+is_deeply(
+ $commands[2],
['wipefs', '--all', "/proc/$$/fd/$parent_fd"],
'parent signatures use retained descriptor',
);
-like($commands[2]->[2], qr{^of=/proc/$$/fd/$parent_fd$}, 'zeroing uses retained descriptor');
+like($commands[3]->[2], qr{^of=/proc/$$/fd/$parent_fd$}, 'zeroing uses retained descriptor');
ok(@verified >= 4, 'topology verified between destructive commands');
-is_deeply($verified[-1], {}, 'unchanged kernel partitions remain verified');
+is_deeply($verified[-1], { 'dm-1' => 1 }, 'removed children excluded from later verification');
+
+reset_case();
+$disk->mock(verify_blockdev_path => sub { $_[0] });
+is_deeply(
+ PVE::Diskmanage::block_device_usage_hint('/dev/dm-0'),
+ { 'in-use' => 'no', 'in-use-by' => '' },
+ 'unused kpartx children are not users',
+);
+put('sys/class/block/dm-0/dm/name', 'array-lun');
+put('sys/class/block/dm-1/dm/name', 'array-lun-part1');
+put('proc/self/mountinfo', '1 0 253:1 / /mounted\\040data rw - ext4 /dev/dm-1 rw');
+is_deeply(
+ PVE::Diskmanage::block_device_usage_hint('/dev/dm-0'),
+ { 'in-use' => 'yes', 'in-use-by' => 'array-lun-part1 mounted at /mounted data' },
+ 'hint includes named child mounts',
+);
+put('proc/self/mountinfo', '1 0 0:1 / / rw - rootfs rootfs rw');
+device('dm-2', '253:2', 'LVM-test');
+put('sys/class/block/dm-2/dm/name', 'vg-data');
+symlink('../../dm-2', "$root/sys/class/block/dm-1/holders/dm-2") or die $!;
+is_deeply(
+ PVE::Diskmanage::block_device_usage_hint('/dev/dm-0'),
+ { 'in-use' => 'yes', 'in-use-by' => 'array-lun-part1 held by vg-data' },
+ 'hint names non-partition holders below kpartx children',
+);
+like(wipe(), qr/array-lun-part1 held by vg-data/, 'worker refusal names dm holders too');
+unlink("$root/sys/class/block/dm-2/dm/name") or die $!;
+like(
+ PVE::Diskmanage::block_device_usage_hint('/dev/dm-0')->{'in-use-by'},
+ qr/held by dm-2/,
+ 'kernel-name fallback for missing dm name',
+);
+unlink("$root/sys/class/block/dm-1/holders/dm-2") or die $!;
+put('proc/swaps', 'deliberately invalid');
+make_path("$root/proc/999999/fd");
+symlink('/dev/dm-1', "$root/proc/999999/fd/3") or die $!;
+is(
+ PVE::Diskmanage::block_device_usage_hint('/dev/dm-0')->{'in-use'},
+ 'no',
+ 'hint excludes swap and process descriptor probes',
+);
+put('proc/self/mountinfo', 'invalid');
+is(
+ PVE::Diskmanage::block_device_usage_hint('/dev/dm-0')->{'in-use'},
+ 'unknown',
+ 'failed metadata probe is not an unused result',
+);
+
+# the paths of a map count with 'map-wwid', for example a logical volume that LVM activated on a
+# path before the map existed
+reset_case();
+put('sys/class/block/sdb/dev', '8:16');
+make_path("$root/sys/class/block/sdb/holders", "$root/sys/class/block/dm-0/slaves");
+symlink('../../sdb', "$root/sys/class/block/dm-0/slaves/sdb") or die $!;
+symlink('../../dm-0', "$root/sys/class/block/sdb/holders/dm-0") or die $!;
+my sub map_hint {
+ my ($wwid) = @_;
+ return PVE::Diskmanage::block_device_usage_hint(
+ '/dev/dm-0',
+ { 'map-wwid' => $wwid // 'test', sysfs => "$root/sys" },
+ );
+}
+is_deeply(
+ map_hint(),
+ { 'in-use' => 'no', 'in-use-by' => '' },
+ 'map paths: held by the map only, with unused kpartx children',
+);
+device('dm-3', '253:3', 'LVM-other');
+put('sys/class/block/dm-3/dm/name', 'oldvg-data');
+symlink('../../dm-3', "$root/sys/class/block/sdb/holders/dm-3") or die $!;
+is_deeply(
+ map_hint(),
+ { 'in-use' => 'yes', 'in-use-by' => 'sdb held by oldvg-data' },
+ 'map paths: a logical volume on a path is a user',
+);
+is(
+ PVE::Diskmanage::block_device_usage_hint('/dev/dm-0')->{'in-use'},
+ 'no',
+ 'map paths: not looked at without the WWID of the map',
+);
+is(map_hint('other')->{'in-use'}, 'unknown', 'map paths: unknown for a map of another WWID');
+unlink("$root/sys/class/block/sdb/holders/dm-3") or die $!;
+put('proc/self/mountinfo', '1 0 8:16 / /raw rw - ext4 /dev/sdb rw');
+is(map_hint()->{'in-use-by'}, 'sdb mounted at /raw', 'map paths: a mounted path is a user');
+put('proc/self/mountinfo', '1 0 0:1 / / rw - rootfs rootfs rw');
+remove_tree("$root/sys/class/block/sdb");
+is(map_hint()->{'in-use'}, 'unknown', 'map paths: unknown when a path goes away meanwhile');
+device('dm-4', '253:4', 'LVM-map');
+put('sys/class/block/dm-4/dm/name', 'vg-map');
+symlink('../../dm-4', "$root/sys/class/block/dm-0/holders/dm-4") or die $!;
+is_deeply(
+ map_hint(),
+ { 'in-use' => 'yes', 'in-use-by' => 'dm-0 held by vg-map' },
+ 'map paths: a user of the map stays one if the check of a path fails',
+);
+
+# the map changes while its paths are checked
+my $during;
+my sub path_check_mock {
+ $disk->mock(
+ block_device_users => sub {
+ my $found =
+ $users->($_[0], { %{ $_[1] // {} }, sysfs => "$root/sys", procfs => "$root/proc" });
+ $during->() if $during && grep { $_ eq 'sdb' } $_[0]->@*;
+ return $found;
+ },
+ );
+}
+path_check_mock();
+reset_case();
+put('sys/class/block/sdb/dev', '8:16');
+make_path("$root/sys/class/block/sdb/holders", "$root/sys/class/block/dm-0/slaves");
+symlink('../../sdb', "$root/sys/class/block/dm-0/slaves/sdb") or die $!;
+symlink('../../dm-0', "$root/sys/class/block/sdb/holders/dm-0") or die $!;
+$during = sub {
+ put('sys/class/block/sdc/dev', '8:32');
+ make_path("$root/sys/class/block/sdc/holders");
+ symlink('../../sdc', "$root/sys/class/block/dm-0/slaves/sdc");
+ symlink('../../dm-0', "$root/sys/class/block/sdc/holders/dm-0");
+ device('dm-5', '253:5', 'LVM-new');
+ put('sys/class/block/dm-5/dm/name', 'vg-new');
+ symlink('../../dm-5', "$root/sys/class/block/sdc/holders/dm-5");
+};
+like(
+ map_hint()->{'in-use-by'},
+ qr/^check failed: the paths of 'dm-0' changed/,
+ 'map paths: unknown if a path is added during the check',
+);
+$during = undef;
+is(map_hint()->{'in-use-by'}, 'sdc held by vg-new', 'map paths: and its user found the next time');
+unlink("$root/sys/class/block/sdc/holders/dm-5") or die $!;
+$during = sub { put('sys/class/block/dm-0/dm/uuid', 'mpath-other') };
+like(
+ map_hint()->{'in-use-by'},
+ qr/^check failed: 'dm-0' is not the multipath map of 'test'/,
+ 'map paths: unknown if the map changes its identity during the check',
+);
+$during = undef;
+# a user on one path stays one if the check of another path fails
+reset_case();
+put('sys/class/block/sdb/dev', '8:16');
+make_path("$root/sys/class/block/sdb/holders", "$root/sys/class/block/dm-0/slaves");
+symlink('../../sdb', "$root/sys/class/block/dm-0/slaves/sdb") or die $!;
+symlink('../../dm-0', "$root/sys/class/block/sdb/holders/dm-0") or die $!;
+device('dm-3', '253:3', 'LVM-other');
+put('sys/class/block/dm-3/dm/name', 'oldvg-data');
+symlink('../../dm-3', "$root/sys/class/block/sdb/holders/dm-3") or die $!;
+symlink('../../sdc', "$root/sys/class/block/dm-0/slaves/sdc") or die $!;
+is_deeply(
+ map_hint(),
+ { 'in-use' => 'yes', 'in-use-by' => 'sdb held by oldvg-data' },
+ 'map paths: a user of a path stays one if the check of another path fails',
+);
+$disk->mock(
+ block_device_users => sub {
+ $users->($_[0], { %{ $_[1] // {} }, sysfs => "$root/sys", procfs => "$root/proc" });
+ },
+);
+
+@commands = ();
+PVE::Diskmanage::udevadm_trigger('/dev/dm-0', '/dev/sda1');
+is_deeply(
+ \@commands,
+ [['udevadm', 'trigger', '--settle', '/dev/dm-0', '/dev/sda1']],
+ 'device-specific trigger waits for udev processing',
+);
done_testing();
diff --git a/src/test/run_wipe_readiness_tests.pl b/src/test/run_wipe_readiness_tests.pl
new file mode 100755
index 00000000..ef5977a3
--- /dev/null
+++ b/src/test/run_wipe_readiness_tests.pl
@@ -0,0 +1,138 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use File::Path qw(make_path remove_tree);
+use File::Temp qw(tempdir);
+use Test::MockModule;
+use Test::More;
+
+use lib ('.', '..');
+use PVE::Diskmanage;
+use PVE::Multipath;
+use PVE::Multipath::Identity;
+
+my $root = tempdir(CLEANUP => 1);
+my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $mp = Test::MockModule->new('PVE::Multipath');
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
+my ($ids, $maps, $nvme);
+my sub put {
+ my ($path, $value) = @_;
+ my ($dir) = "$root/$path" =~ m{^(.*)/[^/]+$};
+ make_path($dir);
+ open(my $fh, '>', "$root/$path") or die $!;
+ print $fh "$value\n";
+ close($fh) or die $!;
+}
+my sub device {
+ my ($name, $number) = @_;
+ put("sys/class/block/$name/dev", $number);
+ put("sys/class/block/$name/size", '8192');
+ make_path("$root/sys/class/block/$name/holders");
+}
+$disk->mock(
+ is_partition => sub { 0 },
+ is_san_device => sub { 1 },
+ get_nvme_path_status => sub { $nvme },
+ block_device_number => sub { '8:16' },
+);
+$mp->mock(get_maps => sub { $maps });
+my %other_lun;
+$identity->mock(
+ collect => sub { $ids },
+ path_wwid => sub { $_[0]->{paths}->{ $_[1] }->{wwid} },
+ path_is_other_lun => sub { $other_lun{ $_[1] } && $_[2] eq 'test' },
+);
+my sub reset_case {
+ remove_tree("$root/sys", "$root/proc");
+ device('sda', '8:0');
+ put('sys/class/block/sda/device/state', 'running');
+ $ids = { paths => { sda => { wwid => 'test' } } };
+ $maps = [];
+ $nvme = {};
+ put('proc/self/mountinfo', '1 0 0:1 / / rw - rootfs rootfs rw');
+ put('proc/swaps', "Filename\tType\tSize\tUsed\tPriority");
+}
+my sub check {
+ my ($dev) = @_;
+ eval {
+ PVE::Diskmanage::assert_block_device_ready(
+ "/dev/$dev",
+ { sysfs => "$root/sys", procfs => "$root/proc" },
+ );
+ };
+ return $@;
+}
+reset_case();
+is(check('sda'), '', 'single running path needs no path count');
+put('sys/class/block/sda/device/state', 'offline');
+like(check('sda'), qr/not running/, 'offline single path refuses');
+put('sys/class/block/sda/device/state', 'running');
+device('sdb', '8:16');
+$ids->{paths}->{sdb} = { wwid => 'test' };
+like(check('sda'), qr/multiple paths/, 'unmapped same-identity sibling refuses');
+$ids->{paths}->{sdb}->{wwid} = 'other';
+is(check('sda'), '', 'different identity is not a sibling');
+# a local disk that multipathd does not list
+$ids->{paths}->{sdz} = { wwid => undef };
+like(
+ check('sda'),
+ qr/cannot exclude 'sdz' as another path of this LUN/,
+ 'path without identity refuses',
+);
+$other_lun{sdz} = 1;
+is(check('sda'), '', 'path without identity that is provably another LUN does not');
+delete $ids->{paths}->{sdz};
+$ids->{paths}->{sdb}->{wwid} = 'test';
+device('dm-0', '253:0');
+put('sys/class/block/dm-0/dm/uuid', 'mpath-test');
+make_path("$root/sys/class/block/dm-0/slaves");
+symlink('../../sda', "$root/sys/class/block/dm-0/slaves/sda") or die $!;
+symlink('../../dm-0', "$root/sys/class/block/sda/holders/dm-0") or die $!;
+my $path = { dev => 'sda', 'dm-state' => 'active', 'check-state' => 'ready' };
+$maps = [{ sysfs => 'dm-0', wwid => 'test', 'path-groups' => [{ paths => [$path] }] }];
+is(check('dm-0'), '', 'map with current usable path allowed');
+
+for my $state ('faulty', 'unchecked', 'shaky') {
+ $path->{'check-state'} = $state;
+ like(check('dm-0'), qr/no usable path/, "$state checker refuses despite SCSI running");
+}
+$path->{'check-state'} = 'ready';
+$path->{'dm-state'} = 'failed';
+like(check('dm-0'), qr/no usable path/, 'failed dm path refuses');
+$path->{'dm-state'} = 'active';
+$maps->[0]->{wwid} = 'other';
+like(check('dm-0'), qr/no usable path/, 'daemon map identity must match sysfs');
+$maps->[0]->{wwid} = 'test';
+make_path("$root/proc/999999/fd");
+symlink('/dev/sdb', "$root/proc/999999/fd/3") or die $!;
+put('proc/999999/comm', 'qemu');
+like(check('dm-0'), qr/qemu .* has sdb open/, 'raw open of unmapped sibling refuses map wipe');
+symlink('../../sdb', "$root/sys/class/block/dm-0/slaves/sdb") or die $!;
+symlink('../../dm-0', "$root/sys/class/block/sdb/holders/dm-0") or die $!;
+like(check('dm-0'), qr/qemu .* has sdb open/, 'raw open of map member refuses');
+symlink('/usr/sbin/multipathd', "$root/proc/999999/exe") or die $!;
+is(check('dm-0'), '', 'only multipathd checker descriptors excluded');
+unlink("$root/proc/999999/exe") or die $!;
+symlink('/usr/bin/qemu', "$root/proc/999999/exe") or die $!;
+like(check('dm-0'), qr/has sdb open/, 'other executables remain users');
+reset_case();
+device('nvme0n1', '259:0');
+put('sys/class/block/nvme0n1/wwid', 'eui.0123456789abcdef');
+put('sys/class/block/nvme0n1/device/state', 'live');
+is(check('nvme0n1'), '', 'single live NVMe controller needs no path count');
+$nvme = { nvme0n1 => { active => 0 } };
+like(
+ check('nvme0n1'),
+ qr/no usable path/,
+ 'native head with no ANA-usable path refuses despite live state',
+);
+$nvme->{nvme0n1}->{active} = 1;
+is(check('nvme0n1'), '', 'ANA-usable native head allowed');
+device('nvme1n1', '259:1');
+put('sys/class/block/nvme1n1/wwid', 'eui.0123456789abcdef');
+like(check('nvme0n1'), qr/multiple devices/, 'uncoalesced same-identity NVMe namespaces refuse');
+
+done_testing();
diff --git a/src/test/run_wipe_reference_tests.pl b/src/test/run_wipe_reference_tests.pl
index 610cb691..c47f7c00 100755
--- a/src/test/run_wipe_reference_tests.pl
+++ b/src/test/run_wipe_reference_tests.pl
@@ -13,9 +13,11 @@ use PVE::API2::Disks;
my $root = tempdir(CLEANUP => 1);
my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $storage = Test::MockModule->new('PVE::Storage');
my $rpc = Test::MockModule->new('PVE::RPCEnvironment');
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
my $reference = \&PVE::Diskmanage::block_device_reference;
-my ($resolved, $worker, $locked, $written);
+my ($resolved, $worker, $locked, $probes, $written, $rebind);
my sub put {
my ($path, $value) = @_;
my ($dir) = "$root/$path" =~ m{^(.*)/[^/]+$};
@@ -24,8 +26,10 @@ my sub put {
print $fh "$value\n";
close($fh) or die $!;
}
-put('class/block/sda/dev', '8:0');
-put('class/block/sdb/dev', '8:16');
+for my $n (0, 1, 2) {
+ put("class/block/dm-$n/dev", "253:$n");
+ put("class/block/dm-$n/dm/uuid", $n == 2 ? 'mpath-other' : 'mpath-test:123');
+}
{
package ReferenceTestRPC;
@@ -40,17 +44,12 @@ $disk->mock(
ok($locked, 're-resolution occurs after locks') if $_[1];
$reference->($_[0], $_[1], $root);
},
- locked_disk_action => sub {
- $locked = 1;
- eval { $_[0]->() };
- my $err = $@;
- $locked = 0;
- die $err if $err;
- },
+ locked_disk_action => sub { $_[0]->() },
block_device_users => sub { [] },
- is_mounted => sub { undef },
- has_holder => sub { undef },
wipe_partitions => sub { [] },
+ is_san_device => sub { 1 },
+ is_multipath_device => sub { 1 },
+ assert_block_device_ready => sub { },
open_block_device => sub { \*STDOUT },
wipe_blockdev => sub {
$_[2]->{verify}->();
@@ -59,22 +58,89 @@ $disk->mock(
},
udevadm_trigger => sub { },
);
+$storage->mock(
+ config => sub { { ids => {} } },
+ lock_storage_config => sub {
+ local $@;
+ $locked = 1;
+ eval { $_[0]->() };
+ my $err = $@;
+ $locked = 0;
+ die $err if $err;
+ },
+ assert_san_write_safe => sub {
+ $probes++;
+ $resolved = $rebind == 2 ? '/dev/dm-1' : '/dev/dm-2' if $rebind;
+ },
+);
my $method = PVE::API2::Disks->map_method_by_name('wipe_disk')->{code};
my sub queue {
my ($path) = @_;
- $written = undef;
- $resolved = '/dev/sda';
+ ($probes, $written, $rebind) = (0, undef, 0);
+ $resolved = '/dev/dm-0';
$method->({ node => 'test', disk => $path });
}
-queue('/dev/sda');
+my $canonical = '/dev/disk/by-id/dm-uuid-mpath-test:123';
+queue($canonical);
+$resolved = '/dev/dm-1';
eval { $worker->() };
-is($@, '', 'delayed worker accepts the same device instance');
-is($written, '/dev/sda', 'worker uses the verified device');
-queue('/dev/sda');
-$resolved = '/dev/sdb';
+is($@, '', 'delayed worker accepts the same identity after renumbering');
+is($written, '/dev/dm-1', 'worker never uses the old reusable kernel name');
+for my $path ($canonical, '/dev/mapper/friendly') {
+ queue($path);
+ $resolved = '/dev/dm-2';
+ eval { $worker->() };
+ like($@, qr/identity (?:changed|does not match)/, 'rebound alias refuses');
+ is($probes, 0, 'rebound alias refuses before device-reading probes');
+ ok(!defined($written), 'rebound alias does not write');
+}
+queue($canonical);
+$rebind = 1;
eval { $worker->() };
-like($@, qr/identity changed/, 'rebound reference refuses');
-ok(!defined($written), 'rebound reference does not write');
+like($@, qr/identity does not match/, 'rebind during guard probes refuses');
+ok(!defined($written), 'rebind during guard probes does not write');
+queue($canonical);
+$rebind = 2;
+eval { $worker->() };
+is(
+ $@,
+ "cannot use '/dev/dm-0' - device topology changed\n",
+ 'shared instance check refuses same-identity replacement after probing',
+);
+ok(!defined($written), 'same-identity replacement during probes does not write');
+$resolved = '/dev/dm-2';
+eval { $method->({ node => 'test', disk => $canonical }) };
+like($@, qr/identity does not match/, 'canonical name verified at request time too');
+
+$disk->unmock('block_device_reference');
+put('class/block/nvme0n1/dev', '259:0');
+put('class/block/nvme0n1/wwid', 'eui.0123456789abcdef');
+$resolved = '/dev/nvme0n1';
+is(
+ $reference->('/dev/disk/by-id/nvme-eui.0123456789abcdef', undef, $root)->{key},
+ 'nvme:eui.0123456789abcdef',
+ 'NVMe canonical identity verified',
+);
+eval { $reference->('/dev/disk/by-id/nvme-eui.1111111111111111', undef, $root) };
+like($@, qr/identity does not match/, 'wrong NVMe identity refuses');
+put('class/block/sda/dev', '8:0');
+$identity->mock(collect => sub { {} }, path_wwid => sub { '3600abc' });
+$resolved = '/dev/sda';
+is(
+ $reference->('/dev/disk/by-id/scsi-3600abc', undef, $root)->{key},
+ 'scsi:3600abc',
+ 'SCSI by-id verified against live identity',
+);
+eval { $reference->('/dev/disk/by-id/scsi-3600def', undef, $root) };
+like($@, qr/identity does not match/, 'wrong SCSI identity refuses');
+
+is(
+ $reference->('/dev/disk/by-id/wwn-0x600abc', undef, $root)->{key},
+ 'scsi:3600abc',
+ 'WWN alias verified against NAA identity',
+);
+eval { $reference->('/dev/disk/by-id/wwn-0x600def', undef, $root) };
+like($@, qr/identity does not match/, 'wrong WWN refuses');
$disk->unmock('open_block_device');
put('handle', 'not a device');
@@ -86,6 +152,56 @@ my $handle = PVE::Diskmanage::open_block_device("$root/handle", '1:8:0');
ok(defined(fileno($handle)), 'matching opened reference retained');
close($handle) or die $!;
+$disk->unmock('block_device_stamp');
+my %links = (
+ '/dev/mapper/friendly' => '/dev/dm-0',
+ '/dev/disk/by-id/dm-uuid-mpath-test:123' => '/dev/dm-0',
+ '/dev/nvme0n1' => '/dev/nvme0n1',
+ '/dev/disk/by-id/nvme-eui.0123456789abcdef' => '/dev/nvme0n1',
+ '/dev/sda' => '/dev/sda',
+ '/dev/disk/by-id/scsi-3600abc' => '/dev/sda',
+);
+$disk->mock(verify_blockdev_path => sub { $links{ $_[0] } // die "missing link\n" });
+is(
+ PVE::Diskmanage::canonical_blockdev_link('/dev/mapper/friendly', {}, 'test:123', $root),
+ $canonical,
+ 'scan canonical map link comes from UUID, not the friendly name',
+);
+is(
+ PVE::Diskmanage::canonical_blockdev_link('/dev/mapper/friendly', {}, 'other', $root),
+ undef,
+ 'scan omits link when the map identity changed',
+);
+$links{$canonical} = '/dev/dm-2';
+is(
+ PVE::Diskmanage::canonical_blockdev_link('/dev/mapper/friendly', {}, 'test:123', $root),
+ undef,
+ 'scan omits a rebound canonical link',
+);
+delete $links{$canonical};
+is(
+ PVE::Diskmanage::canonical_blockdev_link('/dev/mapper/friendly', {}, 'test:123', $root),
+ undef,
+ 'scan omits a missing canonical link',
+);
+is(
+ PVE::Diskmanage::canonical_blockdev_link('/dev/nvme0n1', {}, undef, $root),
+ '/dev/disk/by-id/nvme-eui.0123456789abcdef',
+ 'scan uses identity-bearing NVMe link',
+);
+is(
+ PVE::Diskmanage::canonical_blockdev_link('/dev/sda', {}, '3600abc', $root),
+ '/dev/disk/by-id/scsi-3600abc',
+ 'scan uses verified single-path SCSI link',
+);
+delete $links{'/dev/disk/by-id/scsi-3600abc'};
+$links{'/dev/disk/by-id/wwn-0x600abc'} = '/dev/sda';
+is(
+ PVE::Diskmanage::canonical_blockdev_link('/dev/sda', {}, '3600abc', $root),
+ '/dev/disk/by-id/wwn-0x600abc',
+ 'scan can use the corresponding WWN link',
+);
+
subtest 'checked wipe keeps verification order and retained handle' => sub {
my @events;
my $handle;
@@ -110,14 +226,18 @@ subtest 'checked wipe keeps verification order and retained handle' => sub {
ok(defined(fileno($handle)), 'parent handle stays open through trigger');
},
);
- PVE::Diskmanage::wipe_blockdev_checked('/dev/sda', {});
+ PVE::Diskmanage::wipe_blockdev_checked('/dev/sda', {}, sub { push @events, 'storage' });
is_deeply(
\@events,
- [qw(reference partitions reference partitions open users
+ [qw(reference partitions ready reference partitions open storage ready users
reference partitions wipe reference partitions trigger)],
- 'retained open, users, verification, wipe and trigger order',
+ 'readiness, retained open, storage check, users, verification, wipe and trigger order',
);
close($handle);
+ @events = ();
+ eval { PVE::Diskmanage::wipe_blockdev_checked('/dev/sda', {}, undef) };
+ like($@, qr/device topology changed/, 'local-to-SAN transition refuses without callback');
+ is_deeply(\@events, ['reference'], 'transition refuses before readiness, opens or writes');
};
done_testing();
diff --git a/src/test/run_wipedisk_tests.pl b/src/test/run_wipedisk_tests.pl
index f110a2f4..dafd08a8 100755
--- a/src/test/run_wipedisk_tests.pl
+++ b/src/test/run_wipedisk_tests.pl
@@ -12,6 +12,23 @@ use PVE::API2::Disks;
my $disk = Test::MockModule->new('PVE::Diskmanage');
my $rpc = Test::MockModule->new('PVE::RPCEnvironment');
my ($worker, $users, $probe_error, $wiped);
+my ($san, $storage_locked, $guard_error) = (0, 0, undef);
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(
+ config => sub { { ids => {} } },
+ lock_storage_config => sub {
+ $storage_locked = 1;
+ my $res = eval { $_[0]->() };
+ my $err = $@;
+ $storage_locked = 0;
+ die $err if $err;
+ return $res;
+ },
+ assert_san_write_safe => sub {
+ ok($storage_locked, 'SAN guard under storage configuration lock');
+ die $guard_error if $guard_error;
+ },
+);
my $inside_worker = 0;
{
@@ -21,23 +38,29 @@ my $inside_worker = 0;
}
$rpc->mock(get => sub { bless {}, 'WipeTestRPC' });
$disk->mock(
- verify_blockdev_path => sub { '/dev/sda' },
+ verify_blockdev_path => sub { '/dev/dm-9' },
block_device_reference => sub {
+ # a local disk is wiped without the cluster-wide lock, which needs quorum
+ is($storage_locked, $san ? 1 : 0, 'storage lock only for a SAN device') if $_[1];
return {
- device => '/dev/sda',
- stamp => '1:8:0',
+ device => '/dev/dm-9',
+ stamp => '1:253:9',
key => 'scsi:test',
partition => '',
};
},
open_block_device => sub { \*STDOUT },
locked_disk_action => sub { $_[0]->() },
+ is_san_device => sub { $san },
+ is_multipath_device => sub { 0 },
is_mounted => sub { undef },
has_holder => sub { undef },
wipe_partitions => sub { [] },
+ assert_block_device_ready => sub { ok($inside_worker, 'readiness checked in worker') },
block_device_users => sub {
+ return [] if $_[1]->{'metadata-only'};
ok($inside_worker, 'users checked in the worker');
- is_deeply($_[0], ['sda'], 'resolved name checked, including partitions');
+ is_deeply($_[0], ['dm-9'], 'resolved name checked, including partitions');
die $probe_error if $probe_error;
return $users;
},
@@ -45,15 +68,26 @@ $disk->mock(
udevadm_trigger => sub { },
);
my $method = PVE::API2::Disks->map_method_by_name('wipe_disk');
+my $pattern = $method->{parameters}->{properties}->{disk}->{pattern};
+for my $path (
+ '/dev/sda1',
+ '/dev/dm-9',
+ '/dev/mapper/array_lun-1.0',
+ '/dev/disk/by-id/scsi-123',
+ '/dev/disk/by-id/dm-uuid-mpath-naa:123',
+) {
+ like($path, qr/$pattern/, 'valid device path');
+}
+unlike('/dev/x;touch', qr/$pattern/, 'metacharacter refused');
for my $case (
[[], undef, 1, qr/^$/],
- [['qemu (PID 7) has sda open'], undef, 0, qr/cannot wipe.*qemu/],
+ [['qemu (PID 7) has dm-9 open'], undef, 0, qr/cannot wipe.*qemu/],
[[], "probe failed\n", 0, qr/probe failed/],
) {
($users, $probe_error, my $expected, my $error) = @$case;
$wiped = 0;
$inside_worker = 0;
- $method->{code}->({ node => 'test', disk => '/dev/sda' });
+ $method->{code}->({ node => 'test', disk => '/dev/mapper/array_lun-1.0' });
is($wiped, 0, 'request does not wipe before worker');
$inside_worker = 1;
eval { $worker->() };
@@ -61,4 +95,16 @@ for my $case (
is($wiped, $expected, 'only unused devices wiped');
}
+$san = 1;
+$users = [];
+$probe_error = undef;
+for my $error (undef, "storage reference\n") {
+ $guard_error = $error;
+ $wiped = 0;
+ $method->{code}->({ node => 'test', disk => '/dev/dm-9' });
+ eval { $worker->() };
+ is($@, $error // '', 'SAN guard outcome');
+ is($wiped, $error ? 0 : 1, 'referenced SAN device not wiped');
+}
+
done_testing();
--
2.47.3
^ permalink raw reply related [relevance 7%]
* [PATCH v4 storage 20/36] disks: lvm: allow volume groups on SAN LUNs and multipath maps
@ 2026-11-13 3:00 11% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-13 3:00 UTC (permalink / raw)
To: pve-devel
The node disk API creates volume groups on local disks only. It takes
a Fibre Channel LUN for one, but not a multipath map, and adds the
storage as local to the node. Accept the LUNs of the SAN inventory and
add their storage as shared and without node restriction. Refuse an
existing storage ID for them: adding the node to a storage with the
same volume group name is meant for local volume groups and would
combine two different volume groups in one shared storage.
Initializing a LUN, here or as base volume of a new LVM storage, now
takes a cluster-wide lock per WWID and refuses a LUN that a storage
references through its volume group, as base volume or as iSCSI
target serving images.
Co-authored-by: Dietmar Maurer <dietmar@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
src/PVE/API2/Disks/LVM.pm | 56 +++---
src/PVE/Storage/LVMPlugin.pm | 74 +++++++-
src/PVE/Storage/SAN.pm | 97 +++++++++-
src/test/Makefile | 8 +-
src/test/disk_api_test.pm | 235 ++++++++++++++++++++++++
src/test/run_disk_api_tests.pl | 11 ++
src/test/run_san_nvme_tests.pl | 91 +++++++++
src/test/run_san_taint_tests.pl | 26 +++
src/test/run_test_lvm_base_conflicts.pl | 232 ++++++++++++++++-------
src/test/run_test_lvm_create.pl | 14 ++
10 files changed, 746 insertions(+), 98 deletions(-)
create mode 100644 src/test/disk_api_test.pm
create mode 100755 src/test/run_disk_api_tests.pl
create mode 100755 src/test/run_san_nvme_tests.pl
diff --git a/src/PVE/API2/Disks/LVM.pm b/src/PVE/API2/Disks/LVM.pm
index 6101743b..a0ab6d69 100644
--- a/src/PVE/API2/Disks/LVM.pm
+++ b/src/PVE/API2/Disks/LVM.pm
@@ -4,6 +4,7 @@ use strict;
use warnings;
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
use PVE::Diskmanage;
use PVE::JSONSchema qw(get_standard_option);
use PVE::API2::Storage::Config;
@@ -130,7 +131,8 @@ __PACKAGE__->register_method({
name => get_standard_option('pve-storage-id'),
device => {
type => 'string',
- description => 'The block device you want to create the volume group on',
+ description => 'The block device you want to create the volume group on.'
+ . ' Multipath mapped devices are supported.',
},
add_storage => {
description => "Configure storage using the Volume Group",
@@ -152,48 +154,54 @@ __PACKAGE__->register_method({
my $node = $param->{node};
$dev = PVE::Diskmanage::verify_blockdev_path($dev);
- PVE::Diskmanage::assert_disk_unused($dev);
+ my $san = PVE::Storage::SAN::is_san_device($dev);
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
my $storage_params = {
type => 'lvm',
vgname => $name,
storage => $name,
content => 'rootdir,images',
- shared => 0,
- nodes => $node,
+ shared => $san ? 1 : 0,
+ $san ? () : (nodes => $node),
};
my $verify_params = [qw(vgname)];
if ($param->{add_storage}) {
$rpcenv->check($user, "/storage", ['Datastore.Allocate']);
+ # only local volume groups of the same name may share a storage that exists already
+ die "storage ID '$name' already defined\n"
+ if $san && PVE::Storage::storage_config(PVE::Storage::config(), $name, 1);
+
# reserve the name and add as disabled, will be enabled below if creation works out
PVE::API2::Storage::Config->create_or_update(
$name, $node, $storage_params, $verify_params, 1,
);
}
+ my $create_group = sub {
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
+ die "volume group with name '${name}' already exists on node '${node}'\n"
+ if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
+
+ if (PVE::Diskmanage::is_partition($dev)) {
+ eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
+ warn $@ if $@;
+ }
+
+ PVE::Storage::LVMPlugin::lvm_create_volume_group($dev, $name, $san);
+
+ PVE::Diskmanage::udevadm_trigger($dev);
+
+ if ($param->{add_storage}) {
+ PVE::API2::Storage::Config->create_or_update(
+ $name, $node, $storage_params, $verify_params,
+ );
+ }
+ };
my $worker = sub {
- PVE::Diskmanage::locked_disk_action(sub {
- PVE::Diskmanage::assert_disk_unused($dev);
- die "volume group with name '${name}' already exists on node '${node}'\n"
- if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
-
- if (PVE::Diskmanage::is_partition($dev)) {
- eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
- warn $@ if $@;
- }
-
- PVE::Storage::LVMPlugin::lvm_create_volume_group($dev, $name);
-
- PVE::Diskmanage::udevadm_trigger($dev);
-
- if ($param->{add_storage}) {
- PVE::API2::Storage::Config->create_or_update(
- $name, $node, $storage_params, $verify_params,
- );
- }
- });
+ $san ? $create_group->() : PVE::Diskmanage::locked_disk_action($create_group);
};
return $rpcenv->fork_worker('lvmcreate', $name, $user, $worker);
diff --git a/src/PVE/Storage/LVMPlugin.pm b/src/PVE/Storage/LVMPlugin.pm
index ee64b782..c9e52b4c 100644
--- a/src/PVE/Storage/LVMPlugin.pm
+++ b/src/PVE/Storage/LVMPlugin.pm
@@ -16,6 +16,7 @@ use PVE::Exception qw(raise_param_exc);
use PVE::Format qw(render_bytes render_duration);
use PVE::INotify;
use PVE::JSONSchema qw(get_standard_option);
+use PVE::Multipath;
use PVE::RESTEnvironment qw(log_warn);
use PVE::Tools qw(run_command file_get_contents file_read_firstline trim);
@@ -147,6 +148,37 @@ sub cached_pv_volume_groups {
return $res;
}
+sub lun_volume_groups {
+ my ($devices) = @_;
+ my $output = '';
+ run_command(
+ [
+ '/sbin/pvs',
+ '--nohints',
+ '--readonly',
+ '--devices',
+ join(',', @$devices),
+ '--reportformat',
+ 'json',
+ '--options',
+ 'pv_name,vg_name',
+ ],
+ timeout => 10,
+ outfunc => sub { $output .= "$_[0]\n" },
+ );
+ my $data = decode_json($output);
+ my $pvs = $data->{report}->[0]->{pv};
+ die "unable to inspect volume groups - invalid pvs report\n" if ref($pvs) ne 'ARRAY';
+ my %vgs;
+ for my $pv (@$pvs) {
+ my $vg = $pv->{vg_name};
+ die "unable to inspect volume groups - missing volume group metadata\n"
+ if !defined($vg) || $vg eq '[unknown]';
+ $vgs{$vg} = 1 if length($vg);
+ }
+ return [sort keys %vgs];
+}
+
sub clear_first_sector {
my ($dev) = shift;
@@ -157,10 +189,16 @@ sub clear_first_sector {
}
}
-sub lvm_create_volume_group {
- my ($device, $vgname, $shared, $guard) = @_;
-
+my sub create_volume_group {
+ my ($device, $vgname, $lun, $guard) = @_;
$device = PVE::Diskmanage::verify_blockdev_path($device);
+ my $fh;
+ if ($lun) {
+ sysopen($fh, $lun->{'by-id'}, O_RDWR) or die "cannot open '$device' - $!\n";
+ }
+ my $check_name = sub {
+ PVE::Storage::SAN::assert_same_device($lun, $fh) if $lun;
+ };
my $refuse_data = sub {
my (@types) = @_;
die "device '$device' contains data ("
@@ -178,7 +216,7 @@ sub lvm_create_volume_group {
if !defined($size) || $size !~ m/^\d+$/ || !$size;
die "unable to probe '$device' - missing device mapper identity\n"
if basename($device) =~ m/^dm-\d+$/ && !defined($uuid);
- if (defined($uuid) && $uuid =~ m/^mpath-/) {
+ if (PVE::Multipath::parse_dm_uuid($uuid)) {
# A queueing map without a running path can stall even a read-only probe.
my $running = 0;
PVE::Tools::dir_glob_foreach(
@@ -247,26 +285,48 @@ sub lvm_create_volume_group {
}
$refuse_data->(keys %signatures) if %signatures;
+ # Only initializing the device needs the checks, an existing volume group on it can be added.
$guard->{check_storage}->($device) if $guard && $guard->{check_storage};
- clear_first_sector($device); # else pvcreate fails
+ PVE::Storage::SAN::assert_lun_unreferenced(
+ PVE::Storage::config(),
+ $lun,
+ $guard ? $guard->{exempt} : undef,
+ ) if $lun;
+
+ $check_name->();
+ clear_first_sector($lun ? '/proc/' . $$ . '/fd/' . fileno($fh) : $device);
# we use --metadatasize 250k, which reseults in "pe_start = 512"
# so pe_start is aligned on a 128k boundary (advantage for SSDs)
my $cmd = ['/sbin/pvcreate', '--metadatasize', '250k', $device];
- run_command($cmd, errmsg => "pvcreate '$device' error");
+ $check_name->();
+ run_command($cmd, errmsg => "pvcreate '$device' error", $lun ? (timeout => 30) : ());
$cmd = ['/sbin/vgcreate', $vgname, $device];
# push @$cmd, '-c', 'y' if $shared; # we do not use this yet
+ $check_name->();
run_command(
$cmd,
+ $lun ? (timeout => 30) : (),
errmsg => "vgcreate $vgname $device error",
errfunc => $ignore_no_medium_warnings,
outfunc => $ignore_no_medium_warnings,
);
}
+sub lvm_create_volume_group {
+ my ($device, $vgname, $shared, $guard) = @_;
+ require PVE::Storage::SAN;
+ my $lun = PVE::Storage::SAN::lun_for_device($device);
+ return create_volume_group($device, $vgname, undef, $guard) if !$lun;
+ PVE::Storage::SAN::with_lun_lock(
+ $lun,
+ sub { create_volume_group($device, $vgname, $lun, $guard) },
+ );
+}
+
sub lvm_destroy_volume_group {
my ($vgname) = @_;
@@ -1130,7 +1190,7 @@ sub on_add_hook {
$path,
$scfg->{vgname},
$scfg->{shared},
- { check_storage => $check_target },
+ { check_storage => $check_target, exempt => $storeid },
);
}
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index f13d9633..210c3a78 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -5,6 +5,7 @@ use v5.36;
use Cwd qw(abs_path);
use File::Basename qw(basename);
+use PVE::Cluster;
use PVE::INotify;
use PVE::Diskmanage;
@@ -15,7 +16,7 @@ use PVE::Multipath::Config;
use PVE::Multipath::Identity;
use PVE::Storage;
use PVE::Storage::LVMPlugin;
-use PVE::Tools qw(file_read_firstline);
+use PVE::Tools qw(file_read_firstline dir_glob_foreach);
sub scan_luns($cfg) {
my $ids = PVE::Multipath::Identity::collect(all => 1);
@@ -186,4 +187,98 @@ sub is_san_device($device, $info = undef) {
|| PVE::Diskmanage::is_remote_transport($info->{transport}) ? 1 : 0;
}
+sub lun_for_device($device) {
+ $device = PVE::Diskmanage::verify_blockdev_path($device);
+ return undef if !is_san_device($device);
+ my $rows = scan_luns(PVE::Storage::config());
+ for my $lun (@$rows) {
+ next if (abs_path($lun->{devpath}) // '') ne $device;
+ die "cannot use '$device' - no stable name under /dev/disk/by-id\n" if !$lun->{'by-id'};
+ # read from sysfs, but used in command lines and in the name of the cluster lock
+ ($lun->{devpath}) = $lun->{devpath} =~ m{\A(/dev/[A-Za-z0-9_.:+/-]+)\z}
+ or die "cannot use '$device' - unexpected device path\n";
+ ($lun->{wwid}) = $lun->{wwid} =~ m/\A([A-Za-z0-9_.:+=-]+)\z/
+ or die "cannot use '$device' - unexpected WWID\n";
+ return $lun;
+ }
+ die "cannot use '$device' - select an identified LUN or its multipath map\n";
+}
+
+sub lun_partitions($lun) {
+ my $device = PVE::Diskmanage::verify_blockdev_path($lun->{devpath});
+ my $name = basename($device);
+ my @parts;
+ dir_glob_foreach(
+ "/sys/class/block/$name",
+ "\Q$name\E.+",
+ sub($part, @) {
+ my ($path) = "/dev/$part" =~ m{\A(/dev/[A-Za-z0-9_.+-]+)\z};
+ push @parts, $path if defined($path) && -e "/sys/class/block/$name/$part/partition";
+ },
+ );
+ dir_glob_foreach(
+ "/sys/class/block/$name/holders",
+ 'dm-\\d+',
+ sub($part, @) {
+ my $map = PVE::Multipath::parse_dm_uuid(
+ file_read_firstline("/sys/class/block/$part/dm/uuid"));
+ my ($path) = "/dev/$part" =~ m{\A(/dev/dm-\d+)\z};
+ push @parts, $path
+ if defined($path) && $map && $map->{partition} && $map->{wwid} eq $lun->{wwid};
+ },
+ );
+ return \@parts;
+}
+
+sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
+ [$lun->{devpath}, lun_partitions($lun)->@*],
+ )->@*;
+ # the paths of a LUN can belong to more than one target
+ my %targets = map { $_->{target} => 1 }
+ grep { $_->{wwid} eq $lun->{wwid} && defined($_->{target}) }
+ values PVE::Multipath::Identity::collect(all => 1)->{paths}->%*;
+ for my $sid (sort keys $cfg->{ids}->%*) {
+ next if defined($exempt) && $sid eq $exempt;
+ my $scfg = $cfg->{ids}->{$sid};
+ my $type = $scfg->{type};
+ if (($type eq 'lvm' || $type eq 'lvmthin') && $vgs{ $scfg->{vgname} // '' }) {
+ die "cannot use '$lun->{devpath}' - volume group is used by storage '$sid'\n";
+ }
+ if (
+ defined($scfg->{target})
+ && $targets{ $scfg->{target} }
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
+ }
+ next if $type ne 'lvm' || !$scfg->{base};
+ my (undef, $volname) = PVE::Storage::Plugin::parse_volume_id($scfg->{base});
+ my ($wwid) = $volname =~ m/(?:^|\.)(?:dm-uuid-mpath|scsi|nvme)-(.+)$/;
+ my $matches = defined($wwid) && $wwid eq $lun->{wwid};
+ if (!$matches) {
+ my $path = eval { abs_path(PVE::Storage::path($cfg, $scfg->{base})) };
+ my $device = abs_path($lun->{devpath});
+ $matches = defined($path) && defined($device) && $path eq $device;
+ }
+ die "cannot use '$lun->{devpath}' - storage '$sid' uses this LUN as its base volume\n"
+ if $matches;
+ }
+ return;
+}
+
+# Serializes writes to a LUN cluster-wide. The code sees the current storage configuration.
+sub with_lun_lock($lun, $code) {
+ my $key = $lun->{wwid} =~ s/([^A-Za-z0-9_.:-])/sprintf('=%02x', ord($1))/ger;
+ PVE::Cluster::cfs_lock_domain("san-$key", undef, $code);
+ die $@ if $@;
+}
+
+sub assert_same_device($lun, $fh) {
+ my @held = stat($fh);
+ my @named = stat($lun->{'by-id'});
+ die "cannot use '$lun->{devpath}' - its by-id name changed\n"
+ if !@held || !@named || $held[6] != $named[6];
+}
+
1;
diff --git a/src/test/Makefile b/src/test/Makefile
index 6348c61e..e453951a 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api
+test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
@@ -69,5 +69,9 @@ test_san_taint: run_san_taint_tests.pl
test_san_lun_scan: run_san_lun_scan_tests.pl
./run_san_lun_scan_tests.pl
-test_san_api: run_san_api_tests.pl
+test_san_api: run_san_api_tests.pl run_san_nvme_tests.pl
./run_san_api_tests.pl
+ ./run_san_nvme_tests.pl
+
+test_disk_api: run_disk_api_tests.pl
+ ./run_disk_api_tests.pl
diff --git a/src/test/disk_api_test.pm b/src/test/disk_api_test.pm
new file mode 100644
index 00000000..32ab5c80
--- /dev/null
+++ b/src/test/disk_api_test.pm
@@ -0,0 +1,235 @@
+package PVE::API2::Disks::Test;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use PVE::API2::Disks;
+use PVE::API2::Disks::LVM;
+use PVE::Diskmanage;
+use PVE::Storage;
+use PVE::Storage::LVMPlugin;
+
+use Test::MockModule;
+use Test::More;
+
+my @transport_cases = (
+ ['none', undef],
+ ['unknown', 'unknown'],
+ ['ata', 'ata'],
+ ['sata', 'sata'],
+ ['sas', 'sas'],
+ ['spi', 'spi'],
+ ['sbp', 'sbp'],
+ ['usb', 'usb'],
+ ['fc', 'fc'],
+ ['fcoe', 'fcoe'],
+ ['iscsi', 'iscsi'],
+ ['nvme', 'nvme'],
+ ['virtio', 'virtio'],
+ ['nvme-fc', 'nvme-fc'],
+ ['nvme-tcp', 'nvme-tcp'],
+ ['nvme-rdma', 'nvme-rdma'],
+ ['nvme-loop', 'nvme-loop'],
+);
+
+my $disks = {};
+my @all;
+for my $case (@transport_cases) {
+ my ($name, $transport) = $case->@*;
+ my $devpath = "/dev/test-$name";
+ my $entry = {
+ devpath => $devpath,
+ gpt => 0,
+ osdid => -1,
+ };
+ $entry->{transport} = $transport if defined($transport);
+ $disks->{$name} = $entry;
+ push @all, $devpath;
+}
+
+my $diskmanage_module = Test::MockModule->new('PVE::Diskmanage', no_auto => 1);
+$diskmanage_module->mock('get_disks' => sub { return $disks });
+
+my $list_handler = PVE::API2::Disks->map_method_by_name('list')->{code};
+my $list_devpaths = sub {
+ my ($param) = @_;
+ my $result = $list_handler->({ node => 'test-node', skipsmart => 1, $param->%* });
+ return [sort map { $_->{devpath} } $result->@*];
+};
+
+is_deeply(
+ $list_devpaths->({}), [sort @all], 'the disk list uses the default disk inventory',
+);
+
+is_deeply(
+ $list_devpaths->({ type => 'unused' }),
+ [sort @all],
+ 'unused disk selection preserves transport visibility',
+);
+
+$diskmanage_module->mock(
+ 'get_disks' => sub {
+ return {
+ 'fc-disk' => {
+ devpath => '/dev/fc-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'fc',
+ },
+ 'fc-partition' => {
+ devpath => '/dev/fc-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/fc-disk',
+ },
+ 'loop-disk' => {
+ devpath => '/dev/loop-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'nvme-loop',
+ },
+ 'loop-partition' => {
+ devpath => '/dev/loop-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/loop-disk',
+ },
+ };
+ },
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1 }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'the plain list keeps FC disks and their partitions',
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1, type => 'unused' }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'unused partitions preserve transport visibility',
+);
+
+subtest 'volume group creation leaves SAN locking to the LVM helper' => sub {
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $disk = $diskmanage_module;
+ my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+ my $rpc = Test::MockModule->new('PVE::RPCEnvironment');
+ my (@stack, @created);
+ my $lock = sub {
+ my ($name, $code) = @_;
+ push @stack, $name;
+ my $res = eval { $code->() };
+ my $err = $@;
+ pop @stack;
+ die $err if $err;
+ return $res;
+ };
+ $storage->mock(lock_storage_config => sub { $lock->('storage.cfg', $_[0]) });
+ $disk->mock(locked_disk_action => sub { $lock->('disk', $_[0]) });
+ $disk->mock(verify_blockdev_path => sub { $_[0] });
+ $disk->mock(assert_disk_unused => sub { });
+ $disk->mock(is_partition => sub { 0 });
+ $disk->mock(udevadm_trigger => sub { });
+ $lvm->mock(lvm_vgs => sub { {} });
+ $lvm->mock(
+ lvm_create_volume_group => sub {
+ is(scalar(@_), 3, 'disk API does not exempt a storage');
+ push @created, [$_[0], join('>', @stack)];
+ },
+ );
+ {
+
+ package MultipathTestRPC;
+ sub get_user { 'root@pam' }
+ sub check { 1 }
+ sub fork_worker { $_[4]->(); return 'test-upid' }
+ }
+ $rpc->mock(get => sub { bless {}, 'MultipathTestRPC' });
+
+ my ($is_map, $is_san) = (1, 0);
+ my $san = Test::MockModule->new('PVE::Storage::SAN');
+ $san->mock(is_san_device => sub { $is_map || $is_san });
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg1', device => '/dev/dm-3' });
+ ($is_map, $is_san) = (0, 1);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg2', device => '/dev/sdc' });
+ ($is_map, $is_san) = (0, 0);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg3', device => '/dev/sdb' });
+ is_deeply(
+ \@created,
+ [
+ ['/dev/dm-3', ''], ['/dev/sdc', ''], ['/dev/sdb', 'disk'],
+ ],
+ 'SAN writes use no local disk or storage configuration lock',
+ );
+ my $config_api = Test::MockModule->new('PVE::API2::Storage::Config');
+ my @params;
+ $config_api->mock(create_or_update => sub { push @params, $_[3] });
+ my $cfg =
+ { ids => { other => { type => 'lvm', vgname => 'other', nodes => { n2 => 1 } } } };
+ $storage->mock(config => sub { $cfg });
+ $is_san = 1;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg4',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 1, 'SAN storage is shared');
+ ok(!exists($params[-1]->{nodes}), 'SAN storage covers all nodes');
+ @created = ();
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'other',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ };
+ like($@, qr/already defined/, 'SAN volume group does not join the storage of another node');
+ is_deeply(\@created, [], 'existing storage ID prevents initialization');
+ $is_san = 0;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg5',
+ device => '/dev/sdb',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 0, 'local storage is not shared');
+ is($params[-1]->{nodes}, 'n1', 'local storage remains node-restricted');
+ @created = ();
+ $disk->mock(assert_disk_unused => sub { die "device is already in use\n" });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like($@, qr/already in use/, 'disk API rejects a used inventory entry');
+ is_deeply(\@created, [], 'used inventory prevents initialization');
+ $disk->mock(assert_disk_unused => sub { });
+ $lvm->mock(lvm_vgs => sub { { vg => {} } });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like(
+ $@,
+ qr/volume group with name 'vg' already exists/,
+ 'stale inventory does not permit an existing VG',
+ );
+ is_deeply(\@created, [], 'existing VG prevents initialization');
+ $disk->unmock($_)
+ for qw(
+ locked_disk_action verify_blockdev_path assert_disk_unused is_partition
+ udevadm_trigger
+ );
+};
+
+done_testing();
diff --git a/src/test/run_disk_api_tests.pl b/src/test/run_disk_api_tests.pl
new file mode 100755
index 00000000..75fc98c6
--- /dev/null
+++ b/src/test/run_disk_api_tests.pl
@@ -0,0 +1,11 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use TAP::Harness;
+
+my $harness = TAP::Harness->new({ verbosity => -2 });
+my $res = $harness->runtests("disk_api_test.pm");
+
+exit -1 if !$res || $res->{failed} || $res->{parse_errors};
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
new file mode 100755
index 00000000..b28efe7d
--- /dev/null
+++ b/src/test/run_san_nvme_tests.pl
@@ -0,0 +1,91 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+our ($backing, @opens);
+
+BEGIN {
+ *CORE::GLOBAL::sysopen = sub (*$$;$) {
+ push @opens, $_[1];
+ my $path = $_[1] =~ m{^/dev/disk/by-id/nvme-} ? $backing : $_[1];
+ return CORE::sysopen($_[0], $path, $_[2]);
+ };
+}
+use lib qw(..);
+use File::Temp qw(tempfile);
+use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
+
+my ($fh, $file) = tempfile('san-nvme-XXXX', DIR => '.', UNLINK => 1);
+close($fh);
+$backing = $file;
+my $device = '/dev/nvme0n1';
+my $link = '/dev/disk/by-id/nvme-eui.0123456789abcdef';
+my $lun =
+ { devpath => $device, 'by-id' => $link, wwid => 'eui.0123456789abcdef', multipath => 'native' };
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $mp = Test::MockModule->new('PVE::Multipath');
+my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $cfg = { ids => {} };
+my @order;
+$storage->mock(config => sub { $cfg });
+$disk->mock(verify_blockdev_path => sub { $device });
+$disk->mock(is_partition => sub { 0 });
+$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(is_iscsi_device => sub { 0 });
+$disk->mock(is_mounted => sub { 0 });
+$disk->mock(has_holder => sub { 0 });
+$mp->mock(device_map => sub { undef });
+$san->mock(abs_path => sub { $device });
+$san->mock(scan_luns => sub { [$lun] });
+$san->mock(lun_partitions => sub { [] });
+$san->mock(assert_same_device => sub { ok(defined(fileno($_[1])), 'held descriptor checked') });
+$lvm->mock(lun_volume_groups => sub { push @order, 'check'; [] });
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-eui.0123456789abcdef', 'native namespace uses the LUN lock');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+is(PVE::Storage::SAN::stable_path($device, $lun->{wwid}), $link, 'native stable path');
+is_deeply(PVE::Storage::SAN::lun_for_device($link), $lun, 'native row selected for writes');
+$disk->mock(is_partition => sub { 1 });
+is(PVE::Storage::SAN::lun_for_device($link), undef, 'a partition is handled as a local device');
+$disk->mock(is_partition => sub { 0 });
+$cfg->{ids}->{data} = { type => 'lvm', base => 'fabric:nvme-eui.0123456789abcdef' };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like($@, qr/base volume/, 'native base reference refuses');
+$cfg->{ids} = {};
+@order = @opens = ();
+$lvm->mock(file_read_firstline => sub { $_[0] =~ m{/size$} ? 1024 : undef });
+$lvm->mock(lvm_pv_info => sub { undef });
+$lvm->mock(
+ clear_first_sector => sub { push @order, 'clear'; ok(-e $_[0], 'VG clear uses held fd') });
+$lvm->mock(
+ run_command => sub {
+ my ($cmd, %opts) = @_;
+ if ($cmd->[0] eq 'wipefs') {
+ $opts{outfunc}->('{"signatures":[]}');
+ } else {
+ is($cmd->[-1], $device, 'VG command uses the checked device');
+ push @order, $cmd->[0];
+ }
+ },
+);
+PVE::Storage::LVMPlugin::lvm_create_volume_group($link, 'data', 1);
+is_deeply(
+ \@order,
+ [qw(lock check clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'native VG sequencing',
+);
+is_deeply(\@opens, [$link], 'VG creation holds the native by-id device');
+
+done_testing();
diff --git a/src/test/run_san_taint_tests.pl b/src/test/run_san_taint_tests.pl
index 35b11cd7..0ccd9e2f 100755
--- a/src/test/run_san_taint_tests.pl
+++ b/src/test/run_san_taint_tests.pl
@@ -31,4 +31,30 @@ for my $bad ('-bad', '1:2', '../dev', "3600a\n") {
like($@, qr/invalid WWID/, 'ambiguous identity refused');
}
+# the LUN that write operations get must be usable in command lines and lock names
+use PVE::Storage::SAN;
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $tainted_dev = PVE::Tools::file_get_contents('/proc/self/comm') =~ s/.*//sr . '/dev/null';
+ok(tainted($tainted_dev), 'device path derived from a file is tainted');
+$san->mock(
+ is_san_device => sub { 1 },
+ scan_luns => sub {
+ return [{
+ devpath => $tainted_dev,
+ wwid => $wwid,
+ 'by-id' => '/dev/null',
+ usage => 'unused',
+ multipath => 'none',
+ }];
+ },
+);
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(verify_blockdev_path => sub { '/dev/null' });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+my $lun = PVE::Storage::SAN::lun_for_device('/dev/null');
+ok(!tainted($lun->{devpath}), 'LUN device path is untainted');
+ok(!tainted($lun->{wwid}), 'LUN WWID is untainted');
+is($lun->{wwid}, '3600a', 'LUN WWID is unchanged');
+
done_testing();
diff --git a/src/test/run_test_lvm_base_conflicts.pl b/src/test/run_test_lvm_base_conflicts.pl
index 26362a74..beb38a4e 100755
--- a/src/test/run_test_lvm_base_conflicts.pl
+++ b/src/test/run_test_lvm_base_conflicts.pl
@@ -2,78 +2,182 @@
use strict;
use warnings;
-
-use Test::MockModule;
+use lib qw(..);
use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
-use lib ('.', '..');
-use PVE::Storage;
-use PVE::Storage::LVMPlugin;
-
-my $storage = Test::MockModule->new('PVE::Storage');
+my $scan = Test::MockModule->new('PVE::Storage::SAN');
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
-my ($cfg, $created, $existing);
-$storage->mock(
- config => sub { $cfg },
- path => sub { '/dev/sda' },
- activate_storage => sub { },
- activate_volumes => sub { },
-);
-$lvm->mock(
- lvm_create_volume_group => sub {
- my ($device, $vgname, $shared, $guard) = @_;
- return if $existing;
- $guard->{check_storage}->($device);
- $created++;
- },
- assert_discard_supported => sub { },
-);
-
-for my $case (
- ['iscsi', {}, 0],
- ['iscsi', { images => 1 }, 1],
- ['iscsidirect', {}, 1],
- ['zfs', {}, 1],
- ['vendor', { images => 1 }, 1],
-) {
- my ($type, $content, $conflict) = @$case;
- $created = 0;
- $cfg = {
- ids => {
- base => { type => 'iscsi', target => 'iqn.test', content => { none => 1 } },
- other => {
- type => $type,
- target => 'iqn.test',
- content => $content,
- disable => 1,
- nodes => { elsewhere => 1 },
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $lun = { wwid => '3600+abc', devpath => '/dev/dm-0', 'iscsi-target' => 'iqn.test' };
+# the LUN is exported through two targets, its row names only the first
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
+$identity->mock(
+ collect => sub {
+ {
+ paths => {
+ sdb => { wwid => '3600+abc', target => 'iqn.test' },
+ sdc => { wwid => '3600+abc', target => 'iqn.second' },
+ sdd => { wwid => '3600+other', target => 'iqn.other' },
},
+ };
+ },
+);
+my $vgs = [];
+$scan->mock(lun_partitions => sub { [] });
+$lvm->mock(lun_volume_groups => sub { $vgs });
+$lvm->mock(cached_pv_volume_groups => sub { die "write check must not use cached PV metadata\n" });
+my $cfg = { ids => {} };
+$storage->mock(config => sub { $cfg });
+my $check = sub {
+ eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun, @_) };
+ return $@;
+};
+is($check->(), '', 'unreferenced LUN accepted');
+for my $type (qw(lvm lvmthin)) {
+ $vgs = ['data'];
+ $cfg->{ids} = {
+ data => {
+ type => $type,
+ vgname => 'data',
+ shared => 1,
+ disable => 1,
+ nodes => { other => 1 },
},
};
- eval {
- PVE::Storage::LVMPlugin->on_add_hook(
- 'test',
- { base => 'base:0.0.1.scsi-test', vgname => 'test' },
- );
- };
- if ($conflict) {
- like($@, qr/storage 'other' serves disk images from this target/, "$type conflict refused");
- like($@, qr/set its content to 'none'/, "$type: remedy named for iSCSI only")
- if $type eq 'iscsi';
- } else {
- is($@, '', 'connection-only storage permits initialization');
+ for my $cached_vg (undef, 'unrelated') {
+ $lun->{vgname} = $cached_vg;
+ $lun->{usage} = 'unused';
+ like($check->(), qr/used by storage 'data'/, "$type refusal ignores display VG and usage");
}
- is($created, $conflict ? 0 : 1, 'no writes on conflicting target');
+ is($check->('data'), '', 'the storage being added can be exempted');
+}
+delete $lun->{vgname};
+delete $lun->{usage};
+$vgs = [];
+$cfg->{ids} = { direct => { type => 'iscsi', target => 'iqn.test', content => { images => 1 } } };
+like($check->(), qr/storage 'direct' serves images from this target$/, 'direct image use refuses');
+$cfg->{ids}->{direct}->{target} = 'iqn.second';
+like($check->(), qr/storage 'direct' serves images/, 'also through another target of the LUN');
+$cfg->{ids}->{direct}->{target} = 'iqn.other';
+is($check->(), '', 'a target of another LUN is no reference');
+$cfg->{ids}->{direct}->{target} = 'iqn.test';
+$cfg->{ids}->{direct}->{content} = { none => 1 };
+is($check->(), '', 'connection-only storage permits use');
- $existing = 1;
- eval {
- PVE::Storage::LVMPlugin->on_add_hook(
- 'test',
- { base => 'base:0.0.1.scsi-test', vgname => 'test' },
- );
- };
- is($@, '', "$type: an existing volume group on the base volume can be added");
- $existing = 0;
+for my $type (qw(iscsidirect zfs)) {
+ local $cfg->{ids}->{other} = { type => $type, target => 'iqn.test', content => {} };
+ like(
+ $check->(),
+ qr/storage 'other' serves images from this target$/,
+ "$type storage of the target refuses",
+ );
}
+$cfg->{ids}->{data} = { type => 'lvm', base => 'direct:0.0.1.dm-uuid-mpath-3600+abc' };
+like($check->(), qr/base volume/, 'base reference refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-3600+abc';
+like($check->(), qr/base volume/, 'scsi WWID in base name refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-legacy';
+$storage->mock(path => sub { '/dev/disk/by-id/legacy' });
+$scan->mock(abs_path => sub { '/dev/dm-0' });
+like($check->(), qr/base volume/, 'resolved alias to the LUN refuses');
+$scan->mock(abs_path => sub { $_[0] eq $lun->{devpath} ? '/dev/dm-0' : '/dev/dm-1' });
+is($check->(), '', 'base on another device is no match');
+$scan->mock(abs_path => sub { undef });
+is($check->(), '', 'unresolvable base is no match');
+$storage->mock(path => sub { die "base unavailable\n" });
+is($check->(), '', 'unavailable base is no match');
+ok(!PVE::Storage::LVMPlugin->can('create_volume_group'), 'creation implementation is lexical');
+$cfg->{ids} = {};
+my @order;
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-3600=2babc', 'lock name escapes unsafe characters without collisions');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+PVE::Storage::SAN::with_lun_lock($lun, sub { push @order, 'write' });
+is_deeply(\@order, [qw(lock write unlock)], 'the code runs under the lock of the LUN');
+
+# volume group creation checks the references only when it has to initialize the LUN
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(
+ verify_blockdev_path => sub { $_[0] },
+ is_mounted => sub { undef },
+ has_holder => sub { undef },
+);
+my ($signatures, $pvinfo) = ('', undef);
+$lun->{'by-id'} = '/dev/null';
+$scan->mock(
+ lun_for_device => sub { $lun },
+ assert_same_device => sub { },
+ assert_lun_unreferenced => sub { push @order, 'check'; die "referenced\n" },
+);
+$lvm->mock(
+ file_read_firstline => sub { $_[0] =~ m{/size$} ? '2048' : undef },
+ lvm_pv_info => sub { $pvinfo },
+ clear_first_sector => sub { push @order, 'clear' },
+ run_command => sub {
+ my ($cmd, %param) = @_;
+ return $param{outfunc}->(qq({"signatures":[$signatures]})) if $cmd->[0] eq 'wipefs';
+ push @order, $cmd->[0];
+ },
+);
+@order = ();
+$signatures = '{"type":"LVM2_member","offset":"0x218"}';
+$pvinfo = { vgname => 'data', in_use => '1' };
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an existing volume group can be added whatever references its LUN');
+is_deeply(\@order, [qw(lock unlock)], 'without reference check or write');
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'other',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/already used by volume group 'data'/, 'another volume group on the LUN refuses');
+@order = ();
+($signatures, $pvinfo) = ('', undef);
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/referenced/, 'initializing a referenced LUN refuses');
+is_deeply(\@order, [qw(lock check)], 'the check precedes the first write');
+$scan->mock(assert_lun_unreferenced =>
+ sub { is($_[2], 'new', 'new storage exempt'); push @order, 'check' });
+@order = ();
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an unreferenced empty LUN is initialized');
+is_deeply(
+ \@order,
+ [qw(lock check clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'checked once, then written under the lock',
+);
done_testing();
diff --git a/src/test/run_test_lvm_create.pl b/src/test/run_test_lvm_create.pl
index d4be25b0..4d94ea9c 100755
--- a/src/test/run_test_lvm_create.pl
+++ b/src/test/run_test_lvm_create.pl
@@ -10,9 +10,12 @@ use Test::More;
use lib ('.', '..');
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+$san->mock(lun_for_device => sub { undef });
my $tools = Test::MockModule->new('PVE::Tools');
my $inotify = Test::MockModule->new('PVE::INotify');
$inotify->mock(nodename => sub { 'testnode' });
@@ -170,6 +173,17 @@ like(
qr/contains data \(gpt\)/,
'a partition table of a map is data, kpartx may not map it',
);
+reset_case();
+($signatures, $partitioned) = ([{ type => 'PMBR' }, { type => 'gpt' }], 1);
+$san->mock(
+ lun_for_device =>
+ sub { { wwid => '3600abc', devpath => '/dev/sda', 'by-id' => '/dev/null' } },
+ with_lun_lock => sub { $_[1]->() },
+);
+like(create(), qr/contains data \(PMBR, gpt\)/, 'a partitioned LUN that is no map is data too');
+is_deeply(\@writes, [], 'partitioned LUN: no writes');
+$san->unmock('with_lun_lock');
+$san->mock(lun_for_device => sub { undef });
my $uuid = 'aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg';
for my $vg ('test', 'other', 'unknown', '') {
^ permalink raw reply related [relevance 11%]
* [PATCH storage 02/17] nvmeof: add a storage for NVMe over Fabrics subsystems
@ 2026-11-13 3:04 20% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-13 3:04 UTC (permalink / raw)
To: pve-devel
NVMe/TCP namespaces need a manual nvme-cli setup on every node so
far. Add a storage type that connects one subsystem through each
configured portal and offers its namespaces as raw volumes. Native
NVMe multipath joins the paths and the kernel reconnects lost ones.
Local disk setup refuses namespaces attached over a fabric, as for
iSCSI LUNs. Wiping a namespace or creating a volume group on it is
refused while a storage serves images from its subsystem. nvme-cli
is only recommended, as no other storage type needs it.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
debian/control | 1 +
src/PVE/Diskmanage.pm | 10 ++
src/PVE/Makefile | 1 +
src/PVE/NVMeOF.pm | 249 +++++++++++++++++++++++++++++
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 204 +++++++++++++++++++++++
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SAN.pm | 13 ++
src/test/Makefile | 6 +-
src/test/run_nvmeof_taint_tests.pl | 60 +++++++
src/test/run_nvmeof_tests.pl | 243 ++++++++++++++++++++++++++++
src/test/run_san_nvme_tests.pl | 13 ++
13 files changed, 803 insertions(+), 2 deletions(-)
create mode 100644 src/PVE/NVMeOF.pm
create mode 100644 src/PVE/Storage/NVMeOFPlugin.pm
create mode 100755 src/test/run_nvmeof_taint_tests.pl
create mode 100755 src/test/run_nvmeof_tests.pl
diff --git a/debian/control b/debian/control
index 14d8a648..99b41f92 100644
--- a/debian/control
+++ b/debian/control
@@ -55,6 +55,7 @@ Depends: bzip2,
${misc:Depends},
${perl:Depends},
Recommends: multipath-tools,
+ nvme-cli,
pve-esxi-import-tools (>= 0.6.0),
skopeo,
zfsutils-linux (>= 2.4.1-pve2),
diff --git a/src/PVE/Diskmanage.pm b/src/PVE/Diskmanage.pm
index 1fec9ec5..7bee3b08 100644
--- a/src/PVE/Diskmanage.pm
+++ b/src/PVE/Diskmanage.pm
@@ -108,6 +108,8 @@ sub disk_is_used {
my $disklist = get_disks($dev, 1, 1);
die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
+ die "'$disk' is not a valid local disk\n"
+ if ($disklist->{$dev}->{transport} // '') =~ /^nvme-(?:tcp|rdma|fc)$/;
return 1 if $disklist->{$dev}->{used};
return 0;
@@ -503,6 +505,14 @@ sub dir_is_empty {
return 1;
}
+# Some controllers pad the NQN or derive it from padded serial/model fields.
+sub read_subsysnqn {
+ my ($path) = @_;
+ my $nqn = file_read_firstline($path) // return undef;
+ $nqn =~ s/\s+$//;
+ return $nqn;
+}
+
# Returns the NVMe transport (pcie, fc, tcp, rdma, loop) of a namespace, either directly from
# its controller, or from any controller of its subsystem for native NVMe multipath setups.
sub get_nvme_transport {
diff --git a/src/PVE/Makefile b/src/PVE/Makefile
index 13fecbf8..238eefd4 100644
--- a/src/PVE/Makefile
+++ b/src/PVE/Makefile
@@ -4,6 +4,7 @@
install:
install -D -m 0644 Storage.pm ${DESTDIR}${PERLDIR}/PVE/Storage.pm
install -D -m 0644 Diskmanage.pm ${DESTDIR}${PERLDIR}/PVE/Diskmanage.pm
+ install -D -m 0644 NVMeOF.pm ${DESTDIR}${PERLDIR}/PVE/NVMeOF.pm
install -D -m 0644 ISCSI/Topology.pm ${DESTDIR}${PERLDIR}/PVE/ISCSI/Topology.pm
install -D -m 0644 Multipath.pm ${DESTDIR}${PERLDIR}/PVE/Multipath.pm
install -D -m 0644 Multipath/Config.pm ${DESTDIR}${PERLDIR}/PVE/Multipath/Config.pm
diff --git a/src/PVE/NVMeOF.pm b/src/PVE/NVMeOF.pm
new file mode 100644
index 00000000..7a3140cb
--- /dev/null
+++ b/src/PVE/NVMeOF.pm
@@ -0,0 +1,249 @@
+package PVE::NVMeOF;
+
+use v5.36;
+
+use Digest::SHA qw(sha1_hex);
+use Fcntl qw(:flock F_GETFD F_SETFD FD_CLOEXEC);
+use File::Path qw(make_path);
+use Socket qw(AF_INET AF_INET6 inet_ntop inet_pton);
+
+use PVE::Diskmanage;
+use PVE::JSONSchema;
+use PVE::Tools qw(dir_glob_foreach file_read_firstline file_set_contents run_command);
+
+our $NVME = '/usr/sbin/nvme';
+our $SYSFS = '/sys';
+our $HOSTNQN_FILE = '/etc/nvme/hostnqn';
+our $HOSTID_FILE = '/etc/nvme/hostid';
+our $RUN_DIR = '/run/pve/nvmeof';
+our $NQN_PATTERN = 'nqn\.[^\s,=]+';
+
+sub canonical_address($addr) {
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ return inet_ntop(AF_INET, $packed);
+ }
+ if (defined(my $packed = inet_pton(AF_INET6, $addr))) {
+ return inet_ntop(AF_INET, substr($packed, 12))
+ if substr($packed, 0, 12) eq ("\0" x 10) . "\xff\xff";
+ return inet_ntop(AF_INET6, $packed);
+ }
+ return lc($addr);
+}
+
+# Link-local IPv6 needs a node-specific interface and cannot identify a shared configured portal.
+sub parse_portal($portal) {
+ my ($addr, $port);
+ if ($portal =~ m/^\[([0-9a-fA-F:.]+)\](?::(\d+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } elsif ($portal =~ m/^(\d+\.\d+\.\d+\.\d+)(?::(\d+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } else {
+ return undef;
+ }
+ return undef if defined($port) && ($port < 1 || $port > 65535);
+ $addr = canonical_address($addr);
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ return undef
+ if $addr eq '0.0.0.0'
+ || $addr eq '255.255.255.255'
+ || (unpack('C', $packed) & 0xf0) == 0xe0;
+ } elsif (defined($packed = inet_pton(AF_INET6, $addr))) {
+ my $prefix = unpack('n', $packed);
+ return undef
+ if $addr eq '::' || ($prefix & 0xffc0) == 0xfe80 || ($prefix & 0xff00) == 0xff00;
+ } else {
+ return undef;
+ }
+ return { traddr => $addr, trsvcid => int($port // 4420) };
+}
+
+PVE::JSONSchema::register_format(
+ 'pve-storage-nvme-portal',
+ sub($portal, $noerr = undef) {
+ return $portal if parse_portal($portal);
+ return undef if $noerr;
+ die "value is not an IPv4 address or a bracketed IPv6 address with optional port\n";
+ },
+);
+
+sub format_path($path) {
+ my $addr = $path->{traddr} =~ /:/ ? "[$path->{traddr}]" : $path->{traddr};
+ return defined($path->{trsvcid}) ? "$addr:$path->{trsvcid}" : $addr;
+}
+
+sub storage_paths($scfg) {
+ return [map { parse_portal($_) // die "invalid portal '$_'\n" }
+ PVE::Tools::split_list($scfg->{'nvme-portals'})];
+}
+
+sub host_identity() {
+ my ($nqn) = (file_read_firstline($HOSTNQN_FILE) // '') =~ /\A($NQN_PATTERN)\z/;
+ my ($id) = (file_read_firstline($HOSTID_FILE) // '') =~
+ /\A([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\z/i;
+ die
+ "invalid or missing NVMe host NQN in '$HOSTNQN_FILE' - install nvme-cli and check the host identity\n"
+ if !defined($nqn) || length($nqn) > 223;
+ die "invalid or missing NVMe host ID in '$HOSTID_FILE' - expected a nonzero UUID\n"
+ if !defined($id) || $id =~ /^[0-]+$/;
+ return { nqn => $nqn, id => lc($id) };
+}
+
+sub is_supported() { return -x $NVME ? 1 : 0 }
+
+sub assert_support() {
+ die "nvme-cli is not installed\n" if !is_supported();
+ run_command(['modprobe', 'nvme-tcp'], timeout => 10)
+ if !-e "$SYSFS/module/nvme_tcp";
+ my $multipath = file_read_firstline("$SYSFS/module/nvme_core/parameters/multipath") // '';
+ die "native NVMe multipath is disabled - enable nvme_core.multipath\n" if $multipath ne 'Y';
+}
+
+sub controllers() {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-fabrics/ctl";
+ dir_glob_foreach(
+ $dir,
+ 'nvme\d+',
+ sub($name, @) {
+ my $address = file_read_firstline("$dir/$name/address") // return;
+ my %address = map { split(/=/, $_, 2) } grep { /=/ } split(/,/, $address);
+ return if !defined($address{traddr});
+ $res->{$name} = {
+ transport => file_read_firstline("$dir/$name/transport") // '',
+ subsystem => PVE::Diskmanage::read_subsysnqn("$dir/$name/subsysnqn") // '',
+ state => file_read_firstline("$dir/$name/state") // 'unknown',
+ traddr => canonical_address($address{traddr}),
+ trsvcid => $address{trsvcid},
+ };
+ },
+ );
+ return $res;
+}
+
+sub subsystem_controllers($subsystem) {
+ my $controllers = controllers();
+ return {
+ map { $_ => $controllers->{$_} } grep {
+ $controllers->{$_}->{subsystem} eq $subsystem
+ && $controllers->{$_}->{transport} eq 'tcp'
+ } keys %$controllers
+ };
+}
+
+sub path_controller($controllers, $path) {
+ for my $name (sort keys %$controllers) {
+ my $ctrl = $controllers->{$name};
+ return $name
+ if $ctrl->{traddr} eq $path->{traddr}
+ && ($ctrl->{trsvcid} // '') eq $path->{trsvcid};
+ }
+ return undef;
+}
+
+sub namespaces($subsystem) {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-subsystem";
+ dir_glob_foreach(
+ $dir,
+ 'nvme-subsys\d+',
+ sub($subsys, @) {
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$dir/$subsys/subsysnqn") // return;
+ return if $nqn ne $subsystem;
+ dir_glob_foreach(
+ "$dir/$subsys",
+ 'nvme\d+n\d+',
+ sub($dev, @) {
+ my $wwid = file_read_firstline("$SYSFS/block/$dev/wwid") // return;
+ my $size = file_read_firstline("$SYSFS/block/$dev/size") // return;
+ $res->{$dev} = {
+ nsid => int(file_read_firstline("$SYSFS/block/$dev/nsid") // 0),
+ wwid => $wwid,
+ size => int($size) * 512,
+ };
+ },
+ );
+ },
+ );
+ return $res;
+}
+
+sub with_lock($code) {
+ my ($res, $timeout) = PVE::Tools::run_fork_with_timeout(
+ 35,
+ sub {
+ make_path($RUN_DIR);
+ open(my $lock, '>>', "$RUN_DIR/fabrics.lock") or die "cannot open NVMe lock - $!\n";
+ flock($lock, LOCK_EX | LOCK_NB)
+ or die "NVMe over Fabrics is busy - another operation is still running\n";
+ # A command still in the kernel must retain serialization after its caller times out.
+ my $flags = fcntl($lock, F_GETFD, 0) // die "cannot read NVMe lock flags - $!\n";
+ fcntl($lock, F_SETFD, $flags & ~FD_CLOEXEC)
+ or die "cannot inherit NVMe lock - $!\n";
+ return $code->();
+ },
+ );
+ die "NVMe over Fabrics operation timed out - it may still be running\n" if $timeout;
+ return $res;
+}
+
+my sub retry_file($scfg, $path) {
+ my ($key) = sha1_hex(join("\0",
+ $scfg->{subsysnqn},
+ format_path($path),
+ $scfg->{'nvme-fast-io-fail-tmo'} // 120)) =~ /\A([0-9a-f]{40})\z/;
+ return "$RUN_DIR/retry/$key";
+}
+
+sub in_cooldown($scfg, $path) {
+ my $mtime = (stat(retry_file($scfg, $path)))[9] // return 0;
+ my $age = time() - $mtime;
+ return $age > -60 && $age < 60;
+}
+
+sub note_connect_failure($scfg, $path) {
+ make_path("$RUN_DIR/retry");
+ file_set_contents(retry_file($scfg, $path), '');
+}
+
+sub connect_path($scfg, $path) {
+ my ($nqn) = $scfg->{subsysnqn} =~ /\A($NQN_PATTERN)\z/;
+ die "invalid subsystem NQN\n"
+ if !defined($nqn)
+ || length($nqn) > 223
+ || $nqn eq 'nqn.2014-08.org.nvmexpress.discovery';
+ my ($fail) = ($scfg->{'nvme-fast-io-fail-tmo'} // 120) =~ /\A(-?\d+)\z/;
+ die "invalid fast I/O fail timeout\n" if !defined($fail) || $fail < -1;
+ return with_lock(sub {
+ return if path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ assert_support();
+ my $host = host_identity();
+ run_command(
+ [
+ $NVME,
+ 'connect',
+ '--transport=tcp',
+ '--nqn',
+ $nqn,
+ '--traddr',
+ $path->{traddr},
+ '--trsvcid',
+ $path->{trsvcid},
+ '--hostnqn',
+ $host->{nqn},
+ '--hostid',
+ $host->{id},
+ '--ctrl-loss-tmo=-1',
+ '--fast_io_fail_tmo',
+ $fail,
+ ],
+ timeout => 30,
+ );
+ # nvme-cli can exit successfully without having connected
+ die "no controller appeared\n"
+ if !path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ unlink(retry_file($scfg, $path));
+ return;
+ });
+}
+
+1;
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index be6e9743..287d64f0 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -32,6 +32,7 @@ use PVE::Storage::LvmThinPlugin;
use PVE::Storage::NFSPlugin;
use PVE::Storage::CIFSPlugin;
use PVE::Storage::ISCSIPlugin;
+use PVE::Storage::NVMeOFPlugin;
use PVE::Storage::RBDPlugin;
use PVE::Storage::CephFSPlugin;
use PVE::Storage::ISCSIDirectPlugin;
@@ -57,6 +58,7 @@ PVE::Storage::LvmThinPlugin->register();
PVE::Storage::NFSPlugin->register();
PVE::Storage::CIFSPlugin->register();
PVE::Storage::ISCSIPlugin->register();
+PVE::Storage::NVMeOFPlugin->register();
PVE::Storage::RBDPlugin->register();
PVE::Storage::CephFSPlugin->register();
PVE::Storage::ISCSIDirectPlugin->register();
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index a2df83c0..7f2ff6c8 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -6,6 +6,7 @@ SOURCES= \
NFSPlugin.pm \
CIFSPlugin.pm \
ISCSIPlugin.pm \
+ NVMeOFPlugin.pm \
CephFSPlugin.pm \
RBDPlugin.pm \
ISCSIDirectPlugin.pm \
diff --git a/src/PVE/Storage/NVMeOFPlugin.pm b/src/PVE/Storage/NVMeOFPlugin.pm
new file mode 100644
index 00000000..4dc9803a
--- /dev/null
+++ b/src/PVE/Storage/NVMeOFPlugin.pm
@@ -0,0 +1,204 @@
+package PVE::Storage::NVMeOFPlugin;
+
+use strict;
+use warnings;
+
+use Cwd ();
+use Time::HiRes ();
+
+use PVE::Diskmanage;
+use PVE::Network;
+use PVE::NVMeOF;
+use PVE::Storage::Plugin;
+
+use base qw(PVE::Storage::Plugin);
+
+sub type { return 'nvmeof' }
+
+sub plugindata {
+ return {
+ content => [{ images => 1, none => 1 }, { images => 1 }],
+ select_existing => 1,
+ 'sensitive-properties' => {},
+ };
+}
+
+sub properties {
+ return {
+ subsysnqn => {
+ description => 'The NQN of the NVMe subsystem.',
+ type => 'string',
+ pattern => $PVE::NVMeOF::NQN_PATTERN,
+ maxLength => 223,
+ },
+ 'nvme-portals' => {
+ description =>
+ 'TCP portals of the NVMe subsystem, as IPv4 or bracketed IPv6 addresses'
+ . ' with an optional port (default 4420).',
+ type => 'string',
+ format => 'pve-storage-nvme-portal-list',
+ },
+ 'nvme-fast-io-fail-tmo' => {
+ description => 'Seconds before I/O through a reconnecting path fails. -1 disables'
+ . ' this timeout; I/O can remain queued while paths reconnect.',
+ type => 'integer',
+ minimum => -1,
+ default => 120,
+ },
+ };
+}
+
+sub options {
+ return {
+ subsysnqn => { fixed => 1 },
+ 'nvme-portals' => {},
+ 'nvme-fast-io-fail-tmo' => { optional => 1 },
+ nodes => { optional => 1 },
+ disable => { optional => 1 },
+ content => { optional => 1 },
+ bwlimit => { optional => 1 },
+ };
+}
+
+my sub assert_valid_config {
+ my ($scfg) = @_;
+ die "the discovery subsystem cannot be used as storage\n"
+ if $scfg->{subsysnqn} eq 'nqn.2014-08.org.nvmexpress.discovery';
+ my %seen;
+ for my $path (PVE::NVMeOF::storage_paths($scfg)->@*) {
+ my $portal = PVE::NVMeOF::format_path($path);
+ die "portal '$portal' is listed more than once\n" if $seen{$portal}++;
+ }
+}
+
+sub on_add_hook {
+ my ($class, $storeid, $scfg, %param) = @_;
+ assert_valid_config($scfg);
+ return;
+}
+
+sub on_update_hook_full {
+ my ($class, $storeid, $scfg, $update, $delete, $sensitive) = @_;
+ my $merged = { %$scfg, %$update };
+ delete $merged->{$_} for ($delete // [])->@*;
+ assert_valid_config($merged);
+ return $class->SUPER::on_update_hook_full($storeid, $scfg, $update, $delete, $sensitive);
+}
+
+sub parse_volname {
+ my ($class, $volname) = @_;
+ if ($volname =~ m!^(nvme-[a-zA-Z0-9_.:+-]+)$! && $volname !~ /-part\d+$/) {
+ return ('images', $1, undef, undef, undef, undef, 'raw');
+ }
+ die "unable to parse NVMe over Fabrics volume name '$volname'\n";
+}
+
+sub filesystem_path {
+ my ($class, $scfg, $volname, $snapname) = @_;
+ die "snapshot is not possible on NVMe over Fabrics storage\n" if defined($snapname);
+ my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+ my $path = "/dev/disk/by-id/$name";
+ return wantarray ? ($path, $vmid, $vtype) : $path;
+}
+
+sub create_base { die "can't create base images in NVMe over Fabrics storage\n" }
+sub clone_image { die "can't clone images in NVMe over Fabrics storage\n" }
+sub alloc_image { die "can't allocate space in NVMe over Fabrics storage\n" }
+sub free_image { die "can't free space in NVMe over Fabrics storage\n" }
+sub volume_resize { die "volume resize is not possible on NVMe over Fabrics storage\n" }
+
+sub list_volumes {
+ my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
+ my $res = $class->list_images($storeid, $scfg, $vmid);
+ $_->{content} = 'images' for @$res;
+ return $res;
+}
+
+sub list_images {
+ my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
+ return [] if defined($vmid) && !$vollist;
+ my $namespaces = PVE::NVMeOF::namespaces($scfg->{subsysnqn});
+ my $res = [];
+ for my $dev (sort keys %$namespaces) {
+ my $ns = $namespaces->{$dev};
+ my $volid = "$storeid:nvme-$ns->{wwid}";
+ next if $vollist && !grep { $_ eq $volid } @$vollist;
+ push @$res,
+ {
+ volid => $volid,
+ format => 'raw',
+ size => $ns->{size},
+ vmid => 0,
+ nsid => $ns->{nsid},
+ };
+ }
+ return $res;
+}
+
+sub status {
+ my ($class, $storeid, $scfg, $cache) = @_;
+ my $active = grep { $_->{state} eq 'live' }
+ values PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn})->%*;
+ return (0, 0, 0, $active ? 1 : 0);
+}
+
+sub activate_storage {
+ my ($class, $storeid, $scfg, $cache) = @_;
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ for my $path (PVE::NVMeOF::storage_paths($scfg)->@*) {
+ next if defined(PVE::NVMeOF::path_controller($controllers, $path));
+ next if PVE::NVMeOF::in_cooldown($scfg, $path);
+ eval {
+ die "no answer from portal\n"
+ if !PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2);
+ PVE::NVMeOF::connect_path($scfg, $path);
+ };
+ if (my $err = $@) {
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ warn "storage '$storeid': connecting to '"
+ . PVE::NVMeOF::format_path($path)
+ . "' failed - $err";
+ }
+ }
+ return;
+}
+
+sub deactivate_storage { return }
+
+sub check_connection {
+ my ($class, $storeid, $scfg) = @_;
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ return 1 if grep { $_->{state} eq 'live' } values %$controllers;
+ for my $path (PVE::NVMeOF::storage_paths($scfg)->@*) {
+ next if defined(PVE::NVMeOF::path_controller($controllers, $path));
+ next if PVE::NVMeOF::in_cooldown($scfg, $path);
+ return 1 if PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2);
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ }
+ return 0;
+}
+
+sub activate_volume {
+ my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
+ my $path = $class->filesystem_path($scfg, $volname, $snapname);
+ my $deadline = Time::HiRes::time() + 10;
+ while (!-b $path && Time::HiRes::time() < $deadline) {
+ last if !keys PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn})->%*;
+ Time::HiRes::usleep(250_000);
+ }
+ my $real = Cwd::realpath($path);
+ die "volume '$volname' is not available on this node\n" if !$real || !-b $real;
+ my ($dev) = $real =~ m!^/dev/(nvme\d+n\d+)$!;
+ die "volume '$volname' is not an NVMe namespace\n" if !defined($dev);
+ my $nqn = PVE::Diskmanage::read_subsysnqn("/sys/block/$dev/device/subsysnqn") // '';
+ die "volume '$volname' is not part of subsystem '$scfg->{subsysnqn}'\n"
+ if $nqn ne $scfg->{subsysnqn};
+}
+
+sub volume_has_feature {
+ my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running) = @_;
+ return 1 if $feature eq 'copy' && !defined($snapname);
+ return undef;
+}
+
+1;
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index e4ad7e6f..783d4145 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -42,7 +42,7 @@ our @COMMON_TAR_FLAGS = qw(
);
our @SHARED_STORAGE = (
- 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs',
+ 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs', 'nvmeof',
);
our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index bba3c128..f3682106 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -232,6 +232,11 @@ sub lun_partitions($lun) {
}
sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my $name = basename($lun->{devpath});
+ my $nqn =
+ $name =~ /^nvme\d+n\d+$/
+ ? PVE::Diskmanage::read_subsysnqn("/sys/block/$name/device/subsysnqn")
+ : undef;
my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
[$lun->{devpath}, lun_partitions($lun)->@*],
)->@*;
@@ -253,6 +258,14 @@ sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
) {
die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
}
+ if (
+ $type eq 'nvmeof'
+ && defined($nqn)
+ && $scfg->{subsysnqn} eq $nqn
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this subsystem\n";
+ }
next if $type ne 'lvm' || !$scfg->{base};
my (undef, $volname) = PVE::Storage::Plugin::parse_volume_id($scfg->{base});
my ($wwid) = $volname =~ m/(?:^|\.)(?:dm-uuid-mpath|scsi|nvme)-(.+)$/;
diff --git a/src/test/Makefile b/src/test/Makefile
index c9bcea8f..124612da 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api
+test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api test_nvmeof
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
@@ -76,3 +76,7 @@ test_san_api: run_san_api_tests.pl run_san_wipe_tests.pl run_san_nvme_tests.pl
test_disk_api: run_disk_api_tests.pl
./run_disk_api_tests.pl
+
+test_nvmeof: run_nvmeof_tests.pl run_nvmeof_taint_tests.pl
+ ./run_nvmeof_tests.pl
+ perl -T ./run_nvmeof_taint_tests.pl
diff --git a/src/test/run_nvmeof_taint_tests.pl b/src/test/run_nvmeof_taint_tests.pl
new file mode 100755
index 00000000..3c19f8cc
--- /dev/null
+++ b/src/test/run_nvmeof_taint_tests.pl
@@ -0,0 +1,60 @@
+#!/usr/bin/perl -T
+
+use v5.36;
+use lib qw(..);
+use File::Temp qw(tempdir);
+use Scalar::Util qw(tainted);
+use Test::More;
+use Test::MockModule;
+use PVE::NVMeOF;
+use PVE::Tools qw(file_set_contents file_get_contents);
+
+$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
+delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
+my $dir = tempdir('nvmeof-taint-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::HOSTNQN_FILE = "$dir/hostnqn";
+local $PVE::NVMeOF::HOSTID_FILE = "$dir/hostid";
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+file_set_contents($PVE::NVMeOF::HOSTNQN_FILE, "nqn.host\n");
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "12345678-1234-1234-1234-123456789abc\n");
+file_set_contents("$dir/config", "nqn.test\n192.0.2.1\n120\n");
+my ($nqn, $portal, $fail) = split(/\n/, file_get_contents("$dir/config"));
+ok(tainted($nqn), 'configuration input is tainted');
+my $nvme = Test::MockModule->new('PVE::NVMeOF');
+$nvme->mock(with_lock => sub { $_[0]->() });
+my $commands = 0;
+$nvme->mock(
+ subsystem_controllers => sub {
+ return $commands ? { nvme0 => { traddr => '192.0.2.1', trsvcid => 4420 } } : {};
+ },
+);
+$nvme->mock(assert_support => sub { });
+$nvme->mock(
+ run_command => sub($cmd, %opts) {
+ $commands++;
+ is(
+ scalar(grep { tainted($_) } @$cmd),
+ 0,
+ 'all connect operands are validated and untainted',
+ );
+ PVE::Tools::run_command(['/usr/bin/true', @$cmd], timeout => 5);
+ },
+);
+my $path = PVE::NVMeOF::parse_portal($portal);
+eval { PVE::NVMeOF::connect_path({ subsysnqn => $nqn, 'nvme-fast-io-fail-tmo' => $fail }, $path) };
+is($@, '', 'connect command can execute in taint mode');
+is($commands, 1, 'one connect');
+PVE::NVMeOF::note_connect_failure({ subsysnqn => $nqn }, $path);
+ok(
+ PVE::NVMeOF::in_cooldown({ subsysnqn => $nqn }, $path),
+ 'cooldown accepts validated file-backed configuration',
+);
+for my $bad ('nqn.bad,nqn=other', "nqn.test\n", 'nqn.2014-08.org.nvmexpress.discovery') {
+ eval { PVE::NVMeOF::connect_path({ subsysnqn => $bad }, $path) };
+ like($@, qr/invalid subsystem/, 'invalid connect subsystem refused');
+}
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "00000000-0000-0000-0000-000000000000\n");
+eval { PVE::NVMeOF::host_identity() };
+like($@, qr/nonzero UUID/, 'zero host ID refused');
+
+done_testing();
diff --git a/src/test/run_nvmeof_tests.pl b/src/test/run_nvmeof_tests.pl
new file mode 100755
index 00000000..5ff96833
--- /dev/null
+++ b/src/test/run_nvmeof_tests.pl
@@ -0,0 +1,243 @@
+#!/usr/bin/perl
+
+use v5.36;
+use lib qw(..);
+use File::Temp qw(tempdir);
+use File::Path qw(make_path);
+use Fcntl qw(:flock);
+use Test::More;
+use Test::MockModule;
+use PVE::NVMeOF;
+use PVE::Storage;
+use PVE::Tools qw(file_set_contents);
+
+my $dir = tempdir('nvmeof-test-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+local $PVE::NVMeOF::SYSFS = "$dir/sys";
+my $class = 'PVE::Storage::NVMeOFPlugin';
+my $cfg = {
+ type => 'nvmeof',
+ subsysnqn => 'nqn.test',
+ 'nvme-portals' => '192.0.2.1,[2001:db8::2]:4421',
+ content => { none => 1 },
+};
+
+subtest 'configuration, portals and volumes' => sub {
+ is(PVE::Storage::Plugin->lookup('nvmeof'), $class, 'plugin registered');
+ is_deeply(
+ [sort keys $class->properties()->%*],
+ [qw(nvme-fast-io-fail-tmo nvme-portals subsysnqn)],
+ 'only three plugin-specific properties',
+ );
+ my $parsed = PVE::Storage::Plugin->parse_config(
+ 'storage.cfg',
+ "nvmeof: fabric\n\tsubsysnqn nqn.test\n\tnvme-portals 192.0.2.1\n\tcontent none\n",
+ );
+ is($parsed->{ids}->{fabric}->{subsysnqn}, 'nqn.test', 'storage.cfg accepts the plugin');
+ is_deeply(
+ $parsed->{ids}->{fabric}->{content},
+ { none => 1 },
+ 'connection-only content parses',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ { traddr => '192.0.2.1', trsvcid => 4420 },
+ 'default I/O port',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('[2001:0db8::1]:4421'),
+ { traddr => '2001:db8::1', trsvcid => 4421 },
+ 'canonical IPv6',
+ );
+ for my $bad (
+ 'host.example', '1.2.3.4:0', '1.2.3.4:65536', '[fe80::1]', '[::]', '224.0.0.1',
+ ) {
+ ok(!PVE::NVMeOF::parse_portal($bad), "invalid portal $bad");
+ }
+ eval {
+ $class->on_add_hook('fabric', { %$cfg, 'nvme-portals' => '192.0.2.1,192.0.2.1:4420' });
+ };
+ like($@, qr/listed more than once/, 'duplicate portals refused');
+ eval {
+ $class->on_add_hook(
+ 'fabric',
+ { %$cfg, subsysnqn => 'nqn.2014-08.org.nvmexpress.discovery' },
+ );
+ };
+ like($@, qr/discovery subsystem/, 'discovery subsystem refused');
+ is(
+ scalar($class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef')),
+ '/dev/disk/by-id/nvme-eui.0123456789abcdef',
+ 'stable volume path',
+ );
+ for my $bad ('nvme-../../sda', 'nvme-eui.abc-part1', 'sda') {
+ eval { $class->parse_volname($bad) };
+ like($@, qr/unable to parse/, "invalid volume $bad");
+ }
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ $nvme->mock(
+ namespaces => sub { { nvme0n1 => { wwid => 'eui.abc', size => 4096, nsid => 1 } } });
+ is(
+ $class->list_volumes('fabric', $cfg)->[0]->{volid},
+ 'fabric:nvme-eui.abc',
+ 'content none still offers bases',
+ );
+ is_deeply($class->list_images('fabric', $cfg, 100), [], 'namespaces have no VM owner');
+ $nvme->mock(subsystem_controllers => sub { {} });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test') };
+ like($@, qr/not available/,
+ 'missing namespace fails without waiting on absent controllers');
+};
+
+subtest 'sysfs topology' => sub {
+ my $sys = $PVE::NVMeOF::SYSFS;
+ make_path(
+ "$sys/class/nvme-fabrics/ctl/nvme1",
+ "$sys/class/nvme-subsystem/nvme-subsys0/nvme0n1",
+ "$sys/block/nvme0n1",
+ );
+ my %attrs = (
+ address => 'traddr=192.0.2.1,trsvcid=4420',
+ transport => 'tcp',
+ subsysnqn => 'nqn.test',
+ state => 'connecting',
+ );
+ file_set_contents("$sys/class/nvme-fabrics/ctl/nvme1/$_", "$attrs{$_}\n") for keys %attrs;
+ file_set_contents("$sys/class/nvme-subsystem/nvme-subsys0/subsysnqn", "nqn.test\n");
+ file_set_contents("$sys/block/nvme0n1/wwid", "eui.abc\n");
+ file_set_contents("$sys/block/nvme0n1/size", "8\n");
+ file_set_contents("$sys/block/nvme0n1/nsid", "1\n");
+ is(
+ PVE::NVMeOF::controllers()->{nvme1}->{state},
+ 'connecting',
+ 'reconnecting controller is still present',
+ );
+ is(
+ PVE::NVMeOF::path_controller(
+ PVE::NVMeOF::subsystem_controllers('nqn.test'),
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ ),
+ 'nvme1',
+ 'portal controller found',
+ );
+ is_deeply(
+ PVE::NVMeOF::namespaces('nqn.test'),
+ { nvme0n1 => { wwid => 'eui.abc', size => 4096, nsid => 1 } },
+ 'namespace facts',
+ );
+ is_deeply(PVE::NVMeOF::namespaces('nqn.other'), {}, 'other subsystem excluded');
+};
+
+subtest 'serialized commands inherit the lock' => sub {
+ my $value = PVE::NVMeOF::with_lock(sub {
+ my $out = '';
+ PVE::Tools::run_command(
+ [
+ '/usr/bin/perl',
+ '-MFcntl=:flock',
+ '-e',
+ 'my @held = grep { (readlink($_) // "") =~ /fabrics.lock$/ } glob("/proc/self/fd/*"); die "not inherited" if !@held; open(my $fh, ">>", $ARGV[0]) or die $!; die "lock missing" if flock($fh, LOCK_EX|LOCK_NB); print "locked\\n";',
+ "$PVE::NVMeOF::RUN_DIR/fabrics.lock",
+ ],
+ timeout => 5,
+ outfunc => sub { $out .= $_[0] },
+ );
+ return $out;
+ });
+ is($value, 'locked', 'exec cannot acquire the lock held by its parent');
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or die $!;
+ flock($lock, LOCK_EX) or die $!;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'busy operation never enters callback');
+ close($lock);
+
+ my $tools = Test::MockModule->new('PVE::Tools');
+ my $timed_out = 1;
+ $tools->mock(run_fork_with_timeout => sub { return ($_[1]->(), $timed_out) });
+ my $retained;
+ eval {
+ PVE::NVMeOF::with_lock(sub {
+ my ($path) =
+ grep { (readlink($_) // '') =~ /fabrics.lock$/ } glob('/proc/self/fd/*');
+ my ($fd) = $path =~ m{/(\d+)$};
+ open($retained, '>&', $fd) or die $!;
+ return 1;
+ });
+ };
+ like($@, qr/timed out.*may still be running/, 'timeout does not claim deletion completed');
+ $timed_out = 0;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'retained descriptor keeps serialization after the caller returns');
+ close($retained);
+ is(PVE::NVMeOF::with_lock(sub { 1 }), 1, 'last descriptor close releases serialization');
+};
+
+subtest 'connect options, kernel reconnect and cooldown' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my @commands;
+ my $controllers = {};
+ $nvme->mock(with_lock => sub { $_[0]->() });
+ $nvme->mock(assert_support => sub { });
+ $nvme->mock(host_identity =>
+ sub { { nqn => 'nqn.host', id => '12345678-1234-1234-1234-123456789abc' } });
+ $nvme->mock(subsystem_controllers => sub { $controllers });
+ my $appear = 1;
+ $nvme->mock(
+ run_command => sub($cmd, %opts) {
+ is($opts{timeout}, 30, 'bounded connect');
+ push @commands, $cmd;
+ my %arg =
+ map { $cmd->[$_] => $cmd->[$_ + 1] } grep { $cmd->[$_] =~ /^--tr/ } 0 .. $#$cmd;
+ $controllers->{ 'nvme' . scalar(@commands) } =
+ { traddr => $arg{'--traddr'}, trsvcid => $arg{'--trsvcid'}, state => 'live' }
+ if $appear;
+ },
+ );
+ $net->mock(tcp_ping => sub { 1 });
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 2, 'one connect per missing portal');
+ ok(grep({ $_ eq '--ctrl-loss-tmo=-1' } $commands[0]->@*), 'kernel reconnects indefinitely');
+ is_deeply([@{ $commands[0] }[-2, -1]], ['--fast_io_fail_tmo', 120], 'fast failure default');
+ @commands = ();
+ $controllers = {
+ nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' },
+ nvme2 => { traddr => '2001:db8::2', trsvcid => 4421, state => 'live' },
+ };
+ $class->activate_storage('fabric', $cfg);
+ is_deeply(\@commands, [],
+ 'existing controllers are never reconnected, regardless of state');
+ $class->deactivate_storage('fabric', $cfg);
+ is_deeply(\@commands, [], 'deactivation does not remove controllers');
+ $controllers = {};
+ my $path = PVE::NVMeOF::storage_paths($cfg)->[0];
+ PVE::NVMeOF::note_connect_failure($cfg, $path);
+ ok(PVE::NVMeOF::in_cooldown($cfg, $path), 'failure starts cooldown');
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 1, 'only the other portal connects');
+ ($controllers, $appear) = ({}, 0);
+ my $other = PVE::NVMeOF::storage_paths($cfg)->[1];
+ my $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ $class->activate_storage('fabric', $cfg);
+ }
+ like($warning, qr/no controller appeared/, 'a connect without a controller is a failure');
+ ok(PVE::NVMeOF::in_cooldown($cfg, $other), 'which starts the cooldown too');
+};
+
+subtest 'local disk setup rejects fabric namespaces by transport' => sub {
+ my $disk = Test::MockModule->new('PVE::Diskmanage');
+ for my $transport (qw(nvme-tcp nvme-rdma nvme-fc)) {
+ $disk->mock(get_disks => sub { { nvme0n1 => { transport => $transport } } });
+ eval { PVE::Diskmanage::assert_disk_unused('/dev/nvme0n1') };
+ like($@, qr/not a valid local disk/,
+ "$transport refuses without storage configuration");
+ }
+};
+
+done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
index c2f3c65e..b1a39629 100755
--- a/src/test/run_san_nvme_tests.pl
+++ b/src/test/run_san_nvme_tests.pl
@@ -38,6 +38,7 @@ $storage->mock(config => sub { $cfg });
$disk->mock(verify_blockdev_path => sub { $device });
$disk->mock(is_partition => sub { 0 });
$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(read_subsysnqn => sub { 'nqn.test' });
$disk->mock(is_iscsi_device => sub { 0 });
$disk->mock(is_mounted => sub { 0 });
$disk->mock(has_holder => sub { 0 });
@@ -65,6 +66,18 @@ $disk->mock(is_partition => sub { 0 });
$cfg->{ids}->{data} = { type => 'lvm', base => 'fabric:nvme-eui.0123456789abcdef' };
eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
like($@, qr/base volume/, 'native base reference refuses');
+$cfg->{ids} =
+ { fabric =>
+ { type => 'nvmeof', subsysnqn => 'nqn.test', disable => 1, content => { images => 1 } } };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like(
+ $@,
+ qr/serves images from this subsystem/,
+ 'direct namespace image use refuses even when disabled',
+);
+$cfg->{ids}->{fabric}->{content} = { none => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+is($@, '', 'connection-only storage permits namespace initialization');
$cfg->{ids} = {};
@order = @opens = ();
$tools->mock(file_get_contents => sub { 1024 });
^ permalink raw reply related [relevance 20%]
* [PATCH v5 storage 20/36] disks: lvm: allow volume groups on SAN LUNs and multipath maps
@ 2026-11-16 1:23 10% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-16 1:23 UTC (permalink / raw)
To: pve-devel
The node disk API creates volume groups on local disks only. It takes
a Fibre Channel LUN for one, but not a multipath map, and adds the
storage as local to the node. Accept the LUNs of the SAN inventory and
add their storage as shared and without node restriction. Refuse an
existing storage ID for them: adding the node to a storage with the
same volume group name is meant for local volume groups and would
combine two different volume groups in one shared storage.
Initializing a LUN, here or as base volume of a new LVM storage, now
takes a cluster-wide lock per WWID and refuses a LUN that a storage
references through its volume group, as base volume or as iSCSI
target serving images. The LUN is held open by its stable name
meanwhile, and creation stops if the device name used for the checks
and the LVM commands no longer means that device: the name of a map
can pass to another one while the lock is awaited.
A LUN that a process of the node has open is refused too. A guest
that got the LUN as disk from a third-party storage plugin, or by its
device path, is neither a holder nor a storage reference, and its
disk can look empty. The check reads the open files of the processes
and misses an open through another device node, for example the one
of a container.
Co-authored-by: Dietmar Maurer <dietmar@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
src/PVE/API2/Disks/LVM.pm | 56 +++---
src/PVE/Diskmanage.pm | 21 +++
src/PVE/Storage/LVMPlugin.pm | 80 +++++++-
src/PVE/Storage/SAN.pm | 99 ++++++++++
src/test/Makefile | 8 +-
src/test/disk_api_test.pm | 235 ++++++++++++++++++++++++
src/test/run_disk_api_tests.pl | 11 ++
src/test/run_san_library_tests.pl | 27 +++
src/test/run_san_nvme_tests.pl | 92 ++++++++++
src/test/run_san_taint_tests.pl | 26 +++
src/test/run_test_lvm_base_conflicts.pl | 233 ++++++++++++++++-------
src/test/run_test_lvm_create.pl | 41 +++++
12 files changed, 832 insertions(+), 97 deletions(-)
create mode 100644 src/test/disk_api_test.pm
create mode 100755 src/test/run_disk_api_tests.pl
create mode 100755 src/test/run_san_nvme_tests.pl
diff --git a/src/PVE/API2/Disks/LVM.pm b/src/PVE/API2/Disks/LVM.pm
index 6101743b..a0ab6d69 100644
--- a/src/PVE/API2/Disks/LVM.pm
+++ b/src/PVE/API2/Disks/LVM.pm
@@ -4,6 +4,7 @@ use strict;
use warnings;
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
use PVE::Diskmanage;
use PVE::JSONSchema qw(get_standard_option);
use PVE::API2::Storage::Config;
@@ -130,7 +131,8 @@ __PACKAGE__->register_method({
name => get_standard_option('pve-storage-id'),
device => {
type => 'string',
- description => 'The block device you want to create the volume group on',
+ description => 'The block device you want to create the volume group on.'
+ . ' Multipath mapped devices are supported.',
},
add_storage => {
description => "Configure storage using the Volume Group",
@@ -152,48 +154,54 @@ __PACKAGE__->register_method({
my $node = $param->{node};
$dev = PVE::Diskmanage::verify_blockdev_path($dev);
- PVE::Diskmanage::assert_disk_unused($dev);
+ my $san = PVE::Storage::SAN::is_san_device($dev);
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
my $storage_params = {
type => 'lvm',
vgname => $name,
storage => $name,
content => 'rootdir,images',
- shared => 0,
- nodes => $node,
+ shared => $san ? 1 : 0,
+ $san ? () : (nodes => $node),
};
my $verify_params = [qw(vgname)];
if ($param->{add_storage}) {
$rpcenv->check($user, "/storage", ['Datastore.Allocate']);
+ # only local volume groups of the same name may share a storage that exists already
+ die "storage ID '$name' already defined\n"
+ if $san && PVE::Storage::storage_config(PVE::Storage::config(), $name, 1);
+
# reserve the name and add as disabled, will be enabled below if creation works out
PVE::API2::Storage::Config->create_or_update(
$name, $node, $storage_params, $verify_params, 1,
);
}
+ my $create_group = sub {
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
+ die "volume group with name '${name}' already exists on node '${node}'\n"
+ if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
+
+ if (PVE::Diskmanage::is_partition($dev)) {
+ eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
+ warn $@ if $@;
+ }
+
+ PVE::Storage::LVMPlugin::lvm_create_volume_group($dev, $name, $san);
+
+ PVE::Diskmanage::udevadm_trigger($dev);
+
+ if ($param->{add_storage}) {
+ PVE::API2::Storage::Config->create_or_update(
+ $name, $node, $storage_params, $verify_params,
+ );
+ }
+ };
my $worker = sub {
- PVE::Diskmanage::locked_disk_action(sub {
- PVE::Diskmanage::assert_disk_unused($dev);
- die "volume group with name '${name}' already exists on node '${node}'\n"
- if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
-
- if (PVE::Diskmanage::is_partition($dev)) {
- eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
- warn $@ if $@;
- }
-
- PVE::Storage::LVMPlugin::lvm_create_volume_group($dev, $name);
-
- PVE::Diskmanage::udevadm_trigger($dev);
-
- if ($param->{add_storage}) {
- PVE::API2::Storage::Config->create_or_update(
- $name, $node, $storage_params, $verify_params,
- );
- }
- });
+ $san ? $create_group->() : PVE::Diskmanage::locked_disk_action($create_group);
};
return $rpcenv->fork_worker('lvmcreate', $name, $user, $worker);
diff --git a/src/PVE/Diskmanage.pm b/src/PVE/Diskmanage.pm
index 8670165c..e7efd521 100644
--- a/src/PVE/Diskmanage.pm
+++ b/src/PVE/Diskmanage.pm
@@ -1117,6 +1117,27 @@ sub change_parttype {
run_command(['sgdisk', "-t${partnum}:${parttype}", $blockdev], errmsg => $err);
}
+# Returns the PID and command name of a process that has one of the block devices open, if any.
+# Only sees an open through the device nodes in /dev of the node, so for example not one through
+# the own device node of a container.
+sub device_opener {
+ my (@devices) = @_;
+
+ my %nodes = map { $_ => 1 } grep { defined($_) } map { abs_path($_) } @devices;
+
+ opendir(my $proc, '/proc') or return undef;
+ for my $pid (grep { m/^\d+$/ && $_ != $$ } readdir($proc)) {
+ opendir(my $fds, "/proc/$pid/fd") or next;
+ for my $fd (readdir($fds)) {
+ my $target = readlink("/proc/$pid/fd/$fd") // next;
+ next if !$nodes{$target};
+ my $comm = file_read_firstline("/proc/$pid/comm") // 'unknown';
+ return "$pid ($comm)";
+ }
+ }
+ return undef;
+}
+
# Wipes all labels and the first 200 MiB of a disk/partition (or the whole if it is smaller).
# If called with a partition, also sets the partition type to 0x83 'Linux filesystem'.
# Expected to be called with a result of verify_blockdev_path().
diff --git a/src/PVE/Storage/LVMPlugin.pm b/src/PVE/Storage/LVMPlugin.pm
index 1bfb26c0..ab744266 100644
--- a/src/PVE/Storage/LVMPlugin.pm
+++ b/src/PVE/Storage/LVMPlugin.pm
@@ -17,6 +17,7 @@ use PVE::Exception qw(raise_param_exc);
use PVE::Format qw(render_bytes render_duration);
use PVE::INotify;
use PVE::JSONSchema qw(get_standard_option);
+use PVE::Multipath;
use PVE::RESTEnvironment qw(log_warn);
use PVE::Tools qw(run_command file_get_contents file_read_firstline trim);
@@ -160,6 +161,37 @@ sub cached_pv_volume_groups {
return $res;
}
+sub lun_volume_groups {
+ my ($devices) = @_;
+ my $output = '';
+ run_command(
+ [
+ '/sbin/pvs',
+ '--nohints',
+ '--readonly',
+ '--devices',
+ join(',', @$devices),
+ '--reportformat',
+ 'json',
+ '--options',
+ 'pv_name,vg_name',
+ ],
+ timeout => 10,
+ outfunc => sub { $output .= "$_[0]\n" },
+ );
+ my $data = decode_json($output);
+ my $pvs = $data->{report}->[0]->{pv};
+ die "unable to inspect volume groups - invalid pvs report\n" if ref($pvs) ne 'ARRAY';
+ my %vgs;
+ for my $pv (@$pvs) {
+ my $vg = $pv->{vg_name};
+ die "unable to inspect volume groups - missing volume group metadata\n"
+ if !defined($vg) || $vg eq '[unknown]';
+ $vgs{$vg} = 1 if length($vg);
+ }
+ return [sort keys %vgs];
+}
+
sub clear_first_sector {
my ($dev) = shift;
@@ -170,10 +202,17 @@ sub clear_first_sector {
}
}
-sub lvm_create_volume_group {
- my ($device, $vgname, $shared, $guard) = @_;
-
+my sub create_volume_group {
+ my ($device, $vgname, $lun, $guard) = @_;
$device = PVE::Diskmanage::verify_blockdev_path($device);
+ my $fh;
+ if ($lun) {
+ sysopen($fh, $lun->{'by-id'}, O_RDWR) or die "cannot open '$device' - $!\n";
+ }
+ my $check_name = sub {
+ PVE::Storage::SAN::assert_same_device($lun, $fh, $device) if $lun;
+ };
+ $check_name->();
my $refuse_data = sub {
my (@types) = @_;
die "device '$device' contains data ("
@@ -191,7 +230,7 @@ sub lvm_create_volume_group {
if !defined($size) || $size !~ m/^\d+$/ || !$size;
die "unable to probe '$device' - missing device mapper identity\n"
if basename($device) =~ m/^dm-\d+$/ && !defined($uuid);
- if (defined($uuid) && $uuid =~ m/^mpath-/) {
+ if (PVE::Multipath::parse_dm_uuid($uuid)) {
# A queueing map without a running path can stall even a read-only probe.
my $running = 0;
PVE::Tools::dir_glob_foreach(
@@ -218,6 +257,8 @@ sub lvm_create_volume_group {
}
my %signatures = map { $_->{type} => 1 } $probe->@*;
my $res = lvm_pv_info($device, $signatures{LVM2_member});
+ # also a volume group that exists already only counts if the probes looked at the held LUN
+ $check_name->();
# A PV without metadata copies can belong to a VG whose other devices are not visible. The
# sentinel is not a VG name or orphan proof, even if the use flag contradicts it.
@@ -260,26 +301,51 @@ sub lvm_create_volume_group {
}
$refuse_data->(keys %signatures) if %signatures;
+ # Only initializing the device needs the checks, an existing volume group on it can be added.
$guard->{check_storage}->($device) if $guard && $guard->{check_storage};
- clear_first_sector($device); # else pvcreate fails
+ if ($lun) {
+ my $exempt = $guard ? $guard->{exempt} : undef;
+ PVE::Storage::SAN::assert_lun_unreferenced(PVE::Storage::config(), $lun, $exempt);
+ # a guest with the LUN as disk has it open, without being a holder or a storage reference
+ my $opener = PVE::Diskmanage::device_opener($device);
+ die "cannot create volume group on '$device' - process $opener has it open\n"
+ if defined($opener);
+ }
+
+ $check_name->();
+ clear_first_sector($lun ? '/proc/' . $$ . '/fd/' . fileno($fh) : $device);
# we use --metadatasize 250k, which reseults in "pe_start = 512"
# so pe_start is aligned on a 128k boundary (advantage for SSDs)
my $cmd = ['/sbin/pvcreate', '--metadatasize', '250k', $device];
- run_command($cmd, errmsg => "pvcreate '$device' error");
+ $check_name->();
+ run_command($cmd, errmsg => "pvcreate '$device' error", $lun ? (timeout => 30) : ());
$cmd = ['/sbin/vgcreate', $vgname, $device];
# push @$cmd, '-c', 'y' if $shared; # we do not use this yet
+ $check_name->();
run_command(
$cmd,
+ $lun ? (timeout => 30) : (),
errmsg => "vgcreate $vgname $device error",
errfunc => $ignore_no_medium_warnings,
outfunc => $ignore_no_medium_warnings,
);
}
+sub lvm_create_volume_group {
+ my ($device, $vgname, $shared, $guard) = @_;
+ require PVE::Storage::SAN;
+ my $lun = PVE::Storage::SAN::lun_for_device($device);
+ return create_volume_group($device, $vgname, undef, $guard) if !$lun;
+ PVE::Storage::SAN::with_lun_lock(
+ $lun,
+ sub { create_volume_group($device, $vgname, $lun, $guard) },
+ );
+}
+
sub lvm_destroy_volume_group {
my ($vgname) = @_;
@@ -1143,7 +1209,7 @@ sub on_add_hook {
$path,
$scfg->{vgname},
$scfg->{shared},
- { check_storage => $check_target },
+ { check_storage => $check_target, exempt => $storeid },
);
}
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index 5e742523..812e0718 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -5,6 +5,7 @@ use v5.36;
use Cwd qw(abs_path);
use File::Basename qw(basename);
+use PVE::Cluster;
use PVE::INotify;
use PVE::Tools qw(file_read_firstline dir_glob_foreach);
@@ -194,4 +195,102 @@ sub is_san_device($device, $info = undef) {
|| PVE::Diskmanage::is_remote_transport($info->{transport}) ? 1 : 0;
}
+sub lun_for_device($device) {
+ $device = PVE::Diskmanage::verify_blockdev_path($device);
+ return undef if !is_san_device($device);
+ my $rows = scan_luns(PVE::Storage::config());
+ for my $lun (@$rows) {
+ next if (abs_path($lun->{devpath}) // '') ne $device;
+ die "cannot use '$device' - no stable name under /dev/disk/by-id\n" if !$lun->{'by-id'};
+ # read from sysfs, but used in command lines and in the name of the cluster lock
+ ($lun->{devpath}) = $lun->{devpath} =~ m{\A(/dev/[A-Za-z0-9_.:+/-]+)\z}
+ or die "cannot use '$device' - unexpected device path\n";
+ ($lun->{wwid}) = $lun->{wwid} =~ m/\A([A-Za-z0-9_.:+=-]+)\z/
+ or die "cannot use '$device' - unexpected WWID\n";
+ return $lun;
+ }
+ die "cannot use '$device' - select an identified LUN or its multipath map\n";
+}
+
+sub lun_partitions($lun) {
+ my $device = PVE::Diskmanage::verify_blockdev_path($lun->{devpath});
+ my $name = basename($device);
+ my @parts;
+ dir_glob_foreach(
+ "/sys/class/block/$name",
+ "\Q$name\E.+",
+ sub($part, @) {
+ my ($path) = "/dev/$part" =~ m{\A(/dev/[A-Za-z0-9_.+-]+)\z};
+ push @parts, $path if defined($path) && -e "/sys/class/block/$name/$part/partition";
+ },
+ );
+ dir_glob_foreach(
+ "/sys/class/block/$name/holders",
+ 'dm-\\d+',
+ sub($part, @) {
+ my $map = PVE::Multipath::parse_dm_uuid(
+ file_read_firstline("/sys/class/block/$part/dm/uuid"));
+ my ($path) = "/dev/$part" =~ m{\A(/dev/dm-\d+)\z};
+ push @parts, $path
+ if defined($path) && $map && $map->{partition} && $map->{wwid} eq $lun->{wwid};
+ },
+ );
+ return \@parts;
+}
+
+sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
+ [$lun->{devpath}, lun_partitions($lun)->@*],
+ )->@*;
+ # the paths of a LUN can belong to more than one target
+ my %targets = map { $_->{target} => 1 }
+ grep { $_->{wwid} eq $lun->{wwid} && defined($_->{target}) }
+ values PVE::Multipath::Identity::collect(all => 1)->{paths}->%*;
+ for my $sid (sort keys $cfg->{ids}->%*) {
+ next if defined($exempt) && $sid eq $exempt;
+ my $scfg = $cfg->{ids}->{$sid};
+ my $type = $scfg->{type};
+ if (($type eq 'lvm' || $type eq 'lvmthin') && $vgs{ $scfg->{vgname} // '' }) {
+ die "cannot use '$lun->{devpath}' - volume group is used by storage '$sid'\n";
+ }
+ if (
+ defined($scfg->{target})
+ && $targets{ $scfg->{target} }
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
+ }
+ next if $type ne 'lvm' || !$scfg->{base};
+ my (undef, $volname) = PVE::Storage::Plugin::parse_volume_id($scfg->{base});
+ my ($wwid) = $volname =~ m/(?:^|\.)(?:dm-uuid-mpath|scsi|nvme)-(.+)$/;
+ my $matches = defined($wwid) && $wwid eq $lun->{wwid};
+ if (!$matches) {
+ my $path = eval { abs_path(PVE::Storage::path($cfg, $scfg->{base})) };
+ my $device = abs_path($lun->{devpath});
+ $matches = defined($path) && defined($device) && $path eq $device;
+ }
+ die "cannot use '$lun->{devpath}' - storage '$sid' uses this LUN as its base volume\n"
+ if $matches;
+ }
+ return;
+}
+
+# Serializes writes to a LUN cluster-wide. The code sees the current storage configuration.
+sub with_lun_lock($lun, $code) {
+ my $key = $lun->{wwid} =~ s/([^A-Za-z0-9_.:-])/sprintf('=%02x', ord($1))/ger;
+ PVE::Cluster::cfs_lock_domain("san-$key", undef, $code);
+ die $@ if $@;
+}
+
+# Device names can pass to another device while a LUN waits for its lock or is worked on. All
+# names used for it have to mean the device that is held open.
+sub assert_same_device($lun, $fh, @names) {
+ my @held = stat($fh);
+ for my $name ($lun->{'by-id'}, $lun->{devpath}, @names) {
+ my @named = stat($name);
+ die "cannot use '$lun->{devpath}' - the device behind '$name' changed\n"
+ if !@held || !@named || $held[6] != $named[6];
+ }
+}
+
1;
diff --git a/src/test/Makefile b/src/test/Makefile
index 6348c61e..e453951a 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api
+test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
@@ -69,5 +69,9 @@ test_san_taint: run_san_taint_tests.pl
test_san_lun_scan: run_san_lun_scan_tests.pl
./run_san_lun_scan_tests.pl
-test_san_api: run_san_api_tests.pl
+test_san_api: run_san_api_tests.pl run_san_nvme_tests.pl
./run_san_api_tests.pl
+ ./run_san_nvme_tests.pl
+
+test_disk_api: run_disk_api_tests.pl
+ ./run_disk_api_tests.pl
diff --git a/src/test/disk_api_test.pm b/src/test/disk_api_test.pm
new file mode 100644
index 00000000..32ab5c80
--- /dev/null
+++ b/src/test/disk_api_test.pm
@@ -0,0 +1,235 @@
+package PVE::API2::Disks::Test;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use PVE::API2::Disks;
+use PVE::API2::Disks::LVM;
+use PVE::Diskmanage;
+use PVE::Storage;
+use PVE::Storage::LVMPlugin;
+
+use Test::MockModule;
+use Test::More;
+
+my @transport_cases = (
+ ['none', undef],
+ ['unknown', 'unknown'],
+ ['ata', 'ata'],
+ ['sata', 'sata'],
+ ['sas', 'sas'],
+ ['spi', 'spi'],
+ ['sbp', 'sbp'],
+ ['usb', 'usb'],
+ ['fc', 'fc'],
+ ['fcoe', 'fcoe'],
+ ['iscsi', 'iscsi'],
+ ['nvme', 'nvme'],
+ ['virtio', 'virtio'],
+ ['nvme-fc', 'nvme-fc'],
+ ['nvme-tcp', 'nvme-tcp'],
+ ['nvme-rdma', 'nvme-rdma'],
+ ['nvme-loop', 'nvme-loop'],
+);
+
+my $disks = {};
+my @all;
+for my $case (@transport_cases) {
+ my ($name, $transport) = $case->@*;
+ my $devpath = "/dev/test-$name";
+ my $entry = {
+ devpath => $devpath,
+ gpt => 0,
+ osdid => -1,
+ };
+ $entry->{transport} = $transport if defined($transport);
+ $disks->{$name} = $entry;
+ push @all, $devpath;
+}
+
+my $diskmanage_module = Test::MockModule->new('PVE::Diskmanage', no_auto => 1);
+$diskmanage_module->mock('get_disks' => sub { return $disks });
+
+my $list_handler = PVE::API2::Disks->map_method_by_name('list')->{code};
+my $list_devpaths = sub {
+ my ($param) = @_;
+ my $result = $list_handler->({ node => 'test-node', skipsmart => 1, $param->%* });
+ return [sort map { $_->{devpath} } $result->@*];
+};
+
+is_deeply(
+ $list_devpaths->({}), [sort @all], 'the disk list uses the default disk inventory',
+);
+
+is_deeply(
+ $list_devpaths->({ type => 'unused' }),
+ [sort @all],
+ 'unused disk selection preserves transport visibility',
+);
+
+$diskmanage_module->mock(
+ 'get_disks' => sub {
+ return {
+ 'fc-disk' => {
+ devpath => '/dev/fc-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'fc',
+ },
+ 'fc-partition' => {
+ devpath => '/dev/fc-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/fc-disk',
+ },
+ 'loop-disk' => {
+ devpath => '/dev/loop-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'nvme-loop',
+ },
+ 'loop-partition' => {
+ devpath => '/dev/loop-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/loop-disk',
+ },
+ };
+ },
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1 }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'the plain list keeps FC disks and their partitions',
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1, type => 'unused' }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'unused partitions preserve transport visibility',
+);
+
+subtest 'volume group creation leaves SAN locking to the LVM helper' => sub {
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $disk = $diskmanage_module;
+ my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+ my $rpc = Test::MockModule->new('PVE::RPCEnvironment');
+ my (@stack, @created);
+ my $lock = sub {
+ my ($name, $code) = @_;
+ push @stack, $name;
+ my $res = eval { $code->() };
+ my $err = $@;
+ pop @stack;
+ die $err if $err;
+ return $res;
+ };
+ $storage->mock(lock_storage_config => sub { $lock->('storage.cfg', $_[0]) });
+ $disk->mock(locked_disk_action => sub { $lock->('disk', $_[0]) });
+ $disk->mock(verify_blockdev_path => sub { $_[0] });
+ $disk->mock(assert_disk_unused => sub { });
+ $disk->mock(is_partition => sub { 0 });
+ $disk->mock(udevadm_trigger => sub { });
+ $lvm->mock(lvm_vgs => sub { {} });
+ $lvm->mock(
+ lvm_create_volume_group => sub {
+ is(scalar(@_), 3, 'disk API does not exempt a storage');
+ push @created, [$_[0], join('>', @stack)];
+ },
+ );
+ {
+
+ package MultipathTestRPC;
+ sub get_user { 'root@pam' }
+ sub check { 1 }
+ sub fork_worker { $_[4]->(); return 'test-upid' }
+ }
+ $rpc->mock(get => sub { bless {}, 'MultipathTestRPC' });
+
+ my ($is_map, $is_san) = (1, 0);
+ my $san = Test::MockModule->new('PVE::Storage::SAN');
+ $san->mock(is_san_device => sub { $is_map || $is_san });
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg1', device => '/dev/dm-3' });
+ ($is_map, $is_san) = (0, 1);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg2', device => '/dev/sdc' });
+ ($is_map, $is_san) = (0, 0);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg3', device => '/dev/sdb' });
+ is_deeply(
+ \@created,
+ [
+ ['/dev/dm-3', ''], ['/dev/sdc', ''], ['/dev/sdb', 'disk'],
+ ],
+ 'SAN writes use no local disk or storage configuration lock',
+ );
+ my $config_api = Test::MockModule->new('PVE::API2::Storage::Config');
+ my @params;
+ $config_api->mock(create_or_update => sub { push @params, $_[3] });
+ my $cfg =
+ { ids => { other => { type => 'lvm', vgname => 'other', nodes => { n2 => 1 } } } };
+ $storage->mock(config => sub { $cfg });
+ $is_san = 1;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg4',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 1, 'SAN storage is shared');
+ ok(!exists($params[-1]->{nodes}), 'SAN storage covers all nodes');
+ @created = ();
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'other',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ };
+ like($@, qr/already defined/, 'SAN volume group does not join the storage of another node');
+ is_deeply(\@created, [], 'existing storage ID prevents initialization');
+ $is_san = 0;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg5',
+ device => '/dev/sdb',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 0, 'local storage is not shared');
+ is($params[-1]->{nodes}, 'n1', 'local storage remains node-restricted');
+ @created = ();
+ $disk->mock(assert_disk_unused => sub { die "device is already in use\n" });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like($@, qr/already in use/, 'disk API rejects a used inventory entry');
+ is_deeply(\@created, [], 'used inventory prevents initialization');
+ $disk->mock(assert_disk_unused => sub { });
+ $lvm->mock(lvm_vgs => sub { { vg => {} } });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like(
+ $@,
+ qr/volume group with name 'vg' already exists/,
+ 'stale inventory does not permit an existing VG',
+ );
+ is_deeply(\@created, [], 'existing VG prevents initialization');
+ $disk->unmock($_)
+ for qw(
+ locked_disk_action verify_blockdev_path assert_disk_unused is_partition
+ udevadm_trigger
+ );
+};
+
+done_testing();
diff --git a/src/test/run_disk_api_tests.pl b/src/test/run_disk_api_tests.pl
new file mode 100755
index 00000000..75fc98c6
--- /dev/null
+++ b/src/test/run_disk_api_tests.pl
@@ -0,0 +1,11 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use TAP::Harness;
+
+my $harness = TAP::Harness->new({ verbosity => -2 });
+my $res = $harness->runtests("disk_api_test.pm");
+
+exit -1 if !$res || $res->{failed} || $res->{parse_errors};
diff --git a/src/test/run_san_library_tests.pl b/src/test/run_san_library_tests.pl
index f7ae68d1..d961b87c 100755
--- a/src/test/run_san_library_tests.pl
+++ b/src/test/run_san_library_tests.pl
@@ -105,4 +105,31 @@ subtest 'LVM hints are optional cached display metadata' => sub {
}
};
+subtest 'the names of a held LUN have to mean the held device' => sub {
+ require PVE::Storage::SAN;
+ open(my $fh, '<', '/dev/null') or die "cannot open /dev/null - $!\n";
+ my $lun = { 'by-id' => '/dev/null', devpath => '/dev/null' };
+ my $check = sub {
+ eval { PVE::Storage::SAN::assert_same_device(@_) };
+ return $@;
+ };
+ is($check->($lun, $fh, '/dev/null'), '', 'same device behind all names');
+ like(
+ $check->({ %$lun, 'by-id' => '/dev/zero' }, $fh),
+ qr/'\/dev\/zero' changed/,
+ 'by-id name',
+ );
+ like(
+ $check->({ %$lun, devpath => '/dev/zero' }, $fh),
+ qr/'\/dev\/zero' changed/,
+ 'device path',
+ );
+ like(
+ $check->($lun, $fh, '/dev/zero'),
+ qr/'\/dev\/zero' changed/,
+ 'name used for the commands',
+ );
+ like($check->($lun, $fh, '/dev/gone'), qr/'\/dev\/gone' changed/, 'name without a device');
+};
+
done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
new file mode 100755
index 00000000..f274feb0
--- /dev/null
+++ b/src/test/run_san_nvme_tests.pl
@@ -0,0 +1,92 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+our ($backing, @opens);
+
+BEGIN {
+ *CORE::GLOBAL::sysopen = sub (*$$;$) {
+ push @opens, $_[1];
+ my $path = $_[1] =~ m{^/dev/disk/by-id/nvme-} ? $backing : $_[1];
+ return CORE::sysopen($_[0], $path, $_[2]);
+ };
+}
+use lib qw(..);
+use File::Temp qw(tempfile);
+use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
+
+my ($fh, $file) = tempfile('san-nvme-XXXX', DIR => '.', UNLINK => 1);
+close($fh);
+$backing = $file;
+my $device = '/dev/nvme0n1';
+my $link = '/dev/disk/by-id/nvme-eui.0123456789abcdef';
+my $lun =
+ { devpath => $device, 'by-id' => $link, wwid => 'eui.0123456789abcdef', multipath => 'native' };
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $mp = Test::MockModule->new('PVE::Multipath');
+my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $cfg = { ids => {} };
+my @order;
+$storage->mock(config => sub { $cfg });
+$disk->mock(verify_blockdev_path => sub { $device });
+$disk->mock(is_partition => sub { 0 });
+$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(is_iscsi_device => sub { 0 });
+$disk->mock(is_mounted => sub { 0 });
+$disk->mock(has_holder => sub { 0 });
+$disk->mock(device_opener => sub { undef });
+$mp->mock(device_map => sub { undef });
+$san->mock(abs_path => sub { $device });
+$san->mock(scan_luns => sub { [$lun] });
+$san->mock(lun_partitions => sub { [] });
+$san->mock(assert_same_device => sub { ok(defined(fileno($_[1])), 'held descriptor checked') });
+$lvm->mock(lun_volume_groups => sub { push @order, 'check'; [] });
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-eui.0123456789abcdef', 'native namespace uses the LUN lock');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+is(PVE::Storage::SAN::stable_path($device, $lun->{wwid}), $link, 'native stable path');
+is_deeply(PVE::Storage::SAN::lun_for_device($link), $lun, 'native row selected for writes');
+$disk->mock(is_partition => sub { 1 });
+is(PVE::Storage::SAN::lun_for_device($link), undef, 'a partition is handled as a local device');
+$disk->mock(is_partition => sub { 0 });
+$cfg->{ids}->{data} = { type => 'lvm', base => 'fabric:nvme-eui.0123456789abcdef' };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like($@, qr/base volume/, 'native base reference refuses');
+$cfg->{ids} = {};
+@order = @opens = ();
+$lvm->mock(file_read_firstline => sub { $_[0] =~ m{/size$} ? 1024 : undef });
+$lvm->mock(lvm_pv_info => sub { undef });
+$lvm->mock(
+ clear_first_sector => sub { push @order, 'clear'; ok(-e $_[0], 'VG clear uses held fd') });
+$lvm->mock(
+ run_command => sub {
+ my ($cmd, %opts) = @_;
+ if ($cmd->[0] eq 'wipefs') {
+ $opts{outfunc}->('{"signatures":[]}');
+ } else {
+ is($cmd->[-1], $device, 'VG command uses the checked device');
+ push @order, $cmd->[0];
+ }
+ },
+);
+PVE::Storage::LVMPlugin::lvm_create_volume_group($link, 'data', 1);
+is_deeply(
+ \@order,
+ [qw(lock check clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'native VG sequencing',
+);
+is_deeply(\@opens, [$link], 'VG creation holds the native by-id device');
+
+done_testing();
diff --git a/src/test/run_san_taint_tests.pl b/src/test/run_san_taint_tests.pl
index 35b11cd7..0ccd9e2f 100755
--- a/src/test/run_san_taint_tests.pl
+++ b/src/test/run_san_taint_tests.pl
@@ -31,4 +31,30 @@ for my $bad ('-bad', '1:2', '../dev', "3600a\n") {
like($@, qr/invalid WWID/, 'ambiguous identity refused');
}
+# the LUN that write operations get must be usable in command lines and lock names
+use PVE::Storage::SAN;
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $tainted_dev = PVE::Tools::file_get_contents('/proc/self/comm') =~ s/.*//sr . '/dev/null';
+ok(tainted($tainted_dev), 'device path derived from a file is tainted');
+$san->mock(
+ is_san_device => sub { 1 },
+ scan_luns => sub {
+ return [{
+ devpath => $tainted_dev,
+ wwid => $wwid,
+ 'by-id' => '/dev/null',
+ usage => 'unused',
+ multipath => 'none',
+ }];
+ },
+);
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(verify_blockdev_path => sub { '/dev/null' });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+my $lun = PVE::Storage::SAN::lun_for_device('/dev/null');
+ok(!tainted($lun->{devpath}), 'LUN device path is untainted');
+ok(!tainted($lun->{wwid}), 'LUN WWID is untainted');
+is($lun->{wwid}, '3600a', 'LUN WWID is unchanged');
+
done_testing();
diff --git a/src/test/run_test_lvm_base_conflicts.pl b/src/test/run_test_lvm_base_conflicts.pl
index 26362a74..cba7b117 100755
--- a/src/test/run_test_lvm_base_conflicts.pl
+++ b/src/test/run_test_lvm_base_conflicts.pl
@@ -2,78 +2,183 @@
use strict;
use warnings;
-
-use Test::MockModule;
+use lib qw(..);
use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
-use lib ('.', '..');
-use PVE::Storage;
-use PVE::Storage::LVMPlugin;
-
-my $storage = Test::MockModule->new('PVE::Storage');
+my $scan = Test::MockModule->new('PVE::Storage::SAN');
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
-my ($cfg, $created, $existing);
-$storage->mock(
- config => sub { $cfg },
- path => sub { '/dev/sda' },
- activate_storage => sub { },
- activate_volumes => sub { },
-);
-$lvm->mock(
- lvm_create_volume_group => sub {
- my ($device, $vgname, $shared, $guard) = @_;
- return if $existing;
- $guard->{check_storage}->($device);
- $created++;
- },
- assert_discard_supported => sub { },
-);
-
-for my $case (
- ['iscsi', {}, 0],
- ['iscsi', { images => 1 }, 1],
- ['iscsidirect', {}, 1],
- ['zfs', {}, 1],
- ['vendor', { images => 1 }, 1],
-) {
- my ($type, $content, $conflict) = @$case;
- $created = 0;
- $cfg = {
- ids => {
- base => { type => 'iscsi', target => 'iqn.test', content => { none => 1 } },
- other => {
- type => $type,
- target => 'iqn.test',
- content => $content,
- disable => 1,
- nodes => { elsewhere => 1 },
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $lun = { wwid => '3600+abc', devpath => '/dev/dm-0', 'iscsi-target' => 'iqn.test' };
+# the LUN is exported through two targets, its row names only the first
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
+$identity->mock(
+ collect => sub {
+ {
+ paths => {
+ sdb => { wwid => '3600+abc', target => 'iqn.test' },
+ sdc => { wwid => '3600+abc', target => 'iqn.second' },
+ sdd => { wwid => '3600+other', target => 'iqn.other' },
},
+ };
+ },
+);
+my $vgs = [];
+$scan->mock(lun_partitions => sub { [] });
+$lvm->mock(lun_volume_groups => sub { $vgs });
+$lvm->mock(cached_pv_volume_groups => sub { die "write check must not use cached PV metadata\n" });
+my $cfg = { ids => {} };
+$storage->mock(config => sub { $cfg });
+my $check = sub {
+ eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun, @_) };
+ return $@;
+};
+is($check->(), '', 'unreferenced LUN accepted');
+for my $type (qw(lvm lvmthin)) {
+ $vgs = ['data'];
+ $cfg->{ids} = {
+ data => {
+ type => $type,
+ vgname => 'data',
+ shared => 1,
+ disable => 1,
+ nodes => { other => 1 },
},
};
- eval {
- PVE::Storage::LVMPlugin->on_add_hook(
- 'test',
- { base => 'base:0.0.1.scsi-test', vgname => 'test' },
- );
- };
- if ($conflict) {
- like($@, qr/storage 'other' serves disk images from this target/, "$type conflict refused");
- like($@, qr/set its content to 'none'/, "$type: remedy named for iSCSI only")
- if $type eq 'iscsi';
- } else {
- is($@, '', 'connection-only storage permits initialization');
+ for my $cached_vg (undef, 'unrelated') {
+ $lun->{vgname} = $cached_vg;
+ $lun->{usage} = 'unused';
+ like($check->(), qr/used by storage 'data'/, "$type refusal ignores display VG and usage");
}
- is($created, $conflict ? 0 : 1, 'no writes on conflicting target');
+ is($check->('data'), '', 'the storage being added can be exempted');
+}
+delete $lun->{vgname};
+delete $lun->{usage};
+$vgs = [];
+$cfg->{ids} = { direct => { type => 'iscsi', target => 'iqn.test', content => { images => 1 } } };
+like($check->(), qr/storage 'direct' serves images from this target$/, 'direct image use refuses');
+$cfg->{ids}->{direct}->{target} = 'iqn.second';
+like($check->(), qr/storage 'direct' serves images/, 'also through another target of the LUN');
+$cfg->{ids}->{direct}->{target} = 'iqn.other';
+is($check->(), '', 'a target of another LUN is no reference');
+$cfg->{ids}->{direct}->{target} = 'iqn.test';
+$cfg->{ids}->{direct}->{content} = { none => 1 };
+is($check->(), '', 'connection-only storage permits use');
- $existing = 1;
- eval {
- PVE::Storage::LVMPlugin->on_add_hook(
- 'test',
- { base => 'base:0.0.1.scsi-test', vgname => 'test' },
- );
- };
- is($@, '', "$type: an existing volume group on the base volume can be added");
- $existing = 0;
+for my $type (qw(iscsidirect zfs)) {
+ local $cfg->{ids}->{other} = { type => $type, target => 'iqn.test', content => {} };
+ like(
+ $check->(),
+ qr/storage 'other' serves images from this target$/,
+ "$type storage of the target refuses",
+ );
}
+$cfg->{ids}->{data} = { type => 'lvm', base => 'direct:0.0.1.dm-uuid-mpath-3600+abc' };
+like($check->(), qr/base volume/, 'base reference refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-3600+abc';
+like($check->(), qr/base volume/, 'scsi WWID in base name refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-legacy';
+$storage->mock(path => sub { '/dev/disk/by-id/legacy' });
+$scan->mock(abs_path => sub { '/dev/dm-0' });
+like($check->(), qr/base volume/, 'resolved alias to the LUN refuses');
+$scan->mock(abs_path => sub { $_[0] eq $lun->{devpath} ? '/dev/dm-0' : '/dev/dm-1' });
+is($check->(), '', 'base on another device is no match');
+$scan->mock(abs_path => sub { undef });
+is($check->(), '', 'unresolvable base is no match');
+$storage->mock(path => sub { die "base unavailable\n" });
+is($check->(), '', 'unavailable base is no match');
+ok(!PVE::Storage::LVMPlugin->can('create_volume_group'), 'creation implementation is lexical');
+$cfg->{ids} = {};
+my @order;
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-3600=2babc', 'lock name escapes unsafe characters without collisions');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+PVE::Storage::SAN::with_lun_lock($lun, sub { push @order, 'write' });
+is_deeply(\@order, [qw(lock write unlock)], 'the code runs under the lock of the LUN');
+
+# volume group creation checks the references only when it has to initialize the LUN
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(
+ verify_blockdev_path => sub { $_[0] },
+ is_mounted => sub { undef },
+ has_holder => sub { undef },
+ device_opener => sub { undef },
+);
+my ($signatures, $pvinfo) = ('', undef);
+$lun->{'by-id'} = '/dev/null';
+$scan->mock(
+ lun_for_device => sub { $lun },
+ assert_same_device => sub { },
+ assert_lun_unreferenced => sub { push @order, 'check'; die "referenced\n" },
+);
+$lvm->mock(
+ file_read_firstline => sub { $_[0] =~ m{/size$} ? '2048' : undef },
+ lvm_pv_info => sub { $pvinfo },
+ clear_first_sector => sub { push @order, 'clear' },
+ run_command => sub {
+ my ($cmd, %param) = @_;
+ return $param{outfunc}->(qq({"signatures":[$signatures]})) if $cmd->[0] eq 'wipefs';
+ push @order, $cmd->[0];
+ },
+);
+@order = ();
+$signatures = '{"type":"LVM2_member","offset":"0x218"}';
+$pvinfo = { vgname => 'data', in_use => '1' };
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an existing volume group can be added whatever references its LUN');
+is_deeply(\@order, [qw(lock unlock)], 'without reference check or write');
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'other',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/already used by volume group 'data'/, 'another volume group on the LUN refuses');
+@order = ();
+($signatures, $pvinfo) = ('', undef);
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/referenced/, 'initializing a referenced LUN refuses');
+is_deeply(\@order, [qw(lock check)], 'the check precedes the first write');
+$scan->mock(assert_lun_unreferenced =>
+ sub { is($_[2], 'new', 'new storage exempt'); push @order, 'check' });
+@order = ();
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an unreferenced empty LUN is initialized');
+is_deeply(
+ \@order,
+ [qw(lock check clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'checked once, then written under the lock',
+);
done_testing();
diff --git a/src/test/run_test_lvm_create.pl b/src/test/run_test_lvm_create.pl
index d4be25b0..e33edaa9 100755
--- a/src/test/run_test_lvm_create.pl
+++ b/src/test/run_test_lvm_create.pl
@@ -10,9 +10,12 @@ use Test::More;
use lib ('.', '..');
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+$san->mock(lun_for_device => sub { undef });
my $tools = Test::MockModule->new('PVE::Tools');
my $inotify = Test::MockModule->new('PVE::INotify');
$inotify->mock(nodename => sub { 'testnode' });
@@ -170,6 +173,44 @@ like(
qr/contains data \(gpt\)/,
'a partition table of a map is data, kpartx may not map it',
);
+reset_case();
+($signatures, $partitioned) = ([{ type => 'PMBR' }, { type => 'gpt' }], 1);
+$san->mock(
+ lun_for_device =>
+ sub { { wwid => '3600abc', devpath => '/dev/sda', 'by-id' => '/dev/null' } },
+ with_lun_lock => sub { $_[1]->() },
+);
+like(
+ create(),
+ qr{the device behind '/dev/sda' changed},
+ 'a device name that no longer means the held LUN is refused',
+);
+is_deeply(\@writes, [], 'changed device: no writes');
+$san->mock(assert_same_device => sub { });
+like(create(), qr/contains data \(PMBR, gpt\)/, 'a partitioned LUN that is no map is data too');
+is_deeply(\@writes, [], 'partitioned LUN: no writes');
+reset_case();
+my $opener = '4711 (kvm)';
+$disk->mock(device_opener => sub { $opener });
+$san->mock(assert_lun_unreferenced => sub { });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+like(create(), qr/process 4711 \(kvm\) has it open/, 'a LUN that a process has open is refused');
+is_deeply(\@writes, [], 'open LUN: no writes');
+$opener = undef;
+is(create(), '', 'a LUN that no process has open is initialized');
+is(scalar(@writes), 3, 'unused LUN: initialized');
+reset_case();
+$signatures = [{ type => 'LVM2_member' }];
+$label = '/dev/sda: LVM2 PV';
+$pv = '/dev/sda:1024:test:aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg:1';
+my $checked = 0;
+$san->mock(assert_same_device => sub { die "device changed\n" if ++$checked == 2 });
+like(create(), qr/device changed/, 'an existing volume group only counts on the held LUN');
+$san->unmock('assert_lun_unreferenced');
+$san->unmock('assert_same_device');
+$san->unmock('with_lun_lock');
+$san->mock(lun_for_device => sub { undef });
my $uuid = 'aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg';
for my $vg ('test', 'other', 'unknown', '') {
^ permalink raw reply related [relevance 10%]
* [PATCH v6 cluster,storage,docs,manager 00/42] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM
@ 2026-11-18 6:52 7% Thomas Lamprecht
2026-11-18 6:52 9% ` [PATCH v6 storage 22/42] disks: lvm: allow volume groups on SAN LUNs and multipath maps Thomas Lamprecht
0 siblings, 1 reply; 43+ results
From: Thomas Lamprecht @ 2026-11-18 6:52 UTC (permalink / raw)
To: pve-devel
This is v6 of the combined and reduced series of the cluster-wide
multipath work [0][1] and Dietmar's RFC for guided remote storage setup
and SAN visibility [2].
v6 is v5 [3] rebased onto current master, where plugin API 17 with the
volume types, the plugin metadata for the web UI and the property
isolation for plugins landed underneath, plus what an independent review
of v5 turned up:
- The status update no longer waits for the missing map of an LVM base
volume, nor asks a hanging multipathd for its paths. With three such
storages a pass took 32 seconds instead of 1.2 in my lab. Activating
a volume for a guest still waits.
- An existing volume group on a partition of a multipath map can be
added again, also with the Multipath option of the iSCSI storage.
- The node disk API only creates the storage of a volume group on a
LUN; v5 could join a storage added meanwhile with another volume
group.
- The Fibre Channel setup waits for the volume group task itself and
cannot be closed meanwhile. Closing the task window ended it with a
volume group and no storage.
- The setup menu also needs Datastore.Audit or Datastore.AllocateSpace.
- The first status pass removed a drop-in with one of the generated
names under /etc/multipath/conf.d, also one that Proxmox VE had not
written. Such a file now stays, and the node reports an error while
it needs that name.
- The volume group creation and the wipe also refuse a LUN that is in
use through another of its SCSI paths, for example by a guest started
before the map existed. A name in the request has to lead to the same
device after the LUN lookup still.
- A node only reported the first of the storages that request a map.
- Node > Disks > LVM creates a shared storage on a SAN LUN, on a single
path for a Fibre Channel LUN without a map. Its dialog now points to
the guided setup.
- Enable Multipath under Node > SAN opens the entry dialog, where the
admin sees and chooses the nodes, instead of adding an entry for all.
- Smaller ones: partition bases and LUNs reached through two targets
are attributed to their storage, Node > SAN shows the path counts of
a degraded LUN, and the SAN view names the nodes in Unknown.
- let the disk wipe take by-id, dm-N and mapper names for any device,
so it also wiped a logical volume with a guest disk by such a name.
These names are now accepted for a LUN only.
BlockBridge was very reactive here and tested v5 with 1000 LUNs or
namespaces on a node, one per guest disk. For them LUN inventory took
over ten seconds. New patches 16 and 17 look the disks up by name and
read the udev data with one call, which brought it to under a second for
1000 NVMe/TCP namespaces in my lab. The test also showed the disks of
running guests as unused, as no storage references them. New patches 25,
27, 41 and 42 show the guest or process that has a LUN open for writing,
and a hidden column for the iSCSI target, which names the volume for a
plugin with one target per volume. They come last in their repositories,
so that they can be left out; the NVMe over Fabrics series then applies
up to its last manager patch. A LUN that stays attached with nothing
holding it, for example after a failed detach, still shows as unused:
telling whose it is needs the plugin, and I left that for later.
What I left as is for now: lsblk for the usage of a LUN, as it opens no
device without a udev entry (measured again); 'auto_resize grow_only'
for all maps of a node, as multipath has no other form of it, documented
with how to turn it off; a node that drops the new option when it writes
storage.cfg before it is upgraded, which the chapter covers; and an
empty volume group that another node wipes right after its creation.
Overview of what an admin gets with this:
- Datacenter > Storage > SAN, a new entry below Storage, shows the
multipath state of every node and of the LUNs that Proxmox VE
manages or has a storage on, and edits the multipath entries and
array-specific overrides. I explicitly chose this over the
client/plugin side of Storage, as we do not have e.g. Ceph or
ZFS/LVM/... creation in there either. We might want to rethink and
consolidate our storage interface vs. management story in the
future, but IMO a partial switch now is not worth it, that would add
even more potential for confusion than the new SAN view.
- Its Guided Setup menu leads through shared LVM on a LUN: for iSCSI it
connects or reuses a target, with the initiator names of all nodes at
hand, for Fibre Channel it takes a LUN the nodes already see. Both
set up multipath and end with the state of the LUN on every node.
- Datacenter > Storage > Add keeps its dialogs. The iSCSI one gets a
Multipath option and the LVM one enables Shared for a base storage,
and both point to the SAN view.
- Node > SAN lists the LUNs of a node with their paths and usage, can
wipe a LUN that no storage uses, and shows the iSCSI sessions.
The rules the series follows since v4: nodes add WWIDs and maps but
never remove them, a write is checked where it happens, lists do not
probe devices, there are no new iSCSI operations, the guided setup makes
the API calls an admin would make by hand, and multipath management is
turned on by the admin. The v4 cover [7] has the reasons.
Two things an admin will likely miss: there is no notification when a
LUN loses path redundancy, the state only shows on the SAN pages and in
the API. And Fibre Channel starts at a LUN the nodes already see; the
chapter gives the commands to list WWPNs and rescan the HBAs.
How it works:
- /etc/pve/multipath.cfg holds explicit entries per WWID,
/etc/pve/multipath-overrides.conf array settings; patch 01
registers both. An iSCSI storage with the 'managed-multipath' option
supplies its LUNs without entries. The option is not named
'multipath', as third-party plugins use that name, and the storage
layer leaves out a third-party plugin that declares a property of
another plugin.
- pvestatd calls one function of pve-storage per pass. It adds the
WWIDs the node needs to /etc/multipath/wwids, writes the drop-ins
/etc/multipath/conf.d/pve-*.conf, reloads multipathd after a change,
and publishes the state of the maps that Proxmox VE manages or that a
storage builds on through the node key-value store.
- /cluster/multipath/status aggregates these reports;
/cluster/multipath/{wwid,overrides} edit the two files;
/nodes/{node}/scan/san-luns lists the LUNs of a node and
/nodes/{node}/iscsi its sessions.
- The volumes of an iSCSI storage with the option are named after the
multipath map, so an LVM storage uses them through 'base' as before.
- Volume group creation and wipe run under a cluster lock per LUN. They
refuse a LUN that a storage uses or a process of the node has open,
also through another path. Opens through another device node, such as
one of a container, and users on other hosts are not seen.
Patches:
- cluster 01: register the two configuration files
- storage 02-25: helpers for the disk and iSCSI session inventory
(mostly Dietmar's), the multipath library and configuration, the
iSCSI option, the per-node apply and status with their API, the disk
list of many disks, the LUN inventory, the read-only iSCSI status,
volume groups on LUNs, the wipe and the process that has a LUN open
- docs 26-27: the multipath chapter, rewritten around tasks, and the
paragraph for a LUN that a process has open
- manager 28-42: the pvestatd call, report and API mounts, then the
views, the two dialog changes, the two guided setups, the note in the
add dialogs, and the guest or process and the target of a LUN
Other changes since v5 [3]:
- rebased onto current master in all four repositories, with the plugin
metadata for the iSCSI option and its entry in the pinned property
list
- the setup menu is named Guided Setup instead of Add Storage, as three
different things in two views were called add
- search fields in the LUN lists and the iSCSI tree, which on a node
also match path devices and WWPNs, for example one from the kernel
log
- the process check compares device numbers, and the volume group check
refuses a volume group that any storage names
- style fixes, warnings of three test files, and shorter commit
messages
When applying, versioned dependencies have to be set: pve-manager on
libpve-storage-perl, and libpve-storage-perl (also as build dependency)
on the libpve-cluster-perl with patch 01, as PVE::Storage
registers the two files when it is loaded. pve-manager also needs the
pve-doc-generator (build) and pve-docs with the multipath chapter, for
its help links. If the bound for LVM status commands [4] gets applied
too, whichever is applied second has to pass the status cache to the two
lvm_vgs() calls of the base volume activation, as they can block a
status pass otherwise. Both mark the cache of the status update with
'status_only', in the same line.
The per-node target and portal series [5][6] are independent of this
one. It takes the LUNs of an iSCSI storage from the sessions of its one
target, so if a storage can have several targets per node, whichever is
applied second has to cover that.
I tested on the lab of v4 [7] and v5: a six-node nested cluster with a
NetApp AFF A20 (three iSCSI portals, NVMe/TCP), Linux LIO targets and
software FCoE, upgraded from the v5 build, with the NVMe over Fabrics
series and [4] on top. Most review fixes ran as drills against the fault
they fix, a few have unit tests only. Both guided setups ended optimal
on six nodes, the Fibre Channel one also with a failing task, delayed
and cut-off status requests and Escape pressed during the wait. A guest
on NetApp, Fibre Channel and NVMe/TCP disks went through snapshots, live
migrations, a path cut under I/O, an online resize and a node reboot
with checksums compared. The scale test ran with 1000 NVMe/TCP
namespaces and with 1000 iSCSI LUNs with maps; the disk list and the LUN
inventory gave the same result with the one udev call and with a query
per disk, also on the other five nodes. Guests with a NetApp map, a
Fibre Channel LUN or an NVMe/TCP namespace as disk, also on one path of
a map, showed in the LUN lists, and the wipe and the volume group
creation refused these LUNs. Most of this ran on builds before the last
fixes, which got drills of their own. I looked at each changed view and
dialog in the web UI.
Not repeated for v6: a path cut on Fibre Channel, the CLI procedure, a
LUN that one node is not allowed to see, all paths down with queued I/O,
the SAN views with a stopped multipathd, the multipath status of a node
with 1000 foreign maps and the series installed alone.
[0]: https://lore.proxmox.com/pve-devel/20260626121000.2095591-1-t.lamprecht@proxmox.com/
[1]: https://lore.proxmox.com/pve-devel/20260703124707.1172980-2-t.lamprecht@proxmox.com/
[2]: https://lore.proxmox.com/pve-devel/20260731102156.3947857-1-dietmar@proxmox.com/
[3]: https://lore.proxmox.com/pve-devel/20261116012355.3187417-1-t.lamprecht@proxmox.com/
[4]: https://lore.proxmox.com/pve-devel/20261111015217.941220-1-t.lamprecht@proxmox.com/
[5]: https://lore.proxmox.com/pve-devel/20260430173220.441001-1-m.limbeck@proxmox.com/
[6]: https://lore.proxmox.com/pve-devel/20260804090819.2136483-1-dietmar@proxmox.com/
[7]: https://lore.proxmox.com/pve-devel/20261113030146.1559030-1-t.lamprecht@proxmox.com/
pve-cluster:
Thomas Lamprecht (1):
cfs: observe the multipath configuration files
src/PVE/Cluster.pm | 2 ++
src/pmxcfs/status.c | 2 ++
2 files changed, 4 insertions(+)
pve-storage:
Dietmar Maurer (8):
diskmanage: collect disk transport type from lsblk
diskmanage: qualify NVMe over fabrics transport
diskmanage: optionally include iSCSI session devices in disk enumeration
diskmanage: collect native NVMe multipath path state
iscsi: factor out session device map from device list
diskmanage: add helper to list multipath devices
pvesm: expose the SAN LUN inventory
api: add node-level iSCSI status
Thomas Lamprecht (16):
multipath: add a library around multipathd
multipath: add a cluster-wide configuration
iscsi: add an option to manage storage LUNs with multipath
lvm: activate a missing base volume before using the volume group
multipath: apply the configuration on every node
multipath: publish per-node status
api: add endpoints for the cluster-wide multipath configuration
api: multipath: add the cluster-wide health status
diskmanage: look up the requested disks by name
diskmanage: read the udev data of all disks with one call
api: scan: add a SAN LUN inventory
disks: lvm: drop unused imports
disks: lvm: allow volume groups on SAN LUNs and multipath maps
disks: lvm: refuse to destroy the volume group of a shared storage
disks: allow wiping a SAN LUN that no storage uses
api: scan: report the process that has a SAN LUN open
debian/control | 3 +-
src/PVE/API2/Disks.pm | 46 +-
src/PVE/API2/Disks/LVM.pm | 77 ++-
src/PVE/API2/ISCSI.pm | 166 ++++++
src/PVE/API2/Makefile | 2 +
src/PVE/API2/Multipath.pm | 451 +++++++++++++++
src/PVE/API2/Storage/Scan.pm | 216 ++++++++
src/PVE/CLI/pvesm.pm | 14 +
src/PVE/Diskmanage.pm | 375 +++++++++++--
src/PVE/ISCSI/Topology.pm | 88 +++
src/PVE/Makefile | 6 +
src/PVE/Multipath.pm | 213 ++++++++
src/PVE/Multipath/Config.pm | 204 +++++++
src/PVE/Multipath/Generator.pm | 120 ++++
src/PVE/Multipath/Identity.pm | 44 ++
src/PVE/Multipath/Status.pm | 215 ++++++++
src/PVE/Storage.pm | 2 +-
src/PVE/Storage/ISCSIPlugin.pm | 219 +++++---
src/PVE/Storage/LVMPlugin.pm | 151 ++++-
src/PVE/Storage/Makefile | 3 +-
src/PVE/Storage/SAN.pm | 409 ++++++++++++++
src/test/Makefile | 37 +-
src/test/disk_api_test.pm | 314 +++++++++++
src/test/disk_tests/iscsi/disklist | 1 +
.../disk_tests/iscsi/disklist_expected.json | 19 +
src/test/disk_tests/iscsi/lsblk | 5 +
src/test/disk_tests/iscsi/sda/device/model | 1 +
src/test/disk_tests/iscsi/sda/device/vendor | 1 +
.../disk_tests/iscsi/sda/queue/rotational | 1 +
src/test/disk_tests/iscsi/sda/size | 1 +
src/test/disk_tests/iscsi/sda_udevadm | 21 +
src/test/disk_tests/multipath/disklist | 11 +
.../multipath/disklist_expected.json | 107 ++++
src/test/disk_tests/multipath/dm-0/dm/name | 1 +
src/test/disk_tests/multipath/dm-0/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-0/size | 1 +
src/test/disk_tests/multipath/dm-0_slaves | 4 +
src/test/disk_tests/multipath/dm-1/dm/name | 1 +
src/test/disk_tests/multipath/dm-1/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-1/size | 1 +
src/test/disk_tests/multipath/dm-1_slaves | 4 +
src/test/disk_tests/multipath/dm-2/dm/name | 1 +
src/test/disk_tests/multipath/dm-2/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-2/size | 1 +
src/test/disk_tests/multipath/dm-2_slaves | 0
src/test/disk_tests/multipath/dm-3/dm/name | 1 +
src/test/disk_tests/multipath/dm-3/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-3/size | 1 +
src/test/disk_tests/multipath/dm-3_slaves | 0
src/test/disk_tests/multipath/dm-4/dm/name | 1 +
src/test/disk_tests/multipath/dm-4/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-4/size | 1 +
src/test/disk_tests/multipath/dm-4_slaves | 0
src/test/disk_tests/multipath/lsblk | 77 +++
src/test/disk_tests/multipath/lvs | 0
src/test/disk_tests/multipath/mounts | 1 +
.../multipath/multipath_expected.json | 59 ++
src/test/disk_tests/multipath/multipathd | 124 +++++
.../multipath/multipathd_status_expected.json | 40 ++
.../nvme-subsystem/nvme-subsys0/nvme3/address | 1 +
.../nvme-subsys0/nvme3/nvme2c3n1/ana_state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme3/state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme4/address | 1 +
.../nvme-subsys0/nvme4/nvme2c4n1/ana_state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme4/state | 1 +
.../nvme-subsystem/nvme-subsys1/nvme0/address | 1 +
.../nvme-subsystem/nvme-subsys1/nvme0/state | 1 +
.../disk_tests/multipath/nvme8n1/device/model | 1 +
.../multipath/nvme8n1/device/transport | 1 +
.../multipath/nvme8n1/queue/rotational | 1 +
src/test/disk_tests/multipath/nvme8n1/size | 1 +
src/test/disk_tests/multipath/nvme8n1_udevadm | 14 +
.../disk_tests/multipath/nvme9n1/device/model | 1 +
.../multipath/nvme9n1/device/transport | 1 +
.../multipath/nvme9n1/device/vendor | 1 +
.../multipath/nvme9n1/queue/rotational | 1 +
src/test/disk_tests/multipath/nvme9n1/size | 1 +
src/test/disk_tests/multipath/nvme9n1_udevadm | 12 +
.../multipath/nvme_path_status_expected.json | 19 +
src/test/disk_tests/multipath/partlist | 0
src/test/disk_tests/multipath/pvs | 1 +
.../disk_tests/multipath/sda/device/model | 1 +
.../disk_tests/multipath/sda/device/vendor | 1 +
.../disk_tests/multipath/sda/holders/holder | 1 +
.../disk_tests/multipath/sda/queue/rotational | 1 +
src/test/disk_tests/multipath/sda/size | 1 +
src/test/disk_tests/multipath/sda_udevadm | 18 +
.../disk_tests/multipath/sdb/device/model | 1 +
.../disk_tests/multipath/sdb/device/vendor | 1 +
.../disk_tests/multipath/sdb/holders/holder | 1 +
.../disk_tests/multipath/sdb/queue/rotational | 1 +
src/test/disk_tests/multipath/sdb/size | 1 +
src/test/disk_tests/multipath/sdb_udevadm | 18 +
.../disk_tests/multipath/sdc/device/model | 1 +
.../disk_tests/multipath/sdc/device/vendor | 1 +
.../disk_tests/multipath/sdc/holders/holder | 1 +
.../disk_tests/multipath/sdc/queue/rotational | 1 +
src/test/disk_tests/multipath/sdc/size | 1 +
src/test/disk_tests/multipath/sdc_udevadm | 18 +
.../disk_tests/multipath/sdd/device/model | 1 +
.../disk_tests/multipath/sdd/device/vendor | 1 +
.../disk_tests/multipath/sdd/holders/holder | 1 +
.../disk_tests/multipath/sdd/queue/rotational | 1 +
src/test/disk_tests/multipath/sdd/size | 1 +
src/test/disk_tests/multipath/sdd_udevadm | 18 +
src/test/disk_tests/multipath/zpool | 1 +
.../disk_tests/sas/disklist_expected.json | 1 +
src/test/disk_tests/sas/lsblk | 5 +
src/test/disklist_test.pm | 175 +++++-
src/test/multipath-three-states.json | 52 ++
src/test/plugin_properties_test.pm | 1 +
src/test/run_disk_api_tests.pl | 11 +
src/test/run_iscsi_activation_tests.pl | 109 ++++
src/test/run_lun_identity_tests.pl | 57 ++
src/test/run_multipath_api_tests.pl | 515 ++++++++++++++++++
src/test/run_multipath_tests.pl | 169 ++++++
src/test/run_san_api_tests.pl | 94 ++++
src/test/run_san_library_tests.pl | 135 +++++
src/test/run_san_lun_scan_tests.pl | 252 +++++++++
src/test/run_san_nvme_tests.pl | 120 ++++
src/test/run_san_taint_tests.pl | 60 ++
src/test/run_san_wipe_tests.pl | 255 +++++++++
src/test/run_san_write_check_tests.pl | 205 +++++++
src/test/run_test_lvm_base_activation.pl | 121 ++++
src/test/run_test_lvm_base_volume.pl | 12 +-
src/test/run_test_lvm_create.pl | 46 ++
126 files changed, 6224 insertions(+), 194 deletions(-)
pve-docs:
Thomas Lamprecht (2):
storage: document the cluster-wide multipath management
storage: multipath: describe the use shown for an open LUN
pmxcfs.adoc | 2 +
pve-storage-iscsi.adoc | 11 ++
pve-storage-iscsidirect.adoc | 2 +-
pve-storage-lvm.adoc | 3 +
pve-storage-multipath.adoc | 309 +++++++++++++++++++++++++++++++++++
pvesm.adoc | 18 +-
6 files changed, 339 insertions(+), 6 deletions(-)
pve-manager:
Dietmar Maurer (2):
api: nodes: expose the iSCSI status
ui: node: san: show iSCSI targets and sessions
Thomas Lamprecht (13):
pvestatd: apply the multipath configuration and report the node status
report: add the managed multipath configuration
api: cluster: add the multipath endpoints
ui: dc: add a SAN view
ui: storage: iscsi: add the multipath option
ui: lvm: enable shared when a base storage is selected
ui: node: add SAN LUNs panel
ui: node: san: wipe a LUN that no storage uses
ui: dc: san: add a guided setup for shared LVM on iSCSI
ui: dc: san: add a guided setup for shared LVM on Fibre Channel
ui: storage: point the iSCSI and LVM add dialogs to the SAN view
ui: san: show the guest or process that has a LUN open
ui: node: san: add a column for the iSCSI target of a LUN
PVE/API2/Cluster.pm | 7 +
PVE/API2/Nodes.pm | 7 +
PVE/Report.pm | 3 +
PVE/Service/pvestatd.pm | 7 +
www/manager6/Makefile | 12 +
www/manager6/SANUtils.js | 202 ++++++++++
www/manager6/Utils.js | 19 +
www/manager6/dc/Config.js | 23 +-
www/manager6/dc/MultipathWwidEdit.js | 81 ++++
www/manager6/dc/SAN.js | 374 ++++++++++++++++++
www/manager6/node/Config.js | 24 ++
www/manager6/node/ISCSITargets.js | 150 +++++++
www/manager6/node/LVM.js | 3 +
www/manager6/node/SANLuns.js | 229 +++++++++++
www/manager6/storage/Base.js | 5 +
www/manager6/storage/IScsiEdit.js | 46 +++
www/manager6/storage/LVMEdit.js | 6 +
www/manager6/storage/wizard/FibreChannel.js | 175 ++++++++
www/manager6/storage/wizard/IScsi.js | 274 +++++++++++++
www/manager6/storage/wizard/LunSelect.js | 177 +++++++++
www/manager6/storage/wizard/NodeIdentities.js | 83 ++++
www/manager6/storage/wizard/Wizard.js | 299 ++++++++++++++
www/manager6/window/SANLunState.js | 115 ++++++
www/manager6/window/SANLunWipe.js | 52 +++
24 files changed, 2367 insertions(+), 6 deletions(-)
^ permalink raw reply [relevance 7%]
* [PATCH v6 storage 22/42] disks: lvm: allow volume groups on SAN LUNs and multipath maps
2026-11-18 6:52 7% [PATCH v6 cluster,storage,docs,manager 00/42] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM Thomas Lamprecht
@ 2026-11-18 6:52 9% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-18 6:52 UTC (permalink / raw)
To: pve-devel
The node disk API creates volume groups on local disks only. It
treats a Fibre Channel LUN as a local disk, refuses a multipath map
and adds the storage as local to the node. Accept the LUNs of the SAN
inventory and add their storage as shared for all nodes. Refuse an
existing storage ID for a LUN, and never join a storage that got
added with that ID meanwhile. Joining is meant for local volume groups
of the same name, and on a LUN would combine two different volume
groups in one shared storage. The partitions of a LUN, also the ones
that kpartx maps, stay local devices as before, so that an LVM storage
can still be added for a volume group on one of them.
Initializing a LUN, here or as base volume of an LVM storage that is
being added, takes a cluster-wide lock per WWID. It refuses a LUN that
a storage references through its volume group, as base volume, also
through a partition, or as iSCSI target serving images. The name of a
map can pass to another map while the lock is awaited. So the LUN is
held open by its stable name, and creation stops if a name used for
the checks and the LVM commands no longer leads to the held device.
The lookup of the LUN also resolves the requested name again after its
scan, and stops if the name leads to another device by then.
A LUN that a process of the node has open is refused too. A guest
that got the LUN as disk from a third-party storage plugin, or by its
device path, is neither a holder nor a storage reference, and its disk
can look empty. The check goes by the open files of the processes, so
it misses an open through another device node, for example the one of
a container. Also refused is a LUN whose other SCSI paths or their
partitions are mounted, held by a block device other than the map of
the LUN, or open for writing. An open for reading does not count, as
multipathd keeps the paths open read-only.
Co-authored-by: Dietmar Maurer <dietmar@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
src/PVE/API2/Disks/LVM.pm | 68 ++++---
src/PVE/Diskmanage.pm | 45 +++++
src/PVE/Storage/LVMPlugin.pm | 81 ++++++++-
src/PVE/Storage/SAN.pm | 149 ++++++++++++++++
src/test/Makefile | 11 +-
src/test/disk_api_test.pm | 247 ++++++++++++++++++++++++++
src/test/run_disk_api_tests.pl | 11 ++
src/test/run_san_library_tests.pl | 27 +++
src/test/run_san_nvme_tests.pl | 104 +++++++++++
src/test/run_san_taint_tests.pl | 26 +++
src/test/run_san_write_check_tests.pl | 205 +++++++++++++++++++++
src/test/run_test_lvm_create.pl | 46 +++++
12 files changed, 985 insertions(+), 35 deletions(-)
create mode 100644 src/test/disk_api_test.pm
create mode 100755 src/test/run_disk_api_tests.pl
create mode 100755 src/test/run_san_nvme_tests.pl
create mode 100755 src/test/run_san_write_check_tests.pl
diff --git a/src/PVE/API2/Disks/LVM.pm b/src/PVE/API2/Disks/LVM.pm
index 6101743b..790891b3 100644
--- a/src/PVE/API2/Disks/LVM.pm
+++ b/src/PVE/API2/Disks/LVM.pm
@@ -4,6 +4,7 @@ use strict;
use warnings;
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
use PVE::Diskmanage;
use PVE::JSONSchema qw(get_standard_option);
use PVE::API2::Storage::Config;
@@ -130,10 +131,13 @@ __PACKAGE__->register_method({
name => get_standard_option('pve-storage-id'),
device => {
type => 'string',
- description => 'The block device you want to create the volume group on',
+ description => 'The block device you want to create the volume group on.'
+ . ' Multipath mapped devices are supported.',
},
add_storage => {
- description => "Configure storage using the Volume Group",
+ description => "Configure storage using the Volume Group. On a SAN LUN, this"
+ . " adds a new shared storage for all nodes, otherwise a storage for this node"
+ . " only.",
type => 'boolean',
optional => 1,
default => 0,
@@ -152,48 +156,62 @@ __PACKAGE__->register_method({
my $node = $param->{node};
$dev = PVE::Diskmanage::verify_blockdev_path($dev);
- PVE::Diskmanage::assert_disk_unused($dev);
+ my $san = PVE::Storage::SAN::is_san_device($dev);
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
my $storage_params = {
type => 'lvm',
vgname => $name,
storage => $name,
content => 'rootdir,images',
- shared => 0,
- nodes => $node,
+ shared => $san ? 1 : 0,
+ $san ? () : (nodes => $node),
};
my $verify_params = [qw(vgname)];
if ($param->{add_storage}) {
$rpcenv->check($user, "/storage", ['Datastore.Allocate']);
+ # only local volume groups of the same name may share a storage that exists already
+ die "storage ID '$name' already defined\n"
+ if $san && PVE::Storage::storage_config(PVE::Storage::config(), $name, 1);
+
# reserve the name and add as disabled, will be enabled below if creation works out
PVE::API2::Storage::Config->create_or_update(
$name, $node, $storage_params, $verify_params, 1,
);
}
+ my $create_group = sub {
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
+ die "volume group with name '${name}' already exists on node '${node}'\n"
+ if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
+
+ if (PVE::Diskmanage::is_partition($dev)) {
+ eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
+ warn $@ if $@;
+ }
+
+ # the given name, which the LUN lookup resolves once more after its scan
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ $san ? $param->{device} : $dev,
+ $name,
+ $san,
+ );
+
+ PVE::Diskmanage::udevadm_trigger($dev);
+
+ if ($param->{add_storage} && $san) {
+ # must not join a storage that someone added with this ID in the meantime
+ PVE::API2::Storage::Config->create({%$storage_params});
+ } elsif ($param->{add_storage}) {
+ PVE::API2::Storage::Config->create_or_update(
+ $name, $node, $storage_params, $verify_params,
+ );
+ }
+ };
my $worker = sub {
- PVE::Diskmanage::locked_disk_action(sub {
- PVE::Diskmanage::assert_disk_unused($dev);
- die "volume group with name '${name}' already exists on node '${node}'\n"
- if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
-
- if (PVE::Diskmanage::is_partition($dev)) {
- eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
- warn $@ if $@;
- }
-
- PVE::Storage::LVMPlugin::lvm_create_volume_group($dev, $name);
-
- PVE::Diskmanage::udevadm_trigger($dev);
-
- if ($param->{add_storage}) {
- PVE::API2::Storage::Config->create_or_update(
- $name, $node, $storage_params, $verify_params,
- );
- }
- });
+ $san ? $create_group->() : PVE::Diskmanage::locked_disk_action($create_group);
};
return $rpcenv->fork_worker('lvmcreate', $name, $user, $worker);
diff --git a/src/PVE/Diskmanage.pm b/src/PVE/Diskmanage.pm
index c31cf991..7c85f892 100644
--- a/src/PVE/Diskmanage.pm
+++ b/src/PVE/Diskmanage.pm
@@ -1157,6 +1157,51 @@ sub change_parttype {
run_command(['sgdisk', "-t${partnum}:${parttype}", $blockdev], errmsg => $err);
}
+# Returns the PID and command name of a process for each of the block devices that a process has
+# open, as hash by the resolved path of the device. With 'writable', a process that opened the
+# device only for reading does not count. Only detects an open through the device nodes in /dev
+# of the host, not one through the device node that a container has of its own.
+sub device_openers {
+ my ($devices, %param) = @_;
+
+ # the device number tells a device from a file of that name in another mount namespace
+ my %nodes;
+ for my $path (grep { defined($_) } map { abs_path($_) } @$devices) {
+ my $st = stat($path) // next;
+ $nodes{$path} = $st->rdev;
+ }
+ my $openers = {};
+ return $openers if !%nodes;
+
+ opendir(my $proc, '/proc') or return $openers;
+ for my $pid (grep { m/^\d+$/ && $_ != $$ } readdir($proc)) {
+ opendir(my $fds, "/proc/$pid/fd") or next;
+ for my $fd (readdir($fds)) {
+ my $target = readlink("/proc/$pid/fd/$fd") // next;
+ next if !defined($nodes{$target}) || $openers->{$target};
+ my $st = stat("/proc/$pid/fd/$fd") // next;
+ next if $st->rdev != $nodes{$target};
+ if ($param{writable}) {
+ # the permissions of the link are the access mode of the open file
+ my $link = lstat("/proc/$pid/fd/$fd") // next;
+ next if !($link->mode & S_IWUSR);
+ }
+ my $comm = file_read_firstline("/proc/$pid/comm") // 'unknown';
+ $openers->{$target} = { pid => $pid, command => $comm };
+ }
+ }
+ return $openers;
+}
+
+# Returns the PID and command name of a process that has one of the block devices open, if any.
+sub device_opener {
+ my (@devices) = @_;
+
+ my $openers = device_openers(\@devices);
+ my ($opener) = map { $openers->{$_} } sort keys %$openers;
+ return $opener ? "$opener->{pid} ($opener->{command})" : undef;
+}
+
# Wipes all labels and the first 200 MiB of a disk/partition (or the whole if it is smaller).
# If called with a partition, also sets the partition type to 0x83 'Linux filesystem'.
# Expected to be called with a result of verify_blockdev_path().
diff --git a/src/PVE/Storage/LVMPlugin.pm b/src/PVE/Storage/LVMPlugin.pm
index 451e20ba..a32779cd 100644
--- a/src/PVE/Storage/LVMPlugin.pm
+++ b/src/PVE/Storage/LVMPlugin.pm
@@ -162,6 +162,37 @@ sub cached_pv_volume_groups {
return $res;
}
+sub lun_volume_groups {
+ my ($devices) = @_;
+ my $output = '';
+ run_command(
+ [
+ '/sbin/pvs',
+ '--nohints',
+ '--readonly',
+ '--devices',
+ join(',', @$devices),
+ '--reportformat',
+ 'json',
+ '--options',
+ 'pv_name,vg_name',
+ ],
+ timeout => 10,
+ outfunc => sub { $output .= "$_[0]\n" },
+ );
+ my $data = decode_json($output);
+ my $pvs = $data->{report}->[0]->{pv};
+ die "unable to inspect volume groups - invalid pvs report\n" if ref($pvs) ne 'ARRAY';
+ my %vgs;
+ for my $pv (@$pvs) {
+ my $vg = $pv->{vg_name};
+ die "unable to inspect volume groups - missing volume group metadata\n"
+ if !defined($vg) || $vg eq '[unknown]';
+ $vgs{$vg} = 1 if length($vg);
+ }
+ return [sort keys %vgs];
+}
+
sub clear_first_sector {
my ($dev) = shift;
@@ -172,10 +203,17 @@ sub clear_first_sector {
}
}
-sub lvm_create_volume_group {
- my ($device, $vgname, $shared, $guard) = @_;
-
+my sub create_volume_group {
+ my ($device, $vgname, $lun, $guard) = @_;
$device = PVE::Diskmanage::verify_blockdev_path($device);
+ my $fh;
+ if ($lun) {
+ sysopen($fh, $lun->{'by-id'}, O_RDWR) or die "cannot open '$device' - $!\n";
+ }
+ my $check_name = sub {
+ PVE::Storage::SAN::assert_same_device($lun, $fh, $device) if $lun;
+ };
+ $check_name->();
my $refuse_data = sub {
my (@types) = @_;
die "device '$device' contains data ("
@@ -193,7 +231,8 @@ sub lvm_create_volume_group {
if !defined($size) || $size !~ m/^\d+$/ || !$size;
die "unable to probe '$device' - missing device mapper identity\n"
if basename($device) =~ m/^dm-\d+$/ && !defined($uuid);
- if (defined($uuid) && $uuid =~ m/^mpath-/) {
+ my $map = PVE::Multipath::parse_dm_uuid($uuid);
+ if ($map && !$map->{partition}) {
# A queueing map without a running path can stall even a read-only probe.
my $running = 0;
PVE::Tools::dir_glob_foreach(
@@ -220,6 +259,8 @@ sub lvm_create_volume_group {
}
my %signatures = map { $_->{type} => 1 } $probe->@*;
my $res = lvm_pv_info($device, $signatures{LVM2_member});
+ # also a volume group that exists already only counts if the probes looked at the held LUN
+ $check_name->();
# A PV without metadata copies can belong to a VG whose other devices are not visible. The
# sentinel is not a VG name or orphan proof, even if the use flag contradicts it.
@@ -262,26 +303,52 @@ sub lvm_create_volume_group {
}
$refuse_data->(keys %signatures) if %signatures;
+ # Only initializing the device needs the checks, an existing volume group on it can be added.
$guard->{check_storage}->($device) if $guard && $guard->{check_storage};
- clear_first_sector($device); # else pvcreate fails
+ if ($lun) {
+ my $exempt = $guard ? $guard->{exempt} : undef;
+ PVE::Storage::SAN::assert_lun_unreferenced(PVE::Storage::config(), $lun, $exempt);
+ PVE::Storage::SAN::assert_lun_paths_unused($lun);
+ # a guest with the LUN as disk has it open, without being a holder or a storage reference
+ my $opener = PVE::Diskmanage::device_opener($device);
+ die "cannot create volume group on '$device' - process $opener has it open\n"
+ if defined($opener);
+ }
+
+ $check_name->();
+ clear_first_sector($lun ? '/proc/' . $$ . '/fd/' . fileno($fh) : $device);
# we use --metadatasize 250k, which reseults in "pe_start = 512"
# so pe_start is aligned on a 128k boundary (advantage for SSDs)
my $cmd = ['/sbin/pvcreate', '--metadatasize', '250k', $device];
- run_command($cmd, errmsg => "pvcreate '$device' error");
+ $check_name->();
+ run_command($cmd, errmsg => "pvcreate '$device' error", $lun ? (timeout => 30) : ());
$cmd = ['/sbin/vgcreate', $vgname, $device];
# push @$cmd, '-c', 'y' if $shared; # we do not use this yet
+ $check_name->();
run_command(
$cmd,
+ $lun ? (timeout => 30) : (),
errmsg => "vgcreate $vgname $device error",
errfunc => $ignore_no_medium_warnings,
outfunc => $ignore_no_medium_warnings,
);
}
+sub lvm_create_volume_group {
+ my ($device, $vgname, $shared, $guard) = @_;
+ require PVE::Storage::SAN;
+ my $lun = PVE::Storage::SAN::lun_for_device($device);
+ return create_volume_group($device, $vgname, undef, $guard) if !$lun;
+ PVE::Storage::SAN::with_lun_lock(
+ $lun,
+ sub { create_volume_group($device, $vgname, $lun, $guard) },
+ );
+}
+
sub lvm_destroy_volume_group {
my ($vgname) = @_;
@@ -1161,7 +1228,7 @@ sub on_add_hook {
$path,
$scfg->{vgname},
$scfg->{shared},
- { check_storage => $check_target },
+ { check_storage => $check_target, exempt => $storeid },
);
}
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index 788bb577..bf33e330 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -5,6 +5,7 @@ use v5.36;
use Cwd qw(abs_path);
use File::Basename qw(basename);
+use PVE::Cluster;
use PVE::INotify;
use PVE::Tools qw(file_read_firstline dir_glob_foreach);
@@ -193,4 +194,152 @@ sub is_san_device($device, $info = undef) {
|| PVE::Diskmanage::is_remote_transport($info->{transport}) ? 1 : 0;
}
+sub lun_for_device($name) {
+ my $device = PVE::Diskmanage::verify_blockdev_path($name);
+ return undef if !is_san_device($device);
+ my $rows = scan_luns(PVE::Storage::config());
+ # the device behind a name such as a by-id one can pass to another LUN during the scan
+ die "cannot use '$device' - the device behind '$name' changed\n"
+ if (abs_path($name) // '') ne $device;
+ for my $lun (@$rows) {
+ next if (abs_path($lun->{devpath}) // '') ne $device;
+ die "cannot use '$device' - no stable name under /dev/disk/by-id\n" if !$lun->{'by-id'};
+ # read from sysfs, but used in command lines and in the name of the cluster lock
+ ($lun->{devpath}) = $lun->{devpath} =~ m{\A(/dev/[A-Za-z0-9_.:+/-]+)\z}
+ or die "cannot use '$device' - unexpected device path\n";
+ ($lun->{wwid}) = $lun->{wwid} =~ m/\A([A-Za-z0-9_.:+=-]+)\z/
+ or die "cannot use '$device' - unexpected WWID\n";
+ return $lun;
+ }
+ die "cannot use '$device' - select an identified LUN or its multipath map\n";
+}
+
+sub lun_partitions($lun) {
+ my $device = PVE::Diskmanage::verify_blockdev_path($lun->{devpath});
+ my $name = basename($device);
+ my @parts;
+ dir_glob_foreach(
+ "/sys/class/block/$name",
+ "\Q$name\E.+",
+ sub($part, @) {
+ my ($path) = "/dev/$part" =~ m{\A(/dev/[A-Za-z0-9_.+-]+)\z};
+ push @parts, $path if defined($path) && -e "/sys/class/block/$name/$part/partition";
+ },
+ );
+ dir_glob_foreach(
+ "/sys/class/block/$name/holders",
+ 'dm-\\d+',
+ sub($part, @) {
+ my $map = PVE::Multipath::parse_dm_uuid(
+ file_read_firstline("/sys/class/block/$part/dm/uuid"));
+ my ($path) = "/dev/$part" =~ m{\A(/dev/dm-\d+)\z};
+ push @parts, $path
+ if defined($path) && $map && $map->{partition} && $map->{wwid} eq $lun->{wwid};
+ },
+ );
+ return \@parts;
+}
+
+sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
+ [$lun->{devpath}, lun_partitions($lun)->@*],
+ )->@*;
+ # the paths of a LUN can belong to more than one target
+ my %targets = map { $_->{target} => 1 }
+ grep { $_->{wwid} eq $lun->{wwid} && defined($_->{target}) }
+ values PVE::Multipath::Identity::collect(all => 1)->{paths}->%*;
+ $targets{ $lun->{'iscsi-target'} } = 1 if defined($lun->{'iscsi-target'});
+ for my $sid (sort keys $cfg->{ids}->%*) {
+ next if defined($exempt) && $sid eq $exempt;
+ my $scfg = $cfg->{ids}->{$sid};
+ my $type = $scfg->{type};
+ if ($vgs{ $scfg->{vgname} // '' }) {
+ die "cannot use '$lun->{devpath}' - volume group is used by storage '$sid'\n";
+ }
+ if (
+ defined($scfg->{target})
+ && $targets{ $scfg->{target} }
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
+ }
+ next if $type ne 'lvm' || !$scfg->{base};
+ my (undef, $volname) = PVE::Storage::Plugin::parse_volume_id($scfg->{base});
+ my ($wwid) = $volname =~ m/(?:^|\.)(?:dm-uuid-(?:part\d+-)?mpath|scsi|nvme)-(.+)$/;
+ my $matches = defined($wwid) && $wwid eq $lun->{wwid};
+ if (!$matches) {
+ my $path = eval { abs_path(PVE::Storage::path($cfg, $scfg->{base})) };
+ my $device = abs_path($lun->{devpath});
+ $matches = defined($path) && defined($device) && $path eq $device;
+ }
+ die "cannot use '$lun->{devpath}' - storage '$sid' uses this LUN as its base volume\n"
+ if $matches;
+ }
+ return;
+}
+
+# Serializes writes to a LUN cluster-wide. The code sees the current storage configuration.
+sub with_lun_lock($lun, $code) {
+ my $key = $lun->{wwid} =~ s/([^A-Za-z0-9_.:-])/sprintf('=%02x', ord($1))/ger;
+ PVE::Cluster::cfs_lock_domain("san-$key", undef, $code);
+ die $@ if $@;
+}
+
+# Device names can pass to another device while a LUN waits for its lock or is worked on. All
+# names used for it have to mean the device that is held open.
+sub assert_same_device($lun, $fh, @names) {
+ my @held = stat($fh);
+ for my $name ($lun->{'by-id'}, $lun->{devpath}, @names) {
+ my @named = stat($name);
+ die "cannot use '$lun->{devpath}' - the device behind '$name' changed\n"
+ if !@held || !@named || $held[6] != $named[6];
+ }
+}
+
+sub lun_paths($lun) {
+ my $paths = PVE::Multipath::Identity::collect(all => 1)->{paths};
+ return [
+ map { m/^(sd[a-z]+)$/ ? "/dev/$1" : () }
+ grep { $paths->{$_}->{wwid} eq $lun->{wwid} } sort keys %$paths
+ ];
+}
+
+# The other paths of a LUN reach the same data, but neither the exclusive open of the LUN nor the
+# checks of its device cover them.
+sub assert_lun_paths_unused($lun) {
+ my $device = basename(abs_path($lun->{devpath}) // $lun->{devpath});
+ my %devices; # the paths and their partitions
+ for my $path (grep { basename($_) ne $device } lun_paths($lun)->@*) {
+ if (my $mounted = PVE::Diskmanage::is_mounted($path)) {
+ die "cannot use '$lun->{devpath}' - the LUN is mounted through '$mounted'\n";
+ }
+ my $name = basename($path);
+ $devices{$path} = 1;
+ dir_glob_foreach(
+ "/sys/class/block/$name",
+ "\Q$name\E\\d+",
+ sub($part, @) {
+ $devices{"/dev/$part"} = 1;
+ },
+ );
+ }
+ for my $path (sort keys %devices) {
+ dir_glob_foreach(
+ '/sys/class/block/' . basename($path) . '/holders',
+ '[^.].*',
+ sub($holder, @) {
+ die "cannot use '$lun->{devpath}' - another block device uses the LUN through"
+ . " '$path'\n"
+ if $holder ne $device;
+ },
+ );
+ }
+ my $openers = PVE::Diskmanage::device_openers([sort keys %devices], writable => 1);
+ for my $path (sort keys %$openers) {
+ my $opener = $openers->{$path};
+ die "cannot use '$lun->{devpath}' - process $opener->{pid} ($opener->{command}) has the"
+ . " LUN open through '$path'\n";
+ }
+}
+
1;
diff --git a/src/test/Makefile b/src/test/Makefile
index 2f6f4cd7..0d866d91 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_sensitive_properties test_import_stream test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api
+test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_sensitive_properties test_import_stream test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
@@ -9,9 +9,10 @@ test_lvmplugin: run_test_lvmplugin.pl run_test_lvm_throughput.pl
./run_test_lvmplugin.pl
./run_test_lvm_throughput.pl
-test_lvm_create: run_test_lvm_create.pl run_test_lvm_base_conflicts.pl
+test_lvm_create: run_test_lvm_create.pl run_test_lvm_base_conflicts.pl run_san_write_check_tests.pl
./run_test_lvm_create.pl
./run_test_lvm_base_conflicts.pl
+ ./run_san_write_check_tests.pl
test_lvm_lock_retry: run_test_lvm_lock_retry.pl
./run_test_lvm_lock_retry.pl
@@ -75,5 +76,9 @@ test_san_taint: run_san_taint_tests.pl
test_san_lun_scan: run_san_lun_scan_tests.pl
./run_san_lun_scan_tests.pl
-test_san_api: run_san_api_tests.pl
+test_san_api: run_san_api_tests.pl run_san_nvme_tests.pl
./run_san_api_tests.pl
+ ./run_san_nvme_tests.pl
+
+test_disk_api: run_disk_api_tests.pl
+ ./run_disk_api_tests.pl
diff --git a/src/test/disk_api_test.pm b/src/test/disk_api_test.pm
new file mode 100644
index 00000000..474ad663
--- /dev/null
+++ b/src/test/disk_api_test.pm
@@ -0,0 +1,247 @@
+package PVE::API2::Disks::Test;
+
+use v5.36;
+
+use lib qw(..);
+
+use PVE::API2::Disks;
+use PVE::API2::Disks::LVM;
+use PVE::Diskmanage;
+use PVE::Storage;
+use PVE::Storage::LVMPlugin;
+
+use Test::MockModule;
+use Test::More;
+
+my @transport_cases = (
+ ['none', undef],
+ ['unknown', 'unknown'],
+ ['ata', 'ata'],
+ ['sata', 'sata'],
+ ['sas', 'sas'],
+ ['spi', 'spi'],
+ ['sbp', 'sbp'],
+ ['usb', 'usb'],
+ ['fc', 'fc'],
+ ['fcoe', 'fcoe'],
+ ['iscsi', 'iscsi'],
+ ['nvme', 'nvme'],
+ ['virtio', 'virtio'],
+ ['nvme-fc', 'nvme-fc'],
+ ['nvme-tcp', 'nvme-tcp'],
+ ['nvme-rdma', 'nvme-rdma'],
+ ['nvme-loop', 'nvme-loop'],
+);
+
+my $disks = {};
+my @all;
+for my $case (@transport_cases) {
+ my ($name, $transport) = $case->@*;
+ my $devpath = "/dev/test-$name";
+ my $entry = {
+ devpath => $devpath,
+ gpt => 0,
+ osdid => -1,
+ };
+ $entry->{transport} = $transport if defined($transport);
+ $disks->{$name} = $entry;
+ push @all, $devpath;
+}
+
+my $diskmanage_module = Test::MockModule->new('PVE::Diskmanage', no_auto => 1);
+$diskmanage_module->mock('get_disks' => sub { return $disks });
+
+my $list_handler = PVE::API2::Disks->map_method_by_name('list')->{code};
+my $list_devpaths = sub($param) {
+ my $result = $list_handler->({ node => 'test-node', skipsmart => 1, $param->%* });
+ return [sort map { $_->{devpath} } $result->@*];
+};
+
+is_deeply(
+ $list_devpaths->({}), [sort @all], 'the disk list uses the default disk inventory',
+);
+
+is_deeply(
+ $list_devpaths->({ type => 'unused' }),
+ [sort @all],
+ 'unused disk selection preserves transport visibility',
+);
+
+$diskmanage_module->mock(
+ 'get_disks' => sub {
+ return {
+ 'fc-disk' => {
+ devpath => '/dev/fc-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'fc',
+ },
+ 'fc-partition' => {
+ devpath => '/dev/fc-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/fc-disk',
+ },
+ 'loop-disk' => {
+ devpath => '/dev/loop-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'nvme-loop',
+ },
+ 'loop-partition' => {
+ devpath => '/dev/loop-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/loop-disk',
+ },
+ };
+ },
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1 }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'the plain list keeps FC disks and their partitions',
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1, type => 'unused' }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'unused partitions preserve transport visibility',
+);
+
+subtest 'volume group creation leaves SAN locking to the LVM helper' => sub {
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $disk = $diskmanage_module;
+ my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+ my $rpc = Test::MockModule->new('PVE::RPCEnvironment');
+ my (@stack, @created);
+ my $lock = sub($name, $code) {
+ push @stack, $name;
+ my $res = eval { $code->() };
+ my $err = $@;
+ pop @stack;
+ die $err if $err;
+ return $res;
+ };
+ $storage->mock(lock_storage_config => sub { $lock->('storage.cfg', $_[0]) });
+ $disk->mock(locked_disk_action => sub { $lock->('disk', $_[0]) });
+ $disk->mock(verify_blockdev_path => sub { $_[0] });
+ $disk->mock(assert_disk_unused => sub { });
+ $disk->mock(is_partition => sub { 0 });
+ $disk->mock(udevadm_trigger => sub { });
+ $lvm->mock(lvm_vgs => sub { {} });
+ $lvm->mock(
+ lvm_create_volume_group => sub {
+ is(scalar(@_), 3, 'disk API does not exempt a storage');
+ push @created, [$_[0], join('>', @stack)];
+ },
+ );
+ {
+
+ package MultipathTestRPC;
+ sub get_user { 'root@pam' }
+ sub check { 1 }
+ sub fork_worker { $_[4]->(); return 'test-upid' }
+ }
+ $rpc->mock(get => sub { bless {}, 'MultipathTestRPC' });
+
+ my ($is_map, $is_san) = (1, 0);
+ my $san = Test::MockModule->new('PVE::Storage::SAN');
+ $san->mock(is_san_device => sub { $is_map || $is_san });
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg1', device => '/dev/dm-3' });
+ ($is_map, $is_san) = (0, 1);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg2', device => '/dev/sdc' });
+ ($is_map, $is_san) = (0, 0);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg3', device => '/dev/sdb' });
+ is_deeply(
+ \@created,
+ [
+ ['/dev/dm-3', ''], ['/dev/sdc', ''], ['/dev/sdb', 'disk'],
+ ],
+ 'SAN writes use no local disk or storage configuration lock',
+ );
+ my $config_api = Test::MockModule->new('PVE::API2::Storage::Config');
+ my (@params, @registered);
+ $config_api->mock(
+ create_or_update => sub {
+ push @registered, $_[5] ? 'check' : 'create or update';
+ push @params, $_[3];
+ },
+ create => sub {
+ push @registered, 'create';
+ push @params, $_[1];
+ },
+ );
+ my $cfg =
+ { ids => { other => { type => 'lvm', vgname => 'other', nodes => { n2 => 1 } } } };
+ $storage->mock(config => sub { $cfg });
+ $is_san = 1;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg4',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 1, 'SAN storage is shared');
+ ok(!exists($params[-1]->{nodes}), 'SAN storage covers all nodes');
+ is_deeply(
+ \@registered,
+ ['check', 'create'],
+ 'and only gets created: it never joins a storage added in the meantime',
+ );
+ @registered = ();
+ @created = ();
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'other',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ };
+ like($@, qr/already defined/, 'SAN volume group does not join the storage of another node');
+ is_deeply(\@created, [], 'existing storage ID prevents initialization');
+ $is_san = 0;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg5',
+ device => '/dev/sdb',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 0, 'local storage is not shared');
+ is($params[-1]->{nodes}, 'n1', 'local storage remains node-restricted');
+ is_deeply(\@registered, ['check', 'create or update'], 'and may join one of its name');
+ @created = ();
+ $disk->mock(assert_disk_unused => sub { die "device is already in use\n" });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like($@, qr/already in use/, 'disk API rejects a used inventory entry');
+ is_deeply(\@created, [], 'used inventory prevents initialization');
+ $disk->mock(assert_disk_unused => sub { });
+ $lvm->mock(lvm_vgs => sub { { vg => {} } });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like(
+ $@,
+ qr/volume group with name 'vg' already exists/,
+ 'stale inventory does not permit an existing VG',
+ );
+ is_deeply(\@created, [], 'existing VG prevents initialization');
+ my @mocked = qw(
+ locked_disk_action verify_blockdev_path assert_disk_unused is_partition udevadm_trigger
+ );
+ $disk->unmock($_) for @mocked;
+};
+
+done_testing();
diff --git a/src/test/run_disk_api_tests.pl b/src/test/run_disk_api_tests.pl
new file mode 100755
index 00000000..75fc98c6
--- /dev/null
+++ b/src/test/run_disk_api_tests.pl
@@ -0,0 +1,11 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use TAP::Harness;
+
+my $harness = TAP::Harness->new({ verbosity => -2 });
+my $res = $harness->runtests("disk_api_test.pm");
+
+exit -1 if !$res || $res->{failed} || $res->{parse_errors};
diff --git a/src/test/run_san_library_tests.pl b/src/test/run_san_library_tests.pl
index f7ae68d1..d961b87c 100755
--- a/src/test/run_san_library_tests.pl
+++ b/src/test/run_san_library_tests.pl
@@ -105,4 +105,31 @@ subtest 'LVM hints are optional cached display metadata' => sub {
}
};
+subtest 'the names of a held LUN have to mean the held device' => sub {
+ require PVE::Storage::SAN;
+ open(my $fh, '<', '/dev/null') or die "cannot open /dev/null - $!\n";
+ my $lun = { 'by-id' => '/dev/null', devpath => '/dev/null' };
+ my $check = sub {
+ eval { PVE::Storage::SAN::assert_same_device(@_) };
+ return $@;
+ };
+ is($check->($lun, $fh, '/dev/null'), '', 'same device behind all names');
+ like(
+ $check->({ %$lun, 'by-id' => '/dev/zero' }, $fh),
+ qr/'\/dev\/zero' changed/,
+ 'by-id name',
+ );
+ like(
+ $check->({ %$lun, devpath => '/dev/zero' }, $fh),
+ qr/'\/dev\/zero' changed/,
+ 'device path',
+ );
+ like(
+ $check->($lun, $fh, '/dev/zero'),
+ qr/'\/dev\/zero' changed/,
+ 'name used for the commands',
+ );
+ like($check->($lun, $fh, '/dev/gone'), qr/'\/dev\/gone' changed/, 'name without a device');
+};
+
done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
new file mode 100755
index 00000000..9f243563
--- /dev/null
+++ b/src/test/run_san_nvme_tests.pl
@@ -0,0 +1,104 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+our ($backing, @opens);
+
+BEGIN {
+ *CORE::GLOBAL::sysopen = sub (*$$;$) {
+ push @opens, $_[1];
+ my $path = $_[1] =~ m{^/dev/disk/by-id/nvme-} ? $backing : $_[1];
+ return CORE::sysopen($_[0], $path, $_[2]);
+ };
+}
+use lib qw(..);
+use File::Temp qw(tempfile);
+use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
+
+my ($fh, $file) = tempfile('san-nvme-XXXX', DIR => '.', UNLINK => 1);
+close($fh);
+$backing = $file;
+my $device = '/dev/nvme0n1';
+my $link = '/dev/disk/by-id/nvme-eui.0123456789abcdef';
+my $lun =
+ { devpath => $device, 'by-id' => $link, wwid => 'eui.0123456789abcdef', multipath => 'native' };
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $mp = Test::MockModule->new('PVE::Multipath');
+my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $cfg = { ids => {} };
+my @order;
+$storage->mock(config => sub { $cfg });
+$disk->mock(verify_blockdev_path => sub { $device });
+$disk->mock(is_partition => sub { 0 });
+$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(is_iscsi_device => sub { 0 });
+$disk->mock(is_mounted => sub { 0 });
+$disk->mock(has_holder => sub { 0 });
+$disk->mock(device_opener => sub { undef });
+$mp->mock(device_map => sub { undef });
+$san->mock(abs_path => sub { $device });
+$san->mock(scan_luns => sub { [$lun] });
+$san->mock(lun_partitions => sub { [] });
+$san->mock(assert_same_device => sub { ok(defined(fileno($_[1])), 'held descriptor checked') });
+$lvm->mock(lun_volume_groups => sub { push @order, 'check'; [] });
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-eui.0123456789abcdef', 'native namespace uses the LUN lock');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+is(PVE::Storage::SAN::stable_path($device, $lun->{wwid}), $link, 'native stable path');
+is_deeply(PVE::Storage::SAN::lun_for_device($link), $lun, 'native row selected for writes');
+my $model_link = '/dev/disk/by-id/nvme-NetApp_ONTAP_Controller_81Mkq_1';
+is_deeply(PVE::Storage::SAN::lun_for_device($model_link), $lun, 'any name of the namespace');
+{
+ # the name passes to another device while the LUNs are scanned
+ my $scanned = 0;
+ $san->mock(scan_luns => sub { $scanned = 1; [$lun] });
+ $san->mock(abs_path => sub { $_[0] eq $model_link && $scanned ? '/dev/nvme9n1' : $device });
+ eval { PVE::Storage::SAN::lun_for_device($model_link) };
+ like($@, qr/the device behind '\Q$model_link\E' changed/, 'a name that changed refuses');
+ $san->mock(scan_luns => sub { [$lun] });
+ $san->mock(abs_path => sub { $device });
+}
+$disk->mock(is_partition => sub { 1 });
+is(PVE::Storage::SAN::lun_for_device($link), undef, 'a partition is handled as a local device');
+$disk->mock(is_partition => sub { 0 });
+$cfg->{ids}->{data} = { type => 'lvm', base => 'fabric:nvme-eui.0123456789abcdef' };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like($@, qr/base volume/, 'native base reference refuses');
+$cfg->{ids} = {};
+@order = @opens = ();
+$lvm->mock(file_read_firstline => sub { $_[0] =~ m{/size$} ? 1024 : undef });
+$lvm->mock(lvm_pv_info => sub { undef });
+$lvm->mock(
+ clear_first_sector => sub { push @order, 'clear'; ok(-e $_[0], 'VG clear uses held fd') });
+$lvm->mock(
+ run_command => sub {
+ my ($cmd, %opts) = @_;
+ if ($cmd->[0] eq 'wipefs') {
+ $opts{outfunc}->('{"signatures":[]}');
+ } else {
+ is($cmd->[-1], $device, 'VG command uses the checked device');
+ push @order, $cmd->[0];
+ }
+ },
+);
+PVE::Storage::LVMPlugin::lvm_create_volume_group($link, 'data', 1);
+is_deeply(
+ \@order,
+ [qw(lock check clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'native VG sequencing',
+);
+is_deeply(\@opens, [$link], 'VG creation holds the native by-id device');
+
+done_testing();
diff --git a/src/test/run_san_taint_tests.pl b/src/test/run_san_taint_tests.pl
index 35b11cd7..0ccd9e2f 100755
--- a/src/test/run_san_taint_tests.pl
+++ b/src/test/run_san_taint_tests.pl
@@ -31,4 +31,30 @@ for my $bad ('-bad', '1:2', '../dev', "3600a\n") {
like($@, qr/invalid WWID/, 'ambiguous identity refused');
}
+# the LUN that write operations get must be usable in command lines and lock names
+use PVE::Storage::SAN;
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $tainted_dev = PVE::Tools::file_get_contents('/proc/self/comm') =~ s/.*//sr . '/dev/null';
+ok(tainted($tainted_dev), 'device path derived from a file is tainted');
+$san->mock(
+ is_san_device => sub { 1 },
+ scan_luns => sub {
+ return [{
+ devpath => $tainted_dev,
+ wwid => $wwid,
+ 'by-id' => '/dev/null',
+ usage => 'unused',
+ multipath => 'none',
+ }];
+ },
+);
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(verify_blockdev_path => sub { '/dev/null' });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+my $lun = PVE::Storage::SAN::lun_for_device('/dev/null');
+ok(!tainted($lun->{devpath}), 'LUN device path is untainted');
+ok(!tainted($lun->{wwid}), 'LUN WWID is untainted');
+is($lun->{wwid}, '3600a', 'LUN WWID is unchanged');
+
done_testing();
diff --git a/src/test/run_san_write_check_tests.pl b/src/test/run_san_write_check_tests.pl
new file mode 100755
index 00000000..a4210fba
--- /dev/null
+++ b/src/test/run_san_write_check_tests.pl
@@ -0,0 +1,205 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use lib qw(..);
+use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
+
+my $scan = Test::MockModule->new('PVE::Storage::SAN');
+my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $lun = { wwid => '3600+abc', devpath => '/dev/dm-0', 'iscsi-target' => 'iqn.test' };
+# the LUN is exported through two targets, its row names only the first
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
+my $paths = sub {
+ {
+ paths => {
+ sdb => { wwid => '3600+abc', target => 'iqn.test' },
+ sdc => { wwid => '3600+abc', target => 'iqn.second' },
+ sdd => { wwid => '3600+other', target => 'iqn.other' },
+ },
+ };
+};
+$identity->mock(collect => $paths);
+my $vgs = [];
+$scan->mock(lun_partitions => sub { [] });
+$lvm->mock(lun_volume_groups => sub { $vgs });
+$lvm->mock(cached_pv_volume_groups => sub { die "write check must not use cached PV metadata\n" });
+my $cfg = { ids => {} };
+$storage->mock(config => sub { $cfg });
+my $check = sub {
+ eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun, @_) };
+ return $@;
+};
+is($check->(), '', 'unreferenced LUN accepted');
+for my $type (qw(lvm lvmthin custom)) {
+ $vgs = ['data'];
+ $cfg->{ids} = {
+ data => {
+ type => $type,
+ vgname => 'data',
+ shared => 1,
+ disable => 1,
+ nodes => { other => 1 },
+ },
+ };
+ for my $cached_vg (undef, 'unrelated') {
+ $lun->{vgname} = $cached_vg;
+ $lun->{usage} = 'unused';
+ like($check->(), qr/used by storage 'data'/, "$type refusal ignores display VG and usage");
+ }
+ is($check->('data'), '', 'the storage being added can be exempted');
+}
+delete $lun->{vgname};
+delete $lun->{usage};
+$vgs = [];
+$cfg->{ids} = { direct => { type => 'iscsi', target => 'iqn.test', content => { images => 1 } } };
+like($check->(), qr/storage 'direct' serves images from this target$/, 'direct image use refuses');
+$cfg->{ids}->{direct}->{target} = 'iqn.second';
+like($check->(), qr/storage 'direct' serves images/, 'also through another target of the LUN');
+$cfg->{ids}->{direct}->{target} = 'iqn.other';
+is($check->(), '', 'a target of another LUN is no reference');
+{
+ # multipathd does not answer and udev knows the path by another identity
+ local $lun->{'iscsi-target'} = 'iqn.other';
+ $identity->mock(collect => sub { { paths => {} } });
+ like($check->(), qr/storage 'direct' serves images/, 'the target of the LUN itself counts');
+ $identity->mock(collect => $paths);
+}
+$cfg->{ids}->{direct}->{target} = 'iqn.test';
+$cfg->{ids}->{direct}->{content} = { none => 1 };
+is($check->(), '', 'connection-only storage permits use');
+
+for my $type (qw(iscsidirect zfs)) {
+ local $cfg->{ids}->{other} = { type => $type, target => 'iqn.test', content => {} };
+ like(
+ $check->(),
+ qr/storage 'other' serves images from this target$/,
+ "$type storage of the target refuses",
+ );
+}
+$cfg->{ids}->{data} = { type => 'lvm', base => 'direct:0.0.1.dm-uuid-mpath-3600+abc' };
+like($check->(), qr/base volume/, 'base reference refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-3600+abc';
+like($check->(), qr/base volume/, 'scsi WWID in base name refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.dm-uuid-part1-mpath-3600+abc';
+like($check->(), qr/base volume/, 'a partition of the map as base refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-legacy';
+$storage->mock(path => sub { '/dev/disk/by-id/legacy' });
+$scan->mock(abs_path => sub { '/dev/dm-0' });
+like($check->(), qr/base volume/, 'resolved alias to the LUN refuses');
+$scan->mock(abs_path => sub { $_[0] eq $lun->{devpath} ? '/dev/dm-0' : '/dev/dm-1' });
+is($check->(), '', 'base on another device is no match');
+$scan->mock(abs_path => sub { undef });
+is($check->(), '', 'unresolvable base is no match');
+$storage->mock(path => sub { die "base unavailable\n" });
+is($check->(), '', 'unavailable base is no match');
+ok(!PVE::Storage::LVMPlugin->can('create_volume_group'), 'creation implementation is lexical');
+$cfg->{ids} = {};
+my @order;
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-3600=2babc', 'lock name escapes unsafe characters without collisions');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+PVE::Storage::SAN::with_lun_lock($lun, sub { push @order, 'write' });
+is_deeply(\@order, [qw(lock write unlock)], 'the code runs under the lock of the LUN');
+
+# volume group creation checks the references only when it has to initialize the LUN
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(
+ verify_blockdev_path => sub { $_[0] },
+ is_mounted => sub { undef },
+ has_holder => sub { undef },
+ device_opener => sub { undef },
+);
+my ($signatures, $pvinfo) = ('', undef);
+$lun->{'by-id'} = '/dev/null';
+$scan->mock(
+ lun_for_device => sub { $lun },
+ assert_same_device => sub { },
+ assert_lun_unreferenced => sub { push @order, 'check'; die "referenced\n" },
+);
+$lvm->mock(
+ file_read_firstline => sub { $_[0] =~ m{/size$} ? '2048' : undef },
+ lvm_pv_info => sub { $pvinfo },
+ clear_first_sector => sub { push @order, 'clear' },
+ run_command => sub {
+ my ($cmd, %param) = @_;
+ return $param{outfunc}->(qq({"signatures":[$signatures]})) if $cmd->[0] eq 'wipefs';
+ push @order, $cmd->[0];
+ },
+);
+@order = ();
+$signatures = '{"type":"LVM2_member","offset":"0x218"}';
+$pvinfo = { vgname => 'data', in_use => '1' };
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an existing volume group can be added whatever references its LUN');
+is_deeply(\@order, [qw(lock unlock)], 'without reference check or write');
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'other',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/already used by volume group 'data'/, 'another volume group on the LUN refuses');
+@order = ();
+($signatures, $pvinfo) = ('', undef);
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/referenced/, 'initializing a referenced LUN refuses');
+is_deeply(\@order, [qw(lock check)], 'the check precedes the first write');
+$scan->mock(assert_lun_unreferenced =>
+ sub { is($_[2], 'new', 'new storage exempt'); push @order, 'check' });
+$scan->mock(assert_lun_paths_unused => sub { push @order, 'paths'; die "path in use\n" });
+@order = ();
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/path in use/, 'a LUN that is in use through another path refuses');
+is_deeply(\@order, [qw(lock check paths)], 'before the first write');
+$scan->mock(assert_lun_paths_unused => sub { push @order, 'paths' });
+@order = ();
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an unreferenced empty LUN is initialized');
+is_deeply(
+ \@order,
+ [qw(lock check paths clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'checked once, then written under the lock',
+);
+
+done_testing();
diff --git a/src/test/run_test_lvm_create.pl b/src/test/run_test_lvm_create.pl
index d4be25b0..13058fe2 100755
--- a/src/test/run_test_lvm_create.pl
+++ b/src/test/run_test_lvm_create.pl
@@ -10,9 +10,12 @@ use Test::More;
use lib ('.', '..');
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+$san->mock(lun_for_device => sub { undef });
my $tools = Test::MockModule->new('PVE::Tools');
my $inotify = Test::MockModule->new('PVE::INotify');
$inotify->mock(nodename => sub { 'testnode' });
@@ -43,6 +46,7 @@ $lvm->mock(
if $_[0] =~ m{/(?:uevent|size)/partition$};
return $partitioned ? '1' : undef if $_[0] =~ m{/partition$};
return $holder_uuid if $_[0] =~ m{/dm-5/dm/uuid$};
+ return 'part1-mpath-3600abc' if $map eq 'partition' && $_[0] =~ m{/uuid$};
return $map ? 'mpath-3600abc' : undef if $_[0] =~ m{/uuid$};
return $running ? 'running' : 'offline' if $_[0] =~ m{/state$};
die "unexpected read $_[0]";
@@ -119,6 +123,10 @@ for my $case (
is_deeply(\@probes, [], "$case->[0]: no device reads");
is_deeply(\@writes, [], "$case->[0]: no writes");
}
+reset_case();
+($map, $running) = ('partition', 0);
+is(create(), '', 'the partition of a map has the map as member, not its paths');
+is(scalar(@writes), 3, 'so it is set up like a local partition');
reset_case();
my $storage_checks = 0;
@@ -170,6 +178,44 @@ like(
qr/contains data \(gpt\)/,
'a partition table of a map is data, kpartx may not map it',
);
+reset_case();
+($signatures, $partitioned) = ([{ type => 'PMBR' }, { type => 'gpt' }], 1);
+$san->mock(
+ lun_for_device =>
+ sub { { wwid => '3600abc', devpath => '/dev/sda', 'by-id' => '/dev/null' } },
+ with_lun_lock => sub { $_[1]->() },
+);
+like(
+ create(),
+ qr{the device behind '/dev/sda' changed},
+ 'a device name that no longer means the held LUN is refused',
+);
+is_deeply(\@writes, [], 'changed device: no writes');
+$san->mock(assert_same_device => sub { });
+like(create(), qr/contains data \(PMBR, gpt\)/, 'a partitioned LUN that is no map is data too');
+is_deeply(\@writes, [], 'partitioned LUN: no writes');
+reset_case();
+my $opener = '4711 (kvm)';
+$disk->mock(device_opener => sub { $opener });
+$san->mock(assert_lun_unreferenced => sub { });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+like(create(), qr/process 4711 \(kvm\) has it open/, 'a LUN that a process has open is refused');
+is_deeply(\@writes, [], 'open LUN: no writes');
+$opener = undef;
+is(create(), '', 'a LUN that no process has open is initialized');
+is(scalar(@writes), 3, 'unused LUN: initialized');
+reset_case();
+$signatures = [{ type => 'LVM2_member' }];
+$label = '/dev/sda: LVM2 PV';
+$pv = '/dev/sda:1024:test:aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg:1';
+my $checked = 0;
+$san->mock(assert_same_device => sub { die "device changed\n" if ++$checked == 2 });
+like(create(), qr/device changed/, 'an existing volume group only counts on the held LUN');
+$san->unmock('assert_lun_unreferenced');
+$san->unmock('assert_same_device');
+$san->unmock('with_lun_lock');
+$san->mock(lun_for_device => sub { undef });
my $uuid = 'aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg';
for my $vg ('test', 'other', 'unknown', '') {
^ permalink raw reply related [relevance 9%]
* [PATCH v7 cluster,storage,docs,manager 00/43] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM
@ 2026-11-18 20:25 6% Thomas Lamprecht
2026-11-18 20:26 9% ` [PATCH v7 storage 23/43] disks: lvm: allow volume groups on SAN LUNs and multipath maps Thomas Lamprecht
0 siblings, 1 reply; 43+ results
From: Thomas Lamprecht @ 2026-11-18 20:25 UTC (permalink / raw)
To: pve-devel
This is v7 of the combined and reduced series of the cluster-wide
multipath work [0][1] and Dietmar's RFC for guided remote storage setup
and SAN visibility [2].
v7 is v6 [8] plus what some independent reviews and further lab testing
of v6 turned up, i.e.:
- The checks before a wipe or volume group creation take the members
of a map from the kernel too, not only those whose WWID multipathd
or udev reports, so a guest on such a path or its target is found.
The LUN list names a guest that writes to a partition of a LUN, which
the wipe refused but the list showed as unused.
- The web UI no longer falls back to a device name like /dev/sdX for a
wipe or for the Fibre Channel volume group: a name that passed to
another LUN in between would lead there. A LUN without a name under
/dev/disk/by-id cannot be wiped from the list, which the node refused
anyway, and the Fibre Channel setup waits for that name of the map.
- A drop-in is only replaced if its first line is the generated one,
v6 also took "# Not managed by Proxmox VE", and a node checks all
drop-ins before it changes one. The overrides refuse text after a
'{' and a '}' that is not alone on its line: multipath ignores the
rest of such a line, and with it the sections after it.
- A LUN that a storage requests, but that no node has assembled, shows
as Missing in the SAN view instead of not at all. An LVM base named
after the scsi- link of a LUN is attributed to its storage.
- pvestatd applies the multipath configuration right before the
storage status, so the node and guest status do not wait for it.
- The iSCSI setup offers the LUNs that the connection storage lists,
also one that the scan attributes to another target of the array,
finds a LUN by name, WWID or path, and says which storage blocks the
reuse of a target and why. The initiator names and the window at the
end follow the nodes of the new storage. The Fibre Channel recovery
texts name the volume group and storage ID.
- Enable Multipath under Node > SAN is offered for Fibre Channel LUNs
only, not for an NVMe namespace without native multipath.
- The LUN list names a guest only to users who may see it.
- Smaller ones: the status summary is described as the worst known
state, Expected Paths as the highest of the entry and the portal
counts, the Node > Disks > LVM dialog says that Add Storage on a SAN
LUN creates a shared storage for all nodes, error messages name what
to use instead, and the chapter says what a reader of a LUN and a
kernel partition of it mean for the checks.
What I left as is: findings that repeat points decided for v5 [3],
except the first-target filter of the iSCSI setup, which the content
listing now makes cheap to fix, and master's behavior, such as a kernel
partition of a LUN that is selected on its own, which the chapter now
mentions. wipefs on the claimed device does not re-read the partition
table, but udev does once the wipe closes the device, as the lab showed.
Overview of what an admin gets with this:
- Datacenter > Storage > SAN, a new entry below Storage, shows the
multipath state of every node and of the LUNs that Proxmox VE
manages or has a storage on, and edits the multipath entries and
array-specific overrides. I explicitly chose this over the
client/plugin side of Storage, as we do not have e.g. Ceph or
ZFS/LVM/... creation in there either. We might want to rethink and
consolidate our storage interface vs. management story in the
future, but IMO a partial switch now is not worth it, that would add
even more potential for confusion than the new SAN view.
- Its Guided Setup menu leads through shared LVM on a LUN: for iSCSI it
connects or reuses a target, with the initiator names of its nodes at
hand, for Fibre Channel it takes a LUN the nodes already see. Both
set up multipath and end with the state of the LUN on every node.
- Datacenter > Storage > Add keeps its dialogs. The iSCSI one gets a
Multipath option and the LVM one enables Shared for a base storage,
and both point to the SAN view.
- Node > SAN lists the LUNs of a node with their paths and usage, can
wipe a LUN that no storage uses, and shows the iSCSI sessions.
The rules the series follows since v4: nodes add WWIDs and maps but
never remove them, a write is checked where it happens, lists do not
probe devices, there are no new iSCSI operations, the guided setup makes
the API calls an admin would make by hand, and multipath management is
turned on by the admin. The v4 cover [7] has the reasons.
Two things an admin will likely miss: there is no notification when a
LUN loses path redundancy, the state only shows on the SAN pages and in
the API. And Fibre Channel starts at a LUN the nodes already see; the
chapter gives the commands to list WWPNs and rescan the HBAs.
How it works:
- /etc/pve/multipath.cfg holds explicit entries per WWID,
/etc/pve/multipath-overrides.conf array settings; patch 01
registers both. An iSCSI storage with the 'managed-multipath' option
supplies its LUNs without entries. The option is not named
'multipath', as third-party plugins use that name, and the storage
layer leaves out a third-party plugin that declares a property of
another plugin.
- pvestatd calls one function of pve-storage per pass. It adds the
WWIDs the node needs to /etc/multipath/wwids, writes the drop-ins
/etc/multipath/conf.d/pve-*.conf, reloads multipathd after a change,
and publishes the state of the maps that Proxmox VE manages or that a
storage builds on through the node key-value store.
- /cluster/multipath/status aggregates these reports;
/cluster/multipath/{wwid,overrides} edit the two files;
/nodes/{node}/scan/san-luns lists the LUNs of a node and
/nodes/{node}/iscsi its sessions.
- The volumes of an iSCSI storage with the option are named after the
multipath map, so an LVM storage uses them through 'base' as before.
- Volume group creation and wipe run under a cluster lock per LUN. They
refuse a LUN that a storage uses or a process of the node has open,
also through another path. Opens through another device node, such as
one of a container, and users on other hosts are not seen.
Patches:
- cluster 01: register the two configuration files
- storage 02-26: helpers for the disk and iSCSI session inventory
(mostly Dietmar's), the multipath library and configuration, the
iSCSI option, the per-node apply and status with their API, the disk
list of many disks, the LUN inventory, the read-only iSCSI status and
the portal of an iSCSI path, volume groups on LUNs, the wipe and the
process that has a LUN open
- docs 27-28: the multipath chapter, rewritten around tasks, and the
paragraph for a LUN that a process has open
- manager 29-43: the pvestatd call, report and API mounts, then the
views, the two dialog changes, the two guided setups, the note in the
add dialogs, and the guest or process and the target of a LUN
Other changes since v6 [8]:
- rebased onto current master; for pve-manager and pve-docs that has a
commit each that ends the technology preview status of snapshots as
volume chains, as they are ready for production use. The guided
setup and the chapter no longer call them a technology preview
either
- the node list of Datacenter > Storage > SAN links each node to its
Node > SAN view, like the content of a storage links a volume to its
guest
- Blockbridge tested v6 with their storage plugin, which runs its own
sessions, thanks! From that: Node > SAN shows a LUN without a
multipath map with its devices as paths, in the state that the kernel
reports for each, so a LUN with a single path also shows whether it
is up. Its Multipath column says Single path for one device, and an
iSCSI path names the portal of its session. The target column also
shows the subsystem of an NVMe namespace, and the LUN lists sort by
the names and uses they show
- the Wipe button under Node > SAN sits apart from the other buttons,
and its dialog also asks to confirm that no other host uses the LUN,
as the checks before the wipe only see such a use through a storage
- the subject of patch 3 spells NVMe over Fabrics like the rest
When applying, versioned dependencies have to be set: pve-manager on
libpve-storage-perl, and libpve-storage-perl (also as build dependency)
on the libpve-cluster-perl with patch 01, as PVE::Storage
registers the two files when it is loaded. pve-cluster with the same
patch keeps the version counters of the two files; with an older pmxcfs
they are read and parsed again on every request. pve-manager also needs
the pve-doc-generator (build) and pve-docs with the multipath chapter,
for its help links. If the bound for LVM status commands [4] gets
applied too, whichever is applied second has to pass the status cache to
the two lvm_vgs() calls of the base volume activation, as they can block
a status pass otherwise. Both mark the cache of the status update with
'status_only', in the same line.
The per-node target and portal series [5][6] are independent of this
one. It takes the LUNs of an iSCSI storage from the sessions of its one
target, so if a storage can have several targets per node, whichever is
applied second has to cover that.
I tested v7 on the lab of v4 [7] to v6, upgraded from the v6 build,
with the NVMe over Fabrics series and [4] on top. The checks of the
fixes ran there: a drop-in with a near-match first line stayed and the
node reported the conflict without touching another file, overrides
on one line were refused, a guest with a partition of an NVMe/TCP
namespace as disk showed in the LUN list and kept the wipe from running,
a storage administrator without VM.Audit got the process but not the
guest, and the button states under Node > SAN were as described. The
iSCSI setup ran on the NetApp with a search, two of six nodes and the
reuse of the connection storage, the target conflict with two storages,
and the Fibre Channel setup with a new entry, once to the end and once
with the task status lost. The link of a node in the SAN view and the
storage dialogs and setup without the technology preview hint I checked
on the final build. A node logged in to an iSCSI target without a map,
as a plugin with its own sessions does, showed OK (1 path) and Single
path, then Failed with the path blocked when its portal was cut, and
with a second portal Optimal and Degraded; the LUN list took 0.6 s
during the cut. The partition lookup of the LUN list costs about 34 us
per device, so 0.1 s for 1000 LUNs with two paths. I looked at each
changed view and dialog. For the rest, the tests of v6 [8] still apply;
I did not repeat the guest, path cut of maps and scale tests.
[0]: https://lore.proxmox.com/pve-devel/20260626121000.2095591-1-t.lamprecht@proxmox.com/
[1]: https://lore.proxmox.com/pve-devel/20260703124707.1172980-2-t.lamprecht@proxmox.com/
[2]: https://lore.proxmox.com/pve-devel/20260731102156.3947857-1-dietmar@proxmox.com/
[3]: https://lore.proxmox.com/pve-devel/20261116012355.3187417-1-t.lamprecht@proxmox.com/
[4]: https://lore.proxmox.com/pve-devel/20261111015217.941220-1-t.lamprecht@proxmox.com/
[5]: https://lore.proxmox.com/pve-devel/20260430173220.441001-1-m.limbeck@proxmox.com/
[6]: https://lore.proxmox.com/pve-devel/20260804090819.2136483-1-dietmar@proxmox.com/
[7]: https://lore.proxmox.com/pve-devel/20261113030146.1559030-1-t.lamprecht@proxmox.com/
[8]: https://lore.proxmox.com/pve-devel/20261118065302.3033937-1-t.lamprecht@proxmox.com/
pve-cluster:
Thomas Lamprecht (1):
cfs: observe the multipath configuration files
src/PVE/Cluster.pm | 2 ++
src/pmxcfs/status.c | 2 ++
2 files changed, 4 insertions(+)
pve-storage:
Dietmar Maurer (8):
diskmanage: collect disk transport type from lsblk
diskmanage: qualify NVMe over Fabrics transport
diskmanage: optionally include iSCSI session devices in disk enumeration
diskmanage: collect native NVMe multipath path state
iscsi: factor out session device map from device list
diskmanage: add helper to list multipath devices
pvesm: expose the SAN LUN inventory
api: add node-level iSCSI status
Thomas Lamprecht (17):
multipath: add a library around multipathd
multipath: add a cluster-wide configuration
iscsi: add an option to manage storage LUNs with multipath
lvm: activate a missing base volume before using the volume group
multipath: apply the configuration on every node
multipath: publish per-node status
api: add endpoints for the cluster-wide multipath configuration
api: multipath: add the cluster-wide health status
diskmanage: look up the requested disks by name
diskmanage: read the udev data of all disks with one call
api: scan: add a SAN LUN inventory
api: scan: name the portal of an iSCSI path
disks: lvm: drop unused imports
disks: lvm: allow volume groups on SAN LUNs and multipath maps
disks: lvm: refuse to destroy the volume group of a shared storage
disks: allow wiping a SAN LUN that no storage uses
api: scan: report the process that has a SAN LUN open
debian/control | 3 +-
src/PVE/API2/Disks.pm | 46 +-
src/PVE/API2/Disks/LVM.pm | 80 ++-
src/PVE/API2/ISCSI.pm | 166 +++++
src/PVE/API2/Makefile | 2 +
src/PVE/API2/Multipath.pm | 451 ++++++++++++++
src/PVE/API2/Storage/Scan.pm | 244 ++++++++
src/PVE/CLI/pvesm.pm | 15 +
src/PVE/Diskmanage.pm | 383 ++++++++++--
src/PVE/ISCSI/Topology.pm | 89 +++
src/PVE/Makefile | 6 +
src/PVE/Multipath.pm | 213 +++++++
src/PVE/Multipath/Config.pm | 209 +++++++
src/PVE/Multipath/Generator.pm | 128 ++++
src/PVE/Multipath/Identity.pm | 44 ++
src/PVE/Multipath/Status.pm | 228 +++++++
src/PVE/Storage.pm | 2 +-
src/PVE/Storage/ISCSIPlugin.pm | 219 ++++---
src/PVE/Storage/LVMPlugin.pm | 156 ++++-
src/PVE/Storage/Makefile | 3 +-
src/PVE/Storage/SAN.pm | 457 ++++++++++++++
src/test/Makefile | 37 +-
src/test/disk_api_test.pm | 314 ++++++++++
src/test/disk_tests/iscsi/disklist | 1 +
.../disk_tests/iscsi/disklist_expected.json | 19 +
src/test/disk_tests/iscsi/lsblk | 5 +
src/test/disk_tests/iscsi/sda/device/model | 1 +
src/test/disk_tests/iscsi/sda/device/vendor | 1 +
.../disk_tests/iscsi/sda/queue/rotational | 1 +
src/test/disk_tests/iscsi/sda/size | 1 +
src/test/disk_tests/iscsi/sda_udevadm | 21 +
src/test/disk_tests/multipath/disklist | 11 +
.../multipath/disklist_expected.json | 107 ++++
src/test/disk_tests/multipath/dm-0/dm/name | 1 +
src/test/disk_tests/multipath/dm-0/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-0/size | 1 +
src/test/disk_tests/multipath/dm-0_slaves | 4 +
src/test/disk_tests/multipath/dm-1/dm/name | 1 +
src/test/disk_tests/multipath/dm-1/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-1/size | 1 +
src/test/disk_tests/multipath/dm-1_slaves | 4 +
src/test/disk_tests/multipath/dm-2/dm/name | 1 +
src/test/disk_tests/multipath/dm-2/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-2/size | 1 +
src/test/disk_tests/multipath/dm-2_slaves | 0
src/test/disk_tests/multipath/dm-3/dm/name | 1 +
src/test/disk_tests/multipath/dm-3/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-3/size | 1 +
src/test/disk_tests/multipath/dm-3_slaves | 0
src/test/disk_tests/multipath/dm-4/dm/name | 1 +
src/test/disk_tests/multipath/dm-4/dm/uuid | 1 +
src/test/disk_tests/multipath/dm-4/size | 1 +
src/test/disk_tests/multipath/dm-4_slaves | 0
src/test/disk_tests/multipath/lsblk | 77 +++
src/test/disk_tests/multipath/lvs | 0
src/test/disk_tests/multipath/mounts | 1 +
.../multipath/multipath_expected.json | 59 ++
src/test/disk_tests/multipath/multipathd | 124 ++++
.../multipath/multipathd_status_expected.json | 40 ++
.../nvme-subsystem/nvme-subsys0/nvme3/address | 1 +
.../nvme-subsys0/nvme3/nvme2c3n1/ana_state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme3/state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme4/address | 1 +
.../nvme-subsys0/nvme4/nvme2c4n1/ana_state | 1 +
.../nvme-subsystem/nvme-subsys0/nvme4/state | 1 +
.../nvme-subsystem/nvme-subsys1/nvme0/address | 1 +
.../nvme-subsystem/nvme-subsys1/nvme0/state | 1 +
.../disk_tests/multipath/nvme8n1/device/model | 1 +
.../multipath/nvme8n1/device/transport | 1 +
.../multipath/nvme8n1/queue/rotational | 1 +
src/test/disk_tests/multipath/nvme8n1/size | 1 +
src/test/disk_tests/multipath/nvme8n1_udevadm | 14 +
.../disk_tests/multipath/nvme9n1/device/model | 1 +
.../multipath/nvme9n1/device/nvme5/transport | 1 +
.../multipath/nvme9n1/device/vendor | 1 +
.../multipath/nvme9n1/queue/rotational | 1 +
src/test/disk_tests/multipath/nvme9n1/size | 1 +
src/test/disk_tests/multipath/nvme9n1_udevadm | 12 +
.../multipath/nvme_path_status_expected.json | 19 +
src/test/disk_tests/multipath/partlist | 0
src/test/disk_tests/multipath/pvs | 1 +
.../disk_tests/multipath/sda/device/model | 1 +
.../disk_tests/multipath/sda/device/vendor | 1 +
.../disk_tests/multipath/sda/holders/holder | 1 +
.../disk_tests/multipath/sda/queue/rotational | 1 +
src/test/disk_tests/multipath/sda/size | 1 +
src/test/disk_tests/multipath/sda_udevadm | 18 +
.../disk_tests/multipath/sdb/device/model | 1 +
.../disk_tests/multipath/sdb/device/vendor | 1 +
.../disk_tests/multipath/sdb/holders/holder | 1 +
.../disk_tests/multipath/sdb/queue/rotational | 1 +
src/test/disk_tests/multipath/sdb/size | 1 +
src/test/disk_tests/multipath/sdb_udevadm | 18 +
.../disk_tests/multipath/sdc/device/model | 1 +
.../disk_tests/multipath/sdc/device/vendor | 1 +
.../disk_tests/multipath/sdc/holders/holder | 1 +
.../disk_tests/multipath/sdc/queue/rotational | 1 +
src/test/disk_tests/multipath/sdc/size | 1 +
src/test/disk_tests/multipath/sdc_udevadm | 18 +
.../disk_tests/multipath/sdd/device/model | 1 +
.../disk_tests/multipath/sdd/device/vendor | 1 +
.../disk_tests/multipath/sdd/holders/holder | 1 +
.../disk_tests/multipath/sdd/queue/rotational | 1 +
src/test/disk_tests/multipath/sdd/size | 1 +
src/test/disk_tests/multipath/sdd_udevadm | 18 +
src/test/disk_tests/multipath/zpool | 1 +
.../disk_tests/sas/disklist_expected.json | 1 +
src/test/disk_tests/sas/lsblk | 5 +
src/test/disklist_test.pm | 179 +++++-
src/test/multipath-three-states.json | 52 ++
src/test/plugin_properties_test.pm | 1 +
src/test/run_disk_api_tests.pl | 11 +
src/test/run_iscsi_activation_tests.pl | 109 ++++
src/test/run_lun_identity_tests.pl | 57 ++
src/test/run_multipath_api_tests.pl | 584 ++++++++++++++++++
src/test/run_multipath_tests.pl | 175 ++++++
src/test/run_san_api_tests.pl | 124 ++++
src/test/run_san_library_tests.pl | 135 ++++
src/test/run_san_lun_scan_tests.pl | 334 ++++++++++
src/test/run_san_nvme_tests.pl | 120 ++++
src/test/run_san_taint_tests.pl | 60 ++
src/test/run_san_wipe_tests.pl | 271 ++++++++
src/test/run_san_write_check_tests.pl | 219 +++++++
src/test/run_test_lvm_base_activation.pl | 121 ++++
src/test/run_test_lvm_base_volume.pl | 16 +-
src/test/run_test_lvm_create.pl | 46 ++
126 files changed, 6566 insertions(+), 197 deletions(-)
pve-docs:
Thomas Lamprecht (2):
storage: document the cluster-wide multipath management
storage: multipath: describe the use shown for an open LUN
pmxcfs.adoc | 2 +
pve-storage-iscsi.adoc | 11 ++
pve-storage-iscsidirect.adoc | 2 +-
pve-storage-lvm.adoc | 3 +
pve-storage-multipath.adoc | 313 +++++++++++++++++++++++++++++++++++
pvesm.adoc | 18 +-
6 files changed, 343 insertions(+), 6 deletions(-)
pve-manager:
Dietmar Maurer (2):
api: nodes: expose the iSCSI status
ui: node: san: show iSCSI targets and sessions
Thomas Lamprecht (13):
pvestatd: apply the multipath configuration and report the node status
report: add the managed multipath configuration
api: cluster: add the multipath endpoints
ui: dc: add a SAN view
ui: storage: iscsi: add the multipath option
ui: lvm: enable shared when a base storage is selected
ui: node: add SAN LUNs panel
ui: node: san: wipe a LUN that no storage uses
ui: dc: san: add a guided setup for shared LVM on iSCSI
ui: dc: san: add a guided setup for shared LVM on Fibre Channel
ui: storage: point the iSCSI and LVM add dialogs to the SAN view
ui: san: show the guest or process that has a LUN open
ui: node: san: add a column for the target or subsystem of a LUN
PVE/API2/Cluster.pm | 7 +
PVE/API2/Nodes.pm | 7 +
PVE/Report.pm | 3 +
PVE/Service/pvestatd.pm | 7 +
www/manager6/Makefile | 12 +
www/manager6/SANUtils.js | 232 ++++++++++
www/manager6/Utils.js | 19 +
www/manager6/dc/Config.js | 23 +-
www/manager6/dc/MultipathWwidEdit.js | 81 ++++
www/manager6/dc/SAN.js | 400 ++++++++++++++++++
www/manager6/node/Config.js | 24 ++
www/manager6/node/ISCSITargets.js | 150 +++++++
www/manager6/node/LVM.js | 5 +
www/manager6/node/SANLuns.js | 233 ++++++++++
www/manager6/storage/Base.js | 5 +
www/manager6/storage/IScsiEdit.js | 46 ++
www/manager6/storage/LVMEdit.js | 6 +
www/manager6/storage/wizard/FibreChannel.js | 187 ++++++++
www/manager6/storage/wizard/IScsi.js | 297 +++++++++++++
www/manager6/storage/wizard/LunSelect.js | 224 ++++++++++
www/manager6/storage/wizard/NodeIdentities.js | 94 ++++
www/manager6/storage/wizard/Wizard.js | 298 +++++++++++++
www/manager6/window/SANLunState.js | 119 ++++++
www/manager6/window/SANLunWipe.js | 64 +++
24 files changed, 2537 insertions(+), 6 deletions(-)
^ permalink raw reply [relevance 6%]
* [PATCH v7 storage 23/43] disks: lvm: allow volume groups on SAN LUNs and multipath maps
2026-11-18 20:25 6% [PATCH v7 cluster,storage,docs,manager 00/43] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM Thomas Lamprecht
@ 2026-11-18 20:26 9% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-18 20:26 UTC (permalink / raw)
To: pve-devel
The node disk API creates volume groups on local disks only. It
treats a Fibre Channel LUN as a local disk, refuses a multipath map
and adds the storage as local to the node. Accept the LUNs of the SAN
inventory and add their storage as shared for all nodes. Refuse an
existing storage ID for a LUN, and never join a storage that got
added with that ID meanwhile. Joining is meant for local volume groups
of the same name, and on a LUN would combine two different volume
groups in one shared storage. The partitions of a LUN, also the ones
that kpartx maps, stay local devices as before, so that an LVM storage
can still be added for a volume group on one of them.
Initializing a LUN, here or as base volume of an LVM storage that is
being added, takes a cluster-wide lock per WWID. It refuses a LUN that
a storage references through its volume group, as base volume, also
through a partition, or as iSCSI target serving images. The name of a
map can pass to another map while the lock is awaited. So the LUN is
held open by its stable name, and creation stops if a name used for
the checks and the LVM commands no longer leads to the held device.
The lookup of the LUN also resolves the requested name again after its
scan, and stops if the name leads to another device by then.
A LUN that a process of the node has open is refused too. A guest
that got the LUN as disk from a third-party storage plugin, or by its
device path, is neither a holder nor a storage reference, and its disk
can look empty. The check goes by the open files of the processes, so
it misses an open through another device node, for example the one of
a container. Also refused is a LUN whose other SCSI paths or their
partitions are mounted, held by a block device other than the map of
the LUN, or open for writing. An open for reading does not count, as
multipathd keeps the paths open read-only.
Co-authored-by: Dietmar Maurer <dietmar@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
src/PVE/API2/Disks/LVM.pm | 71 +++++---
src/PVE/Diskmanage.pm | 45 +++++
src/PVE/Storage/LVMPlugin.pm | 81 ++++++++-
src/PVE/Storage/SAN.pm | 154 ++++++++++++++++
src/test/Makefile | 11 +-
src/test/disk_api_test.pm | 247 ++++++++++++++++++++++++++
src/test/run_disk_api_tests.pl | 11 ++
src/test/run_san_library_tests.pl | 27 +++
src/test/run_san_nvme_tests.pl | 104 +++++++++++
src/test/run_san_taint_tests.pl | 26 +++
src/test/run_san_write_check_tests.pl | 219 +++++++++++++++++++++++
src/test/run_test_lvm_create.pl | 46 +++++
12 files changed, 1006 insertions(+), 36 deletions(-)
create mode 100644 src/test/disk_api_test.pm
create mode 100755 src/test/run_disk_api_tests.pl
create mode 100755 src/test/run_san_nvme_tests.pl
create mode 100755 src/test/run_san_write_check_tests.pl
diff --git a/src/PVE/API2/Disks/LVM.pm b/src/PVE/API2/Disks/LVM.pm
index 6101743b..1fd68f1a 100644
--- a/src/PVE/API2/Disks/LVM.pm
+++ b/src/PVE/API2/Disks/LVM.pm
@@ -4,6 +4,7 @@ use strict;
use warnings;
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
use PVE::Diskmanage;
use PVE::JSONSchema qw(get_standard_option);
use PVE::API2::Storage::Config;
@@ -130,10 +131,13 @@ __PACKAGE__->register_method({
name => get_standard_option('pve-storage-id'),
device => {
type => 'string',
- description => 'The block device you want to create the volume group on',
+ description => 'The block device you want to create the volume group on.'
+ . ' Multipath mapped devices are supported.',
},
add_storage => {
- description => "Configure storage using the Volume Group",
+ description => "Configure storage using the Volume Group. On a SAN LUN, this"
+ . " adds a new shared storage for all nodes. On a local disk, the storage is"
+ . " for this node, or this node joins a matching storage of that ID.",
type => 'boolean',
optional => 1,
default => 0,
@@ -152,48 +156,63 @@ __PACKAGE__->register_method({
my $node = $param->{node};
$dev = PVE::Diskmanage::verify_blockdev_path($dev);
- PVE::Diskmanage::assert_disk_unused($dev);
+ my $san = PVE::Storage::SAN::is_san_device($dev);
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
my $storage_params = {
type => 'lvm',
vgname => $name,
storage => $name,
content => 'rootdir,images',
- shared => 0,
- nodes => $node,
+ shared => $san ? 1 : 0,
+ $san ? () : (nodes => $node),
};
my $verify_params = [qw(vgname)];
if ($param->{add_storage}) {
$rpcenv->check($user, "/storage", ['Datastore.Allocate']);
- # reserve the name and add as disabled, will be enabled below if creation works out
+ # only local volume groups of the same name may share a storage that exists already
+ die "storage ID '$name' already defined\n"
+ if $san && PVE::Storage::storage_config(PVE::Storage::config(), $name, 1);
+
+ # a dry run that checks the parameters, the storage is added after the volume group
PVE::API2::Storage::Config->create_or_update(
$name, $node, $storage_params, $verify_params, 1,
);
}
+ my $create_group = sub {
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
+ die "volume group with name '${name}' already exists on node '${node}'\n"
+ if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
+
+ if (PVE::Diskmanage::is_partition($dev)) {
+ eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
+ warn $@ if $@;
+ }
+
+ # the given name, so that the LUN lookup notices if it passed to another device during
+ # its scan
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ $san ? $param->{device} : $dev,
+ $name,
+ $san,
+ );
+
+ PVE::Diskmanage::udevadm_trigger($dev);
+
+ if ($param->{add_storage} && $san) {
+ # must not join a storage that someone added with this ID in the meantime
+ PVE::API2::Storage::Config->create({%$storage_params});
+ } elsif ($param->{add_storage}) {
+ PVE::API2::Storage::Config->create_or_update(
+ $name, $node, $storage_params, $verify_params,
+ );
+ }
+ };
my $worker = sub {
- PVE::Diskmanage::locked_disk_action(sub {
- PVE::Diskmanage::assert_disk_unused($dev);
- die "volume group with name '${name}' already exists on node '${node}'\n"
- if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
-
- if (PVE::Diskmanage::is_partition($dev)) {
- eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
- warn $@ if $@;
- }
-
- PVE::Storage::LVMPlugin::lvm_create_volume_group($dev, $name);
-
- PVE::Diskmanage::udevadm_trigger($dev);
-
- if ($param->{add_storage}) {
- PVE::API2::Storage::Config->create_or_update(
- $name, $node, $storage_params, $verify_params,
- );
- }
- });
+ $san ? $create_group->() : PVE::Diskmanage::locked_disk_action($create_group);
};
return $rpcenv->fork_worker('lvmcreate', $name, $user, $worker);
diff --git a/src/PVE/Diskmanage.pm b/src/PVE/Diskmanage.pm
index c2c50bcc..29669a28 100644
--- a/src/PVE/Diskmanage.pm
+++ b/src/PVE/Diskmanage.pm
@@ -1165,6 +1165,51 @@ sub change_parttype {
run_command(['sgdisk', "-t${partnum}:${parttype}", $blockdev], errmsg => $err);
}
+# Returns the PID and command name of a process for each of the block devices that a process has
+# open, as hash by the resolved path of the device. With 'writable', a process that opened the
+# device only for reading does not count. Only detects an open through the device nodes in /dev
+# of the host, not one through the device node that a container has of its own.
+sub device_openers {
+ my ($devices, %param) = @_;
+
+ # the device number tells a device from a file of that name in another mount namespace
+ my %nodes;
+ for my $path (grep { defined($_) } map { abs_path($_) } @$devices) {
+ my $st = stat($path) // next;
+ $nodes{$path} = $st->rdev;
+ }
+ my $openers = {};
+ return $openers if !%nodes;
+
+ opendir(my $proc, '/proc') or return $openers;
+ for my $pid (grep { m/^\d+$/ && $_ != $$ } readdir($proc)) {
+ opendir(my $fds, "/proc/$pid/fd") or next;
+ for my $fd (readdir($fds)) {
+ my $target = readlink("/proc/$pid/fd/$fd") // next;
+ next if !defined($nodes{$target}) || $openers->{$target};
+ my $st = stat("/proc/$pid/fd/$fd") // next;
+ next if $st->rdev != $nodes{$target};
+ if ($param{writable}) {
+ # the permissions of the link are the access mode of the open file
+ my $link = lstat("/proc/$pid/fd/$fd") // next;
+ next if !($link->mode & S_IWUSR);
+ }
+ my $comm = file_read_firstline("/proc/$pid/comm") // 'unknown';
+ $openers->{$target} = { pid => $pid, command => $comm };
+ }
+ }
+ return $openers;
+}
+
+# Returns the PID and command name of a process that has one of the block devices open, if any.
+sub device_opener {
+ my (@devices) = @_;
+
+ my $openers = device_openers(\@devices);
+ my ($opener) = map { $openers->{$_} } sort keys %$openers;
+ return $opener ? "$opener->{pid} ($opener->{command})" : undef;
+}
+
# Wipes all labels and the first 200 MiB of a disk/partition (or the whole if it is smaller).
# If called with a partition, also sets the partition type to 0x83 'Linux filesystem'.
# Expected to be called with a result of verify_blockdev_path().
diff --git a/src/PVE/Storage/LVMPlugin.pm b/src/PVE/Storage/LVMPlugin.pm
index bc15f2b3..50c35ff2 100644
--- a/src/PVE/Storage/LVMPlugin.pm
+++ b/src/PVE/Storage/LVMPlugin.pm
@@ -162,6 +162,37 @@ sub cached_pv_volume_groups {
return $res;
}
+sub lun_volume_groups {
+ my ($devices) = @_;
+ my $output = '';
+ run_command(
+ [
+ '/sbin/pvs',
+ '--nohints',
+ '--readonly',
+ '--devices',
+ join(',', @$devices),
+ '--reportformat',
+ 'json',
+ '--options',
+ 'pv_name,vg_name',
+ ],
+ timeout => 10,
+ outfunc => sub { $output .= "$_[0]\n" },
+ );
+ my $data = decode_json($output);
+ my $pvs = $data->{report}->[0]->{pv};
+ die "unable to inspect volume groups - invalid pvs report\n" if ref($pvs) ne 'ARRAY';
+ my %vgs;
+ for my $pv (@$pvs) {
+ my $vg = $pv->{vg_name};
+ die "unable to inspect volume groups - missing volume group metadata\n"
+ if !defined($vg) || $vg eq '[unknown]';
+ $vgs{$vg} = 1 if length($vg);
+ }
+ return [sort keys %vgs];
+}
+
sub clear_first_sector {
my ($dev) = shift;
@@ -172,10 +203,17 @@ sub clear_first_sector {
}
}
-sub lvm_create_volume_group {
- my ($device, $vgname, $shared, $guard) = @_;
-
+my sub create_volume_group {
+ my ($device, $vgname, $lun, $guard) = @_;
$device = PVE::Diskmanage::verify_blockdev_path($device);
+ my $fh;
+ if ($lun) {
+ sysopen($fh, $lun->{'by-id'}, O_RDWR) or die "cannot open '$device' - $!\n";
+ }
+ my $check_name = sub {
+ PVE::Storage::SAN::assert_same_device($lun, $fh, $device) if $lun;
+ };
+ $check_name->();
my $refuse_data = sub {
my (@types) = @_;
die "device '$device' contains data ("
@@ -193,7 +231,8 @@ sub lvm_create_volume_group {
if !defined($size) || $size !~ m/^\d+$/ || !$size;
die "unable to probe '$device' - missing device mapper identity\n"
if basename($device) =~ m/^dm-\d+$/ && !defined($uuid);
- if (defined($uuid) && $uuid =~ m/^mpath-/) {
+ my $map = PVE::Multipath::parse_dm_uuid($uuid);
+ if ($map && !$map->{partition}) {
# A queueing map without a running path can stall even a read-only probe.
my $running = 0;
PVE::Tools::dir_glob_foreach(
@@ -220,6 +259,8 @@ sub lvm_create_volume_group {
}
my %signatures = map { $_->{type} => 1 } $probe->@*;
my $res = lvm_pv_info($device, $signatures{LVM2_member});
+ # also a volume group that exists already only counts if the probes looked at the held LUN
+ $check_name->();
# A PV without metadata copies can belong to a VG whose other devices are not visible. The
# sentinel is not a VG name or orphan proof, even if the use flag contradicts it.
@@ -262,26 +303,52 @@ sub lvm_create_volume_group {
}
$refuse_data->(keys %signatures) if %signatures;
+ # Only initializing the device needs the checks, an existing volume group on it can be added.
$guard->{check_storage}->($device) if $guard && $guard->{check_storage};
- clear_first_sector($device); # else pvcreate fails
+ if ($lun) {
+ my $exempt = $guard ? $guard->{exempt} : undef;
+ PVE::Storage::SAN::assert_lun_unreferenced(PVE::Storage::config(), $lun, $exempt);
+ PVE::Storage::SAN::assert_lun_paths_unused($lun);
+ # a guest with the LUN as disk has it open, without being a holder or a storage reference
+ my $opener = PVE::Diskmanage::device_opener($device);
+ die "cannot create volume group on '$device' - process $opener has it open\n"
+ if defined($opener);
+ }
+
+ $check_name->();
+ clear_first_sector($lun ? '/proc/' . $$ . '/fd/' . fileno($fh) : $device);
# we use --metadatasize 250k, which reseults in "pe_start = 512"
# so pe_start is aligned on a 128k boundary (advantage for SSDs)
my $cmd = ['/sbin/pvcreate', '--metadatasize', '250k', $device];
- run_command($cmd, errmsg => "pvcreate '$device' error");
+ $check_name->();
+ run_command($cmd, errmsg => "pvcreate '$device' error", $lun ? (timeout => 30) : ());
$cmd = ['/sbin/vgcreate', $vgname, $device];
# push @$cmd, '-c', 'y' if $shared; # we do not use this yet
+ $check_name->();
run_command(
$cmd,
+ $lun ? (timeout => 30) : (),
errmsg => "vgcreate $vgname $device error",
errfunc => $ignore_no_medium_warnings,
outfunc => $ignore_no_medium_warnings,
);
}
+sub lvm_create_volume_group {
+ my ($device, $vgname, $shared, $guard) = @_;
+ require PVE::Storage::SAN;
+ my $lun = PVE::Storage::SAN::lun_for_device($device);
+ return create_volume_group($device, $vgname, undef, $guard) if !$lun;
+ PVE::Storage::SAN::with_lun_lock(
+ $lun,
+ sub { create_volume_group($device, $vgname, $lun, $guard) },
+ );
+}
+
sub lvm_destroy_volume_group {
my ($vgname) = @_;
@@ -1162,7 +1229,7 @@ sub on_add_hook {
$path,
$scfg->{vgname},
$scfg->{shared},
- { check_storage => $check_target },
+ { check_storage => $check_target, exempt => $storeid },
);
}
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index 6b92475b..eb34857a 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -5,6 +5,7 @@ use v5.36;
use Cwd qw(abs_path);
use File::Basename qw(basename);
+use PVE::Cluster;
use PVE::INotify;
use PVE::Tools qw(file_read_firstline dir_glob_foreach);
@@ -225,4 +226,157 @@ sub is_san_device($device, $info = undef) {
|| PVE::Diskmanage::is_remote_transport($info->{transport}) ? 1 : 0;
}
+sub lun_for_device($name) {
+ my $device = PVE::Diskmanage::verify_blockdev_path($name);
+ return undef if !is_san_device($device);
+ my $rows = scan_luns(PVE::Storage::config());
+ # the device behind a name such as a by-id one can pass to another LUN during the scan
+ die "cannot use '$device' - the device behind '$name' changed\n"
+ if (abs_path($name) // '') ne $device;
+ for my $lun (@$rows) {
+ next if (abs_path($lun->{devpath}) // '') ne $device;
+ die "cannot use '$device' - no link under /dev/disk/by-id names the WWID of the LUN\n"
+ if !$lun->{'by-id'};
+ # read from sysfs, but used in command lines and in the name of the cluster lock
+ ($lun->{devpath}) = $lun->{devpath} =~ m{\A(/dev/[A-Za-z0-9_.:+/-]+)\z}
+ or die "cannot use '$device' - unexpected device path\n";
+ ($lun->{wwid}) = $lun->{wwid} =~ m/\A([A-Za-z0-9_.:+=-]+)\z/
+ or die "cannot use '$device' - unexpected WWID\n";
+ return $lun;
+ }
+ die "cannot use '$device' - select an identified LUN or its multipath map\n";
+}
+
+sub lun_partitions($lun) {
+ my $device = PVE::Diskmanage::verify_blockdev_path($lun->{devpath});
+ my $name = basename($device);
+ my @parts;
+ dir_glob_foreach(
+ "/sys/class/block/$name",
+ "\Q$name\E.+",
+ sub($part, @) {
+ my ($path) = "/dev/$part" =~ m{\A(/dev/[A-Za-z0-9_.+-]+)\z};
+ push @parts, $path if defined($path) && -e "/sys/class/block/$name/$part/partition";
+ },
+ );
+ dir_glob_foreach(
+ "/sys/class/block/$name/holders",
+ 'dm-\\d+',
+ sub($part, @) {
+ my $map = PVE::Multipath::parse_dm_uuid(
+ file_read_firstline("/sys/class/block/$part/dm/uuid"));
+ my ($path) = "/dev/$part" =~ m{\A(/dev/dm-\d+)\z};
+ push @parts, $path
+ if defined($path) && $map && $map->{partition} && $map->{wwid} eq $lun->{wwid};
+ },
+ );
+ return \@parts;
+}
+
+sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
+ [$lun->{devpath}, lun_partitions($lun)->@*],
+ )->@*;
+ # the paths of a LUN can belong to more than one target
+ my $sessions = PVE::ISCSI::Topology::device_map();
+ my %targets =
+ map { $_->{target} => 1 } map { $sessions->{ basename($_) } // () } lun_paths($lun)->@*;
+ $targets{ $lun->{'iscsi-target'} } = 1 if defined($lun->{'iscsi-target'});
+ for my $sid (sort keys $cfg->{ids}->%*) {
+ next if defined($exempt) && $sid eq $exempt;
+ my $scfg = $cfg->{ids}->{$sid};
+ my $type = $scfg->{type};
+ if ($vgs{ $scfg->{vgname} // '' }) {
+ die "cannot use '$lun->{devpath}' - volume group is used by storage '$sid'\n";
+ }
+ if (
+ defined($scfg->{target})
+ && $targets{ $scfg->{target} }
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
+ }
+ next if $type ne 'lvm' || !$scfg->{base};
+ my (undef, $volname) = PVE::Storage::Plugin::parse_volume_id($scfg->{base});
+ my ($wwid) = $volname =~ m/(?:^|\.)(?:dm-uuid-(?:part\d+-)?mpath|scsi|nvme)-(.+)$/;
+ my $matches = defined($wwid) && $wwid eq $lun->{wwid};
+ if (!$matches) {
+ my $path = eval { abs_path(PVE::Storage::path($cfg, $scfg->{base})) };
+ my $device = abs_path($lun->{devpath});
+ $matches = defined($path) && defined($device) && $path eq $device;
+ }
+ die "cannot use '$lun->{devpath}' - storage '$sid' uses this LUN as its base volume\n"
+ if $matches;
+ }
+ return;
+}
+
+# Serializes writes to a LUN cluster-wide. The storage configuration read in the code is current.
+sub with_lun_lock($lun, $code) {
+ my $key = $lun->{wwid} =~ s/([^A-Za-z0-9_.:-])/sprintf('=%02x', ord($1))/ger;
+ PVE::Cluster::cfs_lock_domain("san-$key", undef, $code);
+ die $@ if $@;
+}
+
+# Device names can pass to another device while a LUN waits for its lock or is worked on. All
+# names used for it have to mean the device that is held open.
+sub assert_same_device($lun, $fh, @names) {
+ my @held = stat($fh);
+ for my $name ($lun->{'by-id'}, $lun->{devpath}, @names) {
+ my @named = stat($name);
+ die "cannot use '$lun->{devpath}' - the device behind '$name' changed\n"
+ if !@held || !@named || $held[6] != $named[6];
+ }
+}
+
+sub lun_paths($lun) {
+ my $paths = PVE::Multipath::Identity::collect(all => 1)->{paths};
+ my %names = map { $_ => 1 } grep { $paths->{$_}->{wwid} eq $lun->{wwid} } keys %$paths;
+ my $device = basename(abs_path($lun->{devpath}) // $lun->{devpath});
+ dir_glob_foreach(
+ "/sys/class/block/$device/slaves",
+ 'sd[a-z]+',
+ sub($slave, @) { $names{$slave} = 1 },
+ );
+ return [map { m/^(sd[a-z]+)$/ ? "/dev/$1" : () } sort keys %names];
+}
+
+# The other paths of a LUN reach the same data, but neither the exclusive open of the LUN nor the
+# checks of its device cover them.
+sub assert_lun_paths_unused($lun) {
+ my $device = basename(abs_path($lun->{devpath}) // $lun->{devpath});
+ my %devices; # the paths and their partitions
+ for my $path (grep { basename($_) ne $device } lun_paths($lun)->@*) {
+ if (my $mounted = PVE::Diskmanage::is_mounted($path)) {
+ die "cannot use '$lun->{devpath}' - the LUN is mounted through '$mounted'\n";
+ }
+ my $name = basename($path);
+ $devices{$path} = 1;
+ dir_glob_foreach(
+ "/sys/class/block/$name",
+ "\Q$name\E\\d+",
+ sub($part, @) {
+ $devices{"/dev/$part"} = 1;
+ },
+ );
+ }
+ for my $path (sort keys %devices) {
+ dir_glob_foreach(
+ '/sys/class/block/' . basename($path) . '/holders',
+ '[^.].*',
+ sub($holder, @) {
+ die "cannot use '$lun->{devpath}' - another block device uses the LUN through"
+ . " '$path'\n"
+ if $holder ne $device;
+ },
+ );
+ }
+ my $openers = PVE::Diskmanage::device_openers([sort keys %devices], writable => 1);
+ for my $path (sort keys %$openers) {
+ my $opener = $openers->{$path};
+ die "cannot use '$lun->{devpath}' - process $opener->{pid} ($opener->{command}) has the"
+ . " LUN open through '$path'\n";
+ }
+}
+
1;
diff --git a/src/test/Makefile b/src/test/Makefile
index 2f6f4cd7..0d866d91 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_sensitive_properties test_import_stream test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api
+test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_sensitive_properties test_import_stream test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
@@ -9,9 +9,10 @@ test_lvmplugin: run_test_lvmplugin.pl run_test_lvm_throughput.pl
./run_test_lvmplugin.pl
./run_test_lvm_throughput.pl
-test_lvm_create: run_test_lvm_create.pl run_test_lvm_base_conflicts.pl
+test_lvm_create: run_test_lvm_create.pl run_test_lvm_base_conflicts.pl run_san_write_check_tests.pl
./run_test_lvm_create.pl
./run_test_lvm_base_conflicts.pl
+ ./run_san_write_check_tests.pl
test_lvm_lock_retry: run_test_lvm_lock_retry.pl
./run_test_lvm_lock_retry.pl
@@ -75,5 +76,9 @@ test_san_taint: run_san_taint_tests.pl
test_san_lun_scan: run_san_lun_scan_tests.pl
./run_san_lun_scan_tests.pl
-test_san_api: run_san_api_tests.pl
+test_san_api: run_san_api_tests.pl run_san_nvme_tests.pl
./run_san_api_tests.pl
+ ./run_san_nvme_tests.pl
+
+test_disk_api: run_disk_api_tests.pl
+ ./run_disk_api_tests.pl
diff --git a/src/test/disk_api_test.pm b/src/test/disk_api_test.pm
new file mode 100644
index 00000000..474ad663
--- /dev/null
+++ b/src/test/disk_api_test.pm
@@ -0,0 +1,247 @@
+package PVE::API2::Disks::Test;
+
+use v5.36;
+
+use lib qw(..);
+
+use PVE::API2::Disks;
+use PVE::API2::Disks::LVM;
+use PVE::Diskmanage;
+use PVE::Storage;
+use PVE::Storage::LVMPlugin;
+
+use Test::MockModule;
+use Test::More;
+
+my @transport_cases = (
+ ['none', undef],
+ ['unknown', 'unknown'],
+ ['ata', 'ata'],
+ ['sata', 'sata'],
+ ['sas', 'sas'],
+ ['spi', 'spi'],
+ ['sbp', 'sbp'],
+ ['usb', 'usb'],
+ ['fc', 'fc'],
+ ['fcoe', 'fcoe'],
+ ['iscsi', 'iscsi'],
+ ['nvme', 'nvme'],
+ ['virtio', 'virtio'],
+ ['nvme-fc', 'nvme-fc'],
+ ['nvme-tcp', 'nvme-tcp'],
+ ['nvme-rdma', 'nvme-rdma'],
+ ['nvme-loop', 'nvme-loop'],
+);
+
+my $disks = {};
+my @all;
+for my $case (@transport_cases) {
+ my ($name, $transport) = $case->@*;
+ my $devpath = "/dev/test-$name";
+ my $entry = {
+ devpath => $devpath,
+ gpt => 0,
+ osdid => -1,
+ };
+ $entry->{transport} = $transport if defined($transport);
+ $disks->{$name} = $entry;
+ push @all, $devpath;
+}
+
+my $diskmanage_module = Test::MockModule->new('PVE::Diskmanage', no_auto => 1);
+$diskmanage_module->mock('get_disks' => sub { return $disks });
+
+my $list_handler = PVE::API2::Disks->map_method_by_name('list')->{code};
+my $list_devpaths = sub($param) {
+ my $result = $list_handler->({ node => 'test-node', skipsmart => 1, $param->%* });
+ return [sort map { $_->{devpath} } $result->@*];
+};
+
+is_deeply(
+ $list_devpaths->({}), [sort @all], 'the disk list uses the default disk inventory',
+);
+
+is_deeply(
+ $list_devpaths->({ type => 'unused' }),
+ [sort @all],
+ 'unused disk selection preserves transport visibility',
+);
+
+$diskmanage_module->mock(
+ 'get_disks' => sub {
+ return {
+ 'fc-disk' => {
+ devpath => '/dev/fc-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'fc',
+ },
+ 'fc-partition' => {
+ devpath => '/dev/fc-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/fc-disk',
+ },
+ 'loop-disk' => {
+ devpath => '/dev/loop-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'nvme-loop',
+ },
+ 'loop-partition' => {
+ devpath => '/dev/loop-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/loop-disk',
+ },
+ };
+ },
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1 }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'the plain list keeps FC disks and their partitions',
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1, type => 'unused' }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'unused partitions preserve transport visibility',
+);
+
+subtest 'volume group creation leaves SAN locking to the LVM helper' => sub {
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $disk = $diskmanage_module;
+ my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+ my $rpc = Test::MockModule->new('PVE::RPCEnvironment');
+ my (@stack, @created);
+ my $lock = sub($name, $code) {
+ push @stack, $name;
+ my $res = eval { $code->() };
+ my $err = $@;
+ pop @stack;
+ die $err if $err;
+ return $res;
+ };
+ $storage->mock(lock_storage_config => sub { $lock->('storage.cfg', $_[0]) });
+ $disk->mock(locked_disk_action => sub { $lock->('disk', $_[0]) });
+ $disk->mock(verify_blockdev_path => sub { $_[0] });
+ $disk->mock(assert_disk_unused => sub { });
+ $disk->mock(is_partition => sub { 0 });
+ $disk->mock(udevadm_trigger => sub { });
+ $lvm->mock(lvm_vgs => sub { {} });
+ $lvm->mock(
+ lvm_create_volume_group => sub {
+ is(scalar(@_), 3, 'disk API does not exempt a storage');
+ push @created, [$_[0], join('>', @stack)];
+ },
+ );
+ {
+
+ package MultipathTestRPC;
+ sub get_user { 'root@pam' }
+ sub check { 1 }
+ sub fork_worker { $_[4]->(); return 'test-upid' }
+ }
+ $rpc->mock(get => sub { bless {}, 'MultipathTestRPC' });
+
+ my ($is_map, $is_san) = (1, 0);
+ my $san = Test::MockModule->new('PVE::Storage::SAN');
+ $san->mock(is_san_device => sub { $is_map || $is_san });
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg1', device => '/dev/dm-3' });
+ ($is_map, $is_san) = (0, 1);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg2', device => '/dev/sdc' });
+ ($is_map, $is_san) = (0, 0);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg3', device => '/dev/sdb' });
+ is_deeply(
+ \@created,
+ [
+ ['/dev/dm-3', ''], ['/dev/sdc', ''], ['/dev/sdb', 'disk'],
+ ],
+ 'SAN writes use no local disk or storage configuration lock',
+ );
+ my $config_api = Test::MockModule->new('PVE::API2::Storage::Config');
+ my (@params, @registered);
+ $config_api->mock(
+ create_or_update => sub {
+ push @registered, $_[5] ? 'check' : 'create or update';
+ push @params, $_[3];
+ },
+ create => sub {
+ push @registered, 'create';
+ push @params, $_[1];
+ },
+ );
+ my $cfg =
+ { ids => { other => { type => 'lvm', vgname => 'other', nodes => { n2 => 1 } } } };
+ $storage->mock(config => sub { $cfg });
+ $is_san = 1;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg4',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 1, 'SAN storage is shared');
+ ok(!exists($params[-1]->{nodes}), 'SAN storage covers all nodes');
+ is_deeply(
+ \@registered,
+ ['check', 'create'],
+ 'and only gets created: it never joins a storage added in the meantime',
+ );
+ @registered = ();
+ @created = ();
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'other',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ };
+ like($@, qr/already defined/, 'SAN volume group does not join the storage of another node');
+ is_deeply(\@created, [], 'existing storage ID prevents initialization');
+ $is_san = 0;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg5',
+ device => '/dev/sdb',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 0, 'local storage is not shared');
+ is($params[-1]->{nodes}, 'n1', 'local storage remains node-restricted');
+ is_deeply(\@registered, ['check', 'create or update'], 'and may join one of its name');
+ @created = ();
+ $disk->mock(assert_disk_unused => sub { die "device is already in use\n" });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like($@, qr/already in use/, 'disk API rejects a used inventory entry');
+ is_deeply(\@created, [], 'used inventory prevents initialization');
+ $disk->mock(assert_disk_unused => sub { });
+ $lvm->mock(lvm_vgs => sub { { vg => {} } });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like(
+ $@,
+ qr/volume group with name 'vg' already exists/,
+ 'stale inventory does not permit an existing VG',
+ );
+ is_deeply(\@created, [], 'existing VG prevents initialization');
+ my @mocked = qw(
+ locked_disk_action verify_blockdev_path assert_disk_unused is_partition udevadm_trigger
+ );
+ $disk->unmock($_) for @mocked;
+};
+
+done_testing();
diff --git a/src/test/run_disk_api_tests.pl b/src/test/run_disk_api_tests.pl
new file mode 100755
index 00000000..75fc98c6
--- /dev/null
+++ b/src/test/run_disk_api_tests.pl
@@ -0,0 +1,11 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use TAP::Harness;
+
+my $harness = TAP::Harness->new({ verbosity => -2 });
+my $res = $harness->runtests("disk_api_test.pm");
+
+exit -1 if !$res || $res->{failed} || $res->{parse_errors};
diff --git a/src/test/run_san_library_tests.pl b/src/test/run_san_library_tests.pl
index f7ae68d1..d961b87c 100755
--- a/src/test/run_san_library_tests.pl
+++ b/src/test/run_san_library_tests.pl
@@ -105,4 +105,31 @@ subtest 'LVM hints are optional cached display metadata' => sub {
}
};
+subtest 'the names of a held LUN have to mean the held device' => sub {
+ require PVE::Storage::SAN;
+ open(my $fh, '<', '/dev/null') or die "cannot open /dev/null - $!\n";
+ my $lun = { 'by-id' => '/dev/null', devpath => '/dev/null' };
+ my $check = sub {
+ eval { PVE::Storage::SAN::assert_same_device(@_) };
+ return $@;
+ };
+ is($check->($lun, $fh, '/dev/null'), '', 'same device behind all names');
+ like(
+ $check->({ %$lun, 'by-id' => '/dev/zero' }, $fh),
+ qr/'\/dev\/zero' changed/,
+ 'by-id name',
+ );
+ like(
+ $check->({ %$lun, devpath => '/dev/zero' }, $fh),
+ qr/'\/dev\/zero' changed/,
+ 'device path',
+ );
+ like(
+ $check->($lun, $fh, '/dev/zero'),
+ qr/'\/dev\/zero' changed/,
+ 'name used for the commands',
+ );
+ like($check->($lun, $fh, '/dev/gone'), qr/'\/dev\/gone' changed/, 'name without a device');
+};
+
done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
new file mode 100755
index 00000000..9f243563
--- /dev/null
+++ b/src/test/run_san_nvme_tests.pl
@@ -0,0 +1,104 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+our ($backing, @opens);
+
+BEGIN {
+ *CORE::GLOBAL::sysopen = sub (*$$;$) {
+ push @opens, $_[1];
+ my $path = $_[1] =~ m{^/dev/disk/by-id/nvme-} ? $backing : $_[1];
+ return CORE::sysopen($_[0], $path, $_[2]);
+ };
+}
+use lib qw(..);
+use File::Temp qw(tempfile);
+use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
+
+my ($fh, $file) = tempfile('san-nvme-XXXX', DIR => '.', UNLINK => 1);
+close($fh);
+$backing = $file;
+my $device = '/dev/nvme0n1';
+my $link = '/dev/disk/by-id/nvme-eui.0123456789abcdef';
+my $lun =
+ { devpath => $device, 'by-id' => $link, wwid => 'eui.0123456789abcdef', multipath => 'native' };
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $mp = Test::MockModule->new('PVE::Multipath');
+my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $cfg = { ids => {} };
+my @order;
+$storage->mock(config => sub { $cfg });
+$disk->mock(verify_blockdev_path => sub { $device });
+$disk->mock(is_partition => sub { 0 });
+$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(is_iscsi_device => sub { 0 });
+$disk->mock(is_mounted => sub { 0 });
+$disk->mock(has_holder => sub { 0 });
+$disk->mock(device_opener => sub { undef });
+$mp->mock(device_map => sub { undef });
+$san->mock(abs_path => sub { $device });
+$san->mock(scan_luns => sub { [$lun] });
+$san->mock(lun_partitions => sub { [] });
+$san->mock(assert_same_device => sub { ok(defined(fileno($_[1])), 'held descriptor checked') });
+$lvm->mock(lun_volume_groups => sub { push @order, 'check'; [] });
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-eui.0123456789abcdef', 'native namespace uses the LUN lock');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+is(PVE::Storage::SAN::stable_path($device, $lun->{wwid}), $link, 'native stable path');
+is_deeply(PVE::Storage::SAN::lun_for_device($link), $lun, 'native row selected for writes');
+my $model_link = '/dev/disk/by-id/nvme-NetApp_ONTAP_Controller_81Mkq_1';
+is_deeply(PVE::Storage::SAN::lun_for_device($model_link), $lun, 'any name of the namespace');
+{
+ # the name passes to another device while the LUNs are scanned
+ my $scanned = 0;
+ $san->mock(scan_luns => sub { $scanned = 1; [$lun] });
+ $san->mock(abs_path => sub { $_[0] eq $model_link && $scanned ? '/dev/nvme9n1' : $device });
+ eval { PVE::Storage::SAN::lun_for_device($model_link) };
+ like($@, qr/the device behind '\Q$model_link\E' changed/, 'a name that changed refuses');
+ $san->mock(scan_luns => sub { [$lun] });
+ $san->mock(abs_path => sub { $device });
+}
+$disk->mock(is_partition => sub { 1 });
+is(PVE::Storage::SAN::lun_for_device($link), undef, 'a partition is handled as a local device');
+$disk->mock(is_partition => sub { 0 });
+$cfg->{ids}->{data} = { type => 'lvm', base => 'fabric:nvme-eui.0123456789abcdef' };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like($@, qr/base volume/, 'native base reference refuses');
+$cfg->{ids} = {};
+@order = @opens = ();
+$lvm->mock(file_read_firstline => sub { $_[0] =~ m{/size$} ? 1024 : undef });
+$lvm->mock(lvm_pv_info => sub { undef });
+$lvm->mock(
+ clear_first_sector => sub { push @order, 'clear'; ok(-e $_[0], 'VG clear uses held fd') });
+$lvm->mock(
+ run_command => sub {
+ my ($cmd, %opts) = @_;
+ if ($cmd->[0] eq 'wipefs') {
+ $opts{outfunc}->('{"signatures":[]}');
+ } else {
+ is($cmd->[-1], $device, 'VG command uses the checked device');
+ push @order, $cmd->[0];
+ }
+ },
+);
+PVE::Storage::LVMPlugin::lvm_create_volume_group($link, 'data', 1);
+is_deeply(
+ \@order,
+ [qw(lock check clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'native VG sequencing',
+);
+is_deeply(\@opens, [$link], 'VG creation holds the native by-id device');
+
+done_testing();
diff --git a/src/test/run_san_taint_tests.pl b/src/test/run_san_taint_tests.pl
index 35b11cd7..0ccd9e2f 100755
--- a/src/test/run_san_taint_tests.pl
+++ b/src/test/run_san_taint_tests.pl
@@ -31,4 +31,30 @@ for my $bad ('-bad', '1:2', '../dev', "3600a\n") {
like($@, qr/invalid WWID/, 'ambiguous identity refused');
}
+# the LUN that write operations get must be usable in command lines and lock names
+use PVE::Storage::SAN;
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $tainted_dev = PVE::Tools::file_get_contents('/proc/self/comm') =~ s/.*//sr . '/dev/null';
+ok(tainted($tainted_dev), 'device path derived from a file is tainted');
+$san->mock(
+ is_san_device => sub { 1 },
+ scan_luns => sub {
+ return [{
+ devpath => $tainted_dev,
+ wwid => $wwid,
+ 'by-id' => '/dev/null',
+ usage => 'unused',
+ multipath => 'none',
+ }];
+ },
+);
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(verify_blockdev_path => sub { '/dev/null' });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+my $lun = PVE::Storage::SAN::lun_for_device('/dev/null');
+ok(!tainted($lun->{devpath}), 'LUN device path is untainted');
+ok(!tainted($lun->{wwid}), 'LUN WWID is untainted');
+is($lun->{wwid}, '3600a', 'LUN WWID is unchanged');
+
done_testing();
diff --git a/src/test/run_san_write_check_tests.pl b/src/test/run_san_write_check_tests.pl
new file mode 100755
index 00000000..acd199a2
--- /dev/null
+++ b/src/test/run_san_write_check_tests.pl
@@ -0,0 +1,219 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use lib qw(..);
+use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
+
+my $scan = Test::MockModule->new('PVE::Storage::SAN');
+my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $lun = { wwid => '3600+abc', devpath => '/dev/dm-0', 'iscsi-target' => 'iqn.test' };
+# the LUN is exported through two targets, its row names only the first
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
+my $paths = sub {
+ {
+ paths => {
+ sdb => { wwid => '3600+abc', target => 'iqn.test' },
+ sdc => { wwid => '3600+abc', target => 'iqn.second' },
+ sdd => { wwid => '3600+other', target => 'iqn.other' },
+ },
+ };
+};
+$identity->mock(collect => $paths);
+my %sessions = (sdb => 'iqn.test', sdc => 'iqn.second', sdd => 'iqn.other');
+my $topology = Test::MockModule->new('PVE::ISCSI::Topology');
+$topology->mock(
+ device_map => sub {
+ return { map { $_ => { target => $sessions{$_} } } keys %sessions };
+ },
+);
+my @slaves;
+$scan->mock(dir_glob_foreach => sub { $_[2]->($_) for $_[0] =~ m{/dm-0/slaves$} ? @slaves : () });
+my $vgs = [];
+$scan->mock(lun_partitions => sub { [] });
+$lvm->mock(lun_volume_groups => sub { $vgs });
+$lvm->mock(cached_pv_volume_groups => sub { die "write check must not use cached PV metadata\n" });
+my $cfg = { ids => {} };
+$storage->mock(config => sub { $cfg });
+my $check = sub {
+ eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun, @_) };
+ return $@;
+};
+is($check->(), '', 'unreferenced LUN accepted');
+for my $type (qw(lvm lvmthin custom)) {
+ $vgs = ['data'];
+ $cfg->{ids} = {
+ data => {
+ type => $type,
+ vgname => 'data',
+ shared => 1,
+ disable => 1,
+ nodes => { other => 1 },
+ },
+ };
+ for my $cached_vg (undef, 'unrelated') {
+ $lun->{vgname} = $cached_vg;
+ $lun->{usage} = 'unused';
+ like($check->(), qr/used by storage 'data'/, "$type refusal ignores display VG and usage");
+ }
+ is($check->('data'), '', 'the storage being added can be exempted');
+}
+delete $lun->{vgname};
+delete $lun->{usage};
+$vgs = [];
+$cfg->{ids} = { direct => { type => 'iscsi', target => 'iqn.test', content => { images => 1 } } };
+like($check->(), qr/storage 'direct' serves images from this target$/, 'direct image use refuses');
+$cfg->{ids}->{direct}->{target} = 'iqn.second';
+like($check->(), qr/storage 'direct' serves images/, 'also through another target of the LUN');
+$cfg->{ids}->{direct}->{target} = 'iqn.other';
+is($check->(), '', 'a target of another LUN is no reference');
+{
+ # multipathd does not answer and udev knows the path by another identity
+ local $lun->{'iscsi-target'} = 'iqn.other';
+ $identity->mock(collect => sub { { paths => {} } });
+ like($check->(), qr/storage 'direct' serves images/, 'the target of the LUN itself counts');
+ $cfg->{ids}->{direct}->{target} = 'iqn.second';
+ is($check->(), '', 'which is the only one known then');
+ @slaves = qw(sdb sdc);
+ like($check->(), qr/storage 'direct' serves images/, 'unless a member of the map has another');
+ @slaves = ();
+ $identity->mock(collect => $paths);
+}
+$cfg->{ids}->{direct}->{target} = 'iqn.test';
+$cfg->{ids}->{direct}->{content} = { none => 1 };
+is($check->(), '', 'connection-only storage permits use');
+
+for my $type (qw(iscsidirect zfs)) {
+ local $cfg->{ids}->{other} = { type => $type, target => 'iqn.test', content => {} };
+ like(
+ $check->(),
+ qr/storage 'other' serves images from this target$/,
+ "$type storage of the target refuses",
+ );
+}
+$cfg->{ids}->{data} = { type => 'lvm', base => 'direct:0.0.1.dm-uuid-mpath-3600+abc' };
+like($check->(), qr/base volume/, 'base reference refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-3600+abc';
+like($check->(), qr/base volume/, 'scsi WWID in base name refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.dm-uuid-part1-mpath-3600+abc';
+like($check->(), qr/base volume/, 'a partition of the map as base refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-legacy';
+$storage->mock(path => sub { '/dev/disk/by-id/legacy' });
+$scan->mock(abs_path => sub { '/dev/dm-0' });
+like($check->(), qr/base volume/, 'resolved alias to the LUN refuses');
+$scan->mock(abs_path => sub { $_[0] eq $lun->{devpath} ? '/dev/dm-0' : '/dev/dm-1' });
+is($check->(), '', 'base on another device is no match');
+$scan->mock(abs_path => sub { undef });
+is($check->(), '', 'unresolvable base is no match');
+$storage->mock(path => sub { die "base unavailable\n" });
+is($check->(), '', 'unavailable base is no match');
+ok(!PVE::Storage::LVMPlugin->can('create_volume_group'), 'creation implementation is lexical');
+$cfg->{ids} = {};
+my @order;
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-3600=2babc', 'lock name escapes unsafe characters without collisions');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+PVE::Storage::SAN::with_lun_lock($lun, sub { push @order, 'write' });
+is_deeply(\@order, [qw(lock write unlock)], 'the code runs under the lock of the LUN');
+
+# volume group creation checks the references only when it has to initialize the LUN
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(
+ verify_blockdev_path => sub { $_[0] },
+ is_mounted => sub { undef },
+ has_holder => sub { undef },
+ device_opener => sub { undef },
+);
+my ($signatures, $pvinfo) = ('', undef);
+$lun->{'by-id'} = '/dev/null';
+$scan->mock(
+ lun_for_device => sub { $lun },
+ assert_same_device => sub { },
+ assert_lun_unreferenced => sub { push @order, 'check'; die "referenced\n" },
+);
+$lvm->mock(
+ file_read_firstline => sub { $_[0] =~ m{/size$} ? '2048' : undef },
+ lvm_pv_info => sub { $pvinfo },
+ clear_first_sector => sub { push @order, 'clear' },
+ run_command => sub {
+ my ($cmd, %param) = @_;
+ return $param{outfunc}->(qq({"signatures":[$signatures]})) if $cmd->[0] eq 'wipefs';
+ push @order, $cmd->[0];
+ },
+);
+@order = ();
+$signatures = '{"type":"LVM2_member","offset":"0x218"}';
+$pvinfo = { vgname => 'data', in_use => '1' };
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an existing volume group can be added whatever references its LUN');
+is_deeply(\@order, [qw(lock unlock)], 'without reference check or write');
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'other',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/already used by volume group 'data'/, 'another volume group on the LUN refuses');
+@order = ();
+($signatures, $pvinfo) = ('', undef);
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/referenced/, 'initializing a referenced LUN refuses');
+is_deeply(\@order, [qw(lock check)], 'the check precedes the first write');
+$scan->mock(assert_lun_unreferenced =>
+ sub { is($_[2], 'new', 'new storage exempt'); push @order, 'check' });
+$scan->mock(assert_lun_paths_unused => sub { push @order, 'paths'; die "path in use\n" });
+@order = ();
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/path in use/, 'a LUN that is in use through another path refuses');
+is_deeply(\@order, [qw(lock check paths)], 'before the first write');
+$scan->mock(assert_lun_paths_unused => sub { push @order, 'paths' });
+@order = ();
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an unreferenced empty LUN is initialized');
+is_deeply(
+ \@order,
+ [qw(lock check paths clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'checked once, then written under the lock',
+);
+
+done_testing();
diff --git a/src/test/run_test_lvm_create.pl b/src/test/run_test_lvm_create.pl
index d4be25b0..13058fe2 100755
--- a/src/test/run_test_lvm_create.pl
+++ b/src/test/run_test_lvm_create.pl
@@ -10,9 +10,12 @@ use Test::More;
use lib ('.', '..');
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+$san->mock(lun_for_device => sub { undef });
my $tools = Test::MockModule->new('PVE::Tools');
my $inotify = Test::MockModule->new('PVE::INotify');
$inotify->mock(nodename => sub { 'testnode' });
@@ -43,6 +46,7 @@ $lvm->mock(
if $_[0] =~ m{/(?:uevent|size)/partition$};
return $partitioned ? '1' : undef if $_[0] =~ m{/partition$};
return $holder_uuid if $_[0] =~ m{/dm-5/dm/uuid$};
+ return 'part1-mpath-3600abc' if $map eq 'partition' && $_[0] =~ m{/uuid$};
return $map ? 'mpath-3600abc' : undef if $_[0] =~ m{/uuid$};
return $running ? 'running' : 'offline' if $_[0] =~ m{/state$};
die "unexpected read $_[0]";
@@ -119,6 +123,10 @@ for my $case (
is_deeply(\@probes, [], "$case->[0]: no device reads");
is_deeply(\@writes, [], "$case->[0]: no writes");
}
+reset_case();
+($map, $running) = ('partition', 0);
+is(create(), '', 'the partition of a map has the map as member, not its paths');
+is(scalar(@writes), 3, 'so it is set up like a local partition');
reset_case();
my $storage_checks = 0;
@@ -170,6 +178,44 @@ like(
qr/contains data \(gpt\)/,
'a partition table of a map is data, kpartx may not map it',
);
+reset_case();
+($signatures, $partitioned) = ([{ type => 'PMBR' }, { type => 'gpt' }], 1);
+$san->mock(
+ lun_for_device =>
+ sub { { wwid => '3600abc', devpath => '/dev/sda', 'by-id' => '/dev/null' } },
+ with_lun_lock => sub { $_[1]->() },
+);
+like(
+ create(),
+ qr{the device behind '/dev/sda' changed},
+ 'a device name that no longer means the held LUN is refused',
+);
+is_deeply(\@writes, [], 'changed device: no writes');
+$san->mock(assert_same_device => sub { });
+like(create(), qr/contains data \(PMBR, gpt\)/, 'a partitioned LUN that is no map is data too');
+is_deeply(\@writes, [], 'partitioned LUN: no writes');
+reset_case();
+my $opener = '4711 (kvm)';
+$disk->mock(device_opener => sub { $opener });
+$san->mock(assert_lun_unreferenced => sub { });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+like(create(), qr/process 4711 \(kvm\) has it open/, 'a LUN that a process has open is refused');
+is_deeply(\@writes, [], 'open LUN: no writes');
+$opener = undef;
+is(create(), '', 'a LUN that no process has open is initialized');
+is(scalar(@writes), 3, 'unused LUN: initialized');
+reset_case();
+$signatures = [{ type => 'LVM2_member' }];
+$label = '/dev/sda: LVM2 PV';
+$pv = '/dev/sda:1024:test:aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg:1';
+my $checked = 0;
+$san->mock(assert_same_device => sub { die "device changed\n" if ++$checked == 2 });
+like(create(), qr/device changed/, 'an existing volume group only counts on the held LUN');
+$san->unmock('assert_lun_unreferenced');
+$san->unmock('assert_same_device');
+$san->unmock('with_lun_lock');
+$san->mock(lun_for_device => sub { undef });
my $uuid = 'aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg';
for my $vg ('test', 'other', 'unknown', '') {
^ permalink raw reply related [relevance 9%]
* [PATCH v2 storage 02/17] nvmeof: add a storage for NVMe over Fabrics subsystems
@ 2026-11-18 20:42 20% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-18 20:42 UTC (permalink / raw)
To: pve-devel
NVMe/TCP namespaces need a manual nvme-cli setup on every node so
far. Add a storage type that connects one subsystem through each
configured portal and offers its namespaces as raw volumes. Native
NVMe multipath joins the paths and the kernel reconnects lost ones.
A second storage for a subsystem is refused: the LUN list, the
controller list and the node status attribute a subsystem to one
storage. Resolving the path of a volume checks an existing device
against the subsystem: a volume name can be the by-id name of any NVMe
device, and not every user of a path activates the volume first.
The plugin isolates its properties, so names like 'portals' belong to
this storage type alone, and a third-party plugin that declares one,
like 'subsysnqn', is not left out. As the first in-tree plugin that
isolates, it makes the storage API check the parameters for adding and
updating a storage of any type against the options of that type alone.
A third-party plugin then has to list the sensitive properties it uses
in options(), as the API change log says.
Local disk setup refuses namespaces attached over a fabric, as for
iSCSI LUNs. Wiping a namespace or creating a volume group on it is
refused while a storage serves images from its subsystem. nvme-cli
is only recommended, as no other storage type needs it.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
ApiChangeLog | 7 +-
debian/control | 1 +
src/PVE/Diskmanage.pm | 2 +
src/PVE/Makefile | 1 +
src/PVE/NVMeOF.pm | 244 +++++++++++++++++++++++
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 223 +++++++++++++++++++++
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SAN.pm | 13 ++
src/test/Makefile | 6 +-
src/test/run_nvmeof_taint_tests.pl | 60 ++++++
src/test/run_nvmeof_tests.pl | 302 +++++++++++++++++++++++++++++
src/test/run_san_nvme_tests.pl | 16 ++
14 files changed, 875 insertions(+), 5 deletions(-)
create mode 100644 src/PVE/NVMeOF.pm
create mode 100644 src/PVE/Storage/NVMeOFPlugin.pm
create mode 100755 src/test/run_nvmeof_taint_tests.pl
create mode 100755 src/test/run_nvmeof_tests.pl
diff --git a/ApiChangeLog b/ApiChangeLog
index 10f39508..d7310fe4 100644
--- a/ApiChangeLog
+++ b/ApiChangeLog
@@ -101,9 +101,10 @@ Future changes should be documented in here.
declares a property of that name is then not loaded until it renames it, so prefer names that
are specific to the plugin, for example prefixed with its type.
- As soon as one such plugin is installed, the API checks the parameters for adding and updating a
- storage against the options of its type alone, for all storage types. So every plugin has to
- list the sensitive properties that it uses in `options()`.
+ Since the in-tree 'nvmeof' plugin isolates its properties, the API checks the parameters for
+ adding and updating a storage against the options of its type alone, for all storage types,
+ also for plugins of older API versions. So every plugin has to list the sensitive properties
+ that it uses in `options()`.
Set 'sensitive-properties' in such a plugin, even if empty. Without it, the fallback list of
version 11 also applies to the plugin's own properties of these names.
diff --git a/debian/control b/debian/control
index d10dfb23..8b9b6455 100644
--- a/debian/control
+++ b/debian/control
@@ -55,6 +55,7 @@ Depends: bzip2,
${misc:Depends},
${perl:Depends},
Recommends: multipath-tools,
+ nvme-cli,
pve-esxi-import-tools (>= 0.6.0),
skopeo,
zfsutils-linux (>= 2.4.1-pve2),
diff --git a/src/PVE/Diskmanage.pm b/src/PVE/Diskmanage.pm
index 8fda7afc..1ad91e06 100644
--- a/src/PVE/Diskmanage.pm
+++ b/src/PVE/Diskmanage.pm
@@ -108,6 +108,8 @@ sub disk_is_used {
my $disklist = get_disks($dev, 1, 1);
die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
+ die "'$disk' is not a valid local disk\n"
+ if ($disklist->{$dev}->{transport} // '') =~ /^nvme-(?:tcp|rdma|fc)$/;
return 1 if $disklist->{$dev}->{used};
return 0;
diff --git a/src/PVE/Makefile b/src/PVE/Makefile
index 13fecbf8..238eefd4 100644
--- a/src/PVE/Makefile
+++ b/src/PVE/Makefile
@@ -4,6 +4,7 @@
install:
install -D -m 0644 Storage.pm ${DESTDIR}${PERLDIR}/PVE/Storage.pm
install -D -m 0644 Diskmanage.pm ${DESTDIR}${PERLDIR}/PVE/Diskmanage.pm
+ install -D -m 0644 NVMeOF.pm ${DESTDIR}${PERLDIR}/PVE/NVMeOF.pm
install -D -m 0644 ISCSI/Topology.pm ${DESTDIR}${PERLDIR}/PVE/ISCSI/Topology.pm
install -D -m 0644 Multipath.pm ${DESTDIR}${PERLDIR}/PVE/Multipath.pm
install -D -m 0644 Multipath/Config.pm ${DESTDIR}${PERLDIR}/PVE/Multipath/Config.pm
diff --git a/src/PVE/NVMeOF.pm b/src/PVE/NVMeOF.pm
new file mode 100644
index 00000000..ebaedf9b
--- /dev/null
+++ b/src/PVE/NVMeOF.pm
@@ -0,0 +1,244 @@
+package PVE::NVMeOF;
+
+use v5.36;
+
+use Digest::SHA qw(sha1_hex);
+use Fcntl qw(:flock F_GETFD F_SETFD FD_CLOEXEC);
+use File::Path qw(make_path);
+use Socket qw(AF_INET AF_INET6 inet_ntop inet_pton);
+
+use PVE::JSONSchema;
+use PVE::Tools qw(dir_glob_foreach file_read_firstline file_set_contents run_command);
+
+use PVE::Diskmanage;
+
+our $NVME = '/usr/sbin/nvme';
+our $SYSFS = '/sys';
+our $HOSTNQN_FILE = '/etc/nvme/hostnqn';
+our $HOSTID_FILE = '/etc/nvme/hostid';
+our $RUN_DIR = '/run/pve/nvmeof';
+our $NQN_PATTERN = 'nqn\.[^\s,=]+';
+
+sub canonical_address($addr) {
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ return inet_ntop(AF_INET, $packed);
+ }
+ if (defined(my $packed = inet_pton(AF_INET6, $addr))) {
+ return inet_ntop(AF_INET, substr($packed, 12))
+ if substr($packed, 0, 12) eq ("\0" x 10) . "\xff\xff";
+ return inet_ntop(AF_INET6, $packed);
+ }
+ return lc($addr);
+}
+
+# Link-local IPv6 needs a node-specific interface and cannot identify a shared configured portal.
+sub parse_portal($portal) {
+ my ($addr, $port);
+ if ($portal =~ m/^\[([0-9a-fA-F:.]+)\](?::([0-9]+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } elsif ($portal =~ m/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(?::([0-9]+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } else {
+ return undef;
+ }
+ return undef if defined($port) && ($port < 1 || $port > 65535);
+ $addr = canonical_address($addr);
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ my $multicast = (unpack('C', $packed) & 0xf0) == 0xe0;
+ return undef if $addr eq '0.0.0.0' || $addr eq '255.255.255.255' || $multicast;
+ } elsif (defined($packed = inet_pton(AF_INET6, $addr))) {
+ my $prefix = unpack('n', $packed);
+ return undef
+ if $addr eq '::' || ($prefix & 0xffc0) == 0xfe80 || ($prefix & 0xff00) == 0xff00;
+ } else {
+ return undef;
+ }
+ return { traddr => $addr, trsvcid => int($port // 4420) };
+}
+
+PVE::JSONSchema::register_format(
+ 'pve-storage-nvme-portal',
+ sub($portal, $noerr = undef) {
+ return $portal if parse_portal($portal);
+ return undef if $noerr;
+ die "value is not an IPv4 address or a bracketed IPv6 address with optional port\n";
+ },
+);
+
+sub format_path($path) {
+ my $addr = $path->{traddr} =~ /:/ ? "[$path->{traddr}]" : $path->{traddr};
+ return defined($path->{trsvcid}) ? "$addr:$path->{trsvcid}" : $addr;
+}
+
+sub storage_paths($scfg) {
+ return [map { parse_portal($_) // die "invalid portal '$_'\n" }
+ PVE::Tools::split_list($scfg->{portals})];
+}
+
+sub host_identity() {
+ my ($nqn) = (file_read_firstline($HOSTNQN_FILE) // '') =~ /\A($NQN_PATTERN)\z/;
+ my ($id) = (file_read_firstline($HOSTID_FILE) // '') =~
+ /\A([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\z/i;
+ if (!defined($nqn) || length($nqn) > 223) {
+ die "invalid or missing NVMe host NQN in '$HOSTNQN_FILE' - install nvme-cli and check the"
+ . " host identity\n";
+ }
+ die "invalid or missing NVMe host ID in '$HOSTID_FILE' - expected a nonzero UUID\n"
+ if !defined($id) || $id =~ /^[0-]+$/;
+ return { nqn => $nqn, id => lc($id) };
+}
+
+sub is_supported() { return -x $NVME ? 1 : 0 }
+
+sub assert_support() {
+ die "nvme-cli is not installed\n" if !is_supported();
+ run_command(['modprobe', 'nvme-tcp'], timeout => 10)
+ if !-e "$SYSFS/module/nvme_tcp";
+ my $multipath = file_read_firstline("$SYSFS/module/nvme_core/parameters/multipath") // '';
+ die "native NVMe multipath is disabled - enable nvme_core.multipath\n" if $multipath ne 'Y';
+}
+
+sub controllers() {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-fabrics/ctl";
+ dir_glob_foreach(
+ $dir,
+ 'nvme[0-9]+',
+ sub($name, @) {
+ my $address = file_read_firstline("$dir/$name/address") // return;
+ my %address = map { split(/=/, $_, 2) } grep { /=/ } split(/,/, $address);
+ return if !defined($address{traddr});
+ $res->{$name} = {
+ transport => file_read_firstline("$dir/$name/transport") // '',
+ subsystem => PVE::Diskmanage::read_subsysnqn("$dir/$name/subsysnqn") // '',
+ state => file_read_firstline("$dir/$name/state") // 'unknown',
+ traddr => canonical_address($address{traddr}),
+ trsvcid => $address{trsvcid},
+ };
+ },
+ );
+ return $res;
+}
+
+sub subsystem_controllers($subsystem) {
+ my $controllers = controllers();
+ return {
+ map { $_ => $controllers->{$_} } grep {
+ $controllers->{$_}->{subsystem} eq $subsystem
+ && $controllers->{$_}->{transport} eq 'tcp'
+ } keys %$controllers
+ };
+}
+
+sub path_controller($controllers, $path) {
+ for my $name (sort keys %$controllers) {
+ my $ctrl = $controllers->{$name};
+ if ($ctrl->{traddr} eq $path->{traddr} && ($ctrl->{trsvcid} // '') eq $path->{trsvcid}) {
+ return $name;
+ }
+ }
+ return undef;
+}
+
+sub namespaces($subsystem) {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-subsystem";
+ dir_glob_foreach(
+ $dir,
+ 'nvme-subsys[0-9]+',
+ sub($subsys, @) {
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$dir/$subsys/subsysnqn") // return;
+ return if $nqn ne $subsystem;
+ dir_glob_foreach(
+ "$dir/$subsys",
+ 'nvme[0-9]+n[0-9]+',
+ sub($dev, @) {
+ my $wwid = file_read_firstline("$SYSFS/block/$dev/wwid") // return;
+ my $size = file_read_firstline("$SYSFS/block/$dev/size") // return;
+ $res->{$dev} = { wwid => $wwid, size => int($size) * 512 };
+ },
+ );
+ },
+ );
+ return $res;
+}
+
+sub with_lock($code) {
+ my ($res, $timeout) = PVE::Tools::run_fork_with_timeout(
+ 35,
+ sub {
+ make_path($RUN_DIR);
+ open(my $lock, '>>', "$RUN_DIR/fabrics.lock") or die "cannot open NVMe lock - $!\n";
+ flock($lock, LOCK_EX | LOCK_NB)
+ or die "NVMe over Fabrics is busy - another operation is still running\n";
+ # A command still in the kernel must retain serialization after its caller times out.
+ my $flags = fcntl($lock, F_GETFD, 0) // die "cannot read NVMe lock flags - $!\n";
+ fcntl($lock, F_SETFD, $flags & ~FD_CLOEXEC)
+ or die "cannot inherit NVMe lock - $!\n";
+ return $code->();
+ },
+ );
+ die "NVMe over Fabrics operation timed out - it may still be running\n" if $timeout;
+ return $res;
+}
+
+my sub retry_file($scfg, $path) {
+ my ($key) =
+ sha1_hex(join(
+ "\0", $scfg->{subsysnqn}, format_path($path), $scfg->{'fast-io-fail-tmo'} // 120)) =~
+ /\A([0-9a-f]{40})\z/;
+ return "$RUN_DIR/retry/$key";
+}
+
+sub in_cooldown($scfg, $path) {
+ my $mtime = (stat(retry_file($scfg, $path)))[9] // return 0;
+ my $age = time() - $mtime;
+ return $age > -60 && $age < 60;
+}
+
+sub note_connect_failure($scfg, $path) {
+ make_path("$RUN_DIR/retry");
+ file_set_contents(retry_file($scfg, $path), '');
+}
+
+sub connect_path($scfg, $path) {
+ my ($nqn) = $scfg->{subsysnqn} =~ /\A($NQN_PATTERN)\z/;
+ if (!defined($nqn) || length($nqn) > 223 || $nqn eq 'nqn.2014-08.org.nvmexpress.discovery') {
+ die "invalid subsystem NQN\n";
+ }
+ my ($fail) = ($scfg->{'fast-io-fail-tmo'} // 120) =~ /\A(-?[0-9]+)\z/;
+ die "invalid fast I/O fail timeout\n" if !defined($fail) || $fail < -1;
+ return with_lock(sub {
+ return if path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ assert_support();
+ my $host = host_identity();
+ run_command(
+ [
+ $NVME,
+ 'connect',
+ '--transport=tcp',
+ '--nqn',
+ $nqn,
+ '--traddr',
+ $path->{traddr},
+ '--trsvcid',
+ $path->{trsvcid},
+ '--hostnqn',
+ $host->{nqn},
+ '--hostid',
+ $host->{id},
+ '--ctrl-loss-tmo=-1',
+ '--fast_io_fail_tmo',
+ $fail,
+ ],
+ timeout => 30,
+ );
+ # nvme-cli can exit successfully without having connected
+ die "no controller appeared\n"
+ if !path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ unlink(retry_file($scfg, $path));
+ return;
+ });
+}
+
+1;
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index 1e9c670a..91283ff2 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -33,6 +33,7 @@ use PVE::Storage::LvmThinPlugin;
use PVE::Storage::NFSPlugin;
use PVE::Storage::CIFSPlugin;
use PVE::Storage::ISCSIPlugin;
+use PVE::Storage::NVMeOFPlugin;
use PVE::Storage::RBDPlugin;
use PVE::Storage::CephFSPlugin;
use PVE::Storage::ISCSIDirectPlugin;
@@ -58,6 +59,7 @@ PVE::Storage::LvmThinPlugin->register();
PVE::Storage::NFSPlugin->register();
PVE::Storage::CIFSPlugin->register();
PVE::Storage::ISCSIPlugin->register();
+PVE::Storage::NVMeOFPlugin->register();
PVE::Storage::RBDPlugin->register();
PVE::Storage::CephFSPlugin->register();
PVE::Storage::ISCSIDirectPlugin->register();
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index a2df83c0..7f2ff6c8 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -6,6 +6,7 @@ SOURCES= \
NFSPlugin.pm \
CIFSPlugin.pm \
ISCSIPlugin.pm \
+ NVMeOFPlugin.pm \
CephFSPlugin.pm \
RBDPlugin.pm \
ISCSIDirectPlugin.pm \
diff --git a/src/PVE/Storage/NVMeOFPlugin.pm b/src/PVE/Storage/NVMeOFPlugin.pm
new file mode 100644
index 00000000..cb514c1d
--- /dev/null
+++ b/src/PVE/Storage/NVMeOFPlugin.pm
@@ -0,0 +1,223 @@
+package PVE::Storage::NVMeOFPlugin;
+
+use v5.36;
+
+use Cwd ();
+use Time::HiRes ();
+
+use PVE::Network;
+
+use PVE::Diskmanage;
+use PVE::NVMeOF;
+use PVE::Storage::Plugin;
+
+use base qw(PVE::Storage::Plugin);
+
+sub type { return 'nvmeof' }
+
+sub plugindata {
+ return {
+ content => [{ images => 1, 'vm-vol' => 1, none => 1 }, { images => 1 }],
+ select_existing => 1,
+ 'isolate-properties' => 1,
+ 'advanced-properties' => {
+ 'fast-io-fail-tmo' => 1,
+ },
+ 'hidden-properties' => {
+ bwlimit => 1,
+ },
+ 'sensitive-properties' => {},
+ };
+}
+
+sub properties {
+ return {
+ subsysnqn => {
+ title => "Subsystem",
+ description => 'The NQN of the NVMe subsystem.',
+ type => 'string',
+ pattern => $PVE::NVMeOF::NQN_PATTERN,
+ maxLength => 223,
+ },
+ portals => {
+ title => "Portals",
+ description =>
+ 'TCP portals of the NVMe subsystem, as IPv4 or bracketed IPv6 addresses'
+ . ' with an optional port (default 4420).',
+ type => 'string',
+ format => 'pve-storage-nvme-portal-list',
+ },
+ 'fast-io-fail-tmo' => {
+ title => "Fail I/O After (s)",
+ description => 'Seconds before I/O through a reconnecting path fails. -1 disables'
+ . ' this timeout; I/O can remain queued while paths reconnect.',
+ type => 'integer',
+ minimum => -1,
+ default => 120,
+ },
+ };
+}
+
+sub options {
+ return {
+ subsysnqn => { fixed => 1 },
+ portals => {},
+ 'fast-io-fail-tmo' => { optional => 1 },
+ nodes => { optional => 1 },
+ disable => { optional => 1 },
+ content => { optional => 1 },
+ bwlimit => { optional => 1 },
+ };
+}
+
+my sub assert_valid_config($scfg) {
+ die "the discovery subsystem cannot be used as storage\n"
+ if $scfg->{subsysnqn} eq 'nqn.2014-08.org.nvmexpress.discovery';
+ my %seen;
+ for my $path (PVE::NVMeOF::storage_paths($scfg)->@*) {
+ my $portal = PVE::NVMeOF::format_path($path);
+ die "portal '$portal' is listed more than once\n" if $seen{$portal}++;
+ }
+}
+
+sub on_add_hook($class, $storeid, $scfg, %param) {
+ assert_valid_config($scfg);
+ # the LUN and controller lists and the node status attribute a subsystem to its one storage
+ my $ids = PVE::Storage::config()->{ids};
+ for my $sid (sort keys %$ids) {
+ next if $sid eq $storeid || $ids->{$sid}->{type} ne 'nvmeof';
+ die "storage '$sid' already uses this subsystem\n"
+ if $ids->{$sid}->{subsysnqn} eq $scfg->{subsysnqn};
+ }
+ return;
+}
+
+sub on_update_hook_full($class, $storeid, $scfg, $update, $delete, $sensitive, @) {
+ my $merged = { %$scfg, %$update };
+ delete $merged->{$_} for ($delete // [])->@*;
+ assert_valid_config($merged);
+ return $class->SUPER::on_update_hook_full($storeid, $scfg, $update, $delete, $sensitive);
+}
+
+sub parse_volname($class, $volname) {
+ if ($volname =~ m!^(nvme-[a-zA-Z0-9_.:+-]+)$! && $volname !~ /-part[0-9]+$/) {
+ return ($class->guest_volume_vtype('raw'), $1, undef, undef, undef, undef, 'raw');
+ }
+ die "unable to parse NVMe over Fabrics volume name '$volname'\n";
+}
+
+# The name of a volume can be the by-id name of any NVMe device, also of a local disk or of a
+# namespace of another subsystem.
+sub assert_namespace($scfg, $volname, $real) {
+ my ($dev) = $real =~ m!^/dev/(nvme[0-9]+n[0-9]+)$!;
+ die "volume '$volname' is not an NVMe namespace\n" if !defined($dev);
+ my $nqn = PVE::Diskmanage::read_subsysnqn("/sys/block/$dev/device/subsysnqn") // '';
+ die "volume '$volname' is not part of subsystem '$scfg->{subsysnqn}'\n"
+ if $nqn ne $scfg->{subsysnqn};
+}
+
+sub filesystem_path($class, $scfg, $volname, $snapname = undef, @) {
+ die "snapshot is not possible on NVMe over Fabrics storage\n" if defined($snapname);
+ my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+ my $path = "/dev/disk/by-id/$name";
+ # not every user of a path activates the volume first, and the base volume of an LVM storage
+ # has no device before its storage connects
+ my $real = Cwd::realpath($path);
+ assert_namespace($scfg, $volname, $real) if defined($real) && -e $real;
+ return wantarray ? ($path, $vmid, $vtype) : $path;
+}
+
+sub create_base { die "can't create base images in NVMe over Fabrics storage\n" }
+sub clone_image { die "can't clone images in NVMe over Fabrics storage\n" }
+sub alloc_image { die "can't allocate space in NVMe over Fabrics storage\n" }
+sub free_image { die "can't free space in NVMe over Fabrics storage\n" }
+sub volume_resize { die "volume resize is not possible on NVMe over Fabrics storage\n" }
+
+sub list_volumes($class, $storeid, $scfg, $vmid = undef, $content_types = undef, @) {
+ my $res = $class->list_images($storeid, $scfg, $vmid);
+ $_->{content} = 'images' for @$res;
+ return $res;
+}
+
+sub list_images($class, $storeid, $scfg, $vmid = undef, $vollist = undef, $cache = undef, @) {
+ return [] if defined($vmid) && !$vollist;
+ my $namespaces = PVE::NVMeOF::namespaces($scfg->{subsysnqn});
+ my $res = [];
+ for my $dev (sort keys %$namespaces) {
+ my $ns = $namespaces->{$dev};
+ my $volid = "$storeid:nvme-$ns->{wwid}";
+ next if $vollist && !grep { $_ eq $volid } @$vollist;
+ push @$res,
+ {
+ volid => $volid,
+ format => 'raw',
+ size => $ns->{size},
+ vmid => 0,
+ };
+ }
+ return $res;
+}
+
+sub status($class, $storeid, $scfg, $cache = undef, @) {
+ my $active = grep { $_->{state} eq 'live' }
+ values PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn})->%*;
+ return (0, 0, 0, $active ? 1 : 0);
+}
+
+sub activate_storage($class, $storeid, $scfg, $cache = undef, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ for my $path (PVE::NVMeOF::storage_paths($scfg)->@*) {
+ next if defined(PVE::NVMeOF::path_controller($controllers, $path));
+ next if PVE::NVMeOF::in_cooldown($scfg, $path);
+ eval {
+ die "no answer from portal\n"
+ if !PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2);
+ PVE::NVMeOF::connect_path($scfg, $path);
+ };
+ if (my $err = $@) {
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ warn "storage '$storeid': connecting to '"
+ . PVE::NVMeOF::format_path($path)
+ . "' failed - $err";
+ }
+ }
+ return;
+}
+
+sub deactivate_storage { return }
+
+sub check_connection($class, $storeid, $scfg, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ return 1 if grep { $_->{state} eq 'live' } values %$controllers;
+ for my $path (PVE::NVMeOF::storage_paths($scfg)->@*) {
+ next if defined(PVE::NVMeOF::path_controller($controllers, $path));
+ next if PVE::NVMeOF::in_cooldown($scfg, $path);
+ return 1 if PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2);
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ }
+ return 0;
+}
+
+sub activate_volume($class, $storeid, $scfg, $volname, $snapname = undef, $cache = undef, @) {
+ my $path = $class->filesystem_path($scfg, $volname, $snapname);
+ # as for the multipath map of an iSCSI LUN, a status pass does not wait for the device
+ my $deadline = Time::HiRes::time() + ($cache && $cache->{status_only} ? 0 : 10);
+ while (!-b $path && Time::HiRes::time() < $deadline) {
+ last if !keys PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn})->%*;
+ Time::HiRes::usleep(250_000);
+ }
+ my $real = Cwd::realpath($path);
+ die "volume '$volname' is not available on this node\n" if !$real || !-b $real;
+ assert_namespace($scfg, $volname, $real);
+}
+
+sub volume_has_feature(
+ $class, $scfg, $feature, $storeid, $volname,
+ $snapname = undef,
+ $running = undef, @,
+) {
+ return 1 if $feature eq 'copy' && !defined($snapname);
+ return undef;
+}
+
+1;
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index 724c2d35..6e305580 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -42,7 +42,7 @@ our @COMMON_TAR_FLAGS = qw(
);
our @SHARED_STORAGE = (
- 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs',
+ 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs', 'nvmeof',
);
our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index b025c03f..86469f5c 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -298,6 +298,11 @@ sub lun_partitions($lun) {
}
sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my $name = basename($lun->{devpath});
+ my $nqn =
+ $name =~ /^nvme\d+n\d+$/
+ ? PVE::Diskmanage::read_subsysnqn("/sys/block/$name/device/subsysnqn")
+ : undef;
my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
[$lun->{devpath}, lun_partitions($lun)->@*],
)->@*;
@@ -320,6 +325,14 @@ sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
) {
die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
}
+ if (
+ $type eq 'nvmeof'
+ && defined($nqn)
+ && $scfg->{subsysnqn} eq $nqn
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this subsystem\n";
+ }
next if $type ne 'lvm' || !$scfg->{base};
my (undef, $volname) = PVE::Storage::Plugin::parse_volume_id($scfg->{base});
my ($wwid) = $volname =~ m/(?:^|\.)(?:dm-uuid-(?:part\d+-)?mpath|scsi|nvme)-(.+)$/;
diff --git a/src/test/Makefile b/src/test/Makefile
index 279ba1ee..c88666f5 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_sensitive_properties test_import_stream test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api
+test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_sensitive_properties test_import_stream test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api test_nvmeof
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
@@ -83,3 +83,7 @@ test_san_api: run_san_api_tests.pl run_san_wipe_tests.pl run_san_nvme_tests.pl
test_disk_api: run_disk_api_tests.pl
./run_disk_api_tests.pl
+
+test_nvmeof: run_nvmeof_tests.pl run_nvmeof_taint_tests.pl
+ ./run_nvmeof_tests.pl
+ perl -T ./run_nvmeof_taint_tests.pl
diff --git a/src/test/run_nvmeof_taint_tests.pl b/src/test/run_nvmeof_taint_tests.pl
new file mode 100755
index 00000000..62405291
--- /dev/null
+++ b/src/test/run_nvmeof_taint_tests.pl
@@ -0,0 +1,60 @@
+#!/usr/bin/perl -T
+
+use v5.36;
+use lib qw(..);
+use File::Temp qw(tempdir);
+use Scalar::Util qw(tainted);
+use Test::More;
+use Test::MockModule;
+use PVE::NVMeOF;
+use PVE::Tools qw(file_set_contents file_get_contents);
+
+$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
+delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
+my $dir = tempdir('nvmeof-taint-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::HOSTNQN_FILE = "$dir/hostnqn";
+local $PVE::NVMeOF::HOSTID_FILE = "$dir/hostid";
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+file_set_contents($PVE::NVMeOF::HOSTNQN_FILE, "nqn.host\n");
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "12345678-1234-1234-1234-123456789abc\n");
+file_set_contents("$dir/config", "nqn.test\n192.0.2.1\n120\n");
+my ($nqn, $portal, $fail) = split(/\n/, file_get_contents("$dir/config"));
+ok(tainted($nqn), 'configuration input is tainted');
+my $nvme = Test::MockModule->new('PVE::NVMeOF');
+$nvme->mock(with_lock => sub { $_[0]->() });
+my $commands = 0;
+$nvme->mock(
+ subsystem_controllers => sub {
+ return $commands ? { nvme0 => { traddr => '192.0.2.1', trsvcid => 4420 } } : {};
+ },
+);
+$nvme->mock(assert_support => sub { });
+$nvme->mock(
+ run_command => sub($cmd, %opts) {
+ $commands++;
+ is(
+ scalar(grep { tainted($_) } @$cmd),
+ 0,
+ 'all connect operands are validated and untainted',
+ );
+ PVE::Tools::run_command(['/usr/bin/true', @$cmd], timeout => 5);
+ },
+);
+my $path = PVE::NVMeOF::parse_portal($portal);
+eval { PVE::NVMeOF::connect_path({ subsysnqn => $nqn, 'fast-io-fail-tmo' => $fail }, $path) };
+is($@, '', 'connect command can execute in taint mode');
+is($commands, 1, 'one connect');
+PVE::NVMeOF::note_connect_failure({ subsysnqn => $nqn }, $path);
+ok(
+ PVE::NVMeOF::in_cooldown({ subsysnqn => $nqn }, $path),
+ 'cooldown accepts validated file-backed configuration',
+);
+for my $bad ('nqn.bad,nqn=other', "nqn.test\n", 'nqn.2014-08.org.nvmexpress.discovery') {
+ eval { PVE::NVMeOF::connect_path({ subsysnqn => $bad }, $path) };
+ like($@, qr/invalid subsystem/, 'invalid connect subsystem refused');
+}
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "00000000-0000-0000-0000-000000000000\n");
+eval { PVE::NVMeOF::host_identity() };
+like($@, qr/nonzero UUID/, 'zero host ID refused');
+
+done_testing();
diff --git a/src/test/run_nvmeof_tests.pl b/src/test/run_nvmeof_tests.pl
new file mode 100755
index 00000000..b75f7a5a
--- /dev/null
+++ b/src/test/run_nvmeof_tests.pl
@@ -0,0 +1,302 @@
+#!/usr/bin/perl
+
+use v5.36;
+use lib qw(..);
+use Fcntl qw(:flock);
+use File::Path qw(make_path);
+use File::Temp qw(tempdir);
+use Test::MockModule;
+use Test::More;
+
+use PVE::Tools qw(file_set_contents);
+
+use PVE::NVMeOF;
+use PVE::Storage;
+
+my $dir = tempdir('nvmeof-test-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+local $PVE::NVMeOF::SYSFS = "$dir/sys";
+my $class = 'PVE::Storage::NVMeOFPlugin';
+my $cfg = {
+ type => 'nvmeof',
+ subsysnqn => 'nqn.test',
+ portals => '192.0.2.1,[2001:db8::2]:4421',
+ content => { none => 1 },
+};
+
+subtest 'configuration, portals and volumes' => sub {
+ is(PVE::Storage::Plugin->lookup('nvmeof'), $class, 'plugin registered');
+ is_deeply(
+ [sort keys $class->properties()->%*],
+ [qw(fast-io-fail-tmo portals subsysnqn)],
+ 'only three plugin-specific properties',
+ );
+ my sub nvmeof_schema($schema) {
+ my @types = map { ($_->{oneOf} // [])->@* } ($schema->{allOf} // [])->@*;
+ my ($nvmeof) = grep { $_->{'instance-type'} eq 'nvmeof' } @types;
+ return $nvmeof->{properties} // {};
+ }
+ my $create = nvmeof_schema(PVE::Storage::Plugin->createSchema());
+ is_deeply(
+ [sort grep { !$create->{$_}->{optional} } keys $create->%*],
+ [qw(portals subsysnqn)],
+ 'adding a storage requires the subsystem and the portals',
+ );
+ my $update = nvmeof_schema(PVE::Storage::Plugin->updateSchema());
+ ok($update->{portals} && !$update->{subsysnqn}, 'the subsystem cannot be changed');
+ my $parsed = PVE::Storage::Plugin->parse_config(
+ 'storage.cfg',
+ "nvmeof: fabric\n\tsubsysnqn nqn.test\n\tportals 192.0.2.1\n\tcontent none\n",
+ );
+ is($parsed->{ids}->{fabric}->{subsysnqn}, 'nqn.test', 'storage.cfg accepts the plugin');
+ is_deeply(
+ $parsed->{ids}->{fabric}->{content},
+ { none => 1 },
+ 'connection-only content parses',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ { traddr => '192.0.2.1', trsvcid => 4420 },
+ 'default I/O port',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('[2001:0db8::1]:4421'),
+ { traddr => '2001:db8::1', trsvcid => 4421 },
+ 'canonical IPv6',
+ );
+
+ for my $bad (
+ 'host.example', '1.2.3.4:0', '1.2.3.4:65536', '[fe80::1]', '[::]', '224.0.0.1',
+ ) {
+ ok(!PVE::NVMeOF::parse_portal($bad), "invalid portal $bad");
+ }
+ eval { $class->on_add_hook('fabric', { %$cfg, portals => '192.0.2.1,192.0.2.1:4420' }); };
+ like($@, qr/listed more than once/, 'duplicate portals refused');
+ eval {
+ $class->on_add_hook(
+ 'fabric',
+ { %$cfg, subsysnqn => 'nqn.2014-08.org.nvmexpress.discovery' },
+ );
+ };
+ like($@, qr/discovery subsystem/, 'discovery subsystem refused');
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $ids = { fabric => $cfg, local => { type => 'dir' } };
+ $storage->mock(config => sub { { ids => $ids } });
+ is(eval { $class->on_add_hook('fabric', $cfg); 1 }, 1, 'a storage is not in its own way');
+ eval { $class->on_add_hook('second', {%$cfg}) };
+ like($@, qr/storage 'fabric' already uses this subsystem/, 'one storage per subsystem');
+ is(
+ scalar($class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef')),
+ '/dev/disk/by-id/nvme-eui.0123456789abcdef',
+ 'stable volume path',
+ );
+ {
+ my $disk = Test::MockModule->new('PVE::Diskmanage');
+ my $nqn = 'nqn.other';
+ $disk->redefine(read_subsysnqn => sub { $nqn });
+ my $check = sub {
+ eval { PVE::Storage::NVMeOFPlugin::assert_namespace($cfg, @_) };
+ $@;
+ };
+ like($check->('nvme-x', '/dev/nvme0n1'), qr/not part of subsystem/, 'other subsystem');
+ like($check->('nvme-x', '/dev/sda'), qr/not an NVMe namespace/, 'other device type');
+ like($check->('nvme-x', '/dev/nvme0n1p1'), qr/not an NVMe namespace/, 'partition');
+ $nqn = 'nqn.test';
+ is($check->('nvme-x', '/dev/nvme0n1'), '', 'namespace of the subsystem');
+ my $cwd = Test::MockModule->new('Cwd');
+ $cwd->redefine(realpath => sub { $dir });
+ eval { $class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef') };
+ like($@, qr/not an NVMe namespace/, 'the path of an existing device is checked');
+ }
+
+ for my $bad ('nvme-../../sda', 'nvme-eui.abc-part1', 'sda') {
+ eval { $class->parse_volname($bad) };
+ like($@, qr/unable to parse/, "invalid volume $bad");
+ }
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ $nvme->mock(namespaces => sub { { nvme0n1 => { wwid => 'eui.abc', size => 4096 } } });
+ is(
+ $class->list_volumes('fabric', $cfg)->[0]->{volid},
+ 'fabric:nvme-eui.abc',
+ 'content none still offers bases',
+ );
+ is_deeply($class->list_images('fabric', $cfg, 100), [], 'namespaces have no VM owner');
+ $nvme->mock(subsystem_controllers => sub { {} });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test') };
+ like($@, qr/not available/,
+ 'missing namespace fails without waiting on absent controllers');
+ my ($now, $queries) = (0, 0);
+ my $clock = Test::MockModule->new('Time::HiRes');
+ $clock->redefine(time => sub { $now += 5 }, usleep => sub { });
+ $nvme->mock(subsystem_controllers => sub { $queries++; { nvme1 => {} } });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test', undef, {}) };
+ is($queries, 1, 'a missing namespace of a connected subsystem is waited for');
+ eval {
+ $class->activate_volume(
+ 'fabric',
+ $cfg,
+ 'nvme-nonexistent-test',
+ undef,
+ { status_only => 1 },
+ );
+ };
+ like($@, qr/not available/, 'in a status pass it fails as well');
+ is($queries, 1, 'but without a wait');
+ is(
+ ($class->parse_volname('nvme-eui.0123456789abcdef'))[0],
+ 'vm-vol',
+ 'namespaces are VM disks',
+ );
+};
+
+subtest 'sysfs topology' => sub {
+ my $sys = $PVE::NVMeOF::SYSFS;
+ make_path(
+ "$sys/class/nvme-fabrics/ctl/nvme1",
+ "$sys/class/nvme-subsystem/nvme-subsys0/nvme0n1",
+ "$sys/block/nvme0n1",
+ );
+ my %attrs = (
+ address => 'traddr=192.0.2.1,trsvcid=4420',
+ transport => 'tcp',
+ subsysnqn => 'nqn.test',
+ state => 'connecting',
+ );
+ file_set_contents("$sys/class/nvme-fabrics/ctl/nvme1/$_", "$attrs{$_}\n") for keys %attrs;
+ file_set_contents("$sys/class/nvme-subsystem/nvme-subsys0/subsysnqn", "nqn.test\n");
+ file_set_contents("$sys/block/nvme0n1/wwid", "eui.abc\n");
+ file_set_contents("$sys/block/nvme0n1/size", "8\n");
+ is(
+ PVE::NVMeOF::controllers()->{nvme1}->{state},
+ 'connecting',
+ 'reconnecting controller is still present',
+ );
+ is(
+ PVE::NVMeOF::path_controller(
+ PVE::NVMeOF::subsystem_controllers('nqn.test'),
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ ),
+ 'nvme1',
+ 'portal controller found',
+ );
+ is_deeply(
+ PVE::NVMeOF::namespaces('nqn.test'),
+ { nvme0n1 => { wwid => 'eui.abc', size => 4096 } },
+ 'namespace facts',
+ );
+ is_deeply(PVE::NVMeOF::namespaces('nqn.other'), {}, 'other subsystem excluded');
+};
+
+subtest 'serialized commands inherit the lock' => sub {
+ my $value = PVE::NVMeOF::with_lock(sub {
+ my $out = '';
+ PVE::Tools::run_command(
+ [
+ '/usr/bin/perl',
+ '-MFcntl=:flock',
+ '-e',
+ 'my @held = grep { (readlink($_) // "") =~ /fabrics.lock$/ } glob("/proc/self/fd/*"); die "not inherited" if !@held; open(my $fh, ">>", $ARGV[0]) or die $!; die "lock missing" if flock($fh, LOCK_EX|LOCK_NB); print "locked\\n";',
+ "$PVE::NVMeOF::RUN_DIR/fabrics.lock",
+ ],
+ timeout => 5,
+ outfunc => sub { $out .= $_[0] },
+ );
+ return $out;
+ });
+ is($value, 'locked', 'exec cannot acquire the lock held by its parent');
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or die $!;
+ flock($lock, LOCK_EX) or die $!;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'busy operation never enters callback');
+ close($lock);
+
+ my $tools = Test::MockModule->new('PVE::Tools');
+ my $timed_out = 1;
+ $tools->mock(run_fork_with_timeout => sub { return ($_[1]->(), $timed_out) });
+ my $retained;
+ eval {
+ PVE::NVMeOF::with_lock(sub {
+ my ($path) =
+ grep { (readlink($_) // '') =~ /fabrics.lock$/ } glob('/proc/self/fd/*');
+ my ($fd) = $path =~ m{/(\d+)$};
+ open($retained, '>&', $fd) or die $!;
+ return 1;
+ });
+ };
+ like($@, qr/timed out.*may still be running/, 'timeout does not claim deletion completed');
+ $timed_out = 0;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'retained descriptor keeps serialization after the caller returns');
+ close($retained);
+ is(PVE::NVMeOF::with_lock(sub { 1 }), 1, 'last descriptor close releases serialization');
+};
+
+subtest 'connect options, kernel reconnect and cooldown' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my @commands;
+ my $controllers = {};
+ $nvme->mock(with_lock => sub { $_[0]->() });
+ $nvme->mock(assert_support => sub { });
+ $nvme->mock(host_identity =>
+ sub { { nqn => 'nqn.host', id => '12345678-1234-1234-1234-123456789abc' } });
+ $nvme->mock(subsystem_controllers => sub { $controllers });
+ my $appear = 1;
+ $nvme->mock(
+ run_command => sub($cmd, %opts) {
+ is($opts{timeout}, 30, 'bounded connect');
+ push @commands, $cmd;
+ my %arg =
+ map { $cmd->[$_] => $cmd->[$_ + 1] } grep { $cmd->[$_] =~ /^--tr/ } 0 .. $#$cmd;
+ my $controller =
+ { traddr => $arg{'--traddr'}, trsvcid => $arg{'--trsvcid'}, state => 'live' };
+ $controllers->{ 'nvme' . scalar(@commands) } = $controller if $appear;
+ },
+ );
+ $net->mock(tcp_ping => sub { 1 });
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 2, 'one connect per missing portal');
+ ok(grep({ $_ eq '--ctrl-loss-tmo=-1' } $commands[0]->@*), 'kernel reconnects indefinitely');
+ is_deeply([@{ $commands[0] }[-2, -1]], ['--fast_io_fail_tmo', 120], 'fast failure default');
+ @commands = ();
+ $controllers = {
+ nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' },
+ nvme2 => { traddr => '2001:db8::2', trsvcid => 4421, state => 'live' },
+ };
+ $class->activate_storage('fabric', $cfg);
+ is_deeply(\@commands, [],
+ 'existing controllers are never reconnected, regardless of state');
+ $class->deactivate_storage('fabric', $cfg);
+ is_deeply(\@commands, [], 'deactivation does not remove controllers');
+ $controllers = {};
+ my $path = PVE::NVMeOF::storage_paths($cfg)->[0];
+ PVE::NVMeOF::note_connect_failure($cfg, $path);
+ ok(PVE::NVMeOF::in_cooldown($cfg, $path), 'failure starts cooldown');
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 1, 'only the other portal connects');
+ ($controllers, $appear) = ({}, 0);
+ my $other = PVE::NVMeOF::storage_paths($cfg)->[1];
+ my $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ $class->activate_storage('fabric', $cfg);
+ }
+ like($warning, qr/no controller appeared/, 'a connect without a controller is a failure');
+ ok(PVE::NVMeOF::in_cooldown($cfg, $other), 'which starts the cooldown too');
+};
+
+subtest 'local disk setup rejects fabric namespaces by transport' => sub {
+ my $disk = Test::MockModule->new('PVE::Diskmanage');
+ for my $transport (qw(nvme-tcp nvme-rdma nvme-fc)) {
+ $disk->mock(get_disks => sub { { nvme0n1 => { transport => $transport } } });
+ eval { PVE::Diskmanage::assert_disk_unused('/dev/nvme0n1') };
+ like($@, qr/not a valid local disk/,
+ "$transport refuses without storage configuration");
+ }
+};
+
+done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
index 51236f87..c74b638a 100755
--- a/src/test/run_san_nvme_tests.pl
+++ b/src/test/run_san_nvme_tests.pl
@@ -38,6 +38,7 @@ $storage->mock(config => sub { $cfg });
$disk->mock(verify_blockdev_path => sub { $device });
$disk->mock(is_partition => sub { 0 });
$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(read_subsysnqn => sub { 'nqn.test' });
$disk->mock(is_iscsi_device => sub { 0 });
$disk->mock(is_mounted => sub { 0 });
$disk->mock(has_holder => sub { 0 });
@@ -78,6 +79,21 @@ $disk->mock(is_partition => sub { 0 });
$cfg->{ids}->{data} = { type => 'lvm', base => 'fabric:nvme-eui.0123456789abcdef' };
eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
like($@, qr/base volume/, 'native base reference refuses');
+$cfg->{ids} =
+ { fabric =>
+ { type => 'nvmeof', subsysnqn => 'nqn.test', disable => 1, content => { images => 1 } } };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like(
+ $@,
+ qr/serves images from this subsystem/,
+ 'direct namespace image use refuses even when disabled',
+);
+$cfg->{ids}->{fabric}->{content} = { 'vm-vol' => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like($@, qr/serves images from this subsystem/, 'also when restricted to VM disks');
+$cfg->{ids}->{fabric}->{content} = { none => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+is($@, '', 'connection-only storage permits namespace initialization');
$cfg->{ids} = {};
@order = @opens = ();
$tools->mock(file_get_contents => sub { 1024 });
^ permalink raw reply related [relevance 20%]
* [PATCH v8 storage 23/43] disks: lvm: allow volume groups on SAN LUNs and multipath maps
@ 2026-11-19 19:46 9% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-19 19:46 UTC (permalink / raw)
To: pve-devel
The node disk API creates volume groups on local disks only. It
treats a Fibre Channel LUN as a local disk, refuses a multipath map
and adds the storage as local to the node. Accept the LUNs of the SAN
inventory and add their storage as shared for all nodes. Refuse an
existing storage ID for a LUN, and never join a storage that got
added with that ID meanwhile. Joining is meant for local volume groups
of the same name, and on a LUN would combine two different volume
groups in one shared storage. The partitions of a LUN, also the ones
that kpartx maps, stay local devices as before, so that an LVM storage
can still be added for a volume group on one of them.
Initializing a LUN, here or as base volume of an LVM storage that is
being added, takes a cluster-wide lock per WWID. It refuses a LUN that a
storage references through its volume group, as base volume, also
through a partition, or as iSCSI target serving images. The name of a
map can pass to another map while the lock is awaited. So the LUN is
held open by its stable name, and creation stops if a name used for the
checks and the LVM commands no longer leads to the held device. The
lookup of the LUN also resolves the requested name again after its scan,
and stops if the name leads to another device by then. The commands run
under the lock have timeouts of their own. On an array in trouble, they
can together take longer than the minute that the cluster lock gives
them. Creation then fails after the command that runs at that time and
leaves what it created so far, as the volume group creation on an iSCSI
base volume of master can.
A LUN that a process of the node has open is refused too. A guest
that got the LUN as disk from a third-party storage plugin, or by its
device path, is neither a holder nor a storage reference, and its disk
can look empty. The check goes by the open files of the processes, so
it misses an open through another device node, for example the one of
a container. Also refused is a LUN whose other SCSI paths or their
partitions are mounted, held by a block device other than the map of
the LUN, or open for writing. An open for reading does not count, as
multipathd keeps the paths open read-only.
The other node disk endpoints, for a directory, an LVM-thin pool, a ZFS
pool or a GPT, are left as they are: they keep accepting a Fibre Channel
LUN or an NVMe namespace as a local disk, which works as long as a
single host uses it.
Co-authored-by: Dietmar Maurer <dietmar@proxmox.com>
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
src/PVE/API2/Disks/LVM.pm | 71 +++++---
src/PVE/Diskmanage.pm | 45 +++++
src/PVE/Storage/LVMPlugin.pm | 81 ++++++++-
src/PVE/Storage/SAN.pm | 154 ++++++++++++++++
src/test/Makefile | 11 +-
src/test/disk_api_test.pm | 247 ++++++++++++++++++++++++++
src/test/run_disk_api_tests.pl | 11 ++
src/test/run_san_library_tests.pl | 27 +++
src/test/run_san_nvme_tests.pl | 106 +++++++++++
src/test/run_san_taint_tests.pl | 26 +++
src/test/run_san_write_check_tests.pl | 219 +++++++++++++++++++++++
src/test/run_test_lvm_create.pl | 46 +++++
12 files changed, 1008 insertions(+), 36 deletions(-)
create mode 100644 src/test/disk_api_test.pm
create mode 100755 src/test/run_disk_api_tests.pl
create mode 100755 src/test/run_san_nvme_tests.pl
create mode 100755 src/test/run_san_write_check_tests.pl
diff --git a/src/PVE/API2/Disks/LVM.pm b/src/PVE/API2/Disks/LVM.pm
index 6101743b..1fd68f1a 100644
--- a/src/PVE/API2/Disks/LVM.pm
+++ b/src/PVE/API2/Disks/LVM.pm
@@ -4,6 +4,7 @@ use strict;
use warnings;
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
use PVE::Diskmanage;
use PVE::JSONSchema qw(get_standard_option);
use PVE::API2::Storage::Config;
@@ -130,10 +131,13 @@ __PACKAGE__->register_method({
name => get_standard_option('pve-storage-id'),
device => {
type => 'string',
- description => 'The block device you want to create the volume group on',
+ description => 'The block device you want to create the volume group on.'
+ . ' Multipath mapped devices are supported.',
},
add_storage => {
- description => "Configure storage using the Volume Group",
+ description => "Configure storage using the Volume Group. On a SAN LUN, this"
+ . " adds a new shared storage for all nodes. On a local disk, the storage is"
+ . " for this node, or this node joins a matching storage of that ID.",
type => 'boolean',
optional => 1,
default => 0,
@@ -152,48 +156,63 @@ __PACKAGE__->register_method({
my $node = $param->{node};
$dev = PVE::Diskmanage::verify_blockdev_path($dev);
- PVE::Diskmanage::assert_disk_unused($dev);
+ my $san = PVE::Storage::SAN::is_san_device($dev);
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
my $storage_params = {
type => 'lvm',
vgname => $name,
storage => $name,
content => 'rootdir,images',
- shared => 0,
- nodes => $node,
+ shared => $san ? 1 : 0,
+ $san ? () : (nodes => $node),
};
my $verify_params = [qw(vgname)];
if ($param->{add_storage}) {
$rpcenv->check($user, "/storage", ['Datastore.Allocate']);
- # reserve the name and add as disabled, will be enabled below if creation works out
+ # only local volume groups of the same name may share a storage that exists already
+ die "storage ID '$name' already defined\n"
+ if $san && PVE::Storage::storage_config(PVE::Storage::config(), $name, 1);
+
+ # a dry run that checks the parameters, the storage is added after the volume group
PVE::API2::Storage::Config->create_or_update(
$name, $node, $storage_params, $verify_params, 1,
);
}
+ my $create_group = sub {
+ PVE::Diskmanage::assert_disk_unused($dev) if !$san;
+ die "volume group with name '${name}' already exists on node '${node}'\n"
+ if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
+
+ if (PVE::Diskmanage::is_partition($dev)) {
+ eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
+ warn $@ if $@;
+ }
+
+ # the given name, so that the LUN lookup notices if it passed to another device during
+ # its scan
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ $san ? $param->{device} : $dev,
+ $name,
+ $san,
+ );
+
+ PVE::Diskmanage::udevadm_trigger($dev);
+
+ if ($param->{add_storage} && $san) {
+ # must not join a storage that someone added with this ID in the meantime
+ PVE::API2::Storage::Config->create({%$storage_params});
+ } elsif ($param->{add_storage}) {
+ PVE::API2::Storage::Config->create_or_update(
+ $name, $node, $storage_params, $verify_params,
+ );
+ }
+ };
my $worker = sub {
- PVE::Diskmanage::locked_disk_action(sub {
- PVE::Diskmanage::assert_disk_unused($dev);
- die "volume group with name '${name}' already exists on node '${node}'\n"
- if PVE::Storage::LVMPlugin::lvm_vgs()->{$name};
-
- if (PVE::Diskmanage::is_partition($dev)) {
- eval { PVE::Diskmanage::change_parttype($dev, '8E00'); };
- warn $@ if $@;
- }
-
- PVE::Storage::LVMPlugin::lvm_create_volume_group($dev, $name);
-
- PVE::Diskmanage::udevadm_trigger($dev);
-
- if ($param->{add_storage}) {
- PVE::API2::Storage::Config->create_or_update(
- $name, $node, $storage_params, $verify_params,
- );
- }
- });
+ $san ? $create_group->() : PVE::Diskmanage::locked_disk_action($create_group);
};
return $rpcenv->fork_worker('lvmcreate', $name, $user, $worker);
diff --git a/src/PVE/Diskmanage.pm b/src/PVE/Diskmanage.pm
index c2c50bcc..29669a28 100644
--- a/src/PVE/Diskmanage.pm
+++ b/src/PVE/Diskmanage.pm
@@ -1165,6 +1165,51 @@ sub change_parttype {
run_command(['sgdisk', "-t${partnum}:${parttype}", $blockdev], errmsg => $err);
}
+# Returns the PID and command name of a process for each of the block devices that a process has
+# open, as hash by the resolved path of the device. With 'writable', a process that opened the
+# device only for reading does not count. Only detects an open through the device nodes in /dev
+# of the host, not one through the device node that a container has of its own.
+sub device_openers {
+ my ($devices, %param) = @_;
+
+ # the device number tells a device from a file of that name in another mount namespace
+ my %nodes;
+ for my $path (grep { defined($_) } map { abs_path($_) } @$devices) {
+ my $st = stat($path) // next;
+ $nodes{$path} = $st->rdev;
+ }
+ my $openers = {};
+ return $openers if !%nodes;
+
+ opendir(my $proc, '/proc') or return $openers;
+ for my $pid (grep { m/^\d+$/ && $_ != $$ } readdir($proc)) {
+ opendir(my $fds, "/proc/$pid/fd") or next;
+ for my $fd (readdir($fds)) {
+ my $target = readlink("/proc/$pid/fd/$fd") // next;
+ next if !defined($nodes{$target}) || $openers->{$target};
+ my $st = stat("/proc/$pid/fd/$fd") // next;
+ next if $st->rdev != $nodes{$target};
+ if ($param{writable}) {
+ # the permissions of the link are the access mode of the open file
+ my $link = lstat("/proc/$pid/fd/$fd") // next;
+ next if !($link->mode & S_IWUSR);
+ }
+ my $comm = file_read_firstline("/proc/$pid/comm") // 'unknown';
+ $openers->{$target} = { pid => $pid, command => $comm };
+ }
+ }
+ return $openers;
+}
+
+# Returns the PID and command name of a process that has one of the block devices open, if any.
+sub device_opener {
+ my (@devices) = @_;
+
+ my $openers = device_openers(\@devices);
+ my ($opener) = map { $openers->{$_} } sort keys %$openers;
+ return $opener ? "$opener->{pid} ($opener->{command})" : undef;
+}
+
# Wipes all labels and the first 200 MiB of a disk/partition (or the whole if it is smaller).
# If called with a partition, also sets the partition type to 0x83 'Linux filesystem'.
# Expected to be called with a result of verify_blockdev_path().
diff --git a/src/PVE/Storage/LVMPlugin.pm b/src/PVE/Storage/LVMPlugin.pm
index 789a1079..ca82ba98 100644
--- a/src/PVE/Storage/LVMPlugin.pm
+++ b/src/PVE/Storage/LVMPlugin.pm
@@ -162,6 +162,37 @@ sub cached_pv_volume_groups {
return $res;
}
+sub lun_volume_groups {
+ my ($devices) = @_;
+ my $output = '';
+ run_command(
+ [
+ '/sbin/pvs',
+ '--nohints',
+ '--readonly',
+ '--devices',
+ join(',', @$devices),
+ '--reportformat',
+ 'json',
+ '--options',
+ 'pv_name,vg_name',
+ ],
+ timeout => 10,
+ outfunc => sub { $output .= "$_[0]\n" },
+ );
+ my $data = decode_json($output);
+ my $pvs = $data->{report}->[0]->{pv};
+ die "unable to inspect volume groups - invalid pvs report\n" if ref($pvs) ne 'ARRAY';
+ my %vgs;
+ for my $pv (@$pvs) {
+ my $vg = $pv->{vg_name};
+ die "unable to inspect volume groups - missing volume group metadata\n"
+ if !defined($vg) || $vg eq '[unknown]';
+ $vgs{$vg} = 1 if length($vg);
+ }
+ return [sort keys %vgs];
+}
+
sub clear_first_sector {
my ($dev) = shift;
@@ -172,10 +203,17 @@ sub clear_first_sector {
}
}
-sub lvm_create_volume_group {
- my ($device, $vgname, $shared, $guard) = @_;
-
+my sub create_volume_group {
+ my ($device, $vgname, $lun, $guard) = @_;
$device = PVE::Diskmanage::verify_blockdev_path($device);
+ my $fh;
+ if ($lun) {
+ sysopen($fh, $lun->{'by-id'}, O_RDWR) or die "cannot open '$device' - $!\n";
+ }
+ my $check_name = sub {
+ PVE::Storage::SAN::assert_same_device($lun, $fh, $device) if $lun;
+ };
+ $check_name->();
my $refuse_data = sub {
my (@types) = @_;
die "device '$device' contains data ("
@@ -193,7 +231,8 @@ sub lvm_create_volume_group {
if !defined($size) || $size !~ m/^\d+$/ || !$size;
die "unable to probe '$device' - missing device mapper identity\n"
if basename($device) =~ m/^dm-\d+$/ && !defined($uuid);
- if (defined($uuid) && $uuid =~ m/^mpath-/) {
+ my $map = PVE::Multipath::parse_dm_uuid($uuid);
+ if ($map && !$map->{partition}) {
# A queueing map without a running path can stall even a read-only probe.
my $running = 0;
PVE::Tools::dir_glob_foreach(
@@ -220,6 +259,8 @@ sub lvm_create_volume_group {
}
my %signatures = map { $_->{type} => 1 } $probe->@*;
my $res = lvm_pv_info($device, $signatures{LVM2_member});
+ # also a volume group that exists already only counts if the probes looked at the held LUN
+ $check_name->();
# A PV without metadata copies can belong to a VG whose other devices are not visible. The
# sentinel is not a VG name or orphan proof, even if the use flag contradicts it.
@@ -262,26 +303,52 @@ sub lvm_create_volume_group {
}
$refuse_data->(keys %signatures) if %signatures;
+ # Only initializing the device needs the checks, an existing volume group on it can be added.
$guard->{check_storage}->($device) if $guard && $guard->{check_storage};
- clear_first_sector($device); # else pvcreate fails
+ if ($lun) {
+ my $exempt = $guard ? $guard->{exempt} : undef;
+ PVE::Storage::SAN::assert_lun_unreferenced(PVE::Storage::config(), $lun, $exempt);
+ PVE::Storage::SAN::assert_lun_paths_unused($lun);
+ # a guest with the LUN as disk has it open, without being a holder or a storage reference
+ my $opener = PVE::Diskmanage::device_opener($device);
+ die "cannot create volume group on '$device' - process $opener has it open\n"
+ if defined($opener);
+ }
+
+ $check_name->();
+ clear_first_sector($lun ? '/proc/' . $$ . '/fd/' . fileno($fh) : $device);
# we use --metadatasize 250k, which reseults in "pe_start = 512"
# so pe_start is aligned on a 128k boundary (advantage for SSDs)
my $cmd = ['/sbin/pvcreate', '--metadatasize', '250k', $device];
- run_command($cmd, errmsg => "pvcreate '$device' error");
+ $check_name->();
+ run_command($cmd, errmsg => "pvcreate '$device' error", $lun ? (timeout => 30) : ());
$cmd = ['/sbin/vgcreate', $vgname, $device];
# push @$cmd, '-c', 'y' if $shared; # we do not use this yet
+ $check_name->();
run_command(
$cmd,
+ $lun ? (timeout => 30) : (),
errmsg => "vgcreate $vgname $device error",
errfunc => $ignore_no_medium_warnings,
outfunc => $ignore_no_medium_warnings,
);
}
+sub lvm_create_volume_group {
+ my ($device, $vgname, $shared, $guard) = @_;
+ require PVE::Storage::SAN;
+ my $lun = PVE::Storage::SAN::lun_for_device($device);
+ return create_volume_group($device, $vgname, undef, $guard) if !$lun;
+ PVE::Storage::SAN::with_lun_lock(
+ $lun,
+ sub { create_volume_group($device, $vgname, $lun, $guard) },
+ );
+}
+
sub lvm_destroy_volume_group {
my ($vgname) = @_;
@@ -1164,7 +1231,7 @@ sub on_add_hook {
$path,
$scfg->{vgname},
$scfg->{shared},
- { check_storage => $check_target },
+ { check_storage => $check_target, exempt => $storeid },
);
}
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index 82fb0e44..8d559d4f 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -5,6 +5,7 @@ use v5.36;
use Cwd qw(abs_path);
use File::Basename qw(basename);
+use PVE::Cluster;
use PVE::INotify;
use PVE::Tools qw(file_read_firstline dir_glob_foreach);
@@ -231,4 +232,157 @@ sub is_san_device($device, $info = undef) {
|| PVE::Diskmanage::is_remote_transport($info->{transport}) ? 1 : 0;
}
+sub lun_for_device($name) {
+ my $device = PVE::Diskmanage::verify_blockdev_path($name);
+ return undef if !is_san_device($device);
+ my $rows = scan_luns(PVE::Storage::config());
+ # the device behind a name such as a by-id one can pass to another LUN during the scan
+ die "cannot use '$device' - the device behind '$name' changed\n"
+ if (abs_path($name) // '') ne $device;
+ for my $lun (@$rows) {
+ next if (abs_path($lun->{devpath}) // '') ne $device;
+ die "cannot use '$device' - no link under /dev/disk/by-id names the WWID of the LUN\n"
+ if !$lun->{'by-id'};
+ # read from sysfs, but used in command lines and in the name of the cluster lock
+ ($lun->{devpath}) = $lun->{devpath} =~ m{\A(/dev/[A-Za-z0-9_.:+/-]+)\z}
+ or die "cannot use '$device' - unexpected device path\n";
+ ($lun->{wwid}) = $lun->{wwid} =~ m/\A([A-Za-z0-9_.:+=-]+)\z/
+ or die "cannot use '$device' - unexpected WWID\n";
+ return $lun;
+ }
+ die "cannot use '$device' - select an identified LUN or its multipath map\n";
+}
+
+sub lun_partitions($lun) {
+ my $device = PVE::Diskmanage::verify_blockdev_path($lun->{devpath});
+ my $name = basename($device);
+ my @parts;
+ dir_glob_foreach(
+ "/sys/class/block/$name",
+ "\Q$name\E.+",
+ sub($part, @) {
+ my ($path) = "/dev/$part" =~ m{\A(/dev/[A-Za-z0-9_.+-]+)\z};
+ push @parts, $path if defined($path) && -e "/sys/class/block/$name/$part/partition";
+ },
+ );
+ dir_glob_foreach(
+ "/sys/class/block/$name/holders",
+ 'dm-\\d+',
+ sub($part, @) {
+ my $map = PVE::Multipath::parse_dm_uuid(
+ file_read_firstline("/sys/class/block/$part/dm/uuid"));
+ my ($path) = "/dev/$part" =~ m{\A(/dev/dm-\d+)\z};
+ push @parts, $path
+ if defined($path) && $map && $map->{partition} && $map->{wwid} eq $lun->{wwid};
+ },
+ );
+ return \@parts;
+}
+
+sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
+ [$lun->{devpath}, lun_partitions($lun)->@*],
+ )->@*;
+ # the paths of a LUN can belong to more than one target
+ my $sessions = PVE::ISCSI::Topology::device_map();
+ my %targets =
+ map { $_->{target} => 1 } map { $sessions->{ basename($_) } // () } lun_paths($lun)->@*;
+ $targets{ $lun->{'iscsi-target'} } = 1 if defined($lun->{'iscsi-target'});
+ for my $sid (sort keys $cfg->{ids}->%*) {
+ next if defined($exempt) && $sid eq $exempt;
+ my $scfg = $cfg->{ids}->{$sid};
+ my $type = $scfg->{type};
+ if ($vgs{ $scfg->{vgname} // '' }) {
+ die "cannot use '$lun->{devpath}' - volume group is used by storage '$sid'\n";
+ }
+ if (
+ defined($scfg->{target})
+ && $targets{ $scfg->{target} }
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
+ }
+ next if $type ne 'lvm' || !$scfg->{base};
+ my $wwid = base_wwid($scfg);
+ my $matches = defined($wwid) && $wwid eq $lun->{wwid};
+ if (!$matches) {
+ my $path = eval { abs_path(PVE::Storage::path($cfg, $scfg->{base})) };
+ my $device = abs_path($lun->{devpath});
+ $matches = defined($path) && defined($device) && $path eq $device;
+ }
+ die "cannot use '$lun->{devpath}' - storage '$sid' uses this LUN as its base volume\n"
+ if $matches;
+ }
+ return;
+}
+
+# Serializes writes to a LUN cluster-wide. The storage configuration read in the code is current.
+sub with_lun_lock($lun, $code) {
+ my $key = $lun->{wwid} =~ s/([^A-Za-z0-9_.:-])/sprintf('=%02x', ord($1))/ger;
+ PVE::Cluster::cfs_lock_domain("san-$key", undef, $code);
+ die $@ if $@;
+}
+
+# Device names can pass to another device while a LUN waits for its lock or is worked on. All
+# names used for it have to mean the device that is held open.
+sub assert_same_device($lun, $fh, @names) {
+ my @held = stat($fh);
+ for my $name ($lun->{'by-id'}, $lun->{devpath}, @names) {
+ my @named = stat($name);
+ die "cannot use '$lun->{devpath}' - the device behind '$name' changed\n"
+ if !@held || !@named || $held[6] != $named[6];
+ }
+}
+
+sub lun_paths($lun) {
+ my $paths = PVE::Multipath::Identity::collect(all => 1)->{paths};
+ my %names = map { $_ => 1 } grep { $paths->{$_}->{wwid} eq $lun->{wwid} } keys %$paths;
+ my $device = basename(abs_path($lun->{devpath}) // $lun->{devpath});
+ dir_glob_foreach(
+ "/sys/class/block/$device/slaves",
+ 'sd[a-z]+',
+ sub($slave, @) { $names{$slave} = 1 },
+ );
+ return [map { m/^(sd[a-z]+)$/ ? "/dev/$1" : () } sort keys %names];
+}
+
+# The other paths of a LUN reach the same data, but neither the exclusive open of the LUN nor the
+# checks of its device cover them.
+sub assert_lun_paths_unused($lun) {
+ my $device = basename(abs_path($lun->{devpath}) // $lun->{devpath});
+ my %devices; # the paths and their partitions
+ for my $path (grep { basename($_) ne $device } lun_paths($lun)->@*) {
+ if (my $mounted = PVE::Diskmanage::is_mounted($path)) {
+ die "cannot use '$lun->{devpath}' - the LUN is mounted through '$mounted'\n";
+ }
+ my $name = basename($path);
+ $devices{$path} = 1;
+ dir_glob_foreach(
+ "/sys/class/block/$name",
+ "\Q$name\E\\d+",
+ sub($part, @) {
+ $devices{"/dev/$part"} = 1;
+ },
+ );
+ }
+ for my $path (sort keys %devices) {
+ dir_glob_foreach(
+ '/sys/class/block/' . basename($path) . '/holders',
+ '[^.].*',
+ sub($holder, @) {
+ if ($holder ne $device) {
+ die "cannot use '$lun->{devpath}' - another block device uses the LUN"
+ . " through '$path'\n";
+ }
+ },
+ );
+ }
+ my $openers = PVE::Diskmanage::device_openers([sort keys %devices], writable => 1);
+ for my $path (sort keys %$openers) {
+ my $opener = $openers->{$path};
+ die "cannot use '$lun->{devpath}' - process $opener->{pid} ($opener->{command}) has the"
+ . " LUN open through '$path'\n";
+ }
+}
+
1;
diff --git a/src/test/Makefile b/src/test/Makefile
index 2f6f4cd7..0d866d91 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_sensitive_properties test_import_stream test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api
+test: test_iscsi test_zfspoolplugin test_lvmplugin test_lvm_create test_lvm_lock_retry test_lvm_base_volume test_lvm_hints test_disklist test_bwlimit test_plugin test_ovf test_volume_access test_remote_command test_sensitive_properties test_import_stream test_multipath test_san_libraries test_lun_identity test_lvm_base_activation test_multipath_api test_san_taint test_san_lun_scan test_san_api test_disk_api
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
@@ -9,9 +9,10 @@ test_lvmplugin: run_test_lvmplugin.pl run_test_lvm_throughput.pl
./run_test_lvmplugin.pl
./run_test_lvm_throughput.pl
-test_lvm_create: run_test_lvm_create.pl run_test_lvm_base_conflicts.pl
+test_lvm_create: run_test_lvm_create.pl run_test_lvm_base_conflicts.pl run_san_write_check_tests.pl
./run_test_lvm_create.pl
./run_test_lvm_base_conflicts.pl
+ ./run_san_write_check_tests.pl
test_lvm_lock_retry: run_test_lvm_lock_retry.pl
./run_test_lvm_lock_retry.pl
@@ -75,5 +76,9 @@ test_san_taint: run_san_taint_tests.pl
test_san_lun_scan: run_san_lun_scan_tests.pl
./run_san_lun_scan_tests.pl
-test_san_api: run_san_api_tests.pl
+test_san_api: run_san_api_tests.pl run_san_nvme_tests.pl
./run_san_api_tests.pl
+ ./run_san_nvme_tests.pl
+
+test_disk_api: run_disk_api_tests.pl
+ ./run_disk_api_tests.pl
diff --git a/src/test/disk_api_test.pm b/src/test/disk_api_test.pm
new file mode 100644
index 00000000..474ad663
--- /dev/null
+++ b/src/test/disk_api_test.pm
@@ -0,0 +1,247 @@
+package PVE::API2::Disks::Test;
+
+use v5.36;
+
+use lib qw(..);
+
+use PVE::API2::Disks;
+use PVE::API2::Disks::LVM;
+use PVE::Diskmanage;
+use PVE::Storage;
+use PVE::Storage::LVMPlugin;
+
+use Test::MockModule;
+use Test::More;
+
+my @transport_cases = (
+ ['none', undef],
+ ['unknown', 'unknown'],
+ ['ata', 'ata'],
+ ['sata', 'sata'],
+ ['sas', 'sas'],
+ ['spi', 'spi'],
+ ['sbp', 'sbp'],
+ ['usb', 'usb'],
+ ['fc', 'fc'],
+ ['fcoe', 'fcoe'],
+ ['iscsi', 'iscsi'],
+ ['nvme', 'nvme'],
+ ['virtio', 'virtio'],
+ ['nvme-fc', 'nvme-fc'],
+ ['nvme-tcp', 'nvme-tcp'],
+ ['nvme-rdma', 'nvme-rdma'],
+ ['nvme-loop', 'nvme-loop'],
+);
+
+my $disks = {};
+my @all;
+for my $case (@transport_cases) {
+ my ($name, $transport) = $case->@*;
+ my $devpath = "/dev/test-$name";
+ my $entry = {
+ devpath => $devpath,
+ gpt => 0,
+ osdid => -1,
+ };
+ $entry->{transport} = $transport if defined($transport);
+ $disks->{$name} = $entry;
+ push @all, $devpath;
+}
+
+my $diskmanage_module = Test::MockModule->new('PVE::Diskmanage', no_auto => 1);
+$diskmanage_module->mock('get_disks' => sub { return $disks });
+
+my $list_handler = PVE::API2::Disks->map_method_by_name('list')->{code};
+my $list_devpaths = sub($param) {
+ my $result = $list_handler->({ node => 'test-node', skipsmart => 1, $param->%* });
+ return [sort map { $_->{devpath} } $result->@*];
+};
+
+is_deeply(
+ $list_devpaths->({}), [sort @all], 'the disk list uses the default disk inventory',
+);
+
+is_deeply(
+ $list_devpaths->({ type => 'unused' }),
+ [sort @all],
+ 'unused disk selection preserves transport visibility',
+);
+
+$diskmanage_module->mock(
+ 'get_disks' => sub {
+ return {
+ 'fc-disk' => {
+ devpath => '/dev/fc-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'fc',
+ },
+ 'fc-partition' => {
+ devpath => '/dev/fc-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/fc-disk',
+ },
+ 'loop-disk' => {
+ devpath => '/dev/loop-disk',
+ gpt => 0,
+ osdid => -1,
+ transport => 'nvme-loop',
+ },
+ 'loop-partition' => {
+ devpath => '/dev/loop-disk1',
+ gpt => 0,
+ osdid => -1,
+ parent => '/dev/loop-disk',
+ },
+ };
+ },
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1 }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'the plain list keeps FC disks and their partitions',
+);
+
+is_deeply(
+ $list_devpaths->({ 'include-partitions' => 1, type => 'unused' }),
+ ['/dev/fc-disk', '/dev/fc-disk1', '/dev/loop-disk', '/dev/loop-disk1'],
+ 'unused partitions preserve transport visibility',
+);
+
+subtest 'volume group creation leaves SAN locking to the LVM helper' => sub {
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $disk = $diskmanage_module;
+ my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+ my $rpc = Test::MockModule->new('PVE::RPCEnvironment');
+ my (@stack, @created);
+ my $lock = sub($name, $code) {
+ push @stack, $name;
+ my $res = eval { $code->() };
+ my $err = $@;
+ pop @stack;
+ die $err if $err;
+ return $res;
+ };
+ $storage->mock(lock_storage_config => sub { $lock->('storage.cfg', $_[0]) });
+ $disk->mock(locked_disk_action => sub { $lock->('disk', $_[0]) });
+ $disk->mock(verify_blockdev_path => sub { $_[0] });
+ $disk->mock(assert_disk_unused => sub { });
+ $disk->mock(is_partition => sub { 0 });
+ $disk->mock(udevadm_trigger => sub { });
+ $lvm->mock(lvm_vgs => sub { {} });
+ $lvm->mock(
+ lvm_create_volume_group => sub {
+ is(scalar(@_), 3, 'disk API does not exempt a storage');
+ push @created, [$_[0], join('>', @stack)];
+ },
+ );
+ {
+
+ package MultipathTestRPC;
+ sub get_user { 'root@pam' }
+ sub check { 1 }
+ sub fork_worker { $_[4]->(); return 'test-upid' }
+ }
+ $rpc->mock(get => sub { bless {}, 'MultipathTestRPC' });
+
+ my ($is_map, $is_san) = (1, 0);
+ my $san = Test::MockModule->new('PVE::Storage::SAN');
+ $san->mock(is_san_device => sub { $is_map || $is_san });
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg1', device => '/dev/dm-3' });
+ ($is_map, $is_san) = (0, 1);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg2', device => '/dev/sdc' });
+ ($is_map, $is_san) = (0, 0);
+ PVE::API2::Disks::LVM->create({ node => 'n1', name => 'vg3', device => '/dev/sdb' });
+ is_deeply(
+ \@created,
+ [
+ ['/dev/dm-3', ''], ['/dev/sdc', ''], ['/dev/sdb', 'disk'],
+ ],
+ 'SAN writes use no local disk or storage configuration lock',
+ );
+ my $config_api = Test::MockModule->new('PVE::API2::Storage::Config');
+ my (@params, @registered);
+ $config_api->mock(
+ create_or_update => sub {
+ push @registered, $_[5] ? 'check' : 'create or update';
+ push @params, $_[3];
+ },
+ create => sub {
+ push @registered, 'create';
+ push @params, $_[1];
+ },
+ );
+ my $cfg =
+ { ids => { other => { type => 'lvm', vgname => 'other', nodes => { n2 => 1 } } } };
+ $storage->mock(config => sub { $cfg });
+ $is_san = 1;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg4',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 1, 'SAN storage is shared');
+ ok(!exists($params[-1]->{nodes}), 'SAN storage covers all nodes');
+ is_deeply(
+ \@registered,
+ ['check', 'create'],
+ 'and only gets created: it never joins a storage added in the meantime',
+ );
+ @registered = ();
+ @created = ();
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'other',
+ device => '/dev/sdc',
+ add_storage => 1,
+ });
+ };
+ like($@, qr/already defined/, 'SAN volume group does not join the storage of another node');
+ is_deeply(\@created, [], 'existing storage ID prevents initialization');
+ $is_san = 0;
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg5',
+ device => '/dev/sdb',
+ add_storage => 1,
+ });
+ is($params[-1]->{shared}, 0, 'local storage is not shared');
+ is($params[-1]->{nodes}, 'n1', 'local storage remains node-restricted');
+ is_deeply(\@registered, ['check', 'create or update'], 'and may join one of its name');
+ @created = ();
+ $disk->mock(assert_disk_unused => sub { die "device is already in use\n" });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like($@, qr/already in use/, 'disk API rejects a used inventory entry');
+ is_deeply(\@created, [], 'used inventory prevents initialization');
+ $disk->mock(assert_disk_unused => sub { });
+ $lvm->mock(lvm_vgs => sub { { vg => {} } });
+ eval {
+ PVE::API2::Disks::LVM->create({
+ node => 'n1',
+ name => 'vg',
+ device => '/dev/sdc',
+ });
+ };
+ like(
+ $@,
+ qr/volume group with name 'vg' already exists/,
+ 'stale inventory does not permit an existing VG',
+ );
+ is_deeply(\@created, [], 'existing VG prevents initialization');
+ my @mocked = qw(
+ locked_disk_action verify_blockdev_path assert_disk_unused is_partition udevadm_trigger
+ );
+ $disk->unmock($_) for @mocked;
+};
+
+done_testing();
diff --git a/src/test/run_disk_api_tests.pl b/src/test/run_disk_api_tests.pl
new file mode 100755
index 00000000..75fc98c6
--- /dev/null
+++ b/src/test/run_disk_api_tests.pl
@@ -0,0 +1,11 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use TAP::Harness;
+
+my $harness = TAP::Harness->new({ verbosity => -2 });
+my $res = $harness->runtests("disk_api_test.pm");
+
+exit -1 if !$res || $res->{failed} || $res->{parse_errors};
diff --git a/src/test/run_san_library_tests.pl b/src/test/run_san_library_tests.pl
index 9fb7c8b4..d17dd111 100755
--- a/src/test/run_san_library_tests.pl
+++ b/src/test/run_san_library_tests.pl
@@ -105,4 +105,31 @@ subtest 'LVM hints are optional cached display metadata' => sub {
}
};
+subtest 'the names of a held LUN have to mean the held device' => sub {
+ require PVE::Storage::SAN;
+ open(my $fh, '<', '/dev/null') or die "cannot open /dev/null - $!\n";
+ my $lun = { 'by-id' => '/dev/null', devpath => '/dev/null' };
+ my $check = sub {
+ eval { PVE::Storage::SAN::assert_same_device(@_) };
+ return $@;
+ };
+ is($check->($lun, $fh, '/dev/null'), '', 'same device behind all names');
+ like(
+ $check->({ %$lun, 'by-id' => '/dev/zero' }, $fh),
+ qr/'\/dev\/zero' changed/,
+ 'by-id name',
+ );
+ like(
+ $check->({ %$lun, devpath => '/dev/zero' }, $fh),
+ qr/'\/dev\/zero' changed/,
+ 'device path',
+ );
+ like(
+ $check->($lun, $fh, '/dev/zero'),
+ qr/'\/dev\/zero' changed/,
+ 'name used for the commands',
+ );
+ like($check->($lun, $fh, '/dev/gone'), qr/'\/dev\/gone' changed/, 'name without a device');
+};
+
done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
new file mode 100755
index 00000000..7b963211
--- /dev/null
+++ b/src/test/run_san_nvme_tests.pl
@@ -0,0 +1,106 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+our ($backing, @opens);
+
+BEGIN {
+ *CORE::GLOBAL::sysopen = sub (*$$;$) {
+ push @opens, $_[1];
+ my $path = $_[1] =~ m{^/dev/disk/by-id/nvme-} ? $backing : $_[1];
+ return CORE::sysopen($_[0], $path, $_[2]);
+ };
+}
+use lib qw(..);
+use File::Temp qw(tempfile);
+use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
+
+my ($fh, $file) = tempfile('san-nvme-XXXX', DIR => '.', UNLINK => 1);
+close($fh);
+$backing = $file;
+my $device = '/dev/nvme0n1';
+my $link = '/dev/disk/by-id/nvme-eui.0123456789abcdef';
+my $lun =
+ { devpath => $device, 'by-id' => $link, wwid => 'eui.0123456789abcdef', multipath => 'native' };
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $mp = Test::MockModule->new('PVE::Multipath');
+my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $cfg = { ids => {} };
+my @order;
+$storage->mock(config => sub { $cfg });
+$disk->mock(verify_blockdev_path => sub { $device });
+$disk->mock(is_partition => sub { 0 });
+$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(is_iscsi_device => sub { 0 });
+$disk->mock(is_mounted => sub { 0 });
+$disk->mock(has_holder => sub { 0 });
+$disk->mock(device_opener => sub { undef });
+$mp->mock(device_map => sub { undef });
+$san->mock(abs_path => sub { $device });
+$san->mock(scan_luns => sub { [$lun] });
+$san->mock(lun_partitions => sub { [] });
+$san->mock(assert_same_device => sub { ok(defined(fileno($_[1])), 'held descriptor checked') });
+$lvm->mock(lun_volume_groups => sub { push @order, 'check'; [] });
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-eui.0123456789abcdef', 'native namespace uses the LUN lock');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+is(PVE::Storage::SAN::stable_path($device, $lun->{wwid}), $link, 'native stable path');
+is_deeply(PVE::Storage::SAN::lun_for_device($link), $lun, 'native row selected for writes');
+my $model_link = '/dev/disk/by-id/nvme-NetApp_ONTAP_Controller_81Mkq_1';
+is_deeply(PVE::Storage::SAN::lun_for_device($model_link), $lun, 'any name of the namespace');
+{
+ # the name passes to another device while the LUNs are scanned
+ my $scanned = 0;
+ $san->mock(scan_luns => sub { $scanned = 1; [$lun] });
+ $san->mock(abs_path => sub { $_[0] eq $model_link && $scanned ? '/dev/nvme9n1' : $device });
+ eval { PVE::Storage::SAN::lun_for_device($model_link) };
+ like($@, qr/the device behind '\Q$model_link\E' changed/, 'a name that changed refuses');
+ $san->mock(scan_luns => sub { [$lun] });
+ $san->mock(abs_path => sub { $device });
+}
+$disk->mock(is_partition => sub { 1 });
+is(PVE::Storage::SAN::lun_for_device($link), undef, 'a partition is handled as a local device');
+$disk->mock(is_partition => sub { 0 });
+for my $base (qw(fabric nvme-fabric)) {
+ $cfg->{ids}->{data} = { type => 'lvm', base => "$base:nvme-eui.0123456789abcdef" };
+ eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+ like($@, qr/base volume/, "native base reference on storage '$base' refuses");
+}
+$cfg->{ids} = {};
+@order = @opens = ();
+$lvm->mock(file_read_firstline => sub { $_[0] =~ m{/size$} ? 1024 : undef });
+$lvm->mock(lvm_pv_info => sub { undef });
+$lvm->mock(
+ clear_first_sector => sub { push @order, 'clear'; ok(-e $_[0], 'VG clear uses held fd') });
+$lvm->mock(
+ run_command => sub {
+ my ($cmd, %opts) = @_;
+ if ($cmd->[0] eq 'wipefs') {
+ $opts{outfunc}->('{"signatures":[]}');
+ } else {
+ is($cmd->[-1], $device, 'VG command uses the checked device');
+ push @order, $cmd->[0];
+ }
+ },
+);
+PVE::Storage::LVMPlugin::lvm_create_volume_group($link, 'data', 1);
+is_deeply(
+ \@order,
+ [qw(lock check clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'native VG sequencing',
+);
+is_deeply(\@opens, [$link], 'VG creation holds the native by-id device');
+
+done_testing();
diff --git a/src/test/run_san_taint_tests.pl b/src/test/run_san_taint_tests.pl
index 35b11cd7..0ccd9e2f 100755
--- a/src/test/run_san_taint_tests.pl
+++ b/src/test/run_san_taint_tests.pl
@@ -31,4 +31,30 @@ for my $bad ('-bad', '1:2', '../dev', "3600a\n") {
like($@, qr/invalid WWID/, 'ambiguous identity refused');
}
+# the LUN that write operations get must be usable in command lines and lock names
+use PVE::Storage::SAN;
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+my $tainted_dev = PVE::Tools::file_get_contents('/proc/self/comm') =~ s/.*//sr . '/dev/null';
+ok(tainted($tainted_dev), 'device path derived from a file is tainted');
+$san->mock(
+ is_san_device => sub { 1 },
+ scan_luns => sub {
+ return [{
+ devpath => $tainted_dev,
+ wwid => $wwid,
+ 'by-id' => '/dev/null',
+ usage => 'unused',
+ multipath => 'none',
+ }];
+ },
+);
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(verify_blockdev_path => sub { '/dev/null' });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+my $lun = PVE::Storage::SAN::lun_for_device('/dev/null');
+ok(!tainted($lun->{devpath}), 'LUN device path is untainted');
+ok(!tainted($lun->{wwid}), 'LUN WWID is untainted');
+is($lun->{wwid}, '3600a', 'LUN WWID is unchanged');
+
done_testing();
diff --git a/src/test/run_san_write_check_tests.pl b/src/test/run_san_write_check_tests.pl
new file mode 100755
index 00000000..acd199a2
--- /dev/null
+++ b/src/test/run_san_write_check_tests.pl
@@ -0,0 +1,219 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use lib qw(..);
+use Test::More;
+use Test::MockModule;
+use PVE::Storage::SAN;
+
+my $scan = Test::MockModule->new('PVE::Storage::SAN');
+my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
+my $storage = Test::MockModule->new('PVE::Storage');
+my $cluster = Test::MockModule->new('PVE::Cluster');
+my $lun = { wwid => '3600+abc', devpath => '/dev/dm-0', 'iscsi-target' => 'iqn.test' };
+# the LUN is exported through two targets, its row names only the first
+my $identity = Test::MockModule->new('PVE::Multipath::Identity');
+my $paths = sub {
+ {
+ paths => {
+ sdb => { wwid => '3600+abc', target => 'iqn.test' },
+ sdc => { wwid => '3600+abc', target => 'iqn.second' },
+ sdd => { wwid => '3600+other', target => 'iqn.other' },
+ },
+ };
+};
+$identity->mock(collect => $paths);
+my %sessions = (sdb => 'iqn.test', sdc => 'iqn.second', sdd => 'iqn.other');
+my $topology = Test::MockModule->new('PVE::ISCSI::Topology');
+$topology->mock(
+ device_map => sub {
+ return { map { $_ => { target => $sessions{$_} } } keys %sessions };
+ },
+);
+my @slaves;
+$scan->mock(dir_glob_foreach => sub { $_[2]->($_) for $_[0] =~ m{/dm-0/slaves$} ? @slaves : () });
+my $vgs = [];
+$scan->mock(lun_partitions => sub { [] });
+$lvm->mock(lun_volume_groups => sub { $vgs });
+$lvm->mock(cached_pv_volume_groups => sub { die "write check must not use cached PV metadata\n" });
+my $cfg = { ids => {} };
+$storage->mock(config => sub { $cfg });
+my $check = sub {
+ eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun, @_) };
+ return $@;
+};
+is($check->(), '', 'unreferenced LUN accepted');
+for my $type (qw(lvm lvmthin custom)) {
+ $vgs = ['data'];
+ $cfg->{ids} = {
+ data => {
+ type => $type,
+ vgname => 'data',
+ shared => 1,
+ disable => 1,
+ nodes => { other => 1 },
+ },
+ };
+ for my $cached_vg (undef, 'unrelated') {
+ $lun->{vgname} = $cached_vg;
+ $lun->{usage} = 'unused';
+ like($check->(), qr/used by storage 'data'/, "$type refusal ignores display VG and usage");
+ }
+ is($check->('data'), '', 'the storage being added can be exempted');
+}
+delete $lun->{vgname};
+delete $lun->{usage};
+$vgs = [];
+$cfg->{ids} = { direct => { type => 'iscsi', target => 'iqn.test', content => { images => 1 } } };
+like($check->(), qr/storage 'direct' serves images from this target$/, 'direct image use refuses');
+$cfg->{ids}->{direct}->{target} = 'iqn.second';
+like($check->(), qr/storage 'direct' serves images/, 'also through another target of the LUN');
+$cfg->{ids}->{direct}->{target} = 'iqn.other';
+is($check->(), '', 'a target of another LUN is no reference');
+{
+ # multipathd does not answer and udev knows the path by another identity
+ local $lun->{'iscsi-target'} = 'iqn.other';
+ $identity->mock(collect => sub { { paths => {} } });
+ like($check->(), qr/storage 'direct' serves images/, 'the target of the LUN itself counts');
+ $cfg->{ids}->{direct}->{target} = 'iqn.second';
+ is($check->(), '', 'which is the only one known then');
+ @slaves = qw(sdb sdc);
+ like($check->(), qr/storage 'direct' serves images/, 'unless a member of the map has another');
+ @slaves = ();
+ $identity->mock(collect => $paths);
+}
+$cfg->{ids}->{direct}->{target} = 'iqn.test';
+$cfg->{ids}->{direct}->{content} = { none => 1 };
+is($check->(), '', 'connection-only storage permits use');
+
+for my $type (qw(iscsidirect zfs)) {
+ local $cfg->{ids}->{other} = { type => $type, target => 'iqn.test', content => {} };
+ like(
+ $check->(),
+ qr/storage 'other' serves images from this target$/,
+ "$type storage of the target refuses",
+ );
+}
+$cfg->{ids}->{data} = { type => 'lvm', base => 'direct:0.0.1.dm-uuid-mpath-3600+abc' };
+like($check->(), qr/base volume/, 'base reference refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-3600+abc';
+like($check->(), qr/base volume/, 'scsi WWID in base name refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.dm-uuid-part1-mpath-3600+abc';
+like($check->(), qr/base volume/, 'a partition of the map as base refuses');
+$cfg->{ids}->{data}->{base} = 'direct:0.0.1.scsi-legacy';
+$storage->mock(path => sub { '/dev/disk/by-id/legacy' });
+$scan->mock(abs_path => sub { '/dev/dm-0' });
+like($check->(), qr/base volume/, 'resolved alias to the LUN refuses');
+$scan->mock(abs_path => sub { $_[0] eq $lun->{devpath} ? '/dev/dm-0' : '/dev/dm-1' });
+is($check->(), '', 'base on another device is no match');
+$scan->mock(abs_path => sub { undef });
+is($check->(), '', 'unresolvable base is no match');
+$storage->mock(path => sub { die "base unavailable\n" });
+is($check->(), '', 'unavailable base is no match');
+ok(!PVE::Storage::LVMPlugin->can('create_volume_group'), 'creation implementation is lexical');
+$cfg->{ids} = {};
+my @order;
+$cluster->mock(
+ cfs_lock_domain => sub {
+ is($_[0], 'san-3600=2babc', 'lock name escapes unsafe characters without collisions');
+ push @order, 'lock';
+ $_[2]->();
+ push @order, 'unlock';
+ $@ = '';
+ },
+);
+PVE::Storage::SAN::with_lun_lock($lun, sub { push @order, 'write' });
+is_deeply(\@order, [qw(lock write unlock)], 'the code runs under the lock of the LUN');
+
+# volume group creation checks the references only when it has to initialize the LUN
+my $disks = Test::MockModule->new('PVE::Diskmanage');
+$disks->mock(
+ verify_blockdev_path => sub { $_[0] },
+ is_mounted => sub { undef },
+ has_holder => sub { undef },
+ device_opener => sub { undef },
+);
+my ($signatures, $pvinfo) = ('', undef);
+$lun->{'by-id'} = '/dev/null';
+$scan->mock(
+ lun_for_device => sub { $lun },
+ assert_same_device => sub { },
+ assert_lun_unreferenced => sub { push @order, 'check'; die "referenced\n" },
+);
+$lvm->mock(
+ file_read_firstline => sub { $_[0] =~ m{/size$} ? '2048' : undef },
+ lvm_pv_info => sub { $pvinfo },
+ clear_first_sector => sub { push @order, 'clear' },
+ run_command => sub {
+ my ($cmd, %param) = @_;
+ return $param{outfunc}->(qq({"signatures":[$signatures]})) if $cmd->[0] eq 'wipefs';
+ push @order, $cmd->[0];
+ },
+);
+@order = ();
+$signatures = '{"type":"LVM2_member","offset":"0x218"}';
+$pvinfo = { vgname => 'data', in_use => '1' };
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an existing volume group can be added whatever references its LUN');
+is_deeply(\@order, [qw(lock unlock)], 'without reference check or write');
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'other',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/already used by volume group 'data'/, 'another volume group on the LUN refuses');
+@order = ();
+($signatures, $pvinfo) = ('', undef);
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/referenced/, 'initializing a referenced LUN refuses');
+is_deeply(\@order, [qw(lock check)], 'the check precedes the first write');
+$scan->mock(assert_lun_unreferenced =>
+ sub { is($_[2], 'new', 'new storage exempt'); push @order, 'check' });
+$scan->mock(assert_lun_paths_unused => sub { push @order, 'paths'; die "path in use\n" });
+@order = ();
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+like($@, qr/path in use/, 'a LUN that is in use through another path refuses');
+is_deeply(\@order, [qw(lock check paths)], 'before the first write');
+$scan->mock(assert_lun_paths_unused => sub { push @order, 'paths' });
+@order = ();
+eval {
+ PVE::Storage::LVMPlugin::lvm_create_volume_group(
+ '/dev/null',
+ 'data',
+ 1,
+ { exempt => 'new' },
+ );
+};
+is($@, '', 'an unreferenced empty LUN is initialized');
+is_deeply(
+ \@order,
+ [qw(lock check paths clear /sbin/pvcreate /sbin/vgcreate unlock)],
+ 'checked once, then written under the lock',
+);
+
+done_testing();
diff --git a/src/test/run_test_lvm_create.pl b/src/test/run_test_lvm_create.pl
index d4be25b0..13058fe2 100755
--- a/src/test/run_test_lvm_create.pl
+++ b/src/test/run_test_lvm_create.pl
@@ -10,9 +10,12 @@ use Test::More;
use lib ('.', '..');
use PVE::Storage::LVMPlugin;
+use PVE::Storage::SAN;
my $lvm = Test::MockModule->new('PVE::Storage::LVMPlugin');
my $disk = Test::MockModule->new('PVE::Diskmanage');
+my $san = Test::MockModule->new('PVE::Storage::SAN');
+$san->mock(lun_for_device => sub { undef });
my $tools = Test::MockModule->new('PVE::Tools');
my $inotify = Test::MockModule->new('PVE::INotify');
$inotify->mock(nodename => sub { 'testnode' });
@@ -43,6 +46,7 @@ $lvm->mock(
if $_[0] =~ m{/(?:uevent|size)/partition$};
return $partitioned ? '1' : undef if $_[0] =~ m{/partition$};
return $holder_uuid if $_[0] =~ m{/dm-5/dm/uuid$};
+ return 'part1-mpath-3600abc' if $map eq 'partition' && $_[0] =~ m{/uuid$};
return $map ? 'mpath-3600abc' : undef if $_[0] =~ m{/uuid$};
return $running ? 'running' : 'offline' if $_[0] =~ m{/state$};
die "unexpected read $_[0]";
@@ -119,6 +123,10 @@ for my $case (
is_deeply(\@probes, [], "$case->[0]: no device reads");
is_deeply(\@writes, [], "$case->[0]: no writes");
}
+reset_case();
+($map, $running) = ('partition', 0);
+is(create(), '', 'the partition of a map has the map as member, not its paths');
+is(scalar(@writes), 3, 'so it is set up like a local partition');
reset_case();
my $storage_checks = 0;
@@ -170,6 +178,44 @@ like(
qr/contains data \(gpt\)/,
'a partition table of a map is data, kpartx may not map it',
);
+reset_case();
+($signatures, $partitioned) = ([{ type => 'PMBR' }, { type => 'gpt' }], 1);
+$san->mock(
+ lun_for_device =>
+ sub { { wwid => '3600abc', devpath => '/dev/sda', 'by-id' => '/dev/null' } },
+ with_lun_lock => sub { $_[1]->() },
+);
+like(
+ create(),
+ qr{the device behind '/dev/sda' changed},
+ 'a device name that no longer means the held LUN is refused',
+);
+is_deeply(\@writes, [], 'changed device: no writes');
+$san->mock(assert_same_device => sub { });
+like(create(), qr/contains data \(PMBR, gpt\)/, 'a partitioned LUN that is no map is data too');
+is_deeply(\@writes, [], 'partitioned LUN: no writes');
+reset_case();
+my $opener = '4711 (kvm)';
+$disk->mock(device_opener => sub { $opener });
+$san->mock(assert_lun_unreferenced => sub { });
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->mock(config => sub { { ids => {} } });
+like(create(), qr/process 4711 \(kvm\) has it open/, 'a LUN that a process has open is refused');
+is_deeply(\@writes, [], 'open LUN: no writes');
+$opener = undef;
+is(create(), '', 'a LUN that no process has open is initialized');
+is(scalar(@writes), 3, 'unused LUN: initialized');
+reset_case();
+$signatures = [{ type => 'LVM2_member' }];
+$label = '/dev/sda: LVM2 PV';
+$pv = '/dev/sda:1024:test:aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg:1';
+my $checked = 0;
+$san->mock(assert_same_device => sub { die "device changed\n" if ++$checked == 2 });
+like(create(), qr/device changed/, 'an existing volume group only counts on the held LUN');
+$san->unmock('assert_lun_unreferenced');
+$san->unmock('assert_same_device');
+$san->unmock('with_lun_lock');
+$san->mock(lun_for_device => sub { undef });
my $uuid = 'aaaaaa-bbbb-cccc-dddd-eeee-ffff-gggggg';
for my $vg ('test', 'other', 'unknown', '') {
^ permalink raw reply related [relevance 9%]
* [PATCH v3 storage,docs,manager 00/18] NVMe over Fabrics storage
@ 2026-11-22 1:25 10% Thomas Lamprecht
2026-11-22 1:25 18% ` [PATCH v3 storage 02/18] nvmeof: add a storage for NVMe over Fabrics subsystems Thomas Lamprecht
0 siblings, 1 reply; 43+ results
From: Thomas Lamprecht @ 2026-11-22 1:25 UTC (permalink / raw)
To: pve-devel
A storage type for NVMe subsystems over TCP on top of the SAN series
[0] (libpve-storage-perl 9.1.22, pve-manager 9.2.36, pve-docs 9.2.20):
namespaces as base volumes for shared LVM or directly as disk images,
using the kernel's native multipath.
This is v3. Besides review fixes for v2 [2], it follows the SAN rework
on master: the guided setup lives under Datacenter > Storage > Add and
asks for one ID, the node API moved under /nodes/{node}/san, and
pvestatd's path notifications cover namespaces too.
This is a deliberately small first version: TCP only, without
authentication or TLS, relying on the array's host NQN allow-list and
a separate storage network. The kernel handles path failover and
reconnects, while the plugin only connects missing portals and never
disconnects on portal or storage removal; disconnecting a controller
is an explicit per-node action. Two prerequisites from the docs: cloned
nodes need distinct host NQNs before connecting, and all nodes must be
upgraded before adding the first nvmeof storage (older nodes drop
unknown storage types when writing storage.cfg).
What it adds:
- Storage type 'nvmeof' (isolated properties, one storage per
subsystem) connecting configured TCP portals with ctrl_loss_tmo=-1
and a configurable fast-io-fail-tmo (default 120s), exposing
namespaces as nvme-<wwid> volumes.
- LVM support for nvmeof namespaces as base volumes, reusing the SAN
reference checks and per-LUN locking.
- Discovery via /nodes/{node}/scan/nvmeof and 'pvesm scan nvmeof', and
node management via /nodes/{node}/san/nvmeof (host identity,
controller list, and guarded per-controller disconnect refusing the
last usable path of any mounted, held, swap, open, or storage-used
namespace; as in the SAN series, the open-process check misses opens
through another device node).
- Cluster status and path-loss notifications covering nvmeof
namespaces. Status reporting works without multipathd; notifications
still require multipathd to be queryable.
- Web UI: guided 'Shared LVM on NVMe over Fabrics' setup under
Datacenter > Storage > Add (shared with iSCSI), nvmeof storage
dialog with discovery, Node > SAN controller list, and host NQNs in
Datacenter > SAN.
- pvereport host NQN and subsystem output, plus nvme-cli as a
Recommends of libpve-storage-perl.
Changes since v2 [2]:
- Follow the SAN rework: single-ID wizard deriving '<ID>-base', node
selection in the host NQN list, portal suggestions without default
port 4420, early-close cleanup, and /nodes/{node}/san/nvmeof.
- Notify on lost and restored namespace paths in pvestatd.
- Tighten activation and locking: fail only if no controller is live
(reporting per-portal errors) and warn otherwise; cap extra portal
connects at 15s while holding storage.cfg's lock; wait up to 10s for
the node fabrics lock; clear portal cooldowns on storage creation.
- Enforce WWID-based volume names (model/serial by-id links can alias
within a subsystem) and refuse local disk setup on fabric namespace
partitions.
- Harden Disconnect: also refuse the last usable path of swap
namespaces, and pass expected subsystem and portal from the UI to
catch reused controller numbers.
- Skip the NVMe path walk on nodes without nvmeof storages, and add
NVMe-oF info to pvereport.
- Validation and UI fixes: require at least one portal, trim and clear
wizard portals on discovery portal change, ignore empty or stale
scans, skip SMART on NVMe/FC too, leave Add Multipath Entry blank
for namespaces, and parse LVM base volume IDs first (fixing IDs like
'nvme-a').
- Docs: explain upgrading all nodes first, document local-only checks
for unusable controllers, and list nvmeof in the intro and LVM
chapters.
The ZFS over NVMe/TCP plugin on the list [3] brings its own initiator.
Because 'nvmeof' isolates its properties, names do not clash; sharing
connect helpers can follow once both are in.
Packaging: pve-manager needs versioned Depends on libpve-storage-perl
and pve-docs (plus Build-Depends on pve-doc-generator);
libpve-storage-perl should break pve-manager without patch 18.
Testing builds on the v1 [1] and v2 [2] runs on a six-node nested
cluster (dual-portal Linux nvmet and NetApp AFF A20). For v3 on master,
I re-ran both guided setups from Add (new nvmet at 1/1, reused NetApp
at 2/2), cut one NetApp path for a minute and both for 40s under guest
I/O (1/2 and Failed 0/2, storages inactive, I/O requeued cleanly, full
recovery), live-migrated a guest with disks on both storages, and
disconnected controllers via the API on every node. After the final
review fixes, I also verified model/serial by-id refusals, Disconnect
refusals for a mismatched subsystem or in-use LVM namespace, and UI
controller disconnect.
The 15s activation cap, swap and partition refusals, non-NQN subsystem
names, and skipped path walk are covered by unit tests only. Earlier on
v3, storage status reconnected a controller once another process
released the fabrics lock after five seconds.
[0]: https://lore.proxmox.com/pve-devel/20261119194655.3163258-1-t.lamprecht@proxmox.com/
[1]: https://lore.proxmox.com/pve-devel/20261113030541.1591528-1-t.lamprecht@proxmox.com/
[2]: https://lore.proxmox.com/pve-devel/20261118204302.3100813-1-t.lamprecht@proxmox.com/
[3]: https://lore.proxmox.com/pve-devel/20261005002609.571-1-joaquinvarela@neatech.ar/
pve-storage:
Thomas Lamprecht (9):
diskmanage: skip SMART queries for NVMe fabric namespaces
nvmeof: add a storage for NVMe over Fabrics subsystems
lvm: allow a volume group on an NVMe over Fabrics namespace
api: scan: add NVMe over Fabrics discovery
pvesm: add a scan command for NVMe over Fabrics
api: san luns: attribute NVMe namespaces to storage
api: add node-level NVMe over Fabrics status and controller removal
multipath: report the NVMe host NQN of each node
multipath: report NVMe over Fabrics namespaces in the cluster status
ApiChangeLog | 9 +-
debian/control | 1 +
src/PVE/API2/Makefile | 1 +
src/PVE/API2/NVMeOF.pm | 199 +++++++++++
src/PVE/API2/SAN/Cluster.pm | 22 +-
src/PVE/API2/SAN/Node.pm | 17 +-
src/PVE/API2/Storage/Scan.pm | 49 +++
src/PVE/CLI/pvesm.pm | 13 +
src/PVE/Diskmanage.pm | 29 +-
src/PVE/Makefile | 1 +
src/PVE/Multipath/Status.pm | 72 +++-
src/PVE/NVMeOF.pm | 445 +++++++++++++++++++++++
src/PVE/Storage.pm | 2 +
src/PVE/Storage/LVMPlugin.pm | 3 +-
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 266 ++++++++++++++
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SAN.pm | 32 +-
src/test/Makefile | 6 +
src/test/disklist_test.pm | 14 +
src/test/run_multipath_api_tests.pl | 132 ++++++-
src/test/run_nvmeof_api_tests.pl | 207 +++++++++++
src/test/run_nvmeof_taint_tests.pl | 67 ++++
src/test/run_nvmeof_tests.pl | 533 ++++++++++++++++++++++++++++
src/test/run_san_api_tests.pl | 4 +-
src/test/run_san_lun_scan_tests.pl | 41 +++
src/test/run_san_nvme_tests.pl | 33 ++
27 files changed, 2160 insertions(+), 41 deletions(-)
pve-docs:
Thomas Lamprecht (1):
storage: document NVMe over Fabrics storages
pve-gui.adoc | 12 ++-
pve-intro.adoc | 3 +-
pve-storage-lvm.adoc | 10 +-
pve-storage-multipath.adoc | 3 +-
pve-storage-nvmeof.adoc | 189 +++++++++++++++++++++++++++++++++++++
pvesm.adoc | 24 +++--
6 files changed, 222 insertions(+), 19 deletions(-)
pve-manager:
Thomas Lamprecht (8):
report: add the NVMe over Fabrics host NQN and subsystems
ui: storage: add NVMe over Fabrics storage
ui: lvm: offer NVMe over Fabrics storages as base storage
ui: storage: add a guided setup for shared LVM on NVMe over Fabrics
ui: node san: list NVMe over Fabrics controllers
ui: san: show the NVMe host NQN of each node
ui: san: show that a namespace uses native multipath
pvestatd: notify on NVMe over Fabrics namespaces as on multipath maps
PVE/MultipathNotification.pm | 5 +-
PVE/Report.pm | 6 +
PVE/Service/pvestatd.pm | 2 +-
test/MultipathNotification_test.pl | 3 +
www/manager6/Makefile | 4 +-
www/manager6/SANUtils.js | 7 +-
www/manager6/Utils.js | 7 +
www/manager6/dc/SAN.js | 49 +++-
www/manager6/dc/StorageView.js | 23 +-
www/manager6/node/Config.js | 9 +-
www/manager6/node/NVMeOFControllers.js | 152 ++++++++++++
www/manager6/storage/IScsiEdit.js | 5 +-
www/manager6/storage/LVMEdit.js | 12 +-
www/manager6/storage/NVMeOFEdit.js | 150 +++++++++++
www/manager6/storage/wizard/LunSelect.js | 35 ++-
www/manager6/storage/wizard/NodeIdentities.js | 57 +++--
.../storage/wizard/{IScsi.js => Target.js} | 232 +++++++++++++-----
www/manager6/storage/wizard/Wizard.js | 60 +++--
www/manager6/window/SANLunState.js | 38 ++-
19 files changed, 699 insertions(+), 157 deletions(-)
^ permalink raw reply [relevance 10%]
* [PATCH v3 storage 02/18] nvmeof: add a storage for NVMe over Fabrics subsystems
2026-11-22 1:25 10% [PATCH v3 storage,docs,manager 00/18] NVMe over Fabrics storage Thomas Lamprecht
@ 2026-11-22 1:25 18% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-22 1:25 UTC (permalink / raw)
To: pve-devel
NVMe/TCP namespaces need a manual nvme-cli setup on every node so far.
Add a storage type that connects one subsystem through each configured
portal and offers its namespaces as raw volumes. Native NVMe multipath
joins the paths and the kernel reconnects lost ones. Only one storage
may use a subsystem, as the LUN list, the controller list and the node
status attribute a subsystem to one storage.
The activation fails if no usable path exists after connecting the
missing portals, so that adding a storage tells why. As adding a
storage holds the lock of the configuration, it tries no further portal
after 15 seconds once a controller is live, and leaves the rest to the
next activation. A portal that failed is retried after a minute, and
adding a storage forgets those failures. Disk setup refuses namespaces
attached over a fabric, as for iSCSI LUNs, and nvme-cli is only
recommended, as no other storage type needs it.
The plugin isolates its properties, so names like 'portals' belong to
this storage type alone, and a third-party plugin that declares one of
them is still loaded. As the first in-tree plugin that isolates, it
makes the storage API check the parameters for adding and updating a
storage of any type against the options of that type alone. A
third-party plugin then has to list the sensitive properties it uses in
options(), as the API change log says.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
ApiChangeLog | 9 +-
debian/control | 1 +
src/PVE/Diskmanage.pm | 7 +-
src/PVE/Makefile | 1 +
src/PVE/NVMeOF.pm | 271 ++++++++++++++++++
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 266 +++++++++++++++++
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SAN.pm | 13 +
src/test/Makefile | 5 +
src/test/run_nvmeof_taint_tests.pl | 62 ++++
src/test/run_nvmeof_tests.pl | 446 +++++++++++++++++++++++++++++
src/test/run_san_nvme_tests.pl | 16 ++
14 files changed, 1096 insertions(+), 6 deletions(-)
create mode 100644 src/PVE/NVMeOF.pm
create mode 100644 src/PVE/Storage/NVMeOFPlugin.pm
create mode 100755 src/test/run_nvmeof_taint_tests.pl
create mode 100755 src/test/run_nvmeof_tests.pl
diff --git a/ApiChangeLog b/ApiChangeLog
index a51578a1..1816e18a 100644
--- a/ApiChangeLog
+++ b/ApiChangeLog
@@ -101,10 +101,11 @@ Future changes should be documented in here.
declares a property of that name is then not loaded until it renames it, so prefer names that
are specific to the plugin, for example prefixed with its type.
- As soon as one such plugin is installed, the API checks the parameters for adding and updating a
- storage against the options of its type alone, for all storage types. So every plugin has to
- list the sensitive properties that it uses in `options()`.
- Set 'sensitive-properties' in such a plugin, even if empty. Without it, the fallback list of
+ Since the in-tree 'nvmeof' plugin isolates its properties, the API checks the parameters for
+ adding and updating a storage against the options of its type alone, for all storage types,
+ also for plugins of older API versions. So every plugin has to list the sensitive properties
+ that it uses in `options()`.
+ Set 'sensitive-properties' in an isolating plugin, even if empty. Without it, the fallback list of
version 11 also applies to the plugin's own properties of these names.
* Pass the guest identity to backup providers
diff --git a/debian/control b/debian/control
index fdcf8117..b5c2f529 100644
--- a/debian/control
+++ b/debian/control
@@ -55,6 +55,7 @@ Depends: bzip2,
${misc:Depends},
${perl:Depends},
Recommends: multipath-tools,
+ nvme-cli,
pve-esxi-import-tools (>= 0.6.0),
skopeo,
zfsutils-linux (>= 2.4.1-pve2),
diff --git a/src/PVE/Diskmanage.pm b/src/PVE/Diskmanage.pm
index be3fb8fc..21857dc6 100644
--- a/src/PVE/Diskmanage.pm
+++ b/src/PVE/Diskmanage.pm
@@ -107,7 +107,12 @@ sub disk_is_used {
my $disklist = get_disks($dev, 1, 1);
- die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
+ my $entry = $disklist->{$dev};
+ die "'$disk' is not a valid local disk\n" if !defined($entry);
+ # a partition has the transport of its disk
+ my ($parent) = ($entry->{parent} // '') =~ m!^/dev/(.+)$!;
+ my $transport = (defined($parent) ? $disklist->{$parent} : $entry)->{transport} // '';
+ die "'$disk' is not a valid local disk\n" if $transport =~ /^nvme-(?:tcp|rdma|fc)$/;
return 1 if $disklist->{$dev}->{used};
return 0;
diff --git a/src/PVE/Makefile b/src/PVE/Makefile
index 13fecbf8..238eefd4 100644
--- a/src/PVE/Makefile
+++ b/src/PVE/Makefile
@@ -4,6 +4,7 @@
install:
install -D -m 0644 Storage.pm ${DESTDIR}${PERLDIR}/PVE/Storage.pm
install -D -m 0644 Diskmanage.pm ${DESTDIR}${PERLDIR}/PVE/Diskmanage.pm
+ install -D -m 0644 NVMeOF.pm ${DESTDIR}${PERLDIR}/PVE/NVMeOF.pm
install -D -m 0644 ISCSI/Topology.pm ${DESTDIR}${PERLDIR}/PVE/ISCSI/Topology.pm
install -D -m 0644 Multipath.pm ${DESTDIR}${PERLDIR}/PVE/Multipath.pm
install -D -m 0644 Multipath/Config.pm ${DESTDIR}${PERLDIR}/PVE/Multipath/Config.pm
diff --git a/src/PVE/NVMeOF.pm b/src/PVE/NVMeOF.pm
new file mode 100644
index 00000000..45b3acfc
--- /dev/null
+++ b/src/PVE/NVMeOF.pm
@@ -0,0 +1,271 @@
+package PVE::NVMeOF;
+
+use v5.36;
+
+use Digest::SHA qw(sha1_hex);
+use Fcntl qw(:flock F_GETFD F_SETFD FD_CLOEXEC);
+use File::Path qw(make_path);
+use Socket qw(AF_INET AF_INET6 inet_ntop inet_pton);
+use Time::HiRes ();
+
+use PVE::JSONSchema;
+use PVE::Tools qw(dir_glob_foreach file_read_firstline file_set_contents run_command);
+
+use PVE::Diskmanage;
+
+our $NVME = '/usr/sbin/nvme';
+our $SYSFS = '/sys';
+our $HOSTNQN_FILE = '/etc/nvme/hostnqn';
+our $HOSTID_FILE = '/etc/nvme/hostid';
+our $RUN_DIR = '/run/pve/nvmeof';
+our $LOCK_WAIT = 10;
+our $NQN_PATTERN = 'nqn\.[^\s,=]+';
+our $DISCOVERY_NQN = 'nqn.2014-08.org.nvmexpress.discovery';
+
+sub canonical_address($addr) {
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ return inet_ntop(AF_INET, $packed);
+ }
+ if (defined(my $packed = inet_pton(AF_INET6, $addr))) {
+ return inet_ntop(AF_INET, substr($packed, 12))
+ if substr($packed, 0, 12) eq ("\0" x 10) . "\xff\xff";
+ return inet_ntop(AF_INET6, $packed);
+ }
+ return lc($addr);
+}
+
+# Link-local IPv6 needs a node-specific interface and cannot identify a shared configured portal.
+sub parse_portal($portal) {
+ my ($addr, $port);
+ if ($portal =~ m/^\[([0-9a-fA-F:.]+)\](?::([0-9]+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } elsif ($portal =~ m/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(?::([0-9]+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } else {
+ return undef;
+ }
+ return undef if defined($port) && ($port < 1 || $port > 65535);
+ $addr = canonical_address($addr);
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ my $multicast = (unpack('C', $packed) & 0xf0) == 0xe0;
+ return undef if $addr eq '0.0.0.0' || $addr eq '255.255.255.255' || $multicast;
+ } elsif (defined($packed = inet_pton(AF_INET6, $addr))) {
+ my $prefix = unpack('n', $packed);
+ return undef
+ if $addr eq '::' || ($prefix & 0xffc0) == 0xfe80 || ($prefix & 0xff00) == 0xff00;
+ } else {
+ return undef;
+ }
+ return { traddr => $addr, trsvcid => int($port // 4420) };
+}
+
+PVE::JSONSchema::register_format(
+ 'pve-storage-nvme-portal',
+ sub($portal, $noerr = undef) {
+ return $portal if parse_portal($portal);
+ return undef if $noerr;
+ die "value is not an IPv4 address or a bracketed IPv6 address with optional port\n";
+ },
+);
+
+sub format_path($path) {
+ # an IPv6 address, not the address of a Fibre Channel port, which has a colon too
+ my $ipv6 = $path->{traddr} =~ /:/ && $path->{traddr} =~ /^[0-9a-fA-F:.]+$/;
+ my $addr = $ipv6 ? "[$path->{traddr}]" : $path->{traddr};
+ return defined($path->{trsvcid}) ? "$addr:$path->{trsvcid}" : $addr;
+}
+
+sub storage_paths($scfg) {
+ return [map { parse_portal($_) // die "invalid portal '$_'\n" }
+ PVE::Tools::split_list($scfg->{portals})];
+}
+
+sub host_identity() {
+ my ($nqn) = (file_read_firstline($HOSTNQN_FILE) // '') =~ /\A($NQN_PATTERN)\z/;
+ my ($id) = (file_read_firstline($HOSTID_FILE) // '') =~
+ /\A([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\z/i;
+ if (!defined($nqn) || length($nqn) > 223) {
+ die "invalid or missing NVMe host NQN in '$HOSTNQN_FILE' - install nvme-cli and check the"
+ . " host identity\n";
+ }
+ die "invalid or missing NVMe host ID in '$HOSTID_FILE' - expected a nonzero UUID\n"
+ if !defined($id) || $id =~ /^[0-]+$/;
+ return { nqn => $nqn, id => lc($id) };
+}
+
+sub is_supported() { return -x $NVME ? 1 : 0 }
+
+sub assert_support() {
+ die "nvme-cli is not installed\n" if !is_supported();
+ run_command(['modprobe', 'nvme-tcp'], timeout => 10)
+ if !-e "$SYSFS/module/nvme_tcp";
+ my $multipath = file_read_firstline("$SYSFS/module/nvme_core/parameters/multipath") // '';
+ die "native NVMe multipath is disabled - enable nvme_core.multipath\n" if $multipath ne 'Y';
+}
+
+sub controllers() {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-fabrics/ctl";
+ dir_glob_foreach(
+ $dir,
+ 'nvme[0-9]+',
+ sub($name, @) {
+ my $address = file_read_firstline("$dir/$name/address") // return;
+ my %address = map { split(/=/, $_, 2) } grep { /=/ } split(/,/, $address);
+ return if !defined($address{traddr});
+ $res->{$name} = {
+ transport => file_read_firstline("$dir/$name/transport") // '',
+ subsystem => PVE::Diskmanage::read_subsysnqn("$dir/$name/subsysnqn") // '',
+ state => file_read_firstline("$dir/$name/state") // 'unknown',
+ traddr => canonical_address($address{traddr}),
+ trsvcid => $address{trsvcid},
+ };
+ },
+ );
+ return $res;
+}
+
+sub subsystem_controllers($subsystem) {
+ my $controllers = controllers();
+ return {
+ map { $_ => $controllers->{$_} } grep {
+ $controllers->{$_}->{subsystem} eq $subsystem
+ && $controllers->{$_}->{transport} eq 'tcp'
+ } keys %$controllers
+ };
+}
+
+# The NQN of a subsystem, untainted, or undef if it is invalid or the one of the discovery service.
+sub subsystem_nqn($nqn) {
+ my ($res) = ($nqn // '') =~ /\A($NQN_PATTERN)\z/;
+ return undef if !defined($res) || length($res) > 223 || $res eq $DISCOVERY_NQN;
+ return $res;
+}
+
+sub namespace_wwid($dev) {
+ return file_read_firstline("$SYSFS/block/$dev/wwid");
+}
+
+sub has_live_controller($controllers) {
+ return scalar(grep { $_->{state} eq 'live' } values %$controllers);
+}
+
+sub path_controller($controllers, $path) {
+ for my $name (sort keys %$controllers) {
+ my $ctrl = $controllers->{$name};
+ if ($ctrl->{traddr} eq $path->{traddr} && ($ctrl->{trsvcid} // '') eq $path->{trsvcid}) {
+ return $name;
+ }
+ }
+ return undef;
+}
+
+sub namespaces($subsystem) {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-subsystem";
+ dir_glob_foreach(
+ $dir,
+ 'nvme-subsys[0-9]+',
+ sub($subsys, @) {
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$dir/$subsys/subsysnqn") // return;
+ return if $nqn ne $subsystem;
+ dir_glob_foreach(
+ "$dir/$subsys",
+ 'nvme[0-9]+n[0-9]+',
+ sub($dev, @) {
+ my $wwid = file_read_firstline("$SYSFS/block/$dev/wwid") // return;
+ my $size = file_read_firstline("$SYSFS/block/$dev/size") // return;
+ $res->{$dev} = { wwid => $wwid, size => int($size) * 512 };
+ },
+ );
+ },
+ );
+ return $res;
+}
+
+sub with_lock($code) {
+ my ($res, $timeout) = PVE::Tools::run_fork_with_timeout(
+ $LOCK_WAIT + 35,
+ sub {
+ make_path($RUN_DIR);
+ open(my $lock, '>>', "$RUN_DIR/fabrics.lock") or die "cannot open NVMe lock - $!\n";
+ # a busy lock fails a connect and arms the cooldown of its portal, so wait a while
+ my $deadline = Time::HiRes::time() + $LOCK_WAIT;
+ while (!flock($lock, LOCK_EX | LOCK_NB)) {
+ die "NVMe over Fabrics is busy - another operation is still running\n"
+ if Time::HiRes::time() >= $deadline;
+ Time::HiRes::usleep(100_000);
+ }
+ # Commands inherit the lock, so that it stays held until they exit, even if the caller
+ # timed out while one was stuck in the kernel.
+ my $flags = fcntl($lock, F_GETFD, 0) // die "cannot read NVMe lock flags - $!\n";
+ fcntl($lock, F_SETFD, $flags & ~FD_CLOEXEC)
+ or die "cannot inherit NVMe lock - $!\n";
+ return $code->();
+ },
+ );
+ die "NVMe over Fabrics operation timed out - it may still be running\n" if $timeout;
+ return $res;
+}
+
+my sub retry_file($scfg, $path) {
+ my ($key) =
+ sha1_hex(join(
+ "\0", $scfg->{subsysnqn}, format_path($path), $scfg->{'fast-io-fail-tmo'} // 120)) =~
+ /\A([0-9a-f]{40})\z/;
+ return "$RUN_DIR/retry/$key";
+}
+
+sub in_cooldown($scfg, $path) {
+ my $mtime = (stat(retry_file($scfg, $path)))[9] // return 0;
+ my $age = time() - $mtime;
+ return $age > -60 && $age < 60;
+}
+
+sub note_connect_failure($scfg, $path) {
+ make_path("$RUN_DIR/retry");
+ file_set_contents(retry_file($scfg, $path), '');
+}
+
+sub clear_connect_failures($scfg) {
+ unlink(retry_file($scfg, $_)) for storage_paths($scfg)->@*;
+}
+
+sub connect_path($scfg, $path) {
+ my $nqn = subsystem_nqn($scfg->{subsysnqn}) // die "invalid subsystem NQN\n";
+ my ($fail) = ($scfg->{'fast-io-fail-tmo'} // 120) =~ /\A(-?[0-9]+)\z/;
+ die "invalid fast I/O fail timeout\n" if !defined($fail) || $fail < -1;
+ return with_lock(sub {
+ return if path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ assert_support();
+ my $host = host_identity();
+ run_command(
+ [
+ $NVME,
+ 'connect',
+ '--transport=tcp',
+ '--nqn',
+ $nqn,
+ '--traddr',
+ $path->{traddr},
+ '--trsvcid',
+ $path->{trsvcid},
+ '--hostnqn',
+ $host->{nqn},
+ '--hostid',
+ $host->{id},
+ '--ctrl-loss-tmo=-1',
+ '--fast_io_fail_tmo',
+ $fail,
+ ],
+ timeout => 30,
+ );
+ # nvme-cli can exit successfully without having connected
+ die "no controller appeared\n"
+ if !path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ unlink(retry_file($scfg, $path));
+ return;
+ });
+}
+
+1;
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index c640cd8e..c77a6755 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -33,6 +33,7 @@ use PVE::Storage::LvmThinPlugin;
use PVE::Storage::NFSPlugin;
use PVE::Storage::CIFSPlugin;
use PVE::Storage::ISCSIPlugin;
+use PVE::Storage::NVMeOFPlugin;
use PVE::Storage::RBDPlugin;
use PVE::Storage::CephFSPlugin;
use PVE::Storage::ISCSIDirectPlugin;
@@ -58,6 +59,7 @@ PVE::Storage::LvmThinPlugin->register();
PVE::Storage::NFSPlugin->register();
PVE::Storage::CIFSPlugin->register();
PVE::Storage::ISCSIPlugin->register();
+PVE::Storage::NVMeOFPlugin->register();
PVE::Storage::RBDPlugin->register();
PVE::Storage::CephFSPlugin->register();
PVE::Storage::ISCSIDirectPlugin->register();
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index a2df83c0..7f2ff6c8 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -6,6 +6,7 @@ SOURCES= \
NFSPlugin.pm \
CIFSPlugin.pm \
ISCSIPlugin.pm \
+ NVMeOFPlugin.pm \
CephFSPlugin.pm \
RBDPlugin.pm \
ISCSIDirectPlugin.pm \
diff --git a/src/PVE/Storage/NVMeOFPlugin.pm b/src/PVE/Storage/NVMeOFPlugin.pm
new file mode 100644
index 00000000..76f73af0
--- /dev/null
+++ b/src/PVE/Storage/NVMeOFPlugin.pm
@@ -0,0 +1,266 @@
+package PVE::Storage::NVMeOFPlugin;
+
+use v5.36;
+
+use Cwd ();
+use Time::HiRes ();
+
+use PVE::Network;
+
+use PVE::Diskmanage;
+use PVE::NVMeOF;
+use PVE::Storage::Plugin;
+
+use base qw(PVE::Storage::Plugin);
+
+# Adding a storage activates it under the lock of the storage configuration, so once a controller
+# is live, no further portal is tried after this many seconds. Later activations connect the rest.
+our $ACTIVATION_BUDGET = 15;
+
+sub type { return 'nvmeof' }
+
+sub plugindata {
+ return {
+ content => [{ images => 1, 'vm-vol' => 1, none => 1 }, { images => 1 }],
+ select_existing => 1,
+ 'isolate-properties' => 1,
+ 'advanced-properties' => {
+ 'fast-io-fail-tmo' => 1,
+ },
+ 'hidden-properties' => {
+ bwlimit => 1,
+ },
+ 'sensitive-properties' => {},
+ };
+}
+
+sub properties {
+ return {
+ subsysnqn => {
+ title => "Subsystem",
+ description => 'The NQN of the NVMe subsystem.',
+ type => 'string',
+ pattern => $PVE::NVMeOF::NQN_PATTERN,
+ maxLength => 223,
+ },
+ portals => {
+ title => "Portals",
+ description =>
+ 'TCP portals of the NVMe subsystem, as IPv4 or bracketed IPv6 addresses'
+ . ' with an optional port (default 4420).',
+ type => 'string',
+ format => 'pve-storage-nvme-portal-list',
+ },
+ 'fast-io-fail-tmo' => {
+ title => "Fail I/O After (s)",
+ description => 'Seconds before I/O through a reconnecting path fails. -1 disables'
+ . ' this timeout; I/O can remain queued while paths reconnect.',
+ type => 'integer',
+ minimum => -1,
+ default => 120,
+ },
+ };
+}
+
+sub options {
+ return {
+ subsysnqn => { fixed => 1 },
+ portals => {},
+ 'fast-io-fail-tmo' => { optional => 1 },
+ nodes => { optional => 1 },
+ disable => { optional => 1 },
+ content => { optional => 1 },
+ bwlimit => { optional => 1 },
+ };
+}
+
+my sub assert_valid_config($scfg) {
+ die "the discovery subsystem cannot be used as storage\n"
+ if $scfg->{subsysnqn} eq $PVE::NVMeOF::DISCOVERY_NQN;
+ my $paths = PVE::NVMeOF::storage_paths($scfg);
+ # the list format also accepts a list of separators only
+ die "no portal given\n" if !@$paths;
+ my %seen;
+ for my $path (@$paths) {
+ my $portal = PVE::NVMeOF::format_path($path);
+ die "portal '$portal' is listed more than once\n" if $seen{$portal}++;
+ }
+}
+
+sub on_add_hook($class, $storeid, $scfg, %param) {
+ assert_valid_config($scfg);
+ # the LUN and controller lists and the node status attribute a subsystem to its one storage
+ my $ids = PVE::Storage::config()->{ids};
+ for my $sid (sort keys %$ids) {
+ next if $sid eq $storeid || $ids->{$sid}->{type} ne 'nvmeof';
+ die "storage '$sid' already uses this subsystem\n"
+ if $ids->{$sid}->{subsysnqn} eq $scfg->{subsysnqn};
+ }
+ # adding the storage again, for example once the array allows the node, tries all portals
+ PVE::NVMeOF::clear_connect_failures($scfg);
+ return;
+}
+
+sub on_update_hook_full($class, $storeid, $scfg, $update, $delete, $sensitive, @) {
+ my $merged = { %$scfg, %$update };
+ delete $merged->{$_} for ($delete // [])->@*;
+ assert_valid_config($merged);
+ return $class->SUPER::on_update_hook_full($storeid, $scfg, $update, $delete, $sensitive);
+}
+
+sub parse_volname($class, $volname) {
+ if ($volname =~ m!^(nvme-[a-zA-Z0-9_.:+-]+)$! && $volname !~ /-part[0-9]+$/) {
+ return ($class->guest_volume_vtype('raw'), $1, undef, undef, undef, undef, 'raw');
+ }
+ die "unable to parse NVMe over Fabrics volume name '$volname'\n";
+}
+
+# The name of a volume can be the by-id name of any NVMe device, also of a local disk or of a
+# namespace of another subsystem.
+sub assert_namespace($scfg, $volname, $real) {
+ my ($dev) = $real =~ m!^/dev/(nvme[0-9]+n[0-9]+)$!;
+ die "volume '$volname' is not an NVMe namespace\n" if !defined($dev);
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$PVE::NVMeOF::SYSFS/block/$dev/device/subsysnqn")
+ // '';
+ die "volume '$volname' is not part of subsystem '$scfg->{subsysnqn}'\n"
+ if $nqn ne $scfg->{subsysnqn};
+ # another by-id name of the subsystem, like model and serial, can name another namespace
+ my $wwid = PVE::NVMeOF::namespace_wwid($dev) // '';
+ die "volume '$volname' is not named after the WWID of its namespace\n"
+ if $volname ne "nvme-$wwid";
+}
+
+sub filesystem_path($class, $scfg, $volname, $snapname = undef, @) {
+ die "snapshot is not possible on NVMe over Fabrics storage\n" if defined($snapname);
+ my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+ my $path = "/dev/disk/by-id/$name";
+ # not every user of a path activates the volume first, and the base volume of an LVM storage
+ # has no device before its storage connects
+ my $real = Cwd::realpath($path);
+ assert_namespace($scfg, $volname, $real) if defined($real) && -e $real;
+ return wantarray ? ($path, $vmid, $vtype) : $path;
+}
+
+sub create_base { die "can't create base images in NVMe over Fabrics storage\n" }
+sub clone_image { die "can't clone images in NVMe over Fabrics storage\n" }
+sub alloc_image { die "can't allocate space in NVMe over Fabrics storage\n" }
+sub free_image { die "can't free space in NVMe over Fabrics storage\n" }
+sub volume_resize { die "volume resize is not possible on NVMe over Fabrics storage\n" }
+
+sub list_volumes($class, $storeid, $scfg, $vmid = undef, $content_types = undef, @) {
+ my $res = $class->list_images($storeid, $scfg, $vmid);
+ $_->{content} = 'images' for @$res;
+ return $res;
+}
+
+sub list_images($class, $storeid, $scfg, $vmid = undef, $vollist = undef, $cache = undef, @) {
+ return [] if defined($vmid) && !$vollist;
+ my $namespaces = PVE::NVMeOF::namespaces($scfg->{subsysnqn});
+ my $res = [];
+ for my $dev (sort keys %$namespaces) {
+ my $ns = $namespaces->{$dev};
+ my $volid = "$storeid:nvme-$ns->{wwid}";
+ next if $vollist && !grep { $_ eq $volid } @$vollist;
+ push @$res,
+ {
+ volid => $volid,
+ format => 'raw',
+ size => $ns->{size},
+ vmid => 0,
+ };
+ }
+ return $res;
+}
+
+sub status($class, $storeid, $scfg, $cache = undef, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ return (0, 0, 0, PVE::NVMeOF::has_live_controller($controllers) ? 1 : 0);
+}
+
+sub activate_storage($class, $storeid, $scfg, $cache = undef, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ my @missing = grep { !defined(PVE::NVMeOF::path_controller($controllers, $_)) }
+ PVE::NVMeOF::storage_paths($scfg)->@*;
+ return if !@missing;
+ # Without these no path connects, which is no reason to wait before the next attempt. A storage
+ # with a usable path still works, with fewer paths.
+ eval {
+ PVE::NVMeOF::assert_support();
+ PVE::NVMeOF::host_identity();
+ };
+ if (my $err = $@) {
+ die $err if !PVE::NVMeOF::has_live_controller($controllers);
+ warn "storage '$storeid': cannot connect to the other portals - $err";
+ return;
+ }
+ my @errors;
+ my $live = PVE::NVMeOF::has_live_controller($controllers);
+ my $deadline = Time::HiRes::time() + $ACTIVATION_BUDGET;
+ for my $path (@missing) {
+ my $portal = PVE::NVMeOF::format_path($path);
+ if ($live && Time::HiRes::time() >= $deadline) {
+ push @errors, "$portal: left for the next activation";
+ next;
+ }
+ if (PVE::NVMeOF::in_cooldown($scfg, $path)) {
+ push @errors, "$portal: failed less than a minute ago";
+ next;
+ }
+ eval {
+ die "no answer from portal\n"
+ if !PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2);
+ PVE::NVMeOF::connect_path($scfg, $path);
+ };
+ if (my $err = $@) {
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ warn "storage '$storeid': connecting to '$portal' failed - $err";
+ chomp $err;
+ push @errors, "$portal: $err";
+ } else {
+ $live = 1;
+ }
+ }
+ # some paths are enough, but without a usable one the namespaces cannot be used
+ $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ die "cannot connect to any portal - " . join('; ', @errors) . "\n"
+ if !PVE::NVMeOF::has_live_controller($controllers);
+ return;
+}
+
+sub deactivate_storage { return }
+
+sub check_connection($class, $storeid, $scfg, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ return 1 if PVE::NVMeOF::has_live_controller($controllers);
+ for my $path (PVE::NVMeOF::storage_paths($scfg)->@*) {
+ next if defined(PVE::NVMeOF::path_controller($controllers, $path));
+ next if PVE::NVMeOF::in_cooldown($scfg, $path);
+ return 1 if PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2);
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ }
+ return 0;
+}
+
+sub activate_volume($class, $storeid, $scfg, $volname, $snapname = undef, $cache = undef, @) {
+ my $path = $class->filesystem_path($scfg, $volname, $snapname);
+ # as for the multipath map of an iSCSI LUN, a status pass does not wait for the device
+ my $deadline = Time::HiRes::time() + ($cache && $cache->{status_only} ? 0 : 10);
+ while (!-b $path && Time::HiRes::time() < $deadline) {
+ last if !keys PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn})->%*;
+ Time::HiRes::usleep(250_000);
+ }
+ my $real = Cwd::realpath($path);
+ die "volume '$volname' is not available on this node\n" if !$real || !-b $real;
+ assert_namespace($scfg, $volname, $real);
+}
+
+sub volume_has_feature(
+ $class, $scfg, $feature, $storeid, $volname,
+ $snapname = undef,
+ $running = undef, @,
+) {
+ return 1 if $feature eq 'copy' && !defined($snapname);
+ return undef;
+}
+
+1;
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index a97f361c..d61e78b6 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -42,7 +42,7 @@ our @COMMON_TAR_FLAGS = qw(
);
our @SHARED_STORAGE = (
- 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs',
+ 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs', 'nvmeof',
);
our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index 0a9e441c..53c24c9e 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -302,6 +302,11 @@ sub lun_partitions($lun) {
}
sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my $name = basename($lun->{devpath});
+ my $nqn =
+ $name =~ /^nvme\d+n\d+$/
+ ? PVE::Diskmanage::read_subsysnqn("/sys/block/$name/device/subsysnqn")
+ : undef;
my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
[$lun->{devpath}, lun_partitions($lun)->@*],
)->@*;
@@ -324,6 +329,14 @@ sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
) {
die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
}
+ if (
+ $type eq 'nvmeof'
+ && defined($nqn)
+ && $scfg->{subsysnqn} eq $nqn
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this subsystem\n";
+ }
next if $type ne 'lvm' || !$scfg->{base};
my $base = PVE::Multipath::parse_base_volume($scfg->{base});
my $matches = $base
diff --git a/src/test/Makefile b/src/test/Makefile
index 3b902c43..ceabd991 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -17,6 +17,7 @@ test: \
test_lvmplugin \
test_multipath \
test_multipath_api \
+ test_nvmeof \
test_ovf \
test_plugin \
test_remote_command \
@@ -115,3 +116,7 @@ test_san_api: run_san_api_tests.pl run_san_wipe_tests.pl run_san_nvme_tests.pl
test_disk_api: run_disk_api_tests.pl
./run_disk_api_tests.pl
+
+test_nvmeof: run_nvmeof_tests.pl run_nvmeof_taint_tests.pl
+ ./run_nvmeof_tests.pl
+ perl -T ./run_nvmeof_taint_tests.pl
diff --git a/src/test/run_nvmeof_taint_tests.pl b/src/test/run_nvmeof_taint_tests.pl
new file mode 100755
index 00000000..6fd37410
--- /dev/null
+++ b/src/test/run_nvmeof_taint_tests.pl
@@ -0,0 +1,62 @@
+#!/usr/bin/perl -T
+
+use v5.36;
+use lib qw(..);
+use File::Temp qw(tempdir);
+use Scalar::Util qw(tainted);
+use Test::MockModule;
+use Test::More;
+
+use PVE::Tools qw(file_get_contents file_set_contents);
+
+use PVE::NVMeOF;
+
+$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
+delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
+my $dir = tempdir('nvmeof-taint-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::HOSTNQN_FILE = "$dir/hostnqn";
+local $PVE::NVMeOF::HOSTID_FILE = "$dir/hostid";
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+file_set_contents($PVE::NVMeOF::HOSTNQN_FILE, "nqn.host\n");
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "12345678-1234-1234-1234-123456789abc\n");
+file_set_contents("$dir/config", "nqn.test\n192.0.2.1\n120\n");
+my ($nqn, $portal, $fail) = split(/\n/, file_get_contents("$dir/config"));
+ok(tainted($nqn), 'configuration input is tainted');
+my $nvme = Test::MockModule->new('PVE::NVMeOF');
+$nvme->mock(with_lock => sub { $_[0]->() });
+my $commands = 0;
+$nvme->mock(
+ subsystem_controllers => sub {
+ return $commands ? { nvme0 => { traddr => '192.0.2.1', trsvcid => 4420 } } : {};
+ },
+);
+$nvme->mock(assert_support => sub { });
+$nvme->mock(
+ run_command => sub($cmd, %opts) {
+ $commands++;
+ is(
+ scalar(grep { tainted($_) } @$cmd),
+ 0,
+ 'all connect operands are validated and untainted',
+ );
+ PVE::Tools::run_command(['/usr/bin/true', @$cmd], timeout => 5);
+ },
+);
+my $path = PVE::NVMeOF::parse_portal($portal);
+eval { PVE::NVMeOF::connect_path({ subsysnqn => $nqn, 'fast-io-fail-tmo' => $fail }, $path) };
+is($@, '', 'connect command can execute in taint mode');
+is($commands, 1, 'one connect');
+PVE::NVMeOF::note_connect_failure({ subsysnqn => $nqn }, $path);
+ok(
+ PVE::NVMeOF::in_cooldown({ subsysnqn => $nqn }, $path),
+ 'cooldown accepts validated file-backed configuration',
+);
+for my $bad ('nqn.bad,nqn=other', "nqn.test\n", 'nqn.2014-08.org.nvmexpress.discovery') {
+ eval { PVE::NVMeOF::connect_path({ subsysnqn => $bad }, $path) };
+ like($@, qr/invalid subsystem/, 'invalid connect subsystem refused');
+}
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "00000000-0000-0000-0000-000000000000\n");
+eval { PVE::NVMeOF::host_identity() };
+like($@, qr/nonzero UUID/, 'zero host ID refused');
+
+done_testing();
diff --git a/src/test/run_nvmeof_tests.pl b/src/test/run_nvmeof_tests.pl
new file mode 100755
index 00000000..cdf228c0
--- /dev/null
+++ b/src/test/run_nvmeof_tests.pl
@@ -0,0 +1,446 @@
+#!/usr/bin/perl
+
+use v5.36;
+use lib qw(..);
+use Fcntl qw(:flock);
+use File::Path qw(make_path remove_tree);
+use File::Temp qw(tempdir);
+use POSIX ();
+use Test::MockModule;
+use Test::More;
+use Time::HiRes ();
+
+use PVE::Tools qw(file_set_contents);
+
+use PVE::NVMeOF;
+use PVE::Storage;
+
+my $dir = tempdir('nvmeof-test-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+local $PVE::NVMeOF::SYSFS = "$dir/sys";
+my $class = 'PVE::Storage::NVMeOFPlugin';
+my $cfg = {
+ type => 'nvmeof',
+ subsysnqn => 'nqn.test',
+ portals => '192.0.2.1,[2001:db8::2]:4421',
+ content => { none => 1 },
+};
+
+subtest 'configuration, portals and volumes' => sub {
+ is(PVE::Storage::Plugin->lookup('nvmeof'), $class, 'plugin registered');
+ is_deeply(
+ [sort keys $class->properties()->%*],
+ [qw(fast-io-fail-tmo portals subsysnqn)],
+ 'only three plugin-specific properties',
+ );
+ my sub nvmeof_schema($schema) {
+ my @types = map { ($_->{oneOf} // [])->@* } ($schema->{allOf} // [])->@*;
+ my ($nvmeof) = grep { $_->{'instance-type'} eq 'nvmeof' } @types;
+ return $nvmeof->{properties} // {};
+ }
+ my $create = nvmeof_schema(PVE::Storage::Plugin->createSchema());
+ is_deeply(
+ [sort grep { !$create->{$_}->{optional} } keys $create->%*],
+ [qw(portals subsysnqn)],
+ 'adding a storage requires the subsystem and the portals',
+ );
+ my $update = nvmeof_schema(PVE::Storage::Plugin->updateSchema());
+ ok($update->{portals} && !$update->{subsysnqn}, 'the subsystem cannot be changed');
+ my $parsed = PVE::Storage::Plugin->parse_config(
+ 'storage.cfg',
+ "nvmeof: fabric\n\tsubsysnqn nqn.test\n\tportals 192.0.2.1\n\tcontent none\n",
+ );
+ is($parsed->{ids}->{fabric}->{subsysnqn}, 'nqn.test', 'storage.cfg accepts the plugin');
+ is_deeply(
+ $parsed->{ids}->{fabric}->{content},
+ { none => 1 },
+ 'connection-only content parses',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ { traddr => '192.0.2.1', trsvcid => 4420 },
+ 'default I/O port',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('[2001:0db8::1]:4421'),
+ { traddr => '2001:db8::1', trsvcid => 4421 },
+ 'canonical IPv6',
+ );
+ is(
+ PVE::NVMeOF::format_path({ traddr => '2001:db8::1', trsvcid => 4421 }),
+ '[2001:db8::1]:4421',
+ 'an IPv6 portal in brackets',
+ );
+ is(
+ PVE::NVMeOF::format_path({ traddr => 'nn-0x2000:pn-0x2001' }),
+ 'nn-0x2000:pn-0x2001',
+ 'the address of a Fibre Channel port as it is',
+ );
+
+ for my $bad (
+ 'host.example', '1.2.3.4:0', '1.2.3.4:65536', '[fe80::1]', '[::]', '224.0.0.1',
+ ) {
+ ok(!PVE::NVMeOF::parse_portal($bad), "invalid portal $bad");
+ }
+ eval { $class->on_add_hook('fabric', { %$cfg, portals => '192.0.2.1,192.0.2.1:4420' }); };
+ like($@, qr/listed more than once/, 'duplicate portals refused');
+ eval { $class->on_add_hook('fabric', { %$cfg, portals => ',,' }); };
+ like($@, qr/no portal given/, 'a list without a portal refused');
+ eval {
+ $class->on_add_hook(
+ 'fabric',
+ { %$cfg, subsysnqn => 'nqn.2014-08.org.nvmexpress.discovery' },
+ );
+ };
+ like($@, qr/discovery subsystem/, 'discovery subsystem refused');
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $ids = { fabric => $cfg, local => { type => 'dir' } };
+ $storage->mock(config => sub { { ids => $ids } });
+ my $first = PVE::NVMeOF::storage_paths($cfg)->[0];
+ PVE::NVMeOF::note_connect_failure($cfg, $first);
+ is(eval { $class->on_add_hook('fabric', $cfg); 1 }, 1, 'a storage is not in its own way');
+ ok(!PVE::NVMeOF::in_cooldown($cfg, $first), 'adding it tries all portals again');
+ eval { $class->on_add_hook('second', {%$cfg}) };
+ like($@, qr/storage 'fabric' already uses this subsystem/, 'one storage per subsystem');
+ is(
+ scalar($class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef')),
+ '/dev/disk/by-id/nvme-eui.0123456789abcdef',
+ 'stable volume path',
+ );
+ {
+ my $disk = Test::MockModule->new('PVE::Diskmanage');
+ my $nqn = 'nqn.other';
+ $disk->redefine(read_subsysnqn => sub { $nqn });
+ my $sysfs = Test::MockModule->new('PVE::NVMeOF');
+ $sysfs->redefine(namespace_wwid => sub { 'x' });
+ my $check = sub {
+ eval { PVE::Storage::NVMeOFPlugin::assert_namespace($cfg, @_) };
+ $@;
+ };
+ like($check->('nvme-x', '/dev/nvme0n1'), qr/not part of subsystem/, 'other subsystem');
+ like($check->('nvme-x', '/dev/sda'), qr/not an NVMe namespace/, 'other device type');
+ like($check->('nvme-x', '/dev/nvme0n1p1'), qr/not an NVMe namespace/, 'partition');
+ $nqn = 'nqn.test';
+ is($check->('nvme-x', '/dev/nvme0n1'), '', 'namespace of the subsystem');
+ like(
+ $check->('nvme-Vendor_Model_123_1', '/dev/nvme0n1'),
+ qr/not named after the WWID/,
+ 'another by-id name of a namespace of the subsystem',
+ );
+ my $cwd = Test::MockModule->new('Cwd');
+ $cwd->redefine(realpath => sub { $dir });
+ eval { $class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef') };
+ like($@, qr/not an NVMe namespace/, 'the path of an existing device is checked');
+ }
+
+ for my $bad ('nvme-../../sda', 'nvme-eui.abc-part1', 'sda') {
+ eval { $class->parse_volname($bad) };
+ like($@, qr/unable to parse/, "invalid volume $bad");
+ }
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ $nvme->mock(namespaces => sub { { nvme0n1 => { wwid => 'eui.abc', size => 4096 } } });
+ is(
+ $class->list_volumes('fabric', $cfg)->[0]->{volid},
+ 'fabric:nvme-eui.abc',
+ 'content none still offers bases',
+ );
+ is_deeply($class->list_images('fabric', $cfg, 100), [], 'namespaces have no VM owner');
+ $nvme->mock(subsystem_controllers => sub { {} });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test') };
+ like($@, qr/not available/,
+ 'missing namespace fails without waiting on absent controllers');
+ my ($now, $queries) = (0, 0);
+ my $clock = Test::MockModule->new('Time::HiRes');
+ $clock->redefine(time => sub { $now += 5 }, usleep => sub { });
+ $nvme->mock(subsystem_controllers => sub { $queries++; { nvme1 => {} } });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test', undef, {}) };
+ is($queries, 1, 'a missing namespace of a connected subsystem is waited for');
+ eval {
+ $class->activate_volume(
+ 'fabric',
+ $cfg,
+ 'nvme-nonexistent-test',
+ undef,
+ { status_only => 1 },
+ );
+ };
+ like($@, qr/not available/, 'in a status pass it fails as well');
+ is($queries, 1, 'but without a wait');
+ is(
+ ($class->parse_volname('nvme-eui.0123456789abcdef'))[0],
+ 'vm-vol',
+ 'namespaces are VM disks',
+ );
+};
+
+subtest 'sysfs topology' => sub {
+ my $sys = $PVE::NVMeOF::SYSFS;
+ make_path(
+ "$sys/class/nvme-fabrics/ctl/nvme1",
+ "$sys/class/nvme-subsystem/nvme-subsys0/nvme0n1",
+ "$sys/block/nvme0n1",
+ );
+ my %attrs = (
+ address => 'traddr=192.0.2.1,trsvcid=4420',
+ transport => 'tcp',
+ subsysnqn => 'nqn.test',
+ state => 'connecting',
+ );
+ file_set_contents("$sys/class/nvme-fabrics/ctl/nvme1/$_", "$attrs{$_}\n") for keys %attrs;
+ file_set_contents("$sys/class/nvme-subsystem/nvme-subsys0/subsysnqn", "nqn.test\n");
+ file_set_contents("$sys/block/nvme0n1/wwid", "eui.abc\n");
+ file_set_contents("$sys/block/nvme0n1/size", "8\n");
+ is(
+ PVE::NVMeOF::controllers()->{nvme1}->{state},
+ 'connecting',
+ 'reconnecting controller is still present',
+ );
+ is(
+ PVE::NVMeOF::path_controller(
+ PVE::NVMeOF::subsystem_controllers('nqn.test'),
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ ),
+ 'nvme1',
+ 'portal controller found',
+ );
+ is_deeply(
+ PVE::NVMeOF::namespaces('nqn.test'),
+ { nvme0n1 => { wwid => 'eui.abc', size => 4096 } },
+ 'namespace facts',
+ );
+ is_deeply(PVE::NVMeOF::namespaces('nqn.other'), {}, 'other subsystem excluded');
+};
+
+subtest 'serialized commands inherit the lock' => sub {
+ local $PVE::NVMeOF::LOCK_WAIT = 0;
+ my $script = join(
+ ' ',
+ 'my @held = grep { (readlink($_) // "") =~ /fabrics.lock$/ } glob("/proc/self/fd/*");',
+ 'die "not inherited" if !@held;',
+ 'open(my $fh, ">>", $ARGV[0]) or die $!;',
+ 'die "lock missing" if flock($fh, LOCK_EX|LOCK_NB);',
+ 'print "locked\\n";',
+ );
+ my $value = PVE::NVMeOF::with_lock(sub {
+ my $out = '';
+ PVE::Tools::run_command(
+ [
+ '/usr/bin/perl',
+ '-MFcntl=:flock',
+ '-e',
+ $script,
+ "$PVE::NVMeOF::RUN_DIR/fabrics.lock",
+ ],
+ timeout => 5,
+ outfunc => sub { $out .= $_[0] },
+ );
+ return $out;
+ });
+ is($value, 'locked', 'exec cannot acquire the lock held by its parent');
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or die $!;
+ flock($lock, LOCK_EX) or die $!;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'busy operation never enters callback');
+ close($lock);
+
+ my $tools = Test::MockModule->new('PVE::Tools');
+ my $timed_out = 1;
+ $tools->mock(run_fork_with_timeout => sub { return ($_[1]->(), $timed_out) });
+ my $retained;
+ eval {
+ PVE::NVMeOF::with_lock(sub {
+ my ($path) =
+ grep { (readlink($_) // '') =~ /fabrics.lock$/ } glob('/proc/self/fd/*');
+ my ($fd) = $path =~ m{/(\d+)$};
+ open($retained, '>&', $fd) or die $!;
+ return 1;
+ });
+ };
+ like($@, qr/timed out.*may still be running/, 'timeout does not claim deletion completed');
+ $timed_out = 0;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'retained descriptor keeps serialization after the caller returns');
+ close($retained);
+ is(PVE::NVMeOF::with_lock(sub { 1 }), 1, 'last descriptor close releases serialization');
+};
+
+subtest 'a short hold of the lock does not fail a connect' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my $scfg = { %$cfg, subsysnqn => 'nqn.wait', portals => '192.0.2.3' };
+ my $ctl = "$PVE::NVMeOF::SYSFS/class/nvme-fabrics/ctl/nvme9";
+ $net->mock(tcp_ping => sub { 1 });
+ $nvme->mock(assert_support => sub { });
+ $nvme->mock(host_identity =>
+ sub { { nqn => 'nqn.host', id => '12345678-1234-1234-1234-123456789abc' } });
+ $nvme->mock(
+ run_command => sub(@) {
+ my %attrs = (
+ address => 'traddr=192.0.2.3,trsvcid=4420',
+ transport => 'tcp',
+ subsysnqn => 'nqn.wait',
+ state => 'live',
+ );
+ make_path($ctl);
+ file_set_contents("$ctl/$_", "$attrs{$_}\n") for keys %attrs;
+ },
+ );
+ pipe(my $held, my $signal) or die "pipe failed - $!\n";
+ my $holder = fork() // die "fork failed - $!\n";
+ if (!$holder) {
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or POSIX::_exit(1);
+ flock($lock, LOCK_EX) or POSIX::_exit(1);
+ syswrite($signal, '1');
+ Time::HiRes::sleep(0.5);
+ POSIX::_exit(0);
+ }
+ close($signal);
+ sysread($held, my $state, 1);
+ is($state, '1', 'another process holds the lock');
+ my $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ $class->activate_storage('wait', $scfg);
+ }
+ waitpid($holder, 0);
+ is($warning, '', 'the connect waits for the lock');
+ my $path = PVE::NVMeOF::storage_paths($scfg)->[0];
+ ok(!PVE::NVMeOF::in_cooldown($scfg, $path), 'and arms no cooldown');
+ is(
+ PVE::NVMeOF::path_controller(PVE::NVMeOF::subsystem_controllers('nqn.wait'), $path),
+ 'nvme9',
+ 'the portal is connected',
+ );
+ remove_tree($ctl);
+};
+
+subtest 'connect options, kernel reconnect and cooldown' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my @commands;
+ my $controllers = {};
+ $nvme->mock(with_lock => sub { $_[0]->() });
+ $nvme->mock(assert_support => sub { });
+ $nvme->mock(host_identity =>
+ sub { { nqn => 'nqn.host', id => '12345678-1234-1234-1234-123456789abc' } });
+ $nvme->mock(subsystem_controllers => sub { $controllers });
+ my $appear = 1;
+ $nvme->mock(
+ run_command => sub($cmd, %opts) {
+ is($opts{timeout}, 30, 'bounded connect');
+ push @commands, $cmd;
+ my %arg =
+ map { $cmd->[$_] => $cmd->[$_ + 1] } grep { $cmd->[$_] =~ /^--tr/ } 0 .. $#$cmd;
+ my $controller =
+ { traddr => $arg{'--traddr'}, trsvcid => $arg{'--trsvcid'}, state => 'live' };
+ $controllers->{ 'nvme' . scalar(@commands) } = $controller if $appear;
+ },
+ );
+ $net->mock(tcp_ping => sub { 1 });
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 2, 'one connect per missing portal');
+ ok(grep({ $_ eq '--ctrl-loss-tmo=-1' } $commands[0]->@*), 'kernel reconnects indefinitely');
+ is_deeply([@{ $commands[0] }[-2, -1]], ['--fast_io_fail_tmo', 120], 'fast failure default');
+ {
+ local $PVE::Storage::NVMeOFPlugin::ACTIVATION_BUDGET = 0;
+ @commands = ();
+ $controllers = {};
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 1, 'with a live controller, a spent time budget leaves the rest');
+ ($controllers, $appear) = ({}, 0);
+ @commands = ();
+ {
+ local $SIG{__WARN__} = sub { };
+ eval { $class->activate_storage('fabric', $cfg) };
+ }
+ is(scalar(@commands), 2, 'without one, every portal is tried');
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ $appear = 1;
+ }
+ @commands = ();
+ $controllers = {
+ nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' },
+ nvme2 => { traddr => '2001:db8::2', trsvcid => 4421, state => 'live' },
+ };
+ $class->activate_storage('fabric', $cfg);
+ is_deeply(\@commands, [],
+ 'existing controllers are never reconnected, regardless of state');
+ $class->deactivate_storage('fabric', $cfg);
+ is_deeply(\@commands, [], 'deactivation does not remove controllers');
+ $controllers = {};
+ my $path = PVE::NVMeOF::storage_paths($cfg)->[0];
+ PVE::NVMeOF::note_connect_failure($cfg, $path);
+ ok(PVE::NVMeOF::in_cooldown($cfg, $path), 'failure starts cooldown');
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 1, 'only the other portal connects');
+ ($controllers, $appear) = ({}, 0);
+ my $other = PVE::NVMeOF::storage_paths($cfg)->[1];
+ my $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ eval { $class->activate_storage('fabric', $cfg) };
+ }
+ like($warning, qr/no controller appeared/, 'a connect without a controller is a failure');
+ ok(PVE::NVMeOF::in_cooldown($cfg, $other), 'which starts the cooldown too');
+ like(
+ $@,
+ qr/^cannot connect to any portal - .*failed less than a minute ago; .*no controller appeared/,
+ 'without any controller the activation fails with the reason of each portal',
+ );
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ $nvme->mock(assert_support => sub { die "nvme-cli is not installed\n" });
+ @commands = ();
+ eval { $class->activate_storage('fabric', $cfg) };
+ is($@, "nvme-cli is not installed\n", 'a missing prerequisite fails the activation');
+ is_deeply(\@commands, [], 'before any connect');
+ ok(!PVE::NVMeOF::in_cooldown($cfg, $path), 'and without a cooldown');
+ $controllers = { nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'live' } };
+ $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ is(
+ eval { $class->activate_storage('fabric', $cfg); 1 },
+ 1,
+ 'but not with a usable path',
+ );
+ }
+ like($warning, qr/cannot connect to the other portals - nvme-cli/, 'which it warns about');
+ $nvme->mock(assert_support => sub { });
+ $controllers =
+ { nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' } };
+ {
+ local $SIG{__WARN__} = sub { };
+ eval { $class->activate_storage('fabric', $cfg) };
+ }
+ like(
+ $@,
+ qr/^cannot connect to any portal/,
+ 'a reconnecting path is not usable when the missing one fails',
+ );
+};
+
+subtest 'local disk setup rejects fabric namespaces by transport' => sub {
+ my $disk = Test::MockModule->new('PVE::Diskmanage');
+ for my $transport (qw(nvme-tcp nvme-rdma nvme-fc)) {
+ $disk->mock(get_disks => sub { { nvme0n1 => { transport => $transport } } });
+ eval { PVE::Diskmanage::assert_disk_unused('/dev/nvme0n1') };
+ like($@, qr/not a valid local disk/,
+ "$transport refuses without storage configuration");
+ $disk->mock(
+ get_disks => sub {
+ {
+ nvme0n1 => { transport => $transport },
+ nvme0n1p1 => { parent => '/dev/nvme0n1', type => 'partition' },
+ };
+ },
+ );
+ eval { PVE::Diskmanage::assert_disk_unused('/dev/nvme0n1p1') };
+ like($@, qr/not a valid local disk/, "$transport refuses a partition of a namespace");
+ }
+};
+
+done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
index 3245b774..2a9a2121 100755
--- a/src/test/run_san_nvme_tests.pl
+++ b/src/test/run_san_nvme_tests.pl
@@ -38,6 +38,7 @@ $storage->mock(config => sub { $cfg });
$disk->mock(verify_blockdev_path => sub { $device });
$disk->mock(is_partition => sub { 0 });
$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(read_subsysnqn => sub { 'nqn.test' });
$disk->mock(is_iscsi_device => sub { 0 });
$disk->mock(is_mounted => sub { 0 });
$disk->mock(has_holder => sub { 0 });
@@ -86,6 +87,21 @@ for my $base (qw(fabric nvme-fabric)) {
eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
like($@, qr/base volume/, "native base reference on storage '$base' refuses");
}
+$cfg->{ids} =
+ { fabric =>
+ { type => 'nvmeof', subsysnqn => 'nqn.test', disable => 1, content => { images => 1 } } };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like(
+ $@,
+ qr/serves images from this subsystem/,
+ 'direct namespace image use refuses even when disabled',
+);
+$cfg->{ids}->{fabric}->{content} = { 'vm-vol' => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like($@, qr/serves images from this subsystem/, 'also when restricted to VM disks');
+$cfg->{ids}->{fabric}->{content} = { none => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+is($@, '', 'connection-only storage permits namespace initialization');
$cfg->{ids} = {};
@order = @opens = ();
$tools->mock(file_get_contents => sub { 1024 });
^ permalink raw reply related [relevance 18%]
* [PATCH v4 storage,docs,manager 00/25] NVMe over Fabrics storage
@ 2026-11-23 1:47 10% Thomas Lamprecht
2026-11-23 1:47 17% ` [PATCH v4 storage 04/25] nvmeof: add a storage for NVMe over Fabrics subsystems Thomas Lamprecht
0 siblings, 1 reply; 43+ results
From: Thomas Lamprecht @ 2026-11-23 1:47 UTC (permalink / raw)
To: pve-devel
A storage type for NVMe subsystems reached over TCP, on top of the
applied SAN series [0]: namespaces as base volumes of shared LVM, or
directly as raw VM disks, using the kernel's native NVMe multipath.
This is a deliberately small first version: TCP only, without
authentication or TLS, so access relies on the target's host NQN list
and a dedicated storage network. The plugin connects missing portals and
never disconnects controllers on config change or removal; disconnecting
a controller is an explicit per-node action. The kernel handles path
reconnection, and the SAN series provides LUN inventory, guided setup,
and pre-write guards.
Two operational prerequisites:
- Cloned nodes need distinct /etc/nvme/hostnqn and /etc/nvme/hostid
before connecting.
- All cluster nodes must be upgraded to pve-manager 9.2.38 before
adding the first nvmeof storage, as older nodes drop unknown storage
types when writing storage.cfg; creating the first one is refused
until all nodes are online on 9.2.38+.
What it adds:
- Storage type 'nvmeof' (subsysnqn + TCP portals, one storage per
subsystem, isolated properties, volumes as nvme-<wwid>,
ctrl_loss_tmo=-1, configurable fast-io-fail-tmo defaulting to 120s).
- Shared LVM support with nvmeof volumes as base, discovery via
/nodes/{node}/scan/nvmeof and 'pvesm scan nvmeof', and nvme-cli as a
Recommends of libpve-storage-perl.
- /nodes/{node}/san/nvmeof for host identity, controller listing, and
guarded per-controller disconnect (refused if a namespace in use or
referenced by a storage would lose its last usable path).
- Cluster-wide SAN status and pvestatd path notifications covering
nvmeof namespaces (without requiring multipathd), plus pvereport
output and documentation.
- Web UI: guided "Shared LVM on NVMe over Fabrics" setup, nvmeof
storage dialog with discovery, Node > SAN > NVMe over Fabrics
controller view, host NQN column, and native multipath state display.
Changes since v3 [1]:
- Cluster version & packaging: refuse adding the first nvmeof storage
until all nodes run pve-manager 9.2.38+, and add versioned package
relations assuming the next releases: libpve-storage-perl 9.1.23
(depending on libpve-common-perl 9.2.14 and breaking pve-manager <<
9.2.38), pve-docs 9.2.21, and pve-manager 9.2.38.
- Local disk & wipe isolation: omit TCP/RDMA namespaces from Node >
Disks and Ceph OSD selection (keeping NVMe/FC listed for local LVM
setup), and refuse local wipe on TCP/RDMA namespaces, their
partitions, and detached namespaces without a controller.
- Activation & config hardening: bound activation connect attempts
(~45s without a live controller, ~15s once one is live) and
check_connection (15s); fail activation when all controllers are
reconnecting; keep busy-lock waits out of cooldown while arming
cooldown on hanging connects; clear cooldown on portal edits; refuse
enabling direct image use while an LVM storage uses the subsystem as
base; reject ASCII control chars in NQNs; trim padded discovery
fields; preserve nvme-cli diagnostics on errors.
- Disconnect hardening: also check exclusive claims (e.g. mounts in
other mount namespaces) and non-multipath namespaces numbered after
the subsystem, tolerate brief openers (<1s, e.g. LVM scans), and
give disconnect a 300s lock budget for large subsystems.
- Reporting & notifications: notify on namespaces even without
multipathd; treat unreadable sysfs attributes as incomplete rather
than absent; track absence per source (maps vs namespaces) and label
namespaces as such.
- Web UI & docs: clear stale discovery state immediately when the
discovery portal changes, ignore leading/trailing spaces on typed
portals (also in the shared iSCSI setup), improve narrow-screen
layout of the controller view, refine wipe/edit wording, and update
the storage chapter and cluster API docs.
Tested on a six-node nested cluster against Linux nvmet and a NetApp
AFF A20 (two portals each): both guided setups, live migrations, single
and dual path cuts under write I/O with namespace notifications across
all nodes, restricted users, cluster-version refusal during upgrade,
local disk/wipe exclusions, and removal via wipe + Disconnect in the
web UI. Remaining edge cases (time limits, brief openers, detached
namespaces, multipathd-free notifications, etc.) are covered by unit
tests.
The ZFS-over-NVMe/TCP plugin on the list [2] ships its own initiator;
isolated properties prevent option clashes, and connect helpers can be
shared later. Leaving NVMe/FC partition wipes and Ceph OSDs on NVMe/FC
aligned with Fibre Channel LUNs is left for a SAN-wide follow-up.
[0]: https://lore.proxmox.com/pve-devel/20261119194655.3163258-1-t.lamprecht@proxmox.com/
[1]: https://lore.proxmox.com/pve-devel/20261122012605.1848824-1-t.lamprecht@proxmox.com/
[2]: https://lore.proxmox.com/pve-devel/20261005002609.571-1-joaquinvarela@neatech.ar/
pve-storage:
Thomas Lamprecht (14):
diskmanage: skip SMART queries for NVMe fabric namespaces
diskmanage: list NVMe namespaces attached over TCP or RDMA for SAN only
api: disks: refuse a local wipe of a network NVMe namespace
nvmeof: add a storage for NVMe over Fabrics subsystems
d/control: bump pve-common for plain parameter error names
api: config: check the cluster version before the first nvmeof storage
lvm: allow a volume group on an NVMe over Fabrics namespace
api: scan: add NVMe over Fabrics discovery
pvesm: add a scan command for NVMe over Fabrics
api: san luns: attribute NVMe namespaces to storage
api: add node-level NVMe over Fabrics status and controller removal
multipath: report the NVMe host NQN of each node
multipath: report NVMe over Fabrics namespaces in the cluster status
d/control: break pve-manager versions without namespace notifications
ApiChangeLog | 9 +-
debian/control | 5 +-
src/PVE/API2/Disks.pm | 14 +
src/PVE/API2/Makefile | 1 +
src/PVE/API2/NVMeOF.pm | 200 ++++++
src/PVE/API2/SAN/Cluster.pm | 38 +-
src/PVE/API2/SAN/Node.pm | 17 +-
src/PVE/API2/Storage/Config.pm | 5 +
src/PVE/API2/Storage/Scan.pm | 49 ++
src/PVE/CLI/pvesm.pm | 13 +
src/PVE/Diskmanage.pm | 58 +-
src/PVE/Makefile | 1 +
src/PVE/Multipath/Status.pm | 72 +-
src/PVE/NVMeOF.pm | 514 +++++++++++++
src/PVE/Storage.pm | 2 +
src/PVE/Storage/LVMPlugin.pm | 3 +-
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 300 ++++++++
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SAN.pm | 32 +-
src/test/Makefile | 6 +
src/test/disk_api_test.pm | 20 +-
.../multipath/disklist_expected.json | 16 -
.../nvme_smart/nvme0n1/device/transport | 1 +
src/test/disklist_test.pm | 104 ++-
src/test/run_multipath_api_tests.pl | 132 +++-
src/test/run_nvmeof_api_tests.pl | 222 ++++++
src/test/run_nvmeof_taint_tests.pl | 67 ++
src/test/run_nvmeof_tests.pl | 680 ++++++++++++++++++
src/test/run_san_api_tests.pl | 4 +-
src/test/run_san_lun_scan_tests.pl | 41 ++
src/test/run_san_nvme_tests.pl | 33 +
32 files changed, 2580 insertions(+), 82 deletions(-)
pve-docs:
Thomas Lamprecht (1):
storage: document NVMe over Fabrics storages
notifications.adoc | 5 +-
pve-gui.adoc | 12 ++-
pve-intro.adoc | 3 +-
pve-storage-lvm.adoc | 10 +-
pve-storage-multipath.adoc | 3 +-
pve-storage-nvmeof.adoc | 200 +++++++++++++++++++++++++++++++++++++
pvesm.adoc | 24 +++--
7 files changed, 236 insertions(+), 21 deletions(-)
pve-manager:
Thomas Lamprecht (10):
report: add the NVMe over Fabrics host NQN and subsystems
ui: storage: add NVMe over Fabrics storage
ui: lvm: offer NVMe over Fabrics storages as base storage
ui: storage: add a guided setup for shared LVM on NVMe over Fabrics
ui: node san: list NVMe over Fabrics controllers
ui: san: show the NVMe host NQN of each node
ui: san: show that a namespace uses native multipath
pvestatd: notify on NVMe over Fabrics namespaces as on multipath maps
ui: storage: SAN setup: ignore spaces around a typed portal
d/control: bump versioned dependencies for NVMe over Fabrics
PVE/MultipathNotification.pm | 21 +-
PVE/Report.pm | 6 +
PVE/Service/pvestatd.pm | 16 +-
debian/control | 8 +-
test/MultipathNotification_test.pl | 28 ++-
www/manager6/Makefile | 4 +-
www/manager6/SANUtils.js | 7 +-
www/manager6/Utils.js | 7 +
www/manager6/dc/SAN.js | 49 +++-
www/manager6/dc/StorageView.js | 23 +-
www/manager6/node/Config.js | 9 +-
www/manager6/node/NVMeOFControllers.js | 170 +++++++++++++
www/manager6/storage/IScsiEdit.js | 5 +-
www/manager6/storage/LVMEdit.js | 12 +-
www/manager6/storage/NVMeOFEdit.js | 162 ++++++++++++
www/manager6/storage/wizard/LunSelect.js | 35 ++-
www/manager6/storage/wizard/NodeIdentities.js | 57 +++--
.../storage/wizard/{IScsi.js => Target.js} | 236 +++++++++++++-----
www/manager6/storage/wizard/Wizard.js | 62 +++--
www/manager6/window/SANLunState.js | 38 ++-
www/manager6/window/SANLunWipe.js | 24 +-
21 files changed, 792 insertions(+), 187 deletions(-)
^ permalink raw reply [relevance 10%]
* [PATCH v4 storage 04/25] nvmeof: add a storage for NVMe over Fabrics subsystems
2026-11-23 1:47 10% [PATCH v4 storage,docs,manager 00/25] NVMe over Fabrics storage Thomas Lamprecht
@ 2026-11-23 1:47 17% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-23 1:47 UTC (permalink / raw)
To: pve-devel
NVMe/TCP namespaces need a manual nvme-cli setup on every node so far.
Add a storage type that connects one subsystem through each configured
portal and offers its namespaces as raw volumes. Native NVMe multipath
joins the paths and the kernel reconnects lost ones. Only one storage
may use a subsystem, as the LUN list, the controller list and the node
status attribute a subsystem to one storage.
The activation fails if no controller is live after connecting the
missing portals, also if none was missing, so that adding a storage
tells why. As adding a storage holds the lock of the configuration, it
tries no further portal after 15 seconds once a controller is live, or
after 45 seconds without one, and leaves the rest to the next
activation. A portal whose connect failed is retried after a minute, but
not one that only waited for another fabrics operation, and adding a
storage forgets those failures. The package nvme-cli is only
recommended, as no other storage type needs it.
The plugin isolates its properties, so names like 'portals' belong to
this storage type alone, and a third-party plugin that declares one of
them is still loaded. As the first in-tree plugin that isolates, it
makes the storage API check the parameters for adding and updating a
storage of any type against the options of that type alone, apart from
the sensitive properties of plugins that do not isolate theirs.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
ApiChangeLog | 9 +-
debian/control | 1 +
src/PVE/Makefile | 1 +
src/PVE/NVMeOF.pm | 306 ++++++++++++++++
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 300 ++++++++++++++++
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SAN.pm | 13 +
src/test/Makefile | 5 +
src/test/run_nvmeof_taint_tests.pl | 62 ++++
src/test/run_nvmeof_tests.pl | 543 +++++++++++++++++++++++++++++
src/test/run_san_nvme_tests.pl | 16 +
13 files changed, 1256 insertions(+), 5 deletions(-)
create mode 100644 src/PVE/NVMeOF.pm
create mode 100644 src/PVE/Storage/NVMeOFPlugin.pm
create mode 100755 src/test/run_nvmeof_taint_tests.pl
create mode 100755 src/test/run_nvmeof_tests.pl
diff --git a/ApiChangeLog b/ApiChangeLog
index e8fe58e8..91931d3e 100644
--- a/ApiChangeLog
+++ b/ApiChangeLog
@@ -101,10 +101,11 @@ Future changes should be documented in here.
declares a property of that name is then not loaded until it renames it, so prefer names that
are specific to the plugin, for example prefixed with its type.
- As soon as one such plugin is installed, the API checks the parameters for adding and updating a
- storage against the options of its type alone, for all storage types. Only the sensitive
- properties of a plugin that does not isolate its own are still accepted without being listed in
- its `options()`, by their own names: an alias that only another plugin declares for one is not.
+ Since the in-tree 'nvmeof' plugin isolates its properties, the API checks the parameters for
+ adding and updating a storage against the options of its type alone, for all storage types,
+ also for plugins of older API versions. Only the sensitive properties of a plugin that does not
+ isolate its own are still accepted without being listed in its `options()`, by their own names:
+ an alias that only another plugin declares for one is not.
Set 'sensitive-properties' in an isolating plugin, even if empty. Without it, the fallback list of
version 11 also applies to the plugin's own properties of these names.
diff --git a/debian/control b/debian/control
index fdcf8117..b5c2f529 100644
--- a/debian/control
+++ b/debian/control
@@ -55,6 +55,7 @@ Depends: bzip2,
${misc:Depends},
${perl:Depends},
Recommends: multipath-tools,
+ nvme-cli,
pve-esxi-import-tools (>= 0.6.0),
skopeo,
zfsutils-linux (>= 2.4.1-pve2),
diff --git a/src/PVE/Makefile b/src/PVE/Makefile
index 13fecbf8..238eefd4 100644
--- a/src/PVE/Makefile
+++ b/src/PVE/Makefile
@@ -4,6 +4,7 @@
install:
install -D -m 0644 Storage.pm ${DESTDIR}${PERLDIR}/PVE/Storage.pm
install -D -m 0644 Diskmanage.pm ${DESTDIR}${PERLDIR}/PVE/Diskmanage.pm
+ install -D -m 0644 NVMeOF.pm ${DESTDIR}${PERLDIR}/PVE/NVMeOF.pm
install -D -m 0644 ISCSI/Topology.pm ${DESTDIR}${PERLDIR}/PVE/ISCSI/Topology.pm
install -D -m 0644 Multipath.pm ${DESTDIR}${PERLDIR}/PVE/Multipath.pm
install -D -m 0644 Multipath/Config.pm ${DESTDIR}${PERLDIR}/PVE/Multipath/Config.pm
diff --git a/src/PVE/NVMeOF.pm b/src/PVE/NVMeOF.pm
new file mode 100644
index 00000000..c705835c
--- /dev/null
+++ b/src/PVE/NVMeOF.pm
@@ -0,0 +1,306 @@
+package PVE::NVMeOF;
+
+use v5.36;
+
+use Digest::SHA qw(sha1_hex);
+use Fcntl qw(:flock F_GETFD F_SETFD FD_CLOEXEC);
+use File::Path qw(make_path);
+use POSIX qw(ceil);
+use Socket qw(AF_INET AF_INET6 inet_ntop inet_pton);
+use Time::HiRes ();
+
+use PVE::JSONSchema;
+use PVE::Tools qw(dir_glob_foreach file_read_firstline file_set_contents run_command);
+
+use PVE::Diskmanage;
+
+our $NVME = '/usr/sbin/nvme';
+our $SYSFS = '/sys';
+our $HOSTNQN_FILE = '/etc/nvme/hostnqn';
+our $HOSTID_FILE = '/etc/nvme/hostid';
+our $RUN_DIR = '/run/pve/nvmeof';
+our $LOCK_WAIT = 10;
+# no control characters, which could reach logs and the arguments of nvme-cli
+our $NQN_PATTERN = 'nqn\.[^\s\x00-\x1f\x7f,=]+';
+our $DISCOVERY_NQN = 'nqn.2014-08.org.nvmexpress.discovery';
+our $TIMED_OUT = "NVMe over Fabrics operation timed out - it may still be running\n";
+
+sub canonical_address($addr) {
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ return inet_ntop(AF_INET, $packed);
+ }
+ if (defined(my $packed = inet_pton(AF_INET6, $addr))) {
+ return inet_ntop(AF_INET, substr($packed, 12))
+ if substr($packed, 0, 12) eq ("\0" x 10) . "\xff\xff";
+ return inet_ntop(AF_INET6, $packed);
+ }
+ return lc($addr);
+}
+
+# Link-local IPv6 needs a node-specific interface and cannot identify a shared configured portal.
+sub parse_portal($portal) {
+ my ($addr, $port);
+ if ($portal =~ m/^\[([0-9a-fA-F:.]+)\](?::([0-9]+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } elsif ($portal =~ m/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(?::([0-9]+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } else {
+ return undef;
+ }
+ return undef if defined($port) && ($port < 1 || $port > 65535);
+ $addr = canonical_address($addr);
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ my $multicast = (unpack('C', $packed) & 0xf0) == 0xe0;
+ return undef if $addr eq '0.0.0.0' || $addr eq '255.255.255.255' || $multicast;
+ } elsif (defined($packed = inet_pton(AF_INET6, $addr))) {
+ my $prefix = unpack('n', $packed);
+ return undef
+ if $addr eq '::' || ($prefix & 0xffc0) == 0xfe80 || ($prefix & 0xff00) == 0xff00;
+ } else {
+ return undef;
+ }
+ return { traddr => $addr, trsvcid => int($port // 4420) };
+}
+
+PVE::JSONSchema::register_format(
+ 'pve-storage-nvme-portal',
+ sub($portal, $noerr = undef) {
+ return $portal if parse_portal($portal);
+ return undef if $noerr;
+ die "value is not an IPv4 address or a bracketed IPv6 address with optional port\n";
+ },
+);
+
+sub format_path($path) {
+ # an IPv6 address, not the address of a Fibre Channel port, which has a colon too
+ my $ipv6 = $path->{traddr} =~ /:/ && $path->{traddr} =~ /^[0-9a-fA-F:.]+$/;
+ my $addr = $ipv6 ? "[$path->{traddr}]" : $path->{traddr};
+ return defined($path->{trsvcid}) ? "$addr:$path->{trsvcid}" : $addr;
+}
+
+sub storage_paths($scfg) {
+ return [map { parse_portal($_) // die "invalid portal '$_'\n" }
+ PVE::Tools::split_list($scfg->{portals})];
+}
+
+sub host_identity() {
+ my ($nqn) = (file_read_firstline($HOSTNQN_FILE) // '') =~ /\A($NQN_PATTERN)\z/;
+ my ($id) = (file_read_firstline($HOSTID_FILE) // '') =~
+ /\A([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\z/i;
+ if (!defined($nqn) || length($nqn) > 223) {
+ die "invalid or missing NVMe host NQN in '$HOSTNQN_FILE' - install nvme-cli and check the"
+ . " host identity\n";
+ }
+ die "invalid or missing NVMe host ID in '$HOSTID_FILE' - expected a nonzero UUID\n"
+ if !defined($id) || $id =~ /^[0-]+$/;
+ return { nqn => $nqn, id => lc($id) };
+}
+
+sub is_supported() { return -x $NVME ? 1 : 0 }
+
+sub assert_support() {
+ die "nvme-cli is not installed\n" if !is_supported();
+ run_command(['modprobe', 'nvme-tcp'], timeout => 10)
+ if !-e "$SYSFS/module/nvme_tcp";
+ my $multipath = file_read_firstline("$SYSFS/module/nvme_core/parameters/multipath") // '';
+ die "native NVMe multipath is disabled - enable nvme_core.multipath\n" if $multipath ne 'Y';
+}
+
+sub controllers() {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-fabrics/ctl";
+ dir_glob_foreach(
+ $dir,
+ 'nvme[0-9]+',
+ sub($name, @) {
+ my $address = file_read_firstline("$dir/$name/address") // return;
+ my %address = map { split(/=/, $_, 2) } grep { /=/ } split(/,/, $address);
+ return if !defined($address{traddr});
+ $res->{$name} = {
+ transport => file_read_firstline("$dir/$name/transport") // '',
+ subsystem => PVE::Diskmanage::read_subsysnqn("$dir/$name/subsysnqn") // '',
+ state => file_read_firstline("$dir/$name/state") // 'unknown',
+ traddr => canonical_address($address{traddr}),
+ trsvcid => $address{trsvcid},
+ };
+ },
+ );
+ return $res;
+}
+
+sub subsystem_controllers($subsystem) {
+ my $controllers = controllers();
+ return {
+ map { $_ => $controllers->{$_} } grep {
+ $controllers->{$_}->{subsystem} eq $subsystem
+ && $controllers->{$_}->{transport} eq 'tcp'
+ } keys %$controllers
+ };
+}
+
+# The NQN of a subsystem, untainted, or undef if it is invalid or the one of the discovery service.
+sub subsystem_nqn($nqn) {
+ my ($res) = ($nqn // '') =~ /\A($NQN_PATTERN)\z/;
+ return undef if !defined($res) || length($res) > 223 || $res eq $DISCOVERY_NQN;
+ return $res;
+}
+
+sub namespace_wwid($dev) {
+ return file_read_firstline("$SYSFS/block/$dev/wwid");
+}
+
+sub has_live_controller($controllers) {
+ return scalar(grep { $_->{state} eq 'live' } values %$controllers);
+}
+
+sub path_controller($controllers, $path) {
+ for my $name (sort keys %$controllers) {
+ my $ctrl = $controllers->{$name};
+ if ($ctrl->{traddr} eq $path->{traddr} && ($ctrl->{trsvcid} // '') eq $path->{trsvcid}) {
+ return $name;
+ }
+ }
+ return undef;
+}
+
+sub namespaces($subsystem) {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-subsystem";
+ dir_glob_foreach(
+ $dir,
+ 'nvme-subsys[0-9]+',
+ sub($subsys, @) {
+ # one that cannot be read could be this subsystem, whose namespaces must not look gone
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$dir/$subsys/subsysnqn")
+ // die "cannot read the NQN of NVMe subsystem '$subsys'\n";
+ return if $nqn ne $subsystem;
+ dir_glob_foreach(
+ "$dir/$subsys",
+ 'nvme[0-9]+n[0-9]+',
+ sub($dev, @) {
+ # a failed read must not look like a namespace that is gone
+ my $wwid = file_read_firstline("$SYSFS/block/$dev/wwid")
+ // die "cannot read the WWID of namespace '$dev'\n";
+ my $size = file_read_firstline("$SYSFS/block/$dev/size")
+ // die "cannot read the size of namespace '$dev'\n";
+ $res->{$dev} = { wwid => $wwid, size => int($size) * 512 };
+ },
+ );
+ },
+ );
+ return $res;
+}
+
+# $limit sets the time the operation may take in all, including the wait for the lock.
+sub with_lock($code, $limit = undef) {
+ my $total = $LOCK_WAIT + 35;
+ # an alarm counts whole seconds and none at zero
+ $total = ceil($limit) if defined($limit);
+ $total = 1 if $total < 1;
+ my ($res, $timeout) = PVE::Tools::run_fork_with_timeout(
+ $total,
+ sub {
+ make_path($RUN_DIR);
+ open(my $lock, '>>', "$RUN_DIR/fabrics.lock") or die "cannot open NVMe lock - $!\n";
+ # A busy lock fails the operation, so wait a while for it, but give up before the time
+ # limit, which counts as a hanging operation.
+ my $wait = $LOCK_WAIT < $total ? $LOCK_WAIT : $total - 1;
+ my $deadline = Time::HiRes::time() + $wait;
+ while (!flock($lock, LOCK_EX | LOCK_NB)) {
+ die "NVMe over Fabrics is busy - another operation is still running\n"
+ if Time::HiRes::time() >= $deadline;
+ Time::HiRes::usleep(100_000);
+ }
+ # Commands inherit the lock, so that it stays held until they exit, even if the caller
+ # timed out while one was stuck in the kernel.
+ my $flags = fcntl($lock, F_GETFD, 0) // die "cannot read NVMe lock flags - $!\n";
+ fcntl($lock, F_SETFD, $flags & ~FD_CLOEXEC)
+ or die "cannot inherit NVMe lock - $!\n";
+ return $code->();
+ },
+ );
+ die $TIMED_OUT if $timeout;
+ return $res;
+}
+
+my sub retry_file($scfg, $path) {
+ my ($key) =
+ sha1_hex(join(
+ "\0", $scfg->{subsysnqn}, format_path($path), $scfg->{'fast-io-fail-tmo'} // 120)) =~
+ /\A([0-9a-f]{40})\z/;
+ return "$RUN_DIR/retry/$key";
+}
+
+sub in_cooldown($scfg, $path) {
+ my $mtime = (stat(retry_file($scfg, $path)))[9] // return 0;
+ my $age = time() - $mtime;
+ return $age > -60 && $age < 60;
+}
+
+sub note_connect_failure($scfg, $path) {
+ make_path("$RUN_DIR/retry");
+ file_set_contents(retry_file($scfg, $path), '');
+}
+
+sub clear_connect_failures($scfg) {
+ unlink(retry_file($scfg, $_)) for storage_paths($scfg)->@*;
+}
+
+sub connect_path($scfg, $path, $limit = undef) {
+ my $nqn = subsystem_nqn($scfg->{subsysnqn}) // die "invalid subsystem NQN\n";
+ my ($fail) = ($scfg->{'fast-io-fail-tmo'} // 120) =~ /\A(-?[0-9]+)\z/;
+ die "invalid fast I/O fail timeout\n" if !defined($fail) || $fail < -1;
+ # A connect that hangs until the time limit failed too, but the process that would note it is
+ # gone by then.
+ my $res = eval {
+ with_lock(
+ sub {
+ return if path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ assert_support();
+ my $host = host_identity();
+ # only a failed attempt is a failure of the portal, not a busy lock
+ eval {
+ run_command(
+ [
+ $NVME,
+ 'connect',
+ '--transport=tcp',
+ '--nqn',
+ $nqn,
+ '--traddr',
+ $path->{traddr},
+ '--trsvcid',
+ $path->{trsvcid},
+ '--hostnqn',
+ $host->{nqn},
+ '--hostid',
+ $host->{id},
+ '--ctrl-loss-tmo=-1',
+ '--fast_io_fail_tmo',
+ $fail,
+ ],
+ timeout => 30,
+ errmsg => 'nvme connect',
+ );
+ # nvme-cli can exit successfully without having connected
+ die "no controller appeared\n"
+ if !path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ };
+ if (my $err = $@) {
+ note_connect_failure($scfg, $path);
+ die $err;
+ }
+ unlink(retry_file($scfg, $path));
+ return;
+ },
+ $limit,
+ );
+ };
+ if (my $err = $@) {
+ note_connect_failure($scfg, $path) if $err eq $TIMED_OUT;
+ die $err;
+ }
+ return $res;
+}
+
+1;
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index c640cd8e..c77a6755 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -33,6 +33,7 @@ use PVE::Storage::LvmThinPlugin;
use PVE::Storage::NFSPlugin;
use PVE::Storage::CIFSPlugin;
use PVE::Storage::ISCSIPlugin;
+use PVE::Storage::NVMeOFPlugin;
use PVE::Storage::RBDPlugin;
use PVE::Storage::CephFSPlugin;
use PVE::Storage::ISCSIDirectPlugin;
@@ -58,6 +59,7 @@ PVE::Storage::LvmThinPlugin->register();
PVE::Storage::NFSPlugin->register();
PVE::Storage::CIFSPlugin->register();
PVE::Storage::ISCSIPlugin->register();
+PVE::Storage::NVMeOFPlugin->register();
PVE::Storage::RBDPlugin->register();
PVE::Storage::CephFSPlugin->register();
PVE::Storage::ISCSIDirectPlugin->register();
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index a2df83c0..7f2ff6c8 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -6,6 +6,7 @@ SOURCES= \
NFSPlugin.pm \
CIFSPlugin.pm \
ISCSIPlugin.pm \
+ NVMeOFPlugin.pm \
CephFSPlugin.pm \
RBDPlugin.pm \
ISCSIDirectPlugin.pm \
diff --git a/src/PVE/Storage/NVMeOFPlugin.pm b/src/PVE/Storage/NVMeOFPlugin.pm
new file mode 100644
index 00000000..77b7e541
--- /dev/null
+++ b/src/PVE/Storage/NVMeOFPlugin.pm
@@ -0,0 +1,300 @@
+package PVE::Storage::NVMeOFPlugin;
+
+use v5.36;
+
+use Cwd ();
+use Time::HiRes ();
+
+use PVE::Network;
+
+use PVE::Diskmanage;
+use PVE::NVMeOF;
+use PVE::Storage::Plugin;
+
+use base qw(PVE::Storage::Plugin);
+
+# Adding a storage activates it under the lock of the storage configuration, so no further portal is
+# tried after this many seconds once a controller is live, or after three times as long without one.
+# Later activations connect the rest.
+our $ACTIVATION_BUDGET = 15;
+
+sub type { return 'nvmeof' }
+
+sub plugindata {
+ return {
+ content => [{ images => 1, 'vm-vol' => 1, none => 1 }, { images => 1 }],
+ select_existing => 1,
+ 'isolate-properties' => 1,
+ 'advanced-properties' => {
+ 'fast-io-fail-tmo' => 1,
+ },
+ 'hidden-properties' => {
+ bwlimit => 1,
+ },
+ 'sensitive-properties' => {},
+ };
+}
+
+sub properties {
+ return {
+ subsysnqn => {
+ title => "Subsystem",
+ description => 'The NQN of the NVMe subsystem.',
+ type => 'string',
+ pattern => $PVE::NVMeOF::NQN_PATTERN,
+ maxLength => 223,
+ },
+ portals => {
+ title => "Portals",
+ description =>
+ 'TCP portals of the NVMe subsystem, as IPv4 or bracketed IPv6 addresses'
+ . ' with an optional port (default 4420).',
+ type => 'string',
+ format => 'pve-storage-nvme-portal-list',
+ },
+ 'fast-io-fail-tmo' => {
+ title => "Fail I/O After (s)",
+ description => 'Seconds before I/O through a reconnecting path fails. -1 disables'
+ . ' this timeout; I/O can remain queued while paths reconnect.',
+ type => 'integer',
+ minimum => -1,
+ default => 120,
+ },
+ };
+}
+
+sub options {
+ return {
+ subsysnqn => { fixed => 1 },
+ portals => {},
+ 'fast-io-fail-tmo' => { optional => 1 },
+ nodes => { optional => 1 },
+ disable => { optional => 1 },
+ content => { optional => 1 },
+ bwlimit => { optional => 1 },
+ };
+}
+
+my sub assert_valid_config($scfg) {
+ die "the discovery subsystem cannot be used as storage\n"
+ if $scfg->{subsysnqn} eq $PVE::NVMeOF::DISCOVERY_NQN;
+ my $paths = PVE::NVMeOF::storage_paths($scfg);
+ # the list format also accepts a list of separators only
+ die "no portal given\n" if !@$paths;
+ my %seen;
+ for my $path (@$paths) {
+ my $portal = PVE::NVMeOF::format_path($path);
+ die "portal '$portal' is listed more than once\n" if $seen{$portal}++;
+ }
+}
+
+sub on_add_hook($class, $storeid, $scfg, %param) {
+ assert_valid_config($scfg);
+ # the LUN and controller lists and the node status attribute a subsystem to its one storage
+ my $ids = PVE::Storage::config()->{ids};
+ for my $sid (sort keys %$ids) {
+ next if $sid eq $storeid || $ids->{$sid}->{type} ne 'nvmeof';
+ die "storage '$sid' already uses this subsystem\n"
+ if $ids->{$sid}->{subsysnqn} eq $scfg->{subsysnqn};
+ }
+ # adding the storage again, for example once the array allows the node, tries all portals
+ PVE::NVMeOF::clear_connect_failures($scfg);
+ return;
+}
+
+sub on_update_hook_full($class, $storeid, $scfg, $update, $delete, $sensitive, @) {
+ my $merged = { %$scfg, %$update };
+ delete $merged->{$_} for ($delete // [])->@*;
+ # without the property, the default of the plugin applies, which serves images
+ $merged->{content} //= $class->plugindata()->{content}->[1];
+ assert_valid_config($merged);
+ # the namespace of a volume group must not become a disk image of a guest as well
+ if (
+ PVE::Storage::san_storage_serves_images($merged)
+ && !PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ my $ids = PVE::Storage::config()->{ids};
+ for my $sid (sort keys %$ids) {
+ die "storage '$sid' uses a namespace of this storage as base, so it cannot serve"
+ . " images\n"
+ if $ids->{$sid}->{type} eq 'lvm'
+ && ($ids->{$sid}->{base} // '') =~ /^\Q$storeid\E:/;
+ }
+ }
+ # a changed portal list, for example with a portal fixed and added again, tries all of them
+ PVE::NVMeOF::clear_connect_failures($merged) if exists($update->{portals});
+ return $class->SUPER::on_update_hook_full($storeid, $scfg, $update, $delete, $sensitive);
+}
+
+sub parse_volname($class, $volname) {
+ if ($volname =~ m!^(nvme-[a-zA-Z0-9_.:+-]+)$! && $volname !~ /-part[0-9]+$/) {
+ return ($class->guest_volume_vtype('raw'), $1, undef, undef, undef, undef, 'raw');
+ }
+ die "unable to parse NVMe over Fabrics volume name '$volname'\n";
+}
+
+# The name of a volume can be the by-id name of any NVMe device, also of a local disk or of a
+# namespace of another subsystem.
+sub assert_namespace($scfg, $volname, $real) {
+ my ($dev) = $real =~ m!^/dev/(nvme[0-9]+n[0-9]+)$!;
+ die "volume '$volname' is not an NVMe namespace\n" if !defined($dev);
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$PVE::NVMeOF::SYSFS/block/$dev/device/subsysnqn")
+ // '';
+ die "volume '$volname' is not part of subsystem '$scfg->{subsysnqn}'\n"
+ if $nqn ne $scfg->{subsysnqn};
+ # another by-id name of the subsystem, like model and serial, can name another namespace
+ my $wwid = PVE::NVMeOF::namespace_wwid($dev) // '';
+ die "volume '$volname' is not named after the WWID of its namespace\n"
+ if $volname ne "nvme-$wwid";
+}
+
+sub filesystem_path($class, $scfg, $volname, $snapname = undef, @) {
+ die "snapshot is not possible on NVMe over Fabrics storage\n" if defined($snapname);
+ my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+ my $path = "/dev/disk/by-id/$name";
+ # not every user of a path activates the volume first, and the base volume of an LVM storage
+ # has no device before its storage connects
+ my $real = Cwd::realpath($path);
+ assert_namespace($scfg, $volname, $real) if defined($real) && -e $real;
+ return wantarray ? ($path, $vmid, $vtype) : $path;
+}
+
+sub create_base { die "can't create base images in NVMe over Fabrics storage\n" }
+sub clone_image { die "can't clone images in NVMe over Fabrics storage\n" }
+sub alloc_image { die "can't allocate space in NVMe over Fabrics storage\n" }
+sub free_image { die "can't free space in NVMe over Fabrics storage\n" }
+sub volume_resize { die "volume resize is not possible on NVMe over Fabrics storage\n" }
+
+sub list_volumes($class, $storeid, $scfg, $vmid = undef, $content_types = undef, @) {
+ my $res = $class->list_images($storeid, $scfg, $vmid);
+ $_->{content} = 'images' for @$res;
+ return $res;
+}
+
+sub list_images($class, $storeid, $scfg, $vmid = undef, $vollist = undef, $cache = undef, @) {
+ return [] if defined($vmid) && !$vollist;
+ my $namespaces = PVE::NVMeOF::namespaces($scfg->{subsysnqn});
+ my $res = [];
+ for my $dev (sort keys %$namespaces) {
+ my $ns = $namespaces->{$dev};
+ my $volid = "$storeid:nvme-$ns->{wwid}";
+ next if $vollist && !grep { $_ eq $volid } @$vollist;
+ push @$res,
+ {
+ volid => $volid,
+ format => 'raw',
+ size => $ns->{size},
+ vmid => 0,
+ };
+ }
+ return $res;
+}
+
+sub status($class, $storeid, $scfg, $cache = undef, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ return (0, 0, 0, PVE::NVMeOF::has_live_controller($controllers) ? 1 : 0);
+}
+
+sub activate_storage($class, $storeid, $scfg, $cache = undef, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ my @missing = grep { !defined(PVE::NVMeOF::path_controller($controllers, $_)) }
+ PVE::NVMeOF::storage_paths($scfg)->@*;
+ if (!@missing) {
+ # the kernel reconnects them, but meanwhile the namespaces cannot be used
+ die "no controller of the subsystem is live, all are reconnecting\n"
+ if !PVE::NVMeOF::has_live_controller($controllers);
+ return;
+ }
+ # A missing prerequisite is no failure of a portal, so the portals stay eligible for the next
+ # attempt. A storage with a usable path still works, with fewer paths.
+ eval {
+ PVE::NVMeOF::assert_support();
+ PVE::NVMeOF::host_identity();
+ };
+ if (my $err = $@) {
+ die $err if !PVE::NVMeOF::has_live_controller($controllers);
+ warn "storage '$storeid': cannot connect to the other portals - $err";
+ return;
+ }
+ my @errors;
+ my $live = PVE::NVMeOF::has_live_controller($controllers);
+ my $start = Time::HiRes::time();
+ # The time limit also bounds an attempt that starts late, so that creating a storage ends well
+ # within the lock on the storage configuration it holds meanwhile.
+ my $left = sub { $start + ($live ? 1 : 3) * $ACTIVATION_BUDGET - Time::HiRes::time() };
+ for my $path (@missing) {
+ my $portal = PVE::NVMeOF::format_path($path);
+ if ($left->() < 5) {
+ push @errors, "$portal: not tried within the time limit";
+ next;
+ }
+ if (PVE::NVMeOF::in_cooldown($scfg, $path)) {
+ push @errors, "$portal: failed less than a minute ago";
+ next;
+ }
+ eval {
+ if (!PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2)) {
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ die "no answer from portal\n";
+ }
+ PVE::NVMeOF::connect_path($scfg, $path, $left->());
+ };
+ if (my $err = $@) {
+ warn "storage '$storeid': connecting to '$portal' failed - $err";
+ chomp $err;
+ push @errors, "$portal: $err";
+ } else {
+ $live = 1;
+ }
+ }
+ # some paths are enough, but without a usable one the namespaces cannot be used
+ $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ if (!PVE::NVMeOF::has_live_controller($controllers)) {
+ die "cannot connect to any portal - " . join('; ', @errors) . "\n" if @errors;
+ die "no controller of the subsystem is live yet\n";
+ }
+ return;
+}
+
+sub deactivate_storage { return }
+
+sub check_connection($class, $storeid, $scfg, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ return 1 if PVE::NVMeOF::has_live_controller($controllers);
+ # Creating a storage runs this check and the activation while it holds the configuration lock.
+ # The portals left untried go to the activation, which has a time limit of its own and skips
+ # those that just failed.
+ my $deadline = Time::HiRes::time() + $ACTIVATION_BUDGET;
+ for my $path (PVE::NVMeOF::storage_paths($scfg)->@*) {
+ return 1 if Time::HiRes::time() >= $deadline;
+ next if defined(PVE::NVMeOF::path_controller($controllers, $path));
+ next if PVE::NVMeOF::in_cooldown($scfg, $path);
+ return 1 if PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2);
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ }
+ return 0;
+}
+
+sub activate_volume($class, $storeid, $scfg, $volname, $snapname = undef, $cache = undef, @) {
+ my $path = $class->filesystem_path($scfg, $volname, $snapname);
+ # as for the multipath map of an iSCSI LUN, a status pass does not wait for the device
+ my $deadline = Time::HiRes::time() + ($cache && $cache->{status_only} ? 0 : 10);
+ while (!-b $path && Time::HiRes::time() < $deadline) {
+ last if !keys PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn})->%*;
+ Time::HiRes::usleep(250_000);
+ }
+ my $real = Cwd::realpath($path);
+ die "volume '$volname' is not available on this node\n" if !$real || !-b $real;
+ assert_namespace($scfg, $volname, $real);
+}
+
+sub volume_has_feature(
+ $class, $scfg, $feature, $storeid, $volname,
+ $snapname = undef,
+ $running = undef, @,
+) {
+ return 1 if $feature eq 'copy' && !defined($snapname);
+ return undef;
+}
+
+1;
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index fe243679..7079a259 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -42,7 +42,7 @@ our @COMMON_TAR_FLAGS = qw(
);
our @SHARED_STORAGE = (
- 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs',
+ 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs', 'nvmeof',
);
our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index 0a9e441c..53c24c9e 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -302,6 +302,11 @@ sub lun_partitions($lun) {
}
sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my $name = basename($lun->{devpath});
+ my $nqn =
+ $name =~ /^nvme\d+n\d+$/
+ ? PVE::Diskmanage::read_subsysnqn("/sys/block/$name/device/subsysnqn")
+ : undef;
my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
[$lun->{devpath}, lun_partitions($lun)->@*],
)->@*;
@@ -324,6 +329,14 @@ sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
) {
die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
}
+ if (
+ $type eq 'nvmeof'
+ && defined($nqn)
+ && $scfg->{subsysnqn} eq $nqn
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this subsystem\n";
+ }
next if $type ne 'lvm' || !$scfg->{base};
my $base = PVE::Multipath::parse_base_volume($scfg->{base});
my $matches = $base
diff --git a/src/test/Makefile b/src/test/Makefile
index 3b902c43..ceabd991 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -17,6 +17,7 @@ test: \
test_lvmplugin \
test_multipath \
test_multipath_api \
+ test_nvmeof \
test_ovf \
test_plugin \
test_remote_command \
@@ -115,3 +116,7 @@ test_san_api: run_san_api_tests.pl run_san_wipe_tests.pl run_san_nvme_tests.pl
test_disk_api: run_disk_api_tests.pl
./run_disk_api_tests.pl
+
+test_nvmeof: run_nvmeof_tests.pl run_nvmeof_taint_tests.pl
+ ./run_nvmeof_tests.pl
+ perl -T ./run_nvmeof_taint_tests.pl
diff --git a/src/test/run_nvmeof_taint_tests.pl b/src/test/run_nvmeof_taint_tests.pl
new file mode 100755
index 00000000..6fd37410
--- /dev/null
+++ b/src/test/run_nvmeof_taint_tests.pl
@@ -0,0 +1,62 @@
+#!/usr/bin/perl -T
+
+use v5.36;
+use lib qw(..);
+use File::Temp qw(tempdir);
+use Scalar::Util qw(tainted);
+use Test::MockModule;
+use Test::More;
+
+use PVE::Tools qw(file_get_contents file_set_contents);
+
+use PVE::NVMeOF;
+
+$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
+delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
+my $dir = tempdir('nvmeof-taint-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::HOSTNQN_FILE = "$dir/hostnqn";
+local $PVE::NVMeOF::HOSTID_FILE = "$dir/hostid";
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+file_set_contents($PVE::NVMeOF::HOSTNQN_FILE, "nqn.host\n");
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "12345678-1234-1234-1234-123456789abc\n");
+file_set_contents("$dir/config", "nqn.test\n192.0.2.1\n120\n");
+my ($nqn, $portal, $fail) = split(/\n/, file_get_contents("$dir/config"));
+ok(tainted($nqn), 'configuration input is tainted');
+my $nvme = Test::MockModule->new('PVE::NVMeOF');
+$nvme->mock(with_lock => sub { $_[0]->() });
+my $commands = 0;
+$nvme->mock(
+ subsystem_controllers => sub {
+ return $commands ? { nvme0 => { traddr => '192.0.2.1', trsvcid => 4420 } } : {};
+ },
+);
+$nvme->mock(assert_support => sub { });
+$nvme->mock(
+ run_command => sub($cmd, %opts) {
+ $commands++;
+ is(
+ scalar(grep { tainted($_) } @$cmd),
+ 0,
+ 'all connect operands are validated and untainted',
+ );
+ PVE::Tools::run_command(['/usr/bin/true', @$cmd], timeout => 5);
+ },
+);
+my $path = PVE::NVMeOF::parse_portal($portal);
+eval { PVE::NVMeOF::connect_path({ subsysnqn => $nqn, 'fast-io-fail-tmo' => $fail }, $path) };
+is($@, '', 'connect command can execute in taint mode');
+is($commands, 1, 'one connect');
+PVE::NVMeOF::note_connect_failure({ subsysnqn => $nqn }, $path);
+ok(
+ PVE::NVMeOF::in_cooldown({ subsysnqn => $nqn }, $path),
+ 'cooldown accepts validated file-backed configuration',
+);
+for my $bad ('nqn.bad,nqn=other', "nqn.test\n", 'nqn.2014-08.org.nvmexpress.discovery') {
+ eval { PVE::NVMeOF::connect_path({ subsysnqn => $bad }, $path) };
+ like($@, qr/invalid subsystem/, 'invalid connect subsystem refused');
+}
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "00000000-0000-0000-0000-000000000000\n");
+eval { PVE::NVMeOF::host_identity() };
+like($@, qr/nonzero UUID/, 'zero host ID refused');
+
+done_testing();
diff --git a/src/test/run_nvmeof_tests.pl b/src/test/run_nvmeof_tests.pl
new file mode 100755
index 00000000..fc2b7078
--- /dev/null
+++ b/src/test/run_nvmeof_tests.pl
@@ -0,0 +1,543 @@
+#!/usr/bin/perl
+
+use v5.36;
+use lib qw(..);
+use Fcntl qw(:flock);
+use File::Path qw(make_path remove_tree);
+use File::Temp qw(tempdir);
+use POSIX ();
+use Test::MockModule;
+use Test::More;
+use Time::HiRes ();
+
+use PVE::Tools qw(file_set_contents);
+
+use PVE::NVMeOF;
+use PVE::Storage;
+
+my $dir = tempdir('nvmeof-test-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+local $PVE::NVMeOF::SYSFS = "$dir/sys";
+my $class = 'PVE::Storage::NVMeOFPlugin';
+my $cfg = {
+ type => 'nvmeof',
+ subsysnqn => 'nqn.test',
+ portals => '192.0.2.1,[2001:db8::2]:4421',
+ content => { none => 1 },
+};
+
+subtest 'configuration, portals and volumes' => sub {
+ is(PVE::Storage::Plugin->lookup('nvmeof'), $class, 'plugin registered');
+ is_deeply(
+ [sort keys $class->properties()->%*],
+ [qw(fast-io-fail-tmo portals subsysnqn)],
+ 'only three plugin-specific properties',
+ );
+ my sub nvmeof_schema($schema) {
+ my @types = map { ($_->{oneOf} // [])->@* } ($schema->{allOf} // [])->@*;
+ my ($nvmeof) = grep { $_->{'instance-type'} eq 'nvmeof' } @types;
+ return $nvmeof->{properties} // {};
+ }
+ my $create = nvmeof_schema(PVE::Storage::Plugin->createSchema());
+ is_deeply(
+ [sort grep { !$create->{$_}->{optional} } keys $create->%*],
+ [qw(portals subsysnqn)],
+ 'adding a storage requires the subsystem and the portals',
+ );
+ my $update = nvmeof_schema(PVE::Storage::Plugin->updateSchema());
+ ok($update->{portals} && !$update->{subsysnqn}, 'the subsystem cannot be changed');
+ my $parsed = PVE::Storage::Plugin->parse_config(
+ 'storage.cfg',
+ "nvmeof: fabric\n\tsubsysnqn nqn.test\n\tportals 192.0.2.1\n\tcontent none\n",
+ );
+ is($parsed->{ids}->{fabric}->{subsysnqn}, 'nqn.test', 'storage.cfg accepts the plugin');
+ is_deeply(
+ $parsed->{ids}->{fabric}->{content},
+ { none => 1 },
+ 'connection-only content parses',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ { traddr => '192.0.2.1', trsvcid => 4420 },
+ 'default I/O port',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('[2001:0db8::1]:4421'),
+ { traddr => '2001:db8::1', trsvcid => 4421 },
+ 'canonical IPv6',
+ );
+ is(
+ PVE::NVMeOF::format_path({ traddr => '2001:db8::1', trsvcid => 4421 }),
+ '[2001:db8::1]:4421',
+ 'an IPv6 portal in brackets',
+ );
+ is(
+ PVE::NVMeOF::format_path({ traddr => 'nn-0x2000:pn-0x2001' }),
+ 'nn-0x2000:pn-0x2001',
+ 'the address of a Fibre Channel port as it is',
+ );
+
+ for my $bad (
+ 'host.example', '1.2.3.4:0', '1.2.3.4:65536', '[fe80::1]', '[::]', '224.0.0.1',
+ ) {
+ ok(!PVE::NVMeOF::parse_portal($bad), "invalid portal $bad");
+ }
+ eval { $class->on_add_hook('fabric', { %$cfg, portals => '192.0.2.1,192.0.2.1:4420' }); };
+ like($@, qr/listed more than once/, 'duplicate portals refused');
+ eval { $class->on_add_hook('fabric', { %$cfg, portals => ',,' }); };
+ like($@, qr/no portal given/, 'a list without a portal refused');
+ eval {
+ $class->on_add_hook(
+ 'fabric',
+ { %$cfg, subsysnqn => 'nqn.2014-08.org.nvmexpress.discovery' },
+ );
+ };
+ like($@, qr/discovery subsystem/, 'discovery subsystem refused');
+ ok(!PVE::NVMeOF::subsystem_nqn("nqn.test\e[31m"),
+ 'an NQN with a control character refused');
+ ok(!PVE::NVMeOF::subsystem_nqn("nqn.test\x{2028}x"), 'so is one with a Unicode separator');
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $ids = { fabric => $cfg, local => { type => 'dir' } };
+ $storage->mock(config => sub { { ids => $ids } });
+ my $first = PVE::NVMeOF::storage_paths($cfg)->[0];
+ PVE::NVMeOF::note_connect_failure($cfg, $first);
+ is(eval { $class->on_add_hook('fabric', $cfg); 1 }, 1, 'a storage is not in its own way');
+ ok(!PVE::NVMeOF::in_cooldown($cfg, $first), 'adding it tries all portals again');
+ eval { $class->on_add_hook('second', {%$cfg}) };
+ like($@, qr/storage 'fabric' already uses this subsystem/, 'one storage per subsystem');
+ $ids->{vg} = { type => 'lvm', base => 'fabric:nvme-eui.0123456789abcdef', vgname => 'vg' };
+ my $images = { content => { images => 1 } };
+ eval { $class->on_update_hook_full('fabric', $cfg, $images, [], {}) };
+ like(
+ $@,
+ qr/storage 'vg' uses a namespace/,
+ 'no direct use of a namespace with a volume group',
+ );
+ my $none = { %$cfg, content => { none => 1 } };
+ eval { $class->on_update_hook_full('fabric', $none, {}, ['content'], {}) };
+ like($@, qr/storage 'vg' uses a namespace/, 'also not through the default content');
+ is(
+ eval { $class->on_update_hook_full('other', $cfg, $images, [], {}); 1 },
+ 1,
+ 'unless unused',
+ );
+ delete $ids->{vg};
+ PVE::NVMeOF::note_connect_failure($cfg, $first);
+ $class->on_update_hook_full('fabric', $cfg, { portals => $cfg->{portals} }, [], {});
+ ok(!PVE::NVMeOF::in_cooldown($cfg, $first), 'a new portal list tries all portals again');
+ is(
+ scalar($class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef')),
+ '/dev/disk/by-id/nvme-eui.0123456789abcdef',
+ 'stable volume path',
+ );
+ {
+ my $disk = Test::MockModule->new('PVE::Diskmanage');
+ my $nqn = 'nqn.other';
+ $disk->redefine(read_subsysnqn => sub { $nqn });
+ my $sysfs = Test::MockModule->new('PVE::NVMeOF');
+ $sysfs->redefine(namespace_wwid => sub { 'x' });
+ my $check = sub {
+ eval { PVE::Storage::NVMeOFPlugin::assert_namespace($cfg, @_) };
+ $@;
+ };
+ like($check->('nvme-x', '/dev/nvme0n1'), qr/not part of subsystem/, 'other subsystem');
+ like($check->('nvme-x', '/dev/sda'), qr/not an NVMe namespace/, 'other device type');
+ like($check->('nvme-x', '/dev/nvme0n1p1'), qr/not an NVMe namespace/, 'partition');
+ $nqn = 'nqn.test';
+ is($check->('nvme-x', '/dev/nvme0n1'), '', 'namespace of the subsystem');
+ like(
+ $check->('nvme-Vendor_Model_123_1', '/dev/nvme0n1'),
+ qr/not named after the WWID/,
+ 'another by-id name of a namespace of the subsystem',
+ );
+ my $cwd = Test::MockModule->new('Cwd');
+ $cwd->redefine(realpath => sub { $dir });
+ eval { $class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef') };
+ like($@, qr/not an NVMe namespace/, 'the path of an existing device is checked');
+ }
+
+ for my $bad ('nvme-../../sda', 'nvme-eui.abc-part1', 'sda') {
+ eval { $class->parse_volname($bad) };
+ like($@, qr/unable to parse/, "invalid volume $bad");
+ }
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ $nvme->mock(namespaces => sub { { nvme0n1 => { wwid => 'eui.abc', size => 4096 } } });
+ is(
+ $class->list_volumes('fabric', $cfg)->[0]->{volid},
+ 'fabric:nvme-eui.abc',
+ 'content none still offers bases',
+ );
+ is_deeply($class->list_images('fabric', $cfg, 100), [], 'namespaces have no VM owner');
+ $nvme->mock(subsystem_controllers => sub { {} });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test') };
+ like($@, qr/not available/,
+ 'missing namespace fails without waiting on absent controllers');
+ my ($now, $queries) = (0, 0);
+ my $clock = Test::MockModule->new('Time::HiRes');
+ $clock->redefine(time => sub { $now += 5 }, usleep => sub { });
+ $nvme->mock(subsystem_controllers => sub { $queries++; { nvme1 => {} } });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test', undef, {}) };
+ is($queries, 1, 'a missing namespace of a connected subsystem is waited for');
+ eval {
+ $class->activate_volume(
+ 'fabric',
+ $cfg,
+ 'nvme-nonexistent-test',
+ undef,
+ { status_only => 1 },
+ );
+ };
+ like($@, qr/not available/, 'in a status pass it fails as well');
+ is($queries, 1, 'but without a wait');
+ is(
+ ($class->parse_volname('nvme-eui.0123456789abcdef'))[0],
+ 'vm-vol',
+ 'namespaces are VM disks',
+ );
+};
+
+subtest 'sysfs topology' => sub {
+ my $sys = $PVE::NVMeOF::SYSFS;
+ make_path(
+ "$sys/class/nvme-fabrics/ctl/nvme1",
+ "$sys/class/nvme-subsystem/nvme-subsys0/nvme0n1",
+ "$sys/block/nvme0n1",
+ );
+ my %attrs = (
+ address => 'traddr=192.0.2.1,trsvcid=4420',
+ transport => 'tcp',
+ subsysnqn => 'nqn.test',
+ state => 'connecting',
+ );
+ file_set_contents("$sys/class/nvme-fabrics/ctl/nvme1/$_", "$attrs{$_}\n") for keys %attrs;
+ file_set_contents("$sys/class/nvme-subsystem/nvme-subsys0/subsysnqn", "nqn.test\n");
+ file_set_contents("$sys/block/nvme0n1/wwid", "eui.abc\n");
+ file_set_contents("$sys/block/nvme0n1/size", "8\n");
+ is(
+ PVE::NVMeOF::controllers()->{nvme1}->{state},
+ 'connecting',
+ 'reconnecting controller is still present',
+ );
+ is(
+ PVE::NVMeOF::path_controller(
+ PVE::NVMeOF::subsystem_controllers('nqn.test'),
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ ),
+ 'nvme1',
+ 'portal controller found',
+ );
+ is_deeply(
+ PVE::NVMeOF::namespaces('nqn.test'),
+ { nvme0n1 => { wwid => 'eui.abc', size => 4096 } },
+ 'namespace facts',
+ );
+ is_deeply(PVE::NVMeOF::namespaces('nqn.other'), {}, 'other subsystem excluded');
+ unlink("$sys/block/nvme0n1/wwid");
+ eval { PVE::NVMeOF::namespaces('nqn.test') };
+ like($@, qr/cannot read the WWID/, 'an unreadable namespace is an error, not a gone one');
+ file_set_contents("$sys/block/nvme0n1/wwid", "eui.abc\n");
+ make_path("$sys/class/nvme-subsystem/nvme-subsys9");
+ eval { PVE::NVMeOF::namespaces('nqn.test') };
+ like($@, qr/cannot read the NQN/, 'so is a subsystem that could be the one asked for');
+ rmdir("$sys/class/nvme-subsystem/nvme-subsys9");
+};
+
+subtest 'serialized commands inherit the lock' => sub {
+ local $PVE::NVMeOF::LOCK_WAIT = 0;
+ my $script = join(
+ ' ',
+ 'my @held = grep { (readlink($_) // "") =~ /fabrics.lock$/ } glob("/proc/self/fd/*");',
+ 'die "not inherited" if !@held;',
+ 'open(my $fh, ">>", $ARGV[0]) or die $!;',
+ 'die "lock missing" if flock($fh, LOCK_EX|LOCK_NB);',
+ 'print "locked\\n";',
+ );
+ my $value = PVE::NVMeOF::with_lock(sub {
+ my $out = '';
+ PVE::Tools::run_command(
+ [
+ '/usr/bin/perl',
+ '-MFcntl=:flock',
+ '-e',
+ $script,
+ "$PVE::NVMeOF::RUN_DIR/fabrics.lock",
+ ],
+ timeout => 5,
+ outfunc => sub { $out .= $_[0] },
+ );
+ return $out;
+ });
+ is($value, 'locked', 'exec cannot acquire the lock held by its parent');
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or die $!;
+ flock($lock, LOCK_EX) or die $!;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'busy operation never enters callback');
+ close($lock);
+
+ my $tools = Test::MockModule->new('PVE::Tools');
+ my $timed_out = 1;
+ $tools->mock(run_fork_with_timeout => sub { return ($_[1]->(), $timed_out) });
+ my $retained;
+ eval {
+ PVE::NVMeOF::with_lock(sub {
+ my ($path) =
+ grep { (readlink($_) // '') =~ /fabrics.lock$/ } glob('/proc/self/fd/*');
+ my ($fd) = $path =~ m{/(\d+)$};
+ open($retained, '>&', $fd) or die $!;
+ return 1;
+ });
+ };
+ like($@, qr/timed out.*may still be running/, 'timeout does not claim deletion completed');
+ $timed_out = 0;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'retained descriptor keeps serialization after the caller returns');
+ close($retained);
+ is(PVE::NVMeOF::with_lock(sub { 1 }), 1, 'last descriptor close releases serialization');
+
+ my @timeouts;
+ $tools->mock(run_fork_with_timeout => sub { push @timeouts, $_[0]; return ($_[1]->(), 0) });
+ PVE::NVMeOF::with_lock(sub { 1 }, $_) for undef, 100, 4.2, 0.3;
+ my $hung = PVE::NVMeOF::storage_paths($cfg)->[0];
+ $tools->mock(run_fork_with_timeout => sub { return (undef, 1) });
+ eval { PVE::NVMeOF::connect_path($cfg, $hung) };
+ is($@, $PVE::NVMeOF::TIMED_OUT, 'a hanging connect times out');
+ ok(PVE::NVMeOF::in_cooldown($cfg, $hung), 'and arms the cooldown of its portal');
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ my $full = $PVE::NVMeOF::LOCK_WAIT + 35;
+ is_deeply(
+ \@timeouts, [$full, 100, 5, 1], 'a limit sets the time in whole seconds',
+ );
+};
+
+subtest 'a short hold of the lock does not fail a connect' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my $scfg = { %$cfg, subsysnqn => 'nqn.wait', portals => '192.0.2.3' };
+ my $ctl = "$PVE::NVMeOF::SYSFS/class/nvme-fabrics/ctl/nvme9";
+ $net->mock(tcp_ping => sub { 1 });
+ $nvme->mock(assert_support => sub { });
+ $nvme->mock(host_identity =>
+ sub { { nqn => 'nqn.host', id => '12345678-1234-1234-1234-123456789abc' } });
+ $nvme->mock(
+ run_command => sub(@) {
+ my %attrs = (
+ address => 'traddr=192.0.2.3,trsvcid=4420',
+ transport => 'tcp',
+ subsysnqn => 'nqn.wait',
+ state => 'live',
+ );
+ make_path($ctl);
+ file_set_contents("$ctl/$_", "$attrs{$_}\n") for keys %attrs;
+ },
+ );
+ pipe(my $held, my $signal) or die "pipe failed - $!\n";
+ my $holder = fork() // die "fork failed - $!\n";
+ if (!$holder) {
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or POSIX::_exit(1);
+ flock($lock, LOCK_EX) or POSIX::_exit(1);
+ syswrite($signal, '1');
+ Time::HiRes::sleep(0.5);
+ POSIX::_exit(0);
+ }
+ close($signal);
+ sysread($held, my $state, 1);
+ is($state, '1', 'another process holds the lock');
+ my $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ $class->activate_storage('wait', $scfg);
+ }
+ waitpid($holder, 0);
+ is($warning, '', 'the connect waits for the lock');
+ my $path = PVE::NVMeOF::storage_paths($scfg)->[0];
+ ok(!PVE::NVMeOF::in_cooldown($scfg, $path), 'and arms no cooldown');
+ is(
+ PVE::NVMeOF::path_controller(PVE::NVMeOF::subsystem_controllers('nqn.wait'), $path),
+ 'nvme9',
+ 'the portal is connected',
+ );
+ remove_tree($ctl);
+
+ local $PVE::NVMeOF::LOCK_WAIT = 0.2;
+ pipe($held, $signal) or die "pipe failed - $!\n";
+ $holder = fork() // die "fork failed - $!\n";
+ if (!$holder) {
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or POSIX::_exit(1);
+ flock($lock, LOCK_EX) or POSIX::_exit(1);
+ syswrite($signal, '1');
+ Time::HiRes::sleep(1);
+ POSIX::_exit(0);
+ }
+ close($signal);
+ sysread($held, $state, 1);
+ {
+ local $SIG{__WARN__} = sub { };
+ eval { $class->activate_storage('wait', $scfg) };
+ }
+ waitpid($holder, 0);
+ like($@, qr/NVMe over Fabrics is busy/, 'a longer hold fails the connect');
+ ok(!PVE::NVMeOF::in_cooldown($scfg, $path), 'but arms no cooldown for the portal');
+};
+
+subtest 'connect options, kernel reconnect and cooldown' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my @commands;
+ my $controllers = {};
+ my @limits;
+ $nvme->mock(with_lock => sub { push @limits, $_[1]; $_[0]->() });
+ $nvme->mock(assert_support => sub { });
+ $nvme->mock(host_identity =>
+ sub { { nqn => 'nqn.host', id => '12345678-1234-1234-1234-123456789abc' } });
+ $nvme->mock(subsystem_controllers => sub { $controllers });
+ my $appear = 1;
+ my ($now, $connect_secs) = (0, 0);
+ $nvme->mock(
+ run_command => sub($cmd, %opts) {
+ is($opts{timeout}, 30, 'bounded connect');
+ push @commands, $cmd;
+ $now += $connect_secs;
+ my %arg =
+ map { $cmd->[$_] => $cmd->[$_ + 1] } grep { $cmd->[$_] =~ /^--tr/ } 0 .. $#$cmd;
+ my $controller =
+ { traddr => $arg{'--traddr'}, trsvcid => $arg{'--trsvcid'}, state => 'live' };
+ $controllers->{ 'nvme' . scalar(@commands) } = $controller if $appear;
+ },
+ );
+ $net->mock(tcp_ping => sub { 1 });
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 2, 'one connect per missing portal');
+ ok(grep({ $_ eq '--ctrl-loss-tmo=-1' } $commands[0]->@*), 'kernel reconnects indefinitely');
+ is_deeply([@{ $commands[0] }[-2, -1]], ['--fast_io_fail_tmo', 120], 'fast failure default');
+ {
+ my $clock = Test::MockModule->new('Time::HiRes');
+ $clock->redefine(time => sub { $now });
+ my $activate = sub($secs) {
+ ($controllers, $connect_secs, @commands) = ({}, $secs);
+ local $SIG{__WARN__} = sub { };
+ eval { $class->activate_storage('fabric', $cfg) };
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ return scalar(@commands);
+ };
+ is($activate->(20), 1, 'with a live controller, a spent time budget leaves the rest');
+ $appear = 0;
+ is($activate->(20), 2, 'without one, a slow portal does not keep the next one out');
+ is($activate->(50), 1, 'but a very slow one does');
+ @limits = ();
+ is($activate->(40), 2, 'one that starts late is still tried');
+ is_deeply(\@limits, [45, 5], 'but only for the rest of the time limit');
+ ($appear, $connect_secs) = (1, 0);
+ }
+ @commands = ();
+ $controllers = {
+ nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' },
+ nvme2 => { traddr => '2001:db8::2', trsvcid => 4421, state => 'live' },
+ };
+ $class->activate_storage('fabric', $cfg);
+ is_deeply(\@commands, [],
+ 'existing controllers are never reconnected, regardless of state');
+ $controllers->{nvme2}->{state} = 'connecting';
+ eval { $class->activate_storage('fabric', $cfg) };
+ like($@, qr/all are reconnecting/, 'without a live one the activation fails');
+ is_deeply(\@commands, [], 'but leaves the reconnect to the kernel');
+ $controllers->{nvme2}->{state} = 'live';
+ $class->deactivate_storage('fabric', $cfg);
+ is_deeply(\@commands, [], 'deactivation does not remove controllers');
+ $controllers = {};
+ my $path = PVE::NVMeOF::storage_paths($cfg)->[0];
+ PVE::NVMeOF::note_connect_failure($cfg, $path);
+ ok(PVE::NVMeOF::in_cooldown($cfg, $path), 'failure starts cooldown');
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 1, 'only the other portal connects');
+ ($controllers, $appear) = ({}, 0);
+ my $other = PVE::NVMeOF::storage_paths($cfg)->[1];
+ my $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ eval { $class->activate_storage('fabric', $cfg) };
+ }
+ like($warning, qr/no controller appeared/, 'a connect without a controller is a failure');
+ ok(PVE::NVMeOF::in_cooldown($cfg, $other), 'which starts the cooldown too');
+ like(
+ $@,
+ qr/^cannot connect to any portal - .*failed less than a minute ago; .*no controller appeared/,
+ 'without any controller the activation fails with the reason of each portal',
+ );
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ $nvme->mock(assert_support => sub { die "nvme-cli is not installed\n" });
+ @commands = ();
+ eval { $class->activate_storage('fabric', $cfg) };
+ is($@, "nvme-cli is not installed\n", 'a missing prerequisite fails the activation');
+ is_deeply(\@commands, [], 'before any connect');
+ ok(!PVE::NVMeOF::in_cooldown($cfg, $path), 'and without a cooldown');
+ $controllers = { nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'live' } };
+ $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ is(
+ eval { $class->activate_storage('fabric', $cfg); 1 },
+ 1,
+ 'but not with a usable path',
+ );
+ }
+ like($warning, qr/cannot connect to the other portals - nvme-cli/, 'which it warns about');
+ $nvme->mock(assert_support => sub { });
+ $controllers =
+ { nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' } };
+ {
+ local $SIG{__WARN__} = sub { };
+ eval { $class->activate_storage('fabric', $cfg) };
+ }
+ like(
+ $@,
+ qr/^cannot connect to any portal/,
+ 'a reconnecting path is not usable when the missing one fails',
+ );
+ # a connect that worked, but whose controller is not live yet
+ ($controllers, $now, $connect_secs) = ({}, 0, 0);
+ $net->mock(tcp_ping => sub { 1 });
+ $nvme->mock(
+ run_command => sub($cmd, %opts) {
+ my %arg =
+ map { $cmd->[$_] => $cmd->[$_ + 1] } grep { $cmd->[$_] =~ /^--tr/ } 0 .. $#$cmd;
+ $controllers->{nvme7} =
+ { traddr => $arg{'--traddr'}, trsvcid => $arg{'--trsvcid'}, state => 'connecting' };
+ },
+ );
+ eval { $class->activate_storage('fabric', { %$cfg, portals => '192.0.2.7' }) };
+ is($@, "no controller of the subsystem is live yet\n", 'says so without an empty reason');
+};
+
+subtest 'the connection check has a time limit too' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my $clock = Test::MockModule->new('Time::HiRes');
+ my ($now, $pings) = (0, 0);
+ $clock->redefine(time => sub { $now });
+ $nvme->mock(subsystem_controllers => sub { {} });
+ $net->mock(tcp_ping => sub { $now += 2; $pings++; 0 });
+ my $scfg = { %$cfg, portals => join(',', map { "192.0.2.$_" } 1 .. 20) };
+ is($class->check_connection('many', $scfg), 1, 'untried portals go to the activation');
+ is($pings, 8, 'which the check leaves after its time limit');
+ ok(
+ PVE::NVMeOF::in_cooldown($scfg, PVE::NVMeOF::parse_portal('192.0.2.8')),
+ 'the failed ones cool down',
+ );
+ ($now, $pings) = (0, 0);
+ is($class->check_connection('many', $scfg), 1, 'a later pass skips the failed portals');
+ ok(
+ PVE::NVMeOF::in_cooldown($scfg, PVE::NVMeOF::parse_portal('192.0.2.16')),
+ 'and gets further',
+ );
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ $scfg->{portals} = '192.0.2.1,192.0.2.2';
+ ($now, $pings) = (0, 0);
+ is($class->check_connection('few', $scfg), 0, 'all tried and none answers');
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+};
+
+done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
index 3245b774..2a9a2121 100755
--- a/src/test/run_san_nvme_tests.pl
+++ b/src/test/run_san_nvme_tests.pl
@@ -38,6 +38,7 @@ $storage->mock(config => sub { $cfg });
$disk->mock(verify_blockdev_path => sub { $device });
$disk->mock(is_partition => sub { 0 });
$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(read_subsysnqn => sub { 'nqn.test' });
$disk->mock(is_iscsi_device => sub { 0 });
$disk->mock(is_mounted => sub { 0 });
$disk->mock(has_holder => sub { 0 });
@@ -86,6 +87,21 @@ for my $base (qw(fabric nvme-fabric)) {
eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
like($@, qr/base volume/, "native base reference on storage '$base' refuses");
}
+$cfg->{ids} =
+ { fabric =>
+ { type => 'nvmeof', subsysnqn => 'nqn.test', disable => 1, content => { images => 1 } } };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like(
+ $@,
+ qr/serves images from this subsystem/,
+ 'direct namespace image use refuses even when disabled',
+);
+$cfg->{ids}->{fabric}->{content} = { 'vm-vol' => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like($@, qr/serves images from this subsystem/, 'also when restricted to VM disks');
+$cfg->{ids}->{fabric}->{content} = { none => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+is($@, '', 'connection-only storage permits namespace initialization');
$cfg->{ids} = {};
@order = @opens = ();
$tools->mock(file_get_contents => sub { 1024 });
^ permalink raw reply related [relevance 17%]
* applied: [PATCH v5 storage,docs,manager 00/26] NVMe over Fabrics storage
@ 2026-11-23 13:31 10% Thomas Lamprecht
2026-11-23 13:31 17% ` [PATCH v5 storage 05/26] nvmeof: add a storage for NVMe over Fabrics subsystems Thomas Lamprecht
0 siblings, 1 reply; 43+ results
From: Thomas Lamprecht @ 2026-11-23 13:31 UTC (permalink / raw)
To: pve-devel
This has been already applied in the current form, sorry for the noise,
but I figured this is the cleaner way than replying to v4 with an
exhaustive list of changes.
A storage type for NVMe subsystems reached over TCP, on top of the
applied SAN series [0]: namespaces as base volumes of shared LVM, or
directly as raw VM disks, using the kernel's native NVMe multipath.
This is a deliberately small first version: TCP only, without
authentication or TLS, so access relies on the target's host NQN list
and a dedicated storage network. The plugin connects missing portals and
never disconnects controllers on config change or removal; disconnecting
a controller is an explicit per-node action. The kernel handles path
reconnection, and the SAN series provides LUN inventory, guided setup,
and pre-write guards.
Two operational prerequisites:
- Cloned nodes need distinct /etc/nvme/hostnqn and /etc/nvme/hostid
before connecting.
- All cluster nodes must be upgraded to pve-manager 9.2.38 before
adding the first nvmeof storage, as older nodes drop unknown storage
types when writing storage.cfg; creating the first one is refused
until all nodes are online on 9.2.38+.
What it adds:
- Storage type 'nvmeof' (subsysnqn + TCP portals, one storage per
subsystem, isolated properties, volumes as nvme-<wwid>,
ctrl_loss_tmo=-1, configurable fast-io-fail-tmo defaulting to 120s).
- Shared LVM support with nvmeof volumes as base, discovery via
/nodes/{node}/scan/nvmeof and 'pvesm scan nvmeof', and nvme-cli as a
Recommends of libpve-storage-perl.
- /nodes/{node}/san/nvmeof for host identity, controller listing, and
guarded per-controller disconnect (refused if a namespace in use or
referenced by a storage would lose its last usable path).
- Cluster-wide SAN status and pvestatd path notifications covering
nvmeof namespaces (without requiring multipathd), plus pvereport
output and documentation.
- Web UI: guided "Shared LVM on NVMe over Fabrics" setup, nvmeof
storage dialog with discovery, Node > SAN > NVMe over Fabrics
controller view, host NQN column, and native multipath state display.
Changes since v4 [1], mostly from its automated review:
- New first patch: do not activate a new storage with the storage
configuration locked (see below).
- Volumes & guards: only accept namespaces that native multipath joins
(a namespace device of a single controller is refused); refuse SAN
reference checks when the subsystem NQN cannot be read; refuse an
LVM base storage that serves its namespaces as disk images, also
when reusing an existing VG, and an unidentifiable namespace instead
of treating it as a local disk; the LVM dialog hides such bases.
- Activation: take liveness from the controller state after a connect,
and report that no controller is live, instead of "not online", when
every portal already has a non-live controller.
- Disconnect: recheck paths (including a last path that recovered),
namespace heads by WWID, controller-owned devices and the controller
identity right before removal; walks over a subsystem refuse an
unreadable sysfs directory instead of treating it as empty.
- Wipe: separate messages for a partition of a network namespace, an
unknown transport, and a transport that changed meanwhile.
- Web UI: the controller list explains its namespace count, and the
portal trim moved before the NVMe-oF setup, as a fix of the existing
iSCSI one.
- Docs: direct use and LVM on the same subsystem exclude each other,
discovery ports (8009, then 4420), the multipath prerequisite on the
target side, and that the guided setup needs discovery.
- Smaller: shared node and transport helpers, clearer errors and
commit messages.
The first patch is a generic fix: adding a storage activated it while
holding the cluster-wide storage.cfg lock, so an unreachable iSCSI or
NVMe over Fabrics portal blocked every other storage configuration
change meanwhile. The activation now runs once the configuration is
written, retried once as pvestatd may activate the new storage at the
same time, and a storage that still fails is removed again. An LVM
storage on such a base gets its base activated before the lock.
Tested as v4, and for these changes on the nested cluster against Linux
nvmet and the NetApp AFF A20: activation and paths of all namespaces
through the new head check, Disconnect of a redundant controller and
refusal of the last path on both targets, and the guided setup end to
end with the release packages on all six nodes; the rest by unit tests.
The ZFS-over-NVMe/TCP plugin on the list [2] ships its own initiator;
isolated properties prevent option clashes, and connect helpers can be
shared later. Leaving NVMe/FC partition wipes and Ceph OSDs on NVMe/FC
aligned with Fibre Channel LUNs is left for a SAN-wide follow-up.
[0]: https://lore.proxmox.com/pve-devel/20261119194655.3163258-1-t.lamprecht@proxmox.com/
[1]: https://lore.proxmox.com/pve-devel/20261123020041.3728085-1-t.lamprecht@proxmox.com/
[2]: https://lore.proxmox.com/pve-devel/20261005002609.571-1-joaquinvarela@neatech.ar/
pve-storage:
Thomas Lamprecht (15):
api: config: activate a new storage without holding the lock
diskmanage: skip SMART queries for NVMe fabric namespaces
diskmanage: list NVMe namespaces attached over TCP or RDMA for SAN only
api: disks: refuse a local wipe of a network NVMe namespace
nvmeof: add a storage for NVMe over Fabrics subsystems
d/control: bump pve-common for plain parameter error names
api: config: check the cluster version before the first nvmeof storage
lvm: allow a volume group on an NVMe over Fabrics namespace
api: scan: add NVMe over Fabrics discovery
pvesm: add a scan command for NVMe over Fabrics
api: san luns: attribute NVMe namespaces to storage
api: add node-level NVMe over Fabrics status and controller removal
multipath: report the NVMe host NQN of each node
multipath: report NVMe over Fabrics namespaces in the cluster status
d/control: break pve-manager versions without namespace notifications
ApiChangeLog | 20 +-
debian/control | 5 +-
src/PVE/API2/Disks.pm | 23 +
src/PVE/API2/Makefile | 1 +
src/PVE/API2/NVMeOF.pm | 200 +++++
src/PVE/API2/SAN/Cluster.pm | 38 +-
src/PVE/API2/SAN/Node.pm | 17 +-
src/PVE/API2/Storage/Config.pm | 74 +-
src/PVE/API2/Storage/Scan.pm | 49 ++
src/PVE/CLI/pvesm.pm | 13 +
src/PVE/Diskmanage.pm | 58 +-
src/PVE/Makefile | 1 +
src/PVE/Multipath/Status.pm | 69 +-
src/PVE/NVMeOF.pm | 566 ++++++++++++++
src/PVE/Storage.pm | 2 +
src/PVE/Storage/LVMPlugin.pm | 24 +-
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 307 ++++++++
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SAN.pm | 34 +-
src/test/Makefile | 10 +
src/test/disk_api_test.pm | 26 +-
.../multipath/disklist_expected.json | 16 -
.../nvme_smart/nvme0n1/device/transport | 1 +
src/test/disklist_test.pm | 104 ++-
src/test/run_multipath_api_tests.pl | 132 +++-
src/test/run_nvmeof_api_tests.pl | 287 +++++++
src/test/run_nvmeof_taint_tests.pl | 67 ++
src/test/run_nvmeof_tests.pl | 714 ++++++++++++++++++
src/test/run_san_api_tests.pl | 4 +-
src/test/run_san_lun_scan_tests.pl | 41 +
src/test/run_san_nvme_tests.pl | 65 ++
src/test/run_storage_create_tests.pl | 120 +++
33 files changed, 2991 insertions(+), 100 deletions(-)
pve-docs:
Thomas Lamprecht (1):
storage: document NVMe over Fabrics storages
notifications.adoc | 5 +-
pve-gui.adoc | 12 ++-
pve-intro.adoc | 3 +-
pve-storage-lvm.adoc | 10 +-
pve-storage-multipath.adoc | 3 +-
pve-storage-nvmeof.adoc | 207 +++++++++++++++++++++++++++++++++++++
pvesm.adoc | 24 +++--
7 files changed, 243 insertions(+), 21 deletions(-)
pve-manager:
Thomas Lamprecht (10):
report: add the NVMe over Fabrics host NQN and subsystems
ui: storage: add NVMe over Fabrics storage
ui: lvm: offer NVMe over Fabrics storages as base storage
ui: storage: SAN setup: ignore spaces around a typed portal
ui: storage: add a guided setup for shared LVM on NVMe over Fabrics
ui: node san: list NVMe over Fabrics controllers
ui: san: show the NVMe host NQN of each node
ui: san: show that a namespace uses native multipath
pvestatd: notify on NVMe over Fabrics namespaces as on multipath maps
d/control: bump versioned dependencies for NVMe over Fabrics
PVE/MultipathNotification.pm | 21 +-
PVE/Report.pm | 6 +
PVE/Service/pvestatd.pm | 16 +-
debian/control | 8 +-
test/MultipathNotification_test.pl | 28 ++-
www/manager6/Makefile | 4 +-
www/manager6/SANUtils.js | 7 +-
www/manager6/Utils.js | 7 +
www/manager6/dc/SAN.js | 49 +++-
www/manager6/dc/StorageView.js | 23 +-
www/manager6/node/Config.js | 9 +-
www/manager6/node/NVMeOFControllers.js | 175 +++++++++++++
www/manager6/storage/IScsiEdit.js | 5 +-
www/manager6/storage/LVMEdit.js | 20 +-
www/manager6/storage/NVMeOFEdit.js | 162 ++++++++++++
www/manager6/storage/wizard/LunSelect.js | 35 ++-
www/manager6/storage/wizard/NodeIdentities.js | 57 +++--
.../storage/wizard/{IScsi.js => Target.js} | 236 +++++++++++++-----
www/manager6/storage/wizard/Wizard.js | 62 +++--
www/manager6/window/SANLunState.js | 38 ++-
www/manager6/window/SANLunWipe.js | 24 +-
21 files changed, 805 insertions(+), 187 deletions(-)
^ permalink raw reply [relevance 10%]
* [PATCH v5 storage 05/26] nvmeof: add a storage for NVMe over Fabrics subsystems
2026-11-23 13:31 10% applied: [PATCH v5 storage,docs,manager 00/26] NVMe over Fabrics storage Thomas Lamprecht
@ 2026-11-23 13:31 17% ` Thomas Lamprecht
0 siblings, 0 replies; 43+ results
From: Thomas Lamprecht @ 2026-11-23 13:31 UTC (permalink / raw)
To: pve-devel
NVMe/TCP namespaces need a manual nvme-cli setup on every node so far.
Add a storage type that connects one subsystem through each configured
portal and offers its namespaces as raw volumes. Native NVMe multipath
joins the paths and the kernel reconnects lost ones; a namespace that it
does not join, as on a target that does not declare that the subsystem
may have several controllers, is refused as volume. Only one storage may
use a subsystem, as the LUN list, the controller list and the node
status attribute a subsystem to one storage.
Activating the storage requires a live controller, also when every
portal already has one, so that adding a storage tells why it cannot be
used. So that an activation, like the one of a status pass, does not
wait long, it tries no further portal after 15 seconds once a controller
is live, or after 45 seconds without one, and leaves the rest to the
next activation. A portal whose connect failed is retried after a
minute, but not one that only waited for another fabrics operation, and
adding a storage forgets those failures. The package nvme-cli is only
recommended, as no other storage type needs it.
With direct use, the SAN checks before wiping a namespace or creating a
volume group on it count every namespace of the subsystem as in use by
the storage. They refuse a namespace whose subsystem they cannot read.
The plugin isolates its properties, so names like 'portals' belong to
this storage type alone, and a third-party plugin that declares one of
them is still loaded. As the first in-tree plugin that isolates, it
makes the storage API check the parameters for adding and updating a
storage of any type against the options of that type alone, apart from
the sensitive properties of plugins that do not isolate theirs.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
ApiChangeLog | 9 +-
debian/control | 1 +
src/PVE/Makefile | 1 +
src/PVE/NVMeOF.pm | 316 ++++++++++++++++
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 307 +++++++++++++++
src/PVE/Storage/Plugin.pm | 2 +-
src/PVE/Storage/SAN.pm | 15 +
src/test/Makefile | 5 +
src/test/run_nvmeof_taint_tests.pl | 62 ++++
src/test/run_nvmeof_tests.pl | 577 +++++++++++++++++++++++++++++
src/test/run_san_nvme_tests.pl | 23 ++
13 files changed, 1316 insertions(+), 5 deletions(-)
create mode 100644 src/PVE/NVMeOF.pm
create mode 100644 src/PVE/Storage/NVMeOFPlugin.pm
create mode 100755 src/test/run_nvmeof_taint_tests.pl
create mode 100755 src/test/run_nvmeof_tests.pl
diff --git a/ApiChangeLog b/ApiChangeLog
index 40c3bea3..b7e7442a 100644
--- a/ApiChangeLog
+++ b/ApiChangeLog
@@ -101,10 +101,11 @@ Future changes should be documented in here.
declares a property of that name is then not loaded until it renames it, so prefer names that
are specific to the plugin, for example prefixed with its type.
- As soon as one such plugin is installed, the API checks the parameters for adding and updating a
- storage against the options of its type alone, for all storage types. Only the sensitive
- properties of a plugin that does not isolate its own are still accepted without being listed in
- its `options()`, by their own names: an alias that only another plugin declares for one is not.
+ Since the in-tree 'nvmeof' plugin isolates its properties, the API checks the parameters for
+ adding and updating a storage against the options of its type alone, for all storage types,
+ also for plugins of older API versions. Only the sensitive properties of a plugin that does not
+ isolate its own are still accepted without being listed in its `options()`, by their own names:
+ an alias that only another plugin declares for one is not.
Set 'sensitive-properties' in an isolating plugin, even if empty. Without it, the fallback list of
version 11 also applies to the plugin's own properties of these names.
diff --git a/debian/control b/debian/control
index fdcf8117..b5c2f529 100644
--- a/debian/control
+++ b/debian/control
@@ -55,6 +55,7 @@ Depends: bzip2,
${misc:Depends},
${perl:Depends},
Recommends: multipath-tools,
+ nvme-cli,
pve-esxi-import-tools (>= 0.6.0),
skopeo,
zfsutils-linux (>= 2.4.1-pve2),
diff --git a/src/PVE/Makefile b/src/PVE/Makefile
index 13fecbf8..238eefd4 100644
--- a/src/PVE/Makefile
+++ b/src/PVE/Makefile
@@ -4,6 +4,7 @@
install:
install -D -m 0644 Storage.pm ${DESTDIR}${PERLDIR}/PVE/Storage.pm
install -D -m 0644 Diskmanage.pm ${DESTDIR}${PERLDIR}/PVE/Diskmanage.pm
+ install -D -m 0644 NVMeOF.pm ${DESTDIR}${PERLDIR}/PVE/NVMeOF.pm
install -D -m 0644 ISCSI/Topology.pm ${DESTDIR}${PERLDIR}/PVE/ISCSI/Topology.pm
install -D -m 0644 Multipath.pm ${DESTDIR}${PERLDIR}/PVE/Multipath.pm
install -D -m 0644 Multipath/Config.pm ${DESTDIR}${PERLDIR}/PVE/Multipath/Config.pm
diff --git a/src/PVE/NVMeOF.pm b/src/PVE/NVMeOF.pm
new file mode 100644
index 00000000..2be6d8e7
--- /dev/null
+++ b/src/PVE/NVMeOF.pm
@@ -0,0 +1,316 @@
+package PVE::NVMeOF;
+
+use v5.36;
+
+use Cwd qw(abs_path);
+use Digest::SHA qw(sha1_hex);
+use Fcntl qw(:flock F_GETFD F_SETFD FD_CLOEXEC);
+use File::Basename qw(basename);
+use File::Path qw(make_path);
+use POSIX qw(ceil);
+use Socket qw(AF_INET AF_INET6 inet_ntop inet_pton);
+use Time::HiRes ();
+
+use PVE::JSONSchema;
+use PVE::Tools qw(dir_glob_foreach file_read_firstline file_set_contents run_command);
+
+use PVE::Diskmanage;
+
+our $NVME = '/usr/sbin/nvme';
+our $SYSFS = '/sys';
+our $HOSTNQN_FILE = '/etc/nvme/hostnqn';
+our $HOSTID_FILE = '/etc/nvme/hostid';
+our $RUN_DIR = '/run/pve/nvmeof';
+our $LOCK_WAIT = 10;
+# no control characters, which could reach logs and the arguments of nvme-cli
+our $NQN_PATTERN = 'nqn\.[^\s\x00-\x1f\x7f,=]+';
+our $DISCOVERY_NQN = 'nqn.2014-08.org.nvmexpress.discovery';
+our $TIMED_OUT = "NVMe over Fabrics operation timed out - it may still be running\n";
+
+sub canonical_address($addr) {
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ return inet_ntop(AF_INET, $packed);
+ }
+ if (defined(my $packed = inet_pton(AF_INET6, $addr))) {
+ return inet_ntop(AF_INET, substr($packed, 12))
+ if substr($packed, 0, 12) eq ("\0" x 10) . "\xff\xff";
+ return inet_ntop(AF_INET6, $packed);
+ }
+ return lc($addr);
+}
+
+# Link-local IPv6 needs a node-specific interface and cannot identify a shared configured portal.
+sub parse_portal($portal) {
+ my ($addr, $port);
+ if ($portal =~ m/^\[([0-9a-fA-F:.]+)\](?::([0-9]+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } elsif ($portal =~ m/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(?::([0-9]+))?$/) {
+ ($addr, $port) = ($1, $2);
+ } else {
+ return undef;
+ }
+ return undef if defined($port) && ($port < 1 || $port > 65535);
+ $addr = canonical_address($addr);
+ if (defined(my $packed = inet_pton(AF_INET, $addr))) {
+ my $multicast = (unpack('C', $packed) & 0xf0) == 0xe0;
+ return undef if $addr eq '0.0.0.0' || $addr eq '255.255.255.255' || $multicast;
+ } elsif (defined($packed = inet_pton(AF_INET6, $addr))) {
+ my $prefix = unpack('n', $packed);
+ return undef
+ if $addr eq '::' || ($prefix & 0xffc0) == 0xfe80 || ($prefix & 0xff00) == 0xff00;
+ } else {
+ return undef;
+ }
+ return { traddr => $addr, trsvcid => int($port // 4420) };
+}
+
+PVE::JSONSchema::register_format(
+ 'pve-storage-nvme-portal',
+ sub($portal, $noerr = undef) {
+ return $portal if parse_portal($portal);
+ return undef if $noerr;
+ die "value is not an IPv4 address or a bracketed IPv6 address with optional port\n";
+ },
+);
+
+sub format_path($path) {
+ # an IPv6 address, not the address of a Fibre Channel port, which has a colon too
+ my $ipv6 = $path->{traddr} =~ /:/ && $path->{traddr} =~ /^[0-9a-fA-F:.]+$/;
+ my $addr = $ipv6 ? "[$path->{traddr}]" : $path->{traddr};
+ return defined($path->{trsvcid}) ? "$addr:$path->{trsvcid}" : $addr;
+}
+
+sub storage_paths($scfg) {
+ return [map { parse_portal($_) // die "invalid portal '$_'\n" }
+ PVE::Tools::split_list($scfg->{portals})];
+}
+
+sub host_identity() {
+ my ($nqn) = (file_read_firstline($HOSTNQN_FILE) // '') =~ /\A($NQN_PATTERN)\z/;
+ my ($id) = (file_read_firstline($HOSTID_FILE) // '') =~
+ /\A([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\z/i;
+ if (!defined($nqn) || length($nqn) > 223) {
+ die "invalid or missing NVMe host NQN in '$HOSTNQN_FILE' - install nvme-cli and check the"
+ . " host identity\n";
+ }
+ die "invalid or missing NVMe host ID in '$HOSTID_FILE' - expected a nonzero UUID\n"
+ if !defined($id) || $id =~ /^[0-]+$/;
+ return { nqn => $nqn, id => lc($id) };
+}
+
+sub is_supported() { return -x $NVME ? 1 : 0 }
+
+sub assert_support() {
+ die "nvme-cli is not installed\n" if !is_supported();
+ run_command(['modprobe', 'nvme-tcp'], timeout => 10)
+ if !-e "$SYSFS/module/nvme_tcp";
+ my $multipath = file_read_firstline("$SYSFS/module/nvme_core/parameters/multipath") // '';
+ die "native NVMe multipath is disabled - enable nvme_core.multipath\n" if $multipath ne 'Y';
+}
+
+sub controllers() {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-fabrics/ctl";
+ dir_glob_foreach(
+ $dir,
+ 'nvme[0-9]+',
+ sub($name, @) {
+ my $address = file_read_firstline("$dir/$name/address") // return;
+ my %address = map { split(/=/, $_, 2) } grep { /=/ } split(/,/, $address);
+ return if !defined($address{traddr});
+ $res->{$name} = {
+ transport => file_read_firstline("$dir/$name/transport") // '',
+ subsystem => PVE::Diskmanage::read_subsysnqn("$dir/$name/subsysnqn") // '',
+ state => file_read_firstline("$dir/$name/state") // 'unknown',
+ traddr => canonical_address($address{traddr}),
+ trsvcid => $address{trsvcid},
+ };
+ },
+ );
+ return $res;
+}
+
+sub subsystem_controllers($subsystem) {
+ my $controllers = controllers();
+ return {
+ map { $_ => $controllers->{$_} } grep {
+ $controllers->{$_}->{subsystem} eq $subsystem
+ && $controllers->{$_}->{transport} eq 'tcp'
+ } keys %$controllers
+ };
+}
+
+# The NQN of a subsystem, untainted, or undef if it is invalid or the one of the discovery service.
+sub subsystem_nqn($nqn) {
+ my ($res) = ($nqn // '') =~ /\A($NQN_PATTERN)\z/;
+ return undef if !defined($res) || length($res) > 223 || $res eq $DISCOVERY_NQN;
+ return $res;
+}
+
+sub namespace_wwid($dev) {
+ return file_read_firstline("$SYSFS/block/$dev/wwid");
+}
+
+# Native NVMe multipath shows a namespace as a device of its subsystem. If the target does not
+# declare that the subsystem may have several controllers, a namespace is a device of each
+# controller instead, without the other paths.
+sub is_namespace_head($dev) {
+ my $parent = abs_path("$SYSFS/block/$dev/device") // return 0;
+ return basename($parent) =~ /^nvme-subsys[0-9]+$/ ? 1 : 0;
+}
+
+sub has_live_controller($controllers) {
+ return scalar(grep { $_->{state} eq 'live' } values %$controllers);
+}
+
+sub path_controller($controllers, $path) {
+ for my $name (sort keys %$controllers) {
+ my $ctrl = $controllers->{$name};
+ if ($ctrl->{traddr} eq $path->{traddr} && ($ctrl->{trsvcid} // '') eq $path->{trsvcid}) {
+ return $name;
+ }
+ }
+ return undef;
+}
+
+sub namespaces($subsystem) {
+ my $res = {};
+ my $dir = "$SYSFS/class/nvme-subsystem";
+ dir_glob_foreach(
+ $dir,
+ 'nvme-subsys[0-9]+',
+ sub($subsys, @) {
+ # one that cannot be read could be this subsystem, whose namespaces must not look gone
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$dir/$subsys/subsysnqn")
+ // die "cannot read the NQN of NVMe subsystem '$subsys'\n";
+ return if $nqn ne $subsystem;
+ dir_glob_foreach(
+ "$dir/$subsys",
+ 'nvme[0-9]+n[0-9]+',
+ sub($dev, @) {
+ # a failed read must not look like a namespace that is gone
+ my $wwid = file_read_firstline("$SYSFS/block/$dev/wwid")
+ // die "cannot read the WWID of namespace '$dev'\n";
+ my $size = file_read_firstline("$SYSFS/block/$dev/size")
+ // die "cannot read the size of namespace '$dev'\n";
+ $res->{$dev} = { wwid => $wwid, size => int($size) * 512 };
+ },
+ );
+ },
+ );
+ return $res;
+}
+
+# $limit sets the time the operation may take in all, including the wait for the lock.
+sub with_lock($code, $limit = undef) {
+ my $total = $LOCK_WAIT + 35;
+ # an alarm counts whole seconds and none at zero
+ $total = ceil($limit) if defined($limit);
+ $total = 1 if $total < 1;
+ my ($res, $timeout) = PVE::Tools::run_fork_with_timeout(
+ $total,
+ sub {
+ make_path($RUN_DIR);
+ open(my $lock, '>>', "$RUN_DIR/fabrics.lock") or die "cannot open NVMe lock - $!\n";
+ # A busy lock fails the operation, so wait a while for it, but give up before the time
+ # limit, which counts as a hanging operation.
+ my $wait = $LOCK_WAIT < $total ? $LOCK_WAIT : $total - 1;
+ my $deadline = Time::HiRes::time() + $wait;
+ while (!flock($lock, LOCK_EX | LOCK_NB)) {
+ die "NVMe over Fabrics is busy - another operation is still running\n"
+ if Time::HiRes::time() >= $deadline;
+ Time::HiRes::usleep(100_000);
+ }
+ # Commands inherit the lock, so that it stays held until they exit, even if the caller
+ # timed out while one was stuck in the kernel.
+ my $flags = fcntl($lock, F_GETFD, 0) // die "cannot read NVMe lock flags - $!\n";
+ fcntl($lock, F_SETFD, $flags & ~FD_CLOEXEC)
+ or die "cannot inherit NVMe lock - $!\n";
+ return $code->();
+ },
+ );
+ die $TIMED_OUT if $timeout;
+ return $res;
+}
+
+my sub retry_file($scfg, $path) {
+ my ($key) =
+ sha1_hex(join(
+ "\0", $scfg->{subsysnqn}, format_path($path), $scfg->{'fast-io-fail-tmo'} // 120)) =~
+ /\A([0-9a-f]{40})\z/;
+ return "$RUN_DIR/retry/$key";
+}
+
+sub in_cooldown($scfg, $path) {
+ my $mtime = (stat(retry_file($scfg, $path)))[9] // return 0;
+ my $age = time() - $mtime;
+ return $age > -60 && $age < 60;
+}
+
+sub note_connect_failure($scfg, $path) {
+ make_path("$RUN_DIR/retry");
+ file_set_contents(retry_file($scfg, $path), '');
+}
+
+sub clear_connect_failures($scfg) {
+ unlink(retry_file($scfg, $_)) for storage_paths($scfg)->@*;
+}
+
+sub connect_path($scfg, $path, $limit = undef) {
+ my $nqn = subsystem_nqn($scfg->{subsysnqn}) // die "invalid subsystem NQN\n";
+ my ($fail) = ($scfg->{'fast-io-fail-tmo'} // 120) =~ /\A(-?[0-9]+)\z/;
+ die "invalid fast I/O fail timeout\n" if !defined($fail) || $fail < -1;
+ # A connect that hangs until the time limit failed too, but the process that would note it is
+ # gone by then.
+ my $res = eval {
+ with_lock(
+ sub {
+ return if path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ assert_support();
+ my $host = host_identity();
+ # only a failed attempt is a failure of the portal, not a busy lock
+ eval {
+ run_command(
+ [
+ $NVME,
+ 'connect',
+ '--transport=tcp',
+ '--nqn',
+ $nqn,
+ '--traddr',
+ $path->{traddr},
+ '--trsvcid',
+ $path->{trsvcid},
+ '--hostnqn',
+ $host->{nqn},
+ '--hostid',
+ $host->{id},
+ '--ctrl-loss-tmo=-1',
+ '--fast_io_fail_tmo',
+ $fail,
+ ],
+ timeout => 30,
+ errmsg => 'nvme connect',
+ );
+ # nvme-cli can exit successfully without having connected
+ die "no controller appeared\n"
+ if !path_controller(subsystem_controllers($scfg->{subsysnqn}), $path);
+ };
+ if (my $err = $@) {
+ note_connect_failure($scfg, $path);
+ die $err;
+ }
+ unlink(retry_file($scfg, $path));
+ return;
+ },
+ $limit,
+ );
+ };
+ if (my $err = $@) {
+ note_connect_failure($scfg, $path) if $err eq $TIMED_OUT;
+ die $err;
+ }
+ return $res;
+}
+
+1;
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index c640cd8e..c77a6755 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -33,6 +33,7 @@ use PVE::Storage::LvmThinPlugin;
use PVE::Storage::NFSPlugin;
use PVE::Storage::CIFSPlugin;
use PVE::Storage::ISCSIPlugin;
+use PVE::Storage::NVMeOFPlugin;
use PVE::Storage::RBDPlugin;
use PVE::Storage::CephFSPlugin;
use PVE::Storage::ISCSIDirectPlugin;
@@ -58,6 +59,7 @@ PVE::Storage::LvmThinPlugin->register();
PVE::Storage::NFSPlugin->register();
PVE::Storage::CIFSPlugin->register();
PVE::Storage::ISCSIPlugin->register();
+PVE::Storage::NVMeOFPlugin->register();
PVE::Storage::RBDPlugin->register();
PVE::Storage::CephFSPlugin->register();
PVE::Storage::ISCSIDirectPlugin->register();
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index a2df83c0..7f2ff6c8 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -6,6 +6,7 @@ SOURCES= \
NFSPlugin.pm \
CIFSPlugin.pm \
ISCSIPlugin.pm \
+ NVMeOFPlugin.pm \
CephFSPlugin.pm \
RBDPlugin.pm \
ISCSIDirectPlugin.pm \
diff --git a/src/PVE/Storage/NVMeOFPlugin.pm b/src/PVE/Storage/NVMeOFPlugin.pm
new file mode 100644
index 00000000..02adc62c
--- /dev/null
+++ b/src/PVE/Storage/NVMeOFPlugin.pm
@@ -0,0 +1,307 @@
+package PVE::Storage::NVMeOFPlugin;
+
+use v5.36;
+
+use Cwd ();
+use Time::HiRes ();
+
+use PVE::Network;
+
+use PVE::Diskmanage;
+use PVE::NVMeOF;
+use PVE::Storage::Plugin;
+
+use base qw(PVE::Storage::Plugin);
+
+# Adding a storage activates it under the lock of the storage configuration, so no further portal is
+# tried after this many seconds once a controller is live, or after three times as long without one.
+# Later activations connect the rest.
+our $ACTIVATION_BUDGET = 15;
+
+sub type { return 'nvmeof' }
+
+sub plugindata {
+ return {
+ content => [{ images => 1, 'vm-vol' => 1, none => 1 }, { images => 1 }],
+ select_existing => 1,
+ 'isolate-properties' => 1,
+ 'advanced-properties' => {
+ 'fast-io-fail-tmo' => 1,
+ },
+ 'hidden-properties' => {
+ bwlimit => 1,
+ },
+ 'sensitive-properties' => {},
+ };
+}
+
+sub properties {
+ return {
+ subsysnqn => {
+ title => "Subsystem",
+ description => 'The NQN of the NVMe subsystem.',
+ type => 'string',
+ pattern => $PVE::NVMeOF::NQN_PATTERN,
+ maxLength => 223,
+ },
+ portals => {
+ title => "Portals",
+ description =>
+ 'TCP portals of the NVMe subsystem, as IPv4 or bracketed IPv6 addresses'
+ . ' with an optional port (default 4420).',
+ type => 'string',
+ format => 'pve-storage-nvme-portal-list',
+ },
+ 'fast-io-fail-tmo' => {
+ title => "Fail I/O After (s)",
+ description => 'Seconds before I/O through a reconnecting path fails. -1 disables'
+ . ' this timeout; I/O can remain queued while paths reconnect.',
+ type => 'integer',
+ minimum => -1,
+ default => 120,
+ },
+ };
+}
+
+sub options {
+ return {
+ subsysnqn => { fixed => 1 },
+ portals => {},
+ 'fast-io-fail-tmo' => { optional => 1 },
+ nodes => { optional => 1 },
+ disable => { optional => 1 },
+ content => { optional => 1 },
+ bwlimit => { optional => 1 },
+ };
+}
+
+my sub assert_valid_config($scfg) {
+ die "the discovery subsystem cannot be used as storage\n"
+ if $scfg->{subsysnqn} eq $PVE::NVMeOF::DISCOVERY_NQN;
+ my $paths = PVE::NVMeOF::storage_paths($scfg);
+ # the list format also accepts a list of separators only
+ die "no portal given\n" if !@$paths;
+ my %seen;
+ for my $path (@$paths) {
+ my $portal = PVE::NVMeOF::format_path($path);
+ die "portal '$portal' is listed more than once\n" if $seen{$portal}++;
+ }
+}
+
+sub on_add_hook($class, $storeid, $scfg, %param) {
+ assert_valid_config($scfg);
+ # the LUN and controller lists and the node status attribute a subsystem to its one storage
+ my $ids = PVE::Storage::config()->{ids};
+ for my $sid (sort keys %$ids) {
+ next if $sid eq $storeid || $ids->{$sid}->{type} ne 'nvmeof';
+ die "storage '$sid' already uses this subsystem\n"
+ if $ids->{$sid}->{subsysnqn} eq $scfg->{subsysnqn};
+ }
+ # adding the storage again, for example once the array allows the node, tries all portals
+ PVE::NVMeOF::clear_connect_failures($scfg);
+ return;
+}
+
+sub on_update_hook_full($class, $storeid, $scfg, $update, $delete, $sensitive, @) {
+ my $merged = { %$scfg, %$update };
+ delete $merged->{$_} for ($delete // [])->@*;
+ # without the property, the default of the plugin applies, which serves images
+ $merged->{content} //= $class->plugindata()->{content}->[1];
+ assert_valid_config($merged);
+ # the namespace of a volume group must not become a disk image of a guest as well
+ if (
+ PVE::Storage::san_storage_serves_images($merged)
+ && !PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ my $ids = PVE::Storage::config()->{ids};
+ for my $sid (sort keys %$ids) {
+ die "storage '$sid' uses a namespace of this storage as base, so it cannot serve"
+ . " images\n"
+ if $ids->{$sid}->{type} eq 'lvm'
+ && ($ids->{$sid}->{base} // '') =~ /^\Q$storeid\E:/;
+ }
+ }
+ # a changed portal list, for example with a portal fixed and added again, tries all of them
+ PVE::NVMeOF::clear_connect_failures($merged) if exists($update->{portals});
+ return $class->SUPER::on_update_hook_full($storeid, $scfg, $update, $delete, $sensitive);
+}
+
+sub parse_volname($class, $volname) {
+ if ($volname =~ m!^(nvme-[a-zA-Z0-9_.:+-]+)$! && $volname !~ /-part[0-9]+$/) {
+ return ($class->guest_volume_vtype('raw'), $1, undef, undef, undef, undef, 'raw');
+ }
+ die "unable to parse NVMe over Fabrics volume name '$volname'\n";
+}
+
+# The name of a volume can be the by-id name of any NVMe device, also of a local disk or of a
+# namespace of another subsystem.
+sub assert_namespace($scfg, $volname, $real) {
+ my ($dev) = $real =~ m!^/dev/(nvme[0-9]+n[0-9]+)$!;
+ die "volume '$volname' is not an NVMe namespace\n" if !defined($dev);
+ my $nqn = PVE::Diskmanage::read_subsysnqn("$PVE::NVMeOF::SYSFS/block/$dev/device/subsysnqn")
+ // '';
+ die "volume '$volname' is not part of subsystem '$scfg->{subsysnqn}'\n"
+ if $nqn ne $scfg->{subsysnqn};
+ die "volume '$volname' is the device of a single controller, not of native NVMe multipath\n"
+ if !PVE::NVMeOF::is_namespace_head($dev);
+ # another by-id name of the subsystem, like model and serial, can name another namespace
+ my $wwid = PVE::NVMeOF::namespace_wwid($dev) // '';
+ die "volume '$volname' is not named after the WWID of its namespace\n"
+ if $volname ne "nvme-$wwid";
+}
+
+sub filesystem_path($class, $scfg, $volname, $snapname = undef, @) {
+ die "snapshot is not possible on NVMe over Fabrics storage\n" if defined($snapname);
+ my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+ my $path = "/dev/disk/by-id/$name";
+ # not every user of a path activates the volume first, and the base volume of an LVM storage
+ # has no device before its storage connects
+ my $real = Cwd::realpath($path);
+ assert_namespace($scfg, $volname, $real) if defined($real) && -e $real;
+ return wantarray ? ($path, $vmid, $vtype) : $path;
+}
+
+sub create_base { die "can't create base images in NVMe over Fabrics storage\n" }
+sub clone_image { die "can't clone images in NVMe over Fabrics storage\n" }
+sub alloc_image { die "can't allocate space in NVMe over Fabrics storage\n" }
+sub free_image { die "can't free space in NVMe over Fabrics storage\n" }
+sub volume_resize { die "volume resize is not possible on NVMe over Fabrics storage\n" }
+
+sub list_volumes($class, $storeid, $scfg, $vmid = undef, $content_types = undef, @) {
+ my $res = $class->list_images($storeid, $scfg, $vmid);
+ $_->{content} = 'images' for @$res;
+ return $res;
+}
+
+sub list_images($class, $storeid, $scfg, $vmid = undef, $vollist = undef, $cache = undef, @) {
+ return [] if defined($vmid) && !$vollist;
+ my $namespaces = PVE::NVMeOF::namespaces($scfg->{subsysnqn});
+ my $res = [];
+ for my $dev (sort keys %$namespaces) {
+ my $ns = $namespaces->{$dev};
+ my $volid = "$storeid:nvme-$ns->{wwid}";
+ next if $vollist && !grep { $_ eq $volid } @$vollist;
+ push @$res,
+ {
+ volid => $volid,
+ format => 'raw',
+ size => $ns->{size},
+ vmid => 0,
+ };
+ }
+ return $res;
+}
+
+sub status($class, $storeid, $scfg, $cache = undef, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ return (0, 0, 0, PVE::NVMeOF::has_live_controller($controllers) ? 1 : 0);
+}
+
+sub activate_storage($class, $storeid, $scfg, $cache = undef, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ my @missing = grep { !defined(PVE::NVMeOF::path_controller($controllers, $_)) }
+ PVE::NVMeOF::storage_paths($scfg)->@*;
+ if (!@missing) {
+ # the kernel reconnects them, but meanwhile the namespaces cannot be used
+ die "no controller of the subsystem is live\n"
+ if !PVE::NVMeOF::has_live_controller($controllers);
+ return;
+ }
+ # A missing prerequisite is no failure of a portal, so the portals stay eligible for the next
+ # attempt. A storage with a usable path still works, with fewer paths.
+ eval {
+ PVE::NVMeOF::assert_support();
+ PVE::NVMeOF::host_identity();
+ };
+ if (my $err = $@) {
+ die $err if !PVE::NVMeOF::has_live_controller($controllers);
+ warn "storage '$storeid': cannot connect to the other portals - $err";
+ return;
+ }
+ my @errors;
+ my $live = PVE::NVMeOF::has_live_controller($controllers);
+ my $start = Time::HiRes::time();
+ # The time limit also bounds an attempt that starts late, so that an activation, like the one of
+ # a status pass, does not wait long for one storage.
+ my $left = sub { $start + ($live ? 1 : 3) * $ACTIVATION_BUDGET - Time::HiRes::time() };
+ for my $path (@missing) {
+ my $portal = PVE::NVMeOF::format_path($path);
+ if ($left->() < 5) {
+ push @errors, "$portal: not tried within the time limit";
+ next;
+ }
+ if (PVE::NVMeOF::in_cooldown($scfg, $path)) {
+ push @errors, "$portal: failed less than a minute ago";
+ next;
+ }
+ eval {
+ if (!PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2)) {
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ die "no answer from portal\n";
+ }
+ PVE::NVMeOF::connect_path($scfg, $path, $left->());
+ };
+ if (my $err = $@) {
+ warn "storage '$storeid': connecting to '$portal' failed - $err";
+ chomp $err;
+ push @errors, "$portal: $err";
+ } else {
+ # a new controller can still be connecting
+ $live = PVE::NVMeOF::has_live_controller(
+ PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn}));
+ }
+ }
+ # some paths are enough, but without a usable one the namespaces cannot be used
+ $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ if (!PVE::NVMeOF::has_live_controller($controllers)) {
+ die "cannot connect to any portal - " . join('; ', @errors) . "\n" if @errors;
+ die "no controller of the subsystem is live yet\n";
+ }
+ return;
+}
+
+sub deactivate_storage { return }
+
+sub check_connection($class, $storeid, $scfg, @) {
+ my $controllers = PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn});
+ return 1 if PVE::NVMeOF::has_live_controller($controllers);
+ my $paths = PVE::NVMeOF::storage_paths($scfg);
+ # with a controller for each portal, there is nothing to connect, only to wait for the kernel
+ die "no controller of the subsystem is live\n"
+ if !grep { !defined(PVE::NVMeOF::path_controller($controllers, $_)) } @$paths;
+ # Many portals that do not answer must not hold up an activation, so the check has a time limit
+ # too. The portals left untried go to the activation, which skips those that just failed.
+ my $deadline = Time::HiRes::time() + $ACTIVATION_BUDGET;
+ for my $path (@$paths) {
+ return 1 if Time::HiRes::time() >= $deadline;
+ next if defined(PVE::NVMeOF::path_controller($controllers, $path));
+ next if PVE::NVMeOF::in_cooldown($scfg, $path);
+ return 1 if PVE::Network::tcp_ping($path->{traddr}, $path->{trsvcid}, 2);
+ PVE::NVMeOF::note_connect_failure($scfg, $path);
+ }
+ return 0;
+}
+
+sub activate_volume($class, $storeid, $scfg, $volname, $snapname = undef, $cache = undef, @) {
+ my $path = $class->filesystem_path($scfg, $volname, $snapname);
+ # as for the multipath map of an iSCSI LUN, a status pass does not wait for the device
+ my $deadline = Time::HiRes::time() + ($cache && $cache->{status_only} ? 0 : 10);
+ while (!-b $path && Time::HiRes::time() < $deadline) {
+ last if !keys PVE::NVMeOF::subsystem_controllers($scfg->{subsysnqn})->%*;
+ Time::HiRes::usleep(250_000);
+ }
+ my $real = Cwd::realpath($path);
+ die "volume '$volname' is not available on this node\n" if !$real || !-b $real;
+ assert_namespace($scfg, $volname, $real);
+}
+
+sub volume_has_feature(
+ $class, $scfg, $feature, $storeid, $volname,
+ $snapname = undef,
+ $running = undef, @,
+) {
+ return 1 if $feature eq 'copy' && !defined($snapname);
+ return undef;
+}
+
+1;
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index fe243679..7079a259 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -42,7 +42,7 @@ our @COMMON_TAR_FLAGS = qw(
);
our @SHARED_STORAGE = (
- 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs',
+ 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs', 'nvmeof',
);
our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/SAN.pm b/src/PVE/Storage/SAN.pm
index 0a9e441c..595c3b55 100644
--- a/src/PVE/Storage/SAN.pm
+++ b/src/PVE/Storage/SAN.pm
@@ -302,6 +302,13 @@ sub lun_partitions($lun) {
}
sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
+ my $name = basename($lun->{devpath});
+ my $nqn;
+ if ($name =~ /^nvme\d+n\d+$/) {
+ # without its subsystem, a storage that offers the namespace to guests cannot be ruled out
+ $nqn = PVE::Diskmanage::read_subsysnqn("/sys/block/$name/device/subsysnqn") // '';
+ die "cannot use '$lun->{devpath}' - cannot read its NVMe subsystem\n" if $nqn eq '';
+ }
my %vgs = map { $_ => 1 } PVE::Storage::LVMPlugin::lun_volume_groups(
[$lun->{devpath}, lun_partitions($lun)->@*],
)->@*;
@@ -324,6 +331,14 @@ sub assert_lun_unreferenced($cfg, $lun, $exempt = undef) {
) {
die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this target\n";
}
+ if (
+ $type eq 'nvmeof'
+ && defined($nqn)
+ && $scfg->{subsysnqn} eq $nqn
+ && PVE::Storage::san_storage_serves_images($scfg)
+ ) {
+ die "cannot use '$lun->{devpath}' - storage '$sid' serves images from this subsystem\n";
+ }
next if $type ne 'lvm' || !$scfg->{base};
my $base = PVE::Multipath::parse_base_volume($scfg->{base});
my $matches = $base
diff --git a/src/test/Makefile b/src/test/Makefile
index 500f9493..ee639e5f 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -17,6 +17,7 @@ test: \
test_lvmplugin \
test_multipath \
test_multipath_api \
+ test_nvmeof \
test_ovf \
test_plugin \
test_remote_command \
@@ -119,3 +120,7 @@ test_disk_api: run_disk_api_tests.pl
test_storage_create: run_storage_create_tests.pl
./run_storage_create_tests.pl
+
+test_nvmeof: run_nvmeof_tests.pl run_nvmeof_taint_tests.pl
+ ./run_nvmeof_tests.pl
+ perl -T ./run_nvmeof_taint_tests.pl
diff --git a/src/test/run_nvmeof_taint_tests.pl b/src/test/run_nvmeof_taint_tests.pl
new file mode 100755
index 00000000..6fd37410
--- /dev/null
+++ b/src/test/run_nvmeof_taint_tests.pl
@@ -0,0 +1,62 @@
+#!/usr/bin/perl -T
+
+use v5.36;
+use lib qw(..);
+use File::Temp qw(tempdir);
+use Scalar::Util qw(tainted);
+use Test::MockModule;
+use Test::More;
+
+use PVE::Tools qw(file_get_contents file_set_contents);
+
+use PVE::NVMeOF;
+
+$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
+delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
+my $dir = tempdir('nvmeof-taint-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::HOSTNQN_FILE = "$dir/hostnqn";
+local $PVE::NVMeOF::HOSTID_FILE = "$dir/hostid";
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+file_set_contents($PVE::NVMeOF::HOSTNQN_FILE, "nqn.host\n");
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "12345678-1234-1234-1234-123456789abc\n");
+file_set_contents("$dir/config", "nqn.test\n192.0.2.1\n120\n");
+my ($nqn, $portal, $fail) = split(/\n/, file_get_contents("$dir/config"));
+ok(tainted($nqn), 'configuration input is tainted');
+my $nvme = Test::MockModule->new('PVE::NVMeOF');
+$nvme->mock(with_lock => sub { $_[0]->() });
+my $commands = 0;
+$nvme->mock(
+ subsystem_controllers => sub {
+ return $commands ? { nvme0 => { traddr => '192.0.2.1', trsvcid => 4420 } } : {};
+ },
+);
+$nvme->mock(assert_support => sub { });
+$nvme->mock(
+ run_command => sub($cmd, %opts) {
+ $commands++;
+ is(
+ scalar(grep { tainted($_) } @$cmd),
+ 0,
+ 'all connect operands are validated and untainted',
+ );
+ PVE::Tools::run_command(['/usr/bin/true', @$cmd], timeout => 5);
+ },
+);
+my $path = PVE::NVMeOF::parse_portal($portal);
+eval { PVE::NVMeOF::connect_path({ subsysnqn => $nqn, 'fast-io-fail-tmo' => $fail }, $path) };
+is($@, '', 'connect command can execute in taint mode');
+is($commands, 1, 'one connect');
+PVE::NVMeOF::note_connect_failure({ subsysnqn => $nqn }, $path);
+ok(
+ PVE::NVMeOF::in_cooldown({ subsysnqn => $nqn }, $path),
+ 'cooldown accepts validated file-backed configuration',
+);
+for my $bad ('nqn.bad,nqn=other', "nqn.test\n", 'nqn.2014-08.org.nvmexpress.discovery') {
+ eval { PVE::NVMeOF::connect_path({ subsysnqn => $bad }, $path) };
+ like($@, qr/invalid subsystem/, 'invalid connect subsystem refused');
+}
+file_set_contents($PVE::NVMeOF::HOSTID_FILE, "00000000-0000-0000-0000-000000000000\n");
+eval { PVE::NVMeOF::host_identity() };
+like($@, qr/nonzero UUID/, 'zero host ID refused');
+
+done_testing();
diff --git a/src/test/run_nvmeof_tests.pl b/src/test/run_nvmeof_tests.pl
new file mode 100755
index 00000000..e8285695
--- /dev/null
+++ b/src/test/run_nvmeof_tests.pl
@@ -0,0 +1,577 @@
+#!/usr/bin/perl
+
+use v5.36;
+use lib qw(..);
+use Fcntl qw(:flock);
+use File::Path qw(make_path remove_tree);
+use File::Temp qw(tempdir);
+use POSIX ();
+use Test::MockModule;
+use Test::More;
+use Time::HiRes ();
+
+use PVE::Tools qw(file_set_contents);
+
+use PVE::NVMeOF;
+use PVE::Storage;
+
+my $dir = tempdir('nvmeof-test-XXXX', DIR => '.', CLEANUP => 1);
+local $PVE::NVMeOF::RUN_DIR = "$dir/run";
+local $PVE::NVMeOF::SYSFS = "$dir/sys";
+my $class = 'PVE::Storage::NVMeOFPlugin';
+my $cfg = {
+ type => 'nvmeof',
+ subsysnqn => 'nqn.test',
+ portals => '192.0.2.1,[2001:db8::2]:4421',
+ content => { none => 1 },
+};
+
+subtest 'configuration, portals and volumes' => sub {
+ is(PVE::Storage::Plugin->lookup('nvmeof'), $class, 'plugin registered');
+ is_deeply(
+ [sort keys $class->properties()->%*],
+ [qw(fast-io-fail-tmo portals subsysnqn)],
+ 'only three plugin-specific properties',
+ );
+ my sub nvmeof_schema($schema) {
+ my @types = map { ($_->{oneOf} // [])->@* } ($schema->{allOf} // [])->@*;
+ my ($nvmeof) = grep { $_->{'instance-type'} eq 'nvmeof' } @types;
+ return $nvmeof->{properties} // {};
+ }
+ my $create = nvmeof_schema(PVE::Storage::Plugin->createSchema());
+ is_deeply(
+ [sort grep { !$create->{$_}->{optional} } keys $create->%*],
+ [qw(portals subsysnqn)],
+ 'adding a storage requires the subsystem and the portals',
+ );
+ my $update = nvmeof_schema(PVE::Storage::Plugin->updateSchema());
+ ok($update->{portals} && !$update->{subsysnqn}, 'the subsystem cannot be changed');
+ my $parsed = PVE::Storage::Plugin->parse_config(
+ 'storage.cfg',
+ "nvmeof: fabric\n\tsubsysnqn nqn.test\n\tportals 192.0.2.1\n\tcontent none\n",
+ );
+ is($parsed->{ids}->{fabric}->{subsysnqn}, 'nqn.test', 'storage.cfg accepts the plugin');
+ is_deeply(
+ $parsed->{ids}->{fabric}->{content},
+ { none => 1 },
+ 'connection-only content parses',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ { traddr => '192.0.2.1', trsvcid => 4420 },
+ 'default I/O port',
+ );
+ is_deeply(
+ PVE::NVMeOF::parse_portal('[2001:0db8::1]:4421'),
+ { traddr => '2001:db8::1', trsvcid => 4421 },
+ 'canonical IPv6',
+ );
+ is(
+ PVE::NVMeOF::format_path({ traddr => '2001:db8::1', trsvcid => 4421 }),
+ '[2001:db8::1]:4421',
+ 'an IPv6 portal in brackets',
+ );
+ is(
+ PVE::NVMeOF::format_path({ traddr => 'nn-0x2000:pn-0x2001' }),
+ 'nn-0x2000:pn-0x2001',
+ 'the address of a Fibre Channel port as it is',
+ );
+
+ for my $bad (
+ 'host.example', '1.2.3.4:0', '1.2.3.4:65536', '[fe80::1]', '[::]', '224.0.0.1',
+ ) {
+ ok(!PVE::NVMeOF::parse_portal($bad), "invalid portal $bad");
+ }
+ eval { $class->on_add_hook('fabric', { %$cfg, portals => '192.0.2.1,192.0.2.1:4420' }); };
+ like($@, qr/listed more than once/, 'duplicate portals refused');
+ eval { $class->on_add_hook('fabric', { %$cfg, portals => ',,' }); };
+ like($@, qr/no portal given/, 'a list without a portal refused');
+ eval {
+ $class->on_add_hook(
+ 'fabric',
+ { %$cfg, subsysnqn => 'nqn.2014-08.org.nvmexpress.discovery' },
+ );
+ };
+ like($@, qr/discovery subsystem/, 'discovery subsystem refused');
+ ok(!PVE::NVMeOF::subsystem_nqn("nqn.test\e[31m"),
+ 'an NQN with a control character refused');
+ ok(!PVE::NVMeOF::subsystem_nqn("nqn.test\x{2028}x"), 'so is one with a Unicode separator');
+ my $storage = Test::MockModule->new('PVE::Storage');
+ my $ids = { fabric => $cfg, local => { type => 'dir' } };
+ $storage->mock(config => sub { { ids => $ids } });
+ my $first = PVE::NVMeOF::storage_paths($cfg)->[0];
+ PVE::NVMeOF::note_connect_failure($cfg, $first);
+ is(eval { $class->on_add_hook('fabric', $cfg); 1 }, 1, 'a storage is not in its own way');
+ ok(!PVE::NVMeOF::in_cooldown($cfg, $first), 'adding it tries all portals again');
+ eval { $class->on_add_hook('second', {%$cfg}) };
+ like($@, qr/storage 'fabric' already uses this subsystem/, 'one storage per subsystem');
+ $ids->{vg} = { type => 'lvm', base => 'fabric:nvme-eui.0123456789abcdef', vgname => 'vg' };
+ my $images = { content => { images => 1 } };
+ eval { $class->on_update_hook_full('fabric', $cfg, $images, [], {}) };
+ like(
+ $@,
+ qr/storage 'vg' uses a namespace/,
+ 'no direct use of a namespace with a volume group',
+ );
+ my $none = { %$cfg, content => { none => 1 } };
+ eval { $class->on_update_hook_full('fabric', $none, {}, ['content'], {}) };
+ like($@, qr/storage 'vg' uses a namespace/, 'also not through the default content');
+ is(
+ eval { $class->on_update_hook_full('other', $cfg, $images, [], {}); 1 },
+ 1,
+ 'unless unused',
+ );
+ delete $ids->{vg};
+ PVE::NVMeOF::note_connect_failure($cfg, $first);
+ $class->on_update_hook_full('fabric', $cfg, { portals => $cfg->{portals} }, [], {});
+ ok(!PVE::NVMeOF::in_cooldown($cfg, $first), 'a new portal list tries all portals again');
+ is(
+ scalar($class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef')),
+ '/dev/disk/by-id/nvme-eui.0123456789abcdef',
+ 'stable volume path',
+ );
+ {
+ my $disk = Test::MockModule->new('PVE::Diskmanage');
+ my $nqn = 'nqn.other';
+ $disk->redefine(read_subsysnqn => sub { $nqn });
+ my $sysfs = Test::MockModule->new('PVE::NVMeOF');
+ my $head = 1;
+ $sysfs->redefine(namespace_wwid => sub { 'x' }, is_namespace_head => sub { $head });
+ my $check = sub {
+ eval { PVE::Storage::NVMeOFPlugin::assert_namespace($cfg, @_) };
+ $@;
+ };
+ like($check->('nvme-x', '/dev/nvme0n1'), qr/not part of subsystem/, 'other subsystem');
+ like($check->('nvme-x', '/dev/sda'), qr/not an NVMe namespace/, 'other device type');
+ like($check->('nvme-x', '/dev/nvme0n1p1'), qr/not an NVMe namespace/, 'partition');
+ $nqn = 'nqn.test';
+ is($check->('nvme-x', '/dev/nvme0n1'), '', 'namespace of the subsystem');
+ $head = 0;
+ like(
+ $check->('nvme-x', '/dev/nvme0n1'),
+ qr/device of a single controller/,
+ 'a namespace without native multipath',
+ );
+ $head = 1;
+ like(
+ $check->('nvme-Vendor_Model_123_1', '/dev/nvme0n1'),
+ qr/not named after the WWID/,
+ 'another by-id name of a namespace of the subsystem',
+ );
+ my $cwd = Test::MockModule->new('Cwd');
+ $cwd->redefine(realpath => sub { $dir });
+ eval { $class->filesystem_path($cfg, 'nvme-eui.0123456789abcdef') };
+ like($@, qr/not an NVMe namespace/, 'the path of an existing device is checked');
+ }
+
+ for my $bad ('nvme-../../sda', 'nvme-eui.abc-part1', 'sda') {
+ eval { $class->parse_volname($bad) };
+ like($@, qr/unable to parse/, "invalid volume $bad");
+ }
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ $nvme->mock(namespaces => sub { { nvme0n1 => { wwid => 'eui.abc', size => 4096 } } });
+ is(
+ $class->list_volumes('fabric', $cfg)->[0]->{volid},
+ 'fabric:nvme-eui.abc',
+ 'content none still offers bases',
+ );
+ is_deeply($class->list_images('fabric', $cfg, 100), [], 'namespaces have no VM owner');
+ $nvme->mock(subsystem_controllers => sub { {} });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test') };
+ like($@, qr/not available/,
+ 'missing namespace fails without waiting on absent controllers');
+ my ($now, $queries) = (0, 0);
+ my $clock = Test::MockModule->new('Time::HiRes');
+ $clock->redefine(time => sub { $now += 5 }, usleep => sub { });
+ $nvme->mock(subsystem_controllers => sub { $queries++; { nvme1 => {} } });
+ eval { $class->activate_volume('fabric', $cfg, 'nvme-nonexistent-test', undef, {}) };
+ is($queries, 1, 'a missing namespace of a connected subsystem is waited for');
+ eval {
+ $class->activate_volume(
+ 'fabric',
+ $cfg,
+ 'nvme-nonexistent-test',
+ undef,
+ { status_only => 1 },
+ );
+ };
+ like($@, qr/not available/, 'in a status pass it fails as well');
+ is($queries, 1, 'but without a wait');
+ is(
+ ($class->parse_volname('nvme-eui.0123456789abcdef'))[0],
+ 'vm-vol',
+ 'namespaces are VM disks',
+ );
+};
+
+subtest 'sysfs topology' => sub {
+ my $sys = $PVE::NVMeOF::SYSFS;
+ make_path(
+ "$sys/class/nvme-fabrics/ctl/nvme1",
+ "$sys/class/nvme-subsystem/nvme-subsys0/nvme0n1",
+ "$sys/block/nvme0n1",
+ );
+ my %attrs = (
+ address => 'traddr=192.0.2.1,trsvcid=4420',
+ transport => 'tcp',
+ subsysnqn => 'nqn.test',
+ state => 'connecting',
+ );
+ file_set_contents("$sys/class/nvme-fabrics/ctl/nvme1/$_", "$attrs{$_}\n") for keys %attrs;
+ file_set_contents("$sys/class/nvme-subsystem/nvme-subsys0/subsysnqn", "nqn.test\n");
+ file_set_contents("$sys/block/nvme0n1/wwid", "eui.abc\n");
+ file_set_contents("$sys/block/nvme0n1/size", "8\n");
+ make_path(
+ "$sys/devices/virtual/nvme-subsystem/nvme-subsys0",
+ "$sys/devices/virtual/nvme-fabrics/ctl/nvme1",
+ "$sys/block/nvme1n1",
+ );
+ symlink('../../devices/virtual/nvme-subsystem/nvme-subsys0', "$sys/block/nvme0n1/device")
+ or die "symlink failed - $!\n";
+ symlink('../../devices/virtual/nvme-fabrics/ctl/nvme1', "$sys/block/nvme1n1/device")
+ or die "symlink failed - $!\n";
+ ok(
+ PVE::NVMeOF::is_namespace_head('nvme0n1'),
+ 'a device of the subsystem is a namespace head',
+ );
+ ok(!PVE::NVMeOF::is_namespace_head('nvme1n1'), 'the device of a single controller is not');
+ ok(!PVE::NVMeOF::is_namespace_head('nvme9n1'), 'nor one that is gone');
+ is(
+ PVE::NVMeOF::controllers()->{nvme1}->{state},
+ 'connecting',
+ 'reconnecting controller is still present',
+ );
+ is(
+ PVE::NVMeOF::path_controller(
+ PVE::NVMeOF::subsystem_controllers('nqn.test'),
+ PVE::NVMeOF::parse_portal('192.0.2.1'),
+ ),
+ 'nvme1',
+ 'portal controller found',
+ );
+ is_deeply(
+ PVE::NVMeOF::namespaces('nqn.test'),
+ { nvme0n1 => { wwid => 'eui.abc', size => 4096 } },
+ 'namespace facts',
+ );
+ is_deeply(PVE::NVMeOF::namespaces('nqn.other'), {}, 'other subsystem excluded');
+ unlink("$sys/block/nvme0n1/wwid");
+ eval { PVE::NVMeOF::namespaces('nqn.test') };
+ like($@, qr/cannot read the WWID/, 'an unreadable namespace is an error, not a gone one');
+ file_set_contents("$sys/block/nvme0n1/wwid", "eui.abc\n");
+ make_path("$sys/class/nvme-subsystem/nvme-subsys9");
+ eval { PVE::NVMeOF::namespaces('nqn.test') };
+ like($@, qr/cannot read the NQN/, 'so is a subsystem that could be the one asked for');
+ rmdir("$sys/class/nvme-subsystem/nvme-subsys9");
+};
+
+subtest 'serialized commands inherit the lock' => sub {
+ local $PVE::NVMeOF::LOCK_WAIT = 0;
+ my $script = join(
+ ' ',
+ 'my @held = grep { (readlink($_) // "") =~ /fabrics.lock$/ } glob("/proc/self/fd/*");',
+ 'die "not inherited" if !@held;',
+ 'open(my $fh, ">>", $ARGV[0]) or die $!;',
+ 'die "lock missing" if flock($fh, LOCK_EX|LOCK_NB);',
+ 'print "locked\\n";',
+ );
+ my $value = PVE::NVMeOF::with_lock(sub {
+ my $out = '';
+ PVE::Tools::run_command(
+ [
+ '/usr/bin/perl',
+ '-MFcntl=:flock',
+ '-e',
+ $script,
+ "$PVE::NVMeOF::RUN_DIR/fabrics.lock",
+ ],
+ timeout => 5,
+ outfunc => sub { $out .= $_[0] },
+ );
+ return $out;
+ });
+ is($value, 'locked', 'exec cannot acquire the lock held by its parent');
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or die $!;
+ flock($lock, LOCK_EX) or die $!;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'busy operation never enters callback');
+ close($lock);
+
+ my $tools = Test::MockModule->new('PVE::Tools');
+ my $timed_out = 1;
+ $tools->mock(run_fork_with_timeout => sub { return ($_[1]->(), $timed_out) });
+ my $retained;
+ eval {
+ PVE::NVMeOF::with_lock(sub {
+ my ($path) =
+ grep { (readlink($_) // '') =~ /fabrics.lock$/ } glob('/proc/self/fd/*');
+ my ($fd) = $path =~ m{/(\d+)$};
+ open($retained, '>&', $fd) or die $!;
+ return 1;
+ });
+ };
+ like($@, qr/timed out.*may still be running/, 'timeout does not claim deletion completed');
+ $timed_out = 0;
+ eval {
+ PVE::NVMeOF::with_lock(sub { die "must not count paths\n" });
+ };
+ like($@, qr/is busy/, 'retained descriptor keeps serialization after the caller returns');
+ close($retained);
+ is(PVE::NVMeOF::with_lock(sub { 1 }), 1, 'last descriptor close releases serialization');
+
+ my @timeouts;
+ $tools->mock(run_fork_with_timeout => sub { push @timeouts, $_[0]; return ($_[1]->(), 0) });
+ PVE::NVMeOF::with_lock(sub { 1 }, $_) for undef, 100, 4.2, 0.3;
+ my $hung = PVE::NVMeOF::storage_paths($cfg)->[0];
+ $tools->mock(run_fork_with_timeout => sub { return (undef, 1) });
+ eval { PVE::NVMeOF::connect_path($cfg, $hung) };
+ is($@, $PVE::NVMeOF::TIMED_OUT, 'a hanging connect times out');
+ ok(PVE::NVMeOF::in_cooldown($cfg, $hung), 'and arms the cooldown of its portal');
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ my $full = $PVE::NVMeOF::LOCK_WAIT + 35;
+ is_deeply(
+ \@timeouts, [$full, 100, 5, 1], 'a limit sets the time in whole seconds',
+ );
+};
+
+subtest 'a short hold of the lock does not fail a connect' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my $scfg = { %$cfg, subsysnqn => 'nqn.wait', portals => '192.0.2.3' };
+ my $ctl = "$PVE::NVMeOF::SYSFS/class/nvme-fabrics/ctl/nvme9";
+ $net->mock(tcp_ping => sub { 1 });
+ $nvme->mock(assert_support => sub { });
+ $nvme->mock(host_identity =>
+ sub { { nqn => 'nqn.host', id => '12345678-1234-1234-1234-123456789abc' } });
+ $nvme->mock(
+ run_command => sub(@) {
+ my %attrs = (
+ address => 'traddr=192.0.2.3,trsvcid=4420',
+ transport => 'tcp',
+ subsysnqn => 'nqn.wait',
+ state => 'live',
+ );
+ make_path($ctl);
+ file_set_contents("$ctl/$_", "$attrs{$_}\n") for keys %attrs;
+ },
+ );
+ pipe(my $held, my $signal) or die "pipe failed - $!\n";
+ my $holder = fork() // die "fork failed - $!\n";
+ if (!$holder) {
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or POSIX::_exit(1);
+ flock($lock, LOCK_EX) or POSIX::_exit(1);
+ syswrite($signal, '1');
+ Time::HiRes::sleep(0.5);
+ POSIX::_exit(0);
+ }
+ close($signal);
+ sysread($held, my $state, 1);
+ is($state, '1', 'another process holds the lock');
+ my $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ $class->activate_storage('wait', $scfg);
+ }
+ waitpid($holder, 0);
+ is($warning, '', 'the connect waits for the lock');
+ my $path = PVE::NVMeOF::storage_paths($scfg)->[0];
+ ok(!PVE::NVMeOF::in_cooldown($scfg, $path), 'and arms no cooldown');
+ is(
+ PVE::NVMeOF::path_controller(PVE::NVMeOF::subsystem_controllers('nqn.wait'), $path),
+ 'nvme9',
+ 'the portal is connected',
+ );
+ remove_tree($ctl);
+
+ local $PVE::NVMeOF::LOCK_WAIT = 0.2;
+ pipe($held, $signal) or die "pipe failed - $!\n";
+ $holder = fork() // die "fork failed - $!\n";
+ if (!$holder) {
+ open(my $lock, '>>', "$PVE::NVMeOF::RUN_DIR/fabrics.lock") or POSIX::_exit(1);
+ flock($lock, LOCK_EX) or POSIX::_exit(1);
+ syswrite($signal, '1');
+ Time::HiRes::sleep(1);
+ POSIX::_exit(0);
+ }
+ close($signal);
+ sysread($held, $state, 1);
+ {
+ local $SIG{__WARN__} = sub { };
+ eval { $class->activate_storage('wait', $scfg) };
+ }
+ waitpid($holder, 0);
+ like($@, qr/NVMe over Fabrics is busy/, 'a longer hold fails the connect');
+ ok(!PVE::NVMeOF::in_cooldown($scfg, $path), 'but arms no cooldown for the portal');
+};
+
+subtest 'connect options, kernel reconnect and cooldown' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my @commands;
+ my $controllers = {};
+ my @limits;
+ $nvme->mock(with_lock => sub { push @limits, $_[1]; $_[0]->() });
+ $nvme->mock(assert_support => sub { });
+ $nvme->mock(host_identity =>
+ sub { { nqn => 'nqn.host', id => '12345678-1234-1234-1234-123456789abc' } });
+ $nvme->mock(subsystem_controllers => sub { $controllers });
+ my $appear = 1;
+ our $state = 'live';
+ my ($now, $connect_secs) = (0, 0);
+ $nvme->mock(
+ run_command => sub($cmd, %opts) {
+ is($opts{timeout}, 30, 'bounded connect');
+ push @commands, $cmd;
+ $now += $connect_secs;
+ my %arg =
+ map { $cmd->[$_] => $cmd->[$_ + 1] } grep { $cmd->[$_] =~ /^--tr/ } 0 .. $#$cmd;
+ my $controller =
+ { traddr => $arg{'--traddr'}, trsvcid => $arg{'--trsvcid'}, state => $state };
+ $controllers->{ 'nvme' . scalar(@commands) } = $controller if $appear;
+ },
+ );
+ $net->mock(tcp_ping => sub { 1 });
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 2, 'one connect per missing portal');
+ ok(grep({ $_ eq '--ctrl-loss-tmo=-1' } $commands[0]->@*), 'kernel reconnects indefinitely');
+ is_deeply([@{ $commands[0] }[-2, -1]], ['--fast_io_fail_tmo', 120], 'fast failure default');
+ {
+ my $clock = Test::MockModule->new('Time::HiRes');
+ $clock->redefine(time => sub { $now });
+ my $activate = sub($secs) {
+ ($controllers, $connect_secs, @commands) = ({}, $secs);
+ local $SIG{__WARN__} = sub { };
+ eval { $class->activate_storage('fabric', $cfg) };
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ return scalar(@commands);
+ };
+ is($activate->(20), 1, 'with a live controller, a spent time budget leaves the rest');
+ $appear = 0;
+ is($activate->(20), 2, 'without one, a slow portal does not keep the next one out');
+ is($activate->(50), 1, 'but a very slow one does');
+ @limits = ();
+ is($activate->(40), 2, 'one that starts late is still tried');
+ is_deeply(\@limits, [45, 5], 'but only for the rest of the time limit');
+ local $state = 'connecting';
+ $appear = 1;
+ is($activate->(20), 2, 'a new controller that is still connecting is not live');
+ $appear = 0;
+ ($appear, $connect_secs) = (1, 0);
+ }
+ @commands = ();
+ $controllers = {
+ nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' },
+ nvme2 => { traddr => '2001:db8::2', trsvcid => 4421, state => 'live' },
+ };
+ $class->activate_storage('fabric', $cfg);
+ is_deeply(\@commands, [],
+ 'existing controllers are never reconnected, regardless of state');
+ $controllers->{nvme2}->{state} = 'connecting';
+ eval { $class->activate_storage('fabric', $cfg) };
+ like($@, qr/no controller of the subsystem is live/, 'without a live one it fails');
+ is_deeply(\@commands, [], 'but leaves the reconnect to the kernel');
+ $controllers->{nvme2}->{state} = 'live';
+ $class->deactivate_storage('fabric', $cfg);
+ is_deeply(\@commands, [], 'deactivation does not remove controllers');
+ $controllers = {};
+ my $path = PVE::NVMeOF::storage_paths($cfg)->[0];
+ PVE::NVMeOF::note_connect_failure($cfg, $path);
+ ok(PVE::NVMeOF::in_cooldown($cfg, $path), 'failure starts cooldown');
+ $class->activate_storage('fabric', $cfg);
+ is(scalar(@commands), 1, 'only the other portal connects');
+ ($controllers, $appear) = ({}, 0);
+ my $other = PVE::NVMeOF::storage_paths($cfg)->[1];
+ my $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ eval { $class->activate_storage('fabric', $cfg) };
+ }
+ like($warning, qr/no controller appeared/, 'a connect without a controller is a failure');
+ ok(PVE::NVMeOF::in_cooldown($cfg, $other), 'which starts the cooldown too');
+ like(
+ $@,
+ qr/^cannot connect to any portal - .*failed less than a minute ago; .*no controller appeared/,
+ 'without any controller the activation fails with the reason of each portal',
+ );
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ $nvme->mock(assert_support => sub { die "nvme-cli is not installed\n" });
+ @commands = ();
+ eval { $class->activate_storage('fabric', $cfg) };
+ is($@, "nvme-cli is not installed\n", 'a missing prerequisite fails the activation');
+ is_deeply(\@commands, [], 'before any connect');
+ ok(!PVE::NVMeOF::in_cooldown($cfg, $path), 'and without a cooldown');
+ $controllers = { nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'live' } };
+ $warning = '';
+ {
+ local $SIG{__WARN__} = sub { $warning .= $_[0] };
+ is(
+ eval { $class->activate_storage('fabric', $cfg); 1 },
+ 1,
+ 'but not with a usable path',
+ );
+ }
+ like($warning, qr/cannot connect to the other portals - nvme-cli/, 'which it warns about');
+ $nvme->mock(assert_support => sub { });
+ $controllers =
+ { nvme1 => { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' } };
+ {
+ local $SIG{__WARN__} = sub { };
+ eval { $class->activate_storage('fabric', $cfg) };
+ }
+ like(
+ $@,
+ qr/^cannot connect to any portal/,
+ 'a reconnecting path is not usable when the missing one fails',
+ );
+ # a connect that worked, but whose controller is not live yet
+ ($controllers, $now, $connect_secs) = ({}, 0, 0);
+ $net->mock(tcp_ping => sub { 1 });
+ $nvme->mock(
+ run_command => sub($cmd, %opts) {
+ my %arg =
+ map { $cmd->[$_] => $cmd->[$_ + 1] } grep { $cmd->[$_] =~ /^--tr/ } 0 .. $#$cmd;
+ $controllers->{nvme7} =
+ { traddr => $arg{'--traddr'}, trsvcid => $arg{'--trsvcid'}, state => 'connecting' };
+ },
+ );
+ eval { $class->activate_storage('fabric', { %$cfg, portals => '192.0.2.7' }) };
+ is($@, "no controller of the subsystem is live yet\n", 'says so without an empty reason');
+};
+
+subtest 'the connection check has a time limit too' => sub {
+ my $nvme = Test::MockModule->new('PVE::NVMeOF');
+ my $net = Test::MockModule->new('PVE::Network');
+ my $clock = Test::MockModule->new('Time::HiRes');
+ my ($now, $pings) = (0, 0);
+ $clock->redefine(time => sub { $now });
+ $nvme->mock(subsystem_controllers => sub { {} });
+ $net->mock(tcp_ping => sub { $now += 2; $pings++; 0 });
+ my $scfg = { %$cfg, portals => join(',', map { "192.0.2.$_" } 1 .. 20) };
+ is($class->check_connection('many', $scfg), 1, 'untried portals go to the activation');
+ is($pings, 8, 'which the check leaves after its time limit');
+ ok(
+ PVE::NVMeOF::in_cooldown($scfg, PVE::NVMeOF::parse_portal('192.0.2.8')),
+ 'the failed ones cool down',
+ );
+ ($now, $pings) = (0, 0);
+ is($class->check_connection('many', $scfg), 1, 'a later pass skips the failed portals');
+ ok(
+ PVE::NVMeOF::in_cooldown($scfg, PVE::NVMeOF::parse_portal('192.0.2.16')),
+ 'and gets further',
+ );
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ $scfg->{portals} = '192.0.2.1,192.0.2.2';
+ ($now, $pings) = (0, 0);
+ is($class->check_connection('few', $scfg), 0, 'all tried and none answers');
+ unlink(glob("$PVE::NVMeOF::RUN_DIR/retry/*"));
+ my $reconnecting = { traddr => '192.0.2.1', trsvcid => 4420, state => 'connecting' };
+ $nvme->mock(subsystem_controllers => sub { { nvme1 => $reconnecting } });
+ ($scfg->{portals}, $pings) = ('192.0.2.1', 0);
+ eval { $class->check_connection('few', $scfg) };
+ is($@, "no controller of the subsystem is live\n", 'with a controller for each portal');
+ is($pings, 0, 'which the check does not ping');
+};
+
+done_testing();
diff --git a/src/test/run_san_nvme_tests.pl b/src/test/run_san_nvme_tests.pl
index 3245b774..61872a60 100755
--- a/src/test/run_san_nvme_tests.pl
+++ b/src/test/run_san_nvme_tests.pl
@@ -38,6 +38,7 @@ $storage->mock(config => sub { $cfg });
$disk->mock(verify_blockdev_path => sub { $device });
$disk->mock(is_partition => sub { 0 });
$disk->mock(get_nvme_transport => sub { 'fc' });
+$disk->mock(read_subsysnqn => sub { 'nqn.test' });
$disk->mock(is_iscsi_device => sub { 0 });
$disk->mock(is_mounted => sub { 0 });
$disk->mock(has_holder => sub { 0 });
@@ -86,6 +87,28 @@ for my $base (qw(fabric nvme-fabric)) {
eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
like($@, qr/base volume/, "native base reference on storage '$base' refuses");
}
+$cfg->{ids} =
+ { fabric =>
+ { type => 'nvmeof', subsysnqn => 'nqn.test', disable => 1, content => { images => 1 } } };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like(
+ $@,
+ qr/serves images from this subsystem/,
+ 'direct namespace image use refuses even when disabled',
+);
+$cfg->{ids}->{fabric}->{content} = { 'vm-vol' => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+like($@, qr/serves images from this subsystem/, 'also when restricted to VM disks');
+$cfg->{ids}->{fabric}->{content} = { none => 1 };
+eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+is($@, '', 'connection-only storage permits namespace initialization');
+
+for my $nqn (undef, '') {
+ $disk->mock(read_subsysnqn => sub { $nqn });
+ eval { PVE::Storage::SAN::assert_lun_unreferenced($cfg, $lun) };
+ like($@, qr/cannot read its NVMe subsystem/, 'an unreadable subsystem refuses');
+}
+$disk->mock(read_subsysnqn => sub { 'nqn.test' });
$cfg->{ids} = {};
@order = @opens = ();
$tools->mock(file_get_contents => sub { 1024 });
^ permalink raw reply related [relevance 17%]
* [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
@ 2026-11-26 15:09 11% ` Joaquin Varela
2026-11-26 15:09 15% ` [PATCH storage v5 03/13] zfsnvme: add storage configuration and volume methods Joaquin Varela
` (7 subsequent siblings)
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:09 UTC (permalink / raw)
To: pve-devel
Add the first part of the 'zfsnvme' storage plugin: ZFS zvols on a
remote Linux target, exported with the kernel nvmet driver over
NVMe/TCP and managed over SSH like ZFS over iSCSI.
This part reads the target state with one 'zfs get' and one 'find' over
configfs, parses it and plans the changes as quoted commands. Parsing
and planning are local and pure. A value that is read from the target
or passed in by a caller is untainted by the capture of the regex that
validates it, as pvedaemon runs with -T. The patch also holds the SSH
runner that every target call goes through. A later patch of this
series registers the plugin.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
src/PVE/Storage/ZFSNVMePlugin.pm | 1007 ++++++++++++++++++++++++++++++
1 file changed, 1007 insertions(+)
create mode 100644 src/PVE/Storage/ZFSNVMePlugin.pm
diff --git a/src/PVE/Storage/ZFSNVMePlugin.pm b/src/PVE/Storage/ZFSNVMePlugin.pm
new file mode 100644
index 00000000..270d559c
--- /dev/null
+++ b/src/PVE/Storage/ZFSNVMePlugin.pm
@@ -0,0 +1,1007 @@
+package PVE::Storage::ZFSNVMePlugin;
+
+use v5.36;
+
+use Compress::Zlib qw(crc32);
+use Digest::SHA qw(sha256_hex);
+use Errno qw(ENOENT);
+use Fcntl qw(O_NOFOLLOW O_RDONLY O_RDWR S_ISCHR);
+use File::Path qw(make_path);
+use List::Util qw(max);
+use MIME::Base64 qw(decode_base64);
+use POSIX qw(SIG_BLOCK SIG_SETMASK SIGHUP SIGINT SIGQUIT SIGTERM sigprocmask);
+use Socket qw(AF_INET6 inet_ntop inet_pton);
+use Time::HiRes;
+
+use PVE::Cluster;
+use PVE::File;
+use PVE::JSONSchema;
+use PVE::Network;
+use PVE::RESTEnvironment qw(log_warn);
+use PVE::RPCEnvironment;
+use PVE::SysFSTools;
+use PVE::Tools qw(file_read_firstline file_set_contents run_command trim);
+
+use base qw(PVE::Storage::Plugin);
+
+# ZFS zvols on a remote Linux target, exported through the kernel NVMe target (nvmet, configured
+# through configfs) over NVMe/TCP and consumed with native NVMe multipath. The ZFS dataset is the
+# source of truth for a namespace (owner NQN, NSID and UUID are ZFS user properties), everything
+# else on the target is derived state that is rebuilt after a restart.
+#
+# Parsing, validation and planning happen locally. Target calls are quoted commands over SSH,
+# sometimes joined with `&&`, with `>` writes into configfs and one `dd | tee` pipe for a key,
+# because configfs needs its writes in order. A pmxcfs domain lock per target serializes the
+# changes in the cluster.
+
+# LogLevel=ERROR keeps a login banner out of the first stderr line, the error text of a failed call.
+my @ssh_cmd = (
+ '/usr/bin/ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'LogLevel=ERROR',
+);
+my $id_rsa_path = '/etc/pve/priv/zfs';
+my $secret_dir = '/etc/pve/priv/storage';
+my $max_paths = 16;
+my $max_hosts = 64;
+my $slow_path_backoff = 60;
+
+my $nvmet_root = '/sys/kernel/config/nvmet';
+my $nvmet_model = 'Proxmox ZFS NVMe';
+my $nvmet_marker = 'ZFSNVME-CONFIGFS';
+my $nvmet_max_nsid = 0xfffffffe;
+my $nvmet_max_command = 65536;
+my $nvmet_lock_wait = 30;
+my $nvmet_last_nsid = 'proxmox:nvme-last-nsid';
+
+my @nvmet_zfs_props =
+ ('type', 'proxmox:nvme-subsys', 'proxmox:nvme-nsid', 'proxmox:nvme-uuid', $nvmet_last_nsid);
+my %nvmet_zfs_keys = (
+ type => 'type',
+ 'proxmox:nvme-subsys' => 'nqn',
+ 'proxmox:nvme-nsid' => 'nsid',
+ 'proxmox:nvme-uuid' => 'uuid',
+ $nvmet_last_nsid => 'last_nsid',
+);
+my @nvmet_cfs_attrs = qw(
+ enable device_path device_uuid buffered_io
+ attr_model attr_serial attr_allow_any_host
+ addr_trtype addr_adrfam addr_traddr addr_trsvcid
+);
+# The commands that _nvmet_render accepts as the first word of a step. Also run on the target are
+# find, which the configfs read starts through env to set its locale, the printf, grep and sha256sum
+# that find runs, and the dd and tee of a key write.
+my %nvmet_commands = map { $_ => 1 } qw(
+ cat chmod env grep ln mkdir modprobe mount printf rm rmdir test zfs
+);
+
+my $RE_NQN = qr{
+ \A
+ nqn \.
+ [A-Za-z0-9] [A-Za-z0-9.-]*
+ :
+ [A-Za-z0-9] [A-Za-z0-9._:-]*
+ \z
+}nxx;
+my $RE_HOST_IFACE = qr{\A [A-Za-z0-9_.-]+ \z}nxx;
+my $RE_DHCHAP_KEY = qr{
+ \A (?<key> DHHC-1 : (?<hash> 0[0-3]) : (?<secret> [A-Za-z0-9+/]+ ={0,2}) :) \z
+}nxx;
+my $RE_TASK_INTERRUPT = qr{
+ \A (?: (?: command \x20 ' .* ' \x20 failed: \x20 )? received \x20 interrupt
+ | interrupted \x20 by \x20 unexpected \x20 signal ) \n \z
+}nsxx;
+my $RE_COMMAND_TIMEOUT = qr{
+ \A (?: command \x20 ' .* ' \x20 failed: \x20 )? got \x20 timeout \n \z
+}nsxx;
+my $RE_COMMAND_EXIT =
+ qr{\A command \x20 ' .* ' \x20 failed: \x20 exit \x20 code \x20 (?<code> [0-9]+) \n \z}nsxx;
+my $RE_FABRICS_VALUE = qr{\A [^\s,\x00]+ \z}nxx;
+my $RE_FABRICS_RESULT = qr{\A instance=(?<instance> [0-9]+) ,cntlid= [0-9]+ \n \z}nxx;
+my $RE_CONFIG_INT = qr{\A -?[0-9]+ \z}nxx;
+my $RE_NVME_CONTROLLER = qr{\A nvme [0-9]+ \z}nxx;
+my $RE_NVME_SUBSYSTEM = qr{\A nvme-subsys [0-9]+ \z}nxx;
+my $RE_NVME_NAMESPACE = qr{\A (?<device> nvme [0-9]+ n [0-9]+) \z}nxx;
+my $RE_TRADDR = qr{(?: \A | ,) traddr=(?<value>[^,]+)}nxx;
+my $RE_TRSVCID = qr{(?: \A | ,) trsvcid=(?<value>[^,]+)}nxx;
+my $RE_HOST_IFACE_ADDRESS = qr{(?: \A | ,) host_iface=(?<value>[^,]+)}nxx;
+# no ':' like ZFSPlugin, and anchor with \z as $ also accepts a trailing newline
+my $RE_ZVOL_SUFFIX = qr{[a-zA-Z0-9_.-]+}nxx;
+my $RE_ZVOL_OWNER = qr{\A (?:vm|base|subvol|basevol)- (?<owner>\d+) - $RE_ZVOL_SUFFIX \z}nxx;
+my $RE_VOLNAME = qr{
+ \A
+ (?: (?<base> (?:base|basevol)- (?<base_vmid>\d+) - $RE_ZVOL_SUFFIX) /)?
+ (?<name> (?<type>base|basevol|vm|subvol)- (?<vmid>\d+) - $RE_ZVOL_SUFFIX)
+ \z
+}nxx;
+my $RE_BASE_SNAPSHOT = qr{\A (?<base> [a-zA-Z0-9_.-]+) \@__base__ \z}nxx;
+my $RE_UNSIGNED_INTEGER = qr{^ (?<value>\d+) $}nxx;
+
+# The named captures untaint the values that were read and those that callers pass, as the daemons
+# run with -T.
+my $RE_NVMET_UUID = qr{
+ \A (?<uuid> [0-9a-fA-F]{8} (?: - [0-9a-fA-F]{4}){3} - [0-9a-fA-F]{12}) \z
+}nxx;
+my $RE_NVMET_NSID = qr{\A (?<nsid> [1-9] [0-9]*) \z}nxx;
+my $RE_NVMET_POOL = qr{\A [A-Za-z0-9] [A-Za-z0-9_.:/-]* \z}nxx;
+my $RE_NVMET_DATASET_NAME = qr{\A (?<name> [A-Za-z0-9] [A-Za-z0-9_.:-]*) \z}nxx;
+my $RE_NVMET_SNAPSHOT = qr{\A (?<snap> [A-Za-z0-9_.:-]+) \z}nxx;
+# as the pve-storage-id format checks it
+my $RE_STORAGE_ID = qr{\A (?<storeid> [a-z] [a-z0-9_.-]* [a-z0-9]) \z}nxxi;
+my $RE_NVMET_TEMPLATE_ZVOL = qr{/ (?<type> vm | base) - (?<suffix> [^/]+) \z}nxx;
+my $RE_NVMET_INHERITED = qr{\A inherited \x20 from \x20 (?<source> .+) \z}nxx;
+my $RE_NVMET_ABANDONED = qr{
+ (?: \A received \x20 interrupt | ; \x20 the \x20 target \x20 state \x20 is \x20 unknown) \n \z
+}nxx;
+
+# attribute names anchor the split, so an NQN containing ':' is never ambiguous
+my $cfs_root = quotemeta($nvmet_root);
+my $RE_CFS_TOP = qr{\A D \x20 $cfs_root (?: / (?<top> hosts | ports | subsystems))? \z}nxx;
+my $RE_CFS_SUBSYS_DIR = qr{\A D \x20 $cfs_root /subsystems/ (?<nqn> [^/]+) \z}nxx;
+my $RE_CFS_SUBSYS_GROUP = qr{
+ \A D \x20 $cfs_root /subsystems/ [^/]+ / (?: namespaces | allowed_hosts) \z
+}nxx;
+my $RE_CFS_NS_DIR = qr{
+ \A D \x20 $cfs_root /subsystems/ (?<nqn> [^/]+) /namespaces/ (?<nsid> [0-9]+) \z
+}nxx;
+my $RE_CFS_PORT_DIR = qr{\A D \x20 $cfs_root /ports/ (?<port> [0-9]+) \z}nxx;
+my $RE_CFS_PORT_GROUP = qr{\A D \x20 $cfs_root /ports/ [0-9]+ /subsystems \z}nxx;
+my $RE_CFS_HOST_DIR = qr{\A D \x20 $cfs_root /hosts/ (?<host> [^/]+) \z}nxx;
+my $RE_CFS_PORT_LINK = qr{
+ \A L \x20 $cfs_root /ports/ (?<port> [0-9]+) /subsystems/ (?<nqn> [^/]+) \z
+}nxx;
+my $RE_CFS_ACL_LINK = qr{
+ \A L \x20 $cfs_root /subsystems/ (?<nqn> [^/]+) /allowed_hosts/ (?<host> [^/]+) \z
+}nxx;
+my $RE_CFS_OTHER_ENTRY = qr{\A [DL] \x20 $cfs_root /}nxx;
+my $RE_CFS_NS_ATTR = qr{
+ \A $cfs_root /subsystems/ (?<nqn> [^/]+) /namespaces/ (?<nsid> [0-9]+)
+ / (?<attr> enable | device_path | device_uuid | buffered_io) : (?<value> .*) \z
+}nxx;
+my $RE_CFS_SUBSYS_ATTR = qr{
+ \A $cfs_root /subsystems/ (?<nqn> [^/]+)
+ / (?<attr> attr_model | attr_serial | attr_allow_any_host) : (?<value> .*) \z
+}nxx;
+my $RE_CFS_PORT_ATTR = qr{
+ \A $cfs_root /ports/ (?<port> [0-9]+)
+ / (?<attr> addr_trtype | addr_adrfam | addr_traddr | addr_trsvcid) : (?<value> .*) \z
+}nxx;
+my $RE_CFS_KEY_DIGEST = qr{
+ \A (?<sha> [0-9a-f]{64}) \x20 [\x20*] $cfs_root /hosts/ (?<host> [^/]+) /dhchap_key \z
+}nxx;
+my $RE_CFS_OTHER_ATTR = qr{\A $cfs_root /}nxx;
+
+sub verify_nvme_nqn($value, $noerr = undef) {
+
+ if (
+ length($value) > 223
+ || $value !~ $RE_NQN
+ ) {
+ return undef if $noerr;
+ die "value is not a valid NVMe qualified name\n";
+ }
+
+ return $value;
+}
+
+sub parse_nvme_host_nqns($value, $noerr = undef) {
+ my $result = [];
+ my $seen = {};
+
+ for my $hostnqn (split(/,/, $value // '')) {
+ $hostnqn = trim($hostnqn);
+ if (!verify_nvme_nqn($hostnqn, 1) || $seen->{$hostnqn}++) {
+ return undef if $noerr;
+ die "invalid or duplicate NVMe host NQN '$hostnqn'\n";
+ }
+ push $result->@*, $hostnqn;
+ if (scalar($result->@*) > $max_hosts) {
+ return undef if $noerr;
+ die "at most $max_hosts NVMe host NQNs are supported\n";
+ }
+ }
+
+ if (!$result->@*) {
+ return undef if $noerr;
+ die "at least one NVMe host NQN is required\n";
+ }
+
+ return $result;
+}
+
+my sub nvmet_server($scfg) {
+ return $scfg->{server};
+}
+
+my sub nvmet_ssh_key($scfg) {
+ return "$id_rsa_path/" . nvmet_server($scfg) . '_id_rsa';
+}
+
+my sub nvmet_lock_id($scfg) {
+ my $server = nvmet_server($scfg) // '';
+ return 'zfsnvme-' . ($server =~ s/[^A-Za-z0-9.-]/_/gr);
+}
+
+my sub secret_path($storeid) {
+ die "invalid storage ID\n" if !defined($storeid) || $storeid !~ $RE_STORAGE_ID;
+ return "$secret_dir/$+{storeid}.nvme-dhchap";
+}
+
+my sub nvmet_nqn($scfg) {
+ my $nqn = $scfg->{subsysnqn};
+ die "invalid NVMe subsystem NQN\n" if !defined($nqn) || !verify_nvme_nqn($nqn, 1);
+ return $nqn;
+}
+
+my sub nvmet_pool($scfg) {
+ my $pool = $scfg->{pool};
+ die "invalid ZFS pool name\n" if !defined($pool) || $pool !~ $RE_NVMET_POOL;
+ return $pool;
+}
+
+my sub nvmet_dataset($scfg, $name) {
+ die "invalid ZFS volume name\n" if !defined($name) || $name !~ $RE_NVMET_DATASET_NAME;
+ my $volume = $+{name};
+ return nvmet_pool($scfg) . "/$volume";
+}
+
+# zfs destroy reads '%' and ',' in a snapshot name as a range and a list.
+my sub nvmet_snapshot($scfg, $name, $snap) {
+ die "invalid snapshot name\n" if !defined($snap) || $snap !~ $RE_NVMET_SNAPSHOT;
+ my $tag = $+{snap};
+ return nvmet_dataset($scfg, $name) . "\@$tag";
+}
+
+# These return the captured text, or undef if the value is not valid.
+my sub nvmet_nsid($value) {
+ return undef if !defined($value) || $value !~ $RE_NVMET_NSID;
+ my $nsid = $+{nsid};
+ return $nsid <= $nvmet_max_nsid ? $nsid : undef;
+}
+
+my sub nvmet_uuid($value) {
+ return defined($value) && $value =~ $RE_NVMET_UUID ? $+{uuid} : undef;
+}
+
+my sub nvmet_canonical_address($address) {
+ return $address if !defined($address) || index($address, ':') < 0;
+ my $packed = inet_pton(AF_INET6, $address) // return $address;
+ return inet_ntop(AF_INET6, $packed);
+}
+
+# Target-provided names only appear in messages when they are well-formed.
+my sub nvmet_label($name) {
+ return $name =~ $RE_NQN ? " '$name'" : '';
+}
+
+my sub nvmet_template_twin($name) {
+ return '' if $name !~ $RE_NVMET_TEMPLATE_ZVOL;
+ my $twin = ($+{type} eq 'vm' ? 'base' : 'vm') . "-$+{suffix}";
+ return substr($name, 0, $-[0]) . "/$twin";
+}
+
+# ZFS waits for transaction groups, which a busy pool can take minutes to sync
+my sub nvmet_long_timeout() {
+ return PVE::RPCEnvironment->is_worker() ? 60 * 60 : 60;
+}
+
+# A step is an argv array, a configfs write (hash with write and value) or a key write (hash with
+# key) fed from stdin. A unit is a list of steps that must stay in one call.
+
+my sub nvmet_subsys_path($nqn) {
+ return "$nvmet_root/subsystems/$nqn";
+}
+
+my sub nvmet_ns_path($nqn, $nsid) {
+ return "$nvmet_root/subsystems/$nqn/namespaces/$nsid";
+}
+
+my sub nvmet_port_path($id) {
+ return "$nvmet_root/ports/$id";
+}
+
+my sub nvmet_host_path($hostnqn) {
+ return "$nvmet_root/hosts/$hostnqn";
+}
+
+my sub nvmet_write($path, $value) {
+ return { write => $path, value => $value };
+}
+
+my sub nvmet_namespaces($cfs, $nqn) {
+ my $subsys = $cfs->{subsystems}->{$nqn};
+ return ($subsys ? $subsys->{namespaces} : undef) // {};
+}
+
+my sub nvmet_port_linked($cfs, $id, $nqn) {
+ my $port = $cfs->{ports}->{$id};
+ return $port && ($port->{links} // {})->{$nqn};
+}
+
+# The first subsystem, by NQN, that allows each host
+my sub nvmet_linked_hosts($cfs) {
+ my %linked;
+ for my $nqn (sort keys $cfs->{subsystems}->%*) {
+ $linked{$_} //= $nqn for keys(($cfs->{subsystems}->{$nqn}->{acl} // {})->%*);
+ }
+ return \%linked;
+}
+
+# Creation stopped after the model write and before the serial: nobody else writes our model and
+# nothing is exported, so completing it is safe. A default model may belong to another tool.
+my sub nvmet_unfinished_subsystem($cfs, $nqn) {
+ my $subsys = $cfs->{subsystems}->{$nqn};
+ return 0 if !$subsys;
+ return
+ $subsys->{attr_model} eq $nvmet_model
+ && !($subsys->{namespaces} // {})->%*
+ && !($subsys->{acl} // {})->%*
+ && !grep { nvmet_port_linked($cfs, $_, $nqn) } keys $cfs->{ports}->%*;
+}
+
+# Same write order as the kernel requires: the device before enabling it.
+my sub nvmet_build_unit($nqn, $nsid, $uuid, $dev) {
+ my $ns = nvmet_ns_path($nqn, $nsid);
+ return [
+ ['test', '-b', $dev],
+ ['mkdir', $ns],
+ nvmet_write("$ns/device_path", $dev),
+ nvmet_write("$ns/device_uuid", $uuid),
+ nvmet_write("$ns/buffered_io", 0),
+ nvmet_write("$ns/enable", 1),
+ ];
+}
+
+my sub nvmet_enable_unit($nqn, $nsid, $dev) {
+ return [['test', '-b', $dev], nvmet_write(nvmet_ns_path($nqn, $nsid) . '/enable', 1)];
+}
+
+my sub nvmet_unexport_unit($nqn, $nsid, $enabled) {
+ my $ns = nvmet_ns_path($nqn, $nsid);
+ return [($enabled ? (nvmet_write("$ns/enable", 0)) : ()), ['rmdir', $ns]];
+}
+
+my sub nvmet_identity($nqn, $nsid, $uuid) {
+ return ("proxmox:nvme-subsys=$nqn", "proxmox:nvme-nsid=$nsid", "proxmox:nvme-uuid=$uuid");
+}
+
+my sub nvmet_zfs_inventory_step($pool) {
+ return [
+ 'zfs',
+ 'get',
+ '-H',
+ '-p',
+ '-d',
+ '1',
+ '-t',
+ 'filesystem,volume',
+ '-o',
+ 'name,property,value,source',
+ join(',', @nvmet_zfs_props),
+ $pool,
+ ];
+}
+
+# Keys are never read back, only their sha256. Only the kernel's own groups of unused objects are
+# skipped, so an object of another tool with one of their names is still listed.
+my sub nvmet_configfs_step($hostnqns) {
+ my @names = map { ('-o', '-name', $_) } @nvmet_cfs_attrs;
+ shift @names;
+ my @keys = map { ('-o', '-path', nvmet_host_path($_) . '/dhchap_key') } $hostnqns->@*;
+ shift @keys;
+ return [
+ 'env',
+ 'LC_ALL=C',
+ 'find',
+ $nvmet_root,
+ '(',
+ '-path',
+ "$nvmet_root/subsystems/*/passthru",
+ '-o',
+ '-path',
+ "$nvmet_root/ports/*/ana_groups",
+ '-o',
+ '-path',
+ "$nvmet_root/ports/*/referrals",
+ ')',
+ '-type',
+ 'd',
+ '-prune',
+ '-o',
+ '-type',
+ 'd',
+ '-exec',
+ 'printf',
+ 'D %s\n',
+ '{}',
+ '+',
+ '-o',
+ '-type',
+ 'l',
+ '-exec',
+ 'printf',
+ 'L %s\n',
+ '{}',
+ '+',
+ '-o',
+ '-type',
+ 'f',
+ '(',
+ @names,
+ ')',
+ '-exec',
+ 'grep',
+ '',
+ '/dev/null',
+ '{}',
+ '+',
+ (@keys ? ('-o', '-type', 'f', '(', @keys, ')', '-exec', 'sha256sum', '{}', '+') : ()),
+ ];
+}
+
+my sub nvmet_state_steps($pool, $hostnqns, $modprobe) {
+ return [
+ ($modprobe ? (['modprobe', 'nvmet_tcp']) : ()),
+ nvmet_zfs_inventory_step($pool),
+ ['printf', '%s\n', $nvmet_marker],
+ nvmet_configfs_step($hostnqns),
+ ];
+}
+
+my sub nvmet_valid_word($word) {
+ return defined($word) && !ref($word) && $word !~ /[\0\r\n]/;
+}
+
+my sub nvmet_valid_path($path) {
+ return nvmet_valid_word($path) && $path =~ m{\A/};
+}
+
+my sub nvmet_quote($word) {
+ return PVE::Tools::shellquote($word);
+}
+
+# Renders steps into one POSIX shell command line: commands joined with `&&`, `>` for configfs
+# writes and one `dd | tee` pipe for a key. No loops, variables or substitutions, every word is
+# quoted and every operand comes from validated configuration.
+sub _nvmet_render($steps) {
+ my $invalid = "internal error: invalid NVMe target step\n";
+ die $invalid if ref($steps) ne 'ARRAY' || !$steps->@*;
+
+ my $keys = 0;
+ my @commands;
+ for my $step ($steps->@*) {
+ if (ref($step) eq 'ARRAY') {
+ die $invalid if !$step->@* || grep { !nvmet_valid_word($_) } $step->@*;
+ die $invalid if !$nvmet_commands{ $step->[0] };
+ push @commands, join(' ', map { nvmet_quote($_) } $step->@*);
+ } elsif (ref($step) eq 'HASH' && exists($step->{write})) {
+ die $invalid
+ if keys($step->%*) != 2
+ || !nvmet_valid_path($step->{write})
+ || !nvmet_valid_word($step->{value});
+ push @commands,
+ q{printf '%s\n' }
+ . nvmet_quote($step->{value}) . ' > '
+ . nvmet_quote($step->{write});
+ } elsif (ref($step) eq 'HASH' && exists($step->{key})) {
+ my $paths = $step->{key};
+ die $invalid
+ if keys($step->%*) != 1
+ || ref($paths) ne 'ARRAY'
+ || !$paths->@*
+ || grep { !nvmet_valid_path($_) } $paths->@*;
+ $keys++;
+ die $invalid if $keys > 1;
+ # configfs needs the whole key in one write(2). dd collects its
+ # input into one output block: GNU dd without bs=, busybox dd only
+ # when ibs and obs differ. tee writes it to every host object.
+ push @commands,
+ 'dd ibs=4096 obs=8192 2>/dev/null | tee '
+ . join(' ', map { nvmet_quote($_) } $paths->@*)
+ . ' >/dev/null';
+ } else {
+ die $invalid;
+ }
+ }
+ return join(' && ', @commands);
+}
+
+# Packs whole units into calls of at most $max bytes of rendered command, the
+# single argument sshd runs, below its limit. A rendered command is ASCII
+# (every operand is validated), so its length is its size in bytes.
+sub _nvmet_chunk($units, $max = $nvmet_max_command) {
+ my (@chunks, @current);
+ for my $unit ($units->@*) {
+ my @next = (@current, $unit->@*);
+ if (length(_nvmet_render(\@next)) > $max) {
+ die "internal error: NVMe target command too long\n"
+ if !@current || length(_nvmet_render($unit)) > $max;
+ push @chunks, [@current];
+ @next = $unit->@*;
+ }
+ @current = @next;
+ }
+ push @chunks, [@current] if @current;
+ return \@chunks;
+}
+
+# Never propagate the context that run_command adds to the task marker, it quotes the command line.
+my sub rethrow_task_interrupt($error) {
+ die "received interrupt\n" if $error =~ $RE_TASK_INTERRUPT;
+}
+
+# The only code that runs anything on the target. Returns a hash with rc (-1 when ssh did not run
+# to its end), out (the lines) and err (the text). It never dies on a failing command, but a
+# stopped task dies with the task marker. %opts are op (label, required), timeout and input
+# (stdin, for keys).
+sub _nvmet_run($scfg, $steps, %opts) {
+ die "internal error: NVMe target call without label\n" if !defined($opts{op});
+ my $command = _nvmet_render($steps);
+ die "internal error: NVMe target command too long\n" if length($command) > $nvmet_max_command;
+ # Not build_ssh_command: it quotes every remote word, and $command is one finished script. The
+ # extra quoting layer would grow it beyond what _nvmet_chunk measures against its size budget.
+ my $cmd =
+ [@ssh_cmd, '-i', nvmet_ssh_key($scfg), '--', 'root@' . nvmet_server($scfg), $command];
+ my (@out, $err);
+ my $rc = 0;
+ # Not noerr, as run_command would then swallow the interrupt of a stopped task too.
+ eval {
+ run_command(
+ $cmd,
+ timeout => $opts{timeout} // 15,
+ outfunc => sub($line) { push @out, $line },
+ errfunc => sub($line) { $err = $line if !defined($err) && $line ne '' },
+ (defined($opts{input}) ? (input => $opts{input}) : ()),
+ );
+ };
+ if (my $error = $@) {
+ rethrow_task_interrupt($error);
+ return { rc => -1, out => [], err => 'timeout' } if $error =~ $RE_COMMAND_TIMEOUT;
+ return { rc => -1, out => [], err => 'ssh failed' } if $error !~ $RE_COMMAND_EXIT;
+ $rc = $+{code};
+ }
+ return { rc => $rc, out => \@out, err => $err // ($rc ? "exit code $rc" : '') };
+}
+
+# _now, _sleep and the other local I/O subs are package subs so that tests can mock them
+sub _now() {
+ return Time::HiRes::clock_gettime(Time::HiRes::CLOCK_MONOTONIC());
+}
+
+sub _sleep($seconds) {
+ Time::HiRes::sleep($seconds);
+ return;
+}
+
+sub _nvmet_split_state($text) {
+ my @parts = split /^\Q$nvmet_marker\E\n/m, $text, -1;
+ die "malformed NVMe target state\n" if @parts != 2;
+ return @parts;
+}
+
+sub _nvmet_property_value($value, $source) {
+ die "malformed ZFS property value\n"
+ if !defined($value)
+ || !defined($source)
+ || $value eq ''
+ || $source eq ''
+ || $value =~ /[\r\n\t]/
+ || $source =~ /[\r\n\t]/;
+ return $value if $source eq 'local' || $source eq 'received';
+ return '-' if $value eq '-' && $source eq '-';
+ if ($source =~ $RE_NVMET_INHERITED) {
+ die "invalid ZFS pool name\n" if $+{source} !~ $RE_NVMET_POOL;
+ return '-';
+ }
+ die "invalid ZFS property source\n";
+}
+
+# The inventory must be complete or the read fails. Children with names PVE never uses (for example
+# with a space) stay datasets but never count as owned.
+sub _nvmet_parse_zfs_inventory($text, $pool) {
+ die "invalid ZFS pool name\n" if $pool !~ $RE_NVMET_POOL;
+
+ my (%rows, %foreign);
+ for my $line (split /\n/, $text) {
+ my @fields = split /\t/, $line, -1;
+ die "malformed ZFS inventory row\n" if @fields != 4 || $line =~ /\r/;
+ my ($dataset, $property, $value, $source) = @fields;
+ if ($dataset ne $pool) {
+ die "ZFS dataset is outside configured pool\n" if index($dataset, "$pool/") != 0;
+ my $child = substr($dataset, length($pool) + 1);
+ die "ZFS dataset is outside configured pool\n"
+ if $child eq '' || index($child, '/') >= 0;
+ $foreign{$dataset} = 1 if $child !~ $RE_NVMET_DATASET_NAME;
+ }
+ my $on = $foreign{$dataset} ? '' : " on '$dataset'";
+ my $key = $nvmet_zfs_keys{$property} // die "unexpected ZFS property$on\n";
+ die "duplicate ZFS property '$property'$on\n" if exists($rows{$dataset}->{$key});
+ if ($key eq 'type') {
+ die "invalid ZFS dataset type$on\n"
+ if ($value ne 'filesystem' && $value ne 'volume') || $source ne '-';
+ $rows{$dataset}->{type} = $value;
+ } else {
+ $rows{$dataset}->{$key} = _nvmet_property_value($value, $source);
+ }
+ }
+ die "ZFS dataset inventory is missing the configured pool\n" if !$rows{$pool};
+
+ my (%types, %volumes);
+ for my $dataset (keys %rows) {
+ my $row = $rows{$dataset};
+ die "incomplete ZFS properties" . ($foreign{$dataset} ? '' : " on '$dataset'") . "\n"
+ if keys($row->%*) != scalar(@nvmet_zfs_props);
+ $types{$dataset} = $row->{type};
+ next if $row->{type} ne 'volume';
+ # nvmet shows device_uuid and udev names the by-id link in lower case
+ $volumes{$dataset} =
+ $foreign{$dataset}
+ ? { nqn => '-', nsid => '-', uuid => '-' }
+ : { nqn => $row->{nqn}, nsid => $row->{nsid}, uuid => lc($row->{uuid}) };
+ }
+ my $last_nsid = $rows{$pool}->{last_nsid};
+ return {
+ types => \%types,
+ volumes => \%volumes,
+ last_nsid => nvmet_nsid($last_nsid) // 0,
+ };
+}
+
+# every object must be complete, unknown objects of newer kernels are ignored
+sub _nvmet_parse_configfs($text) {
+ my $state = { subsystems => {}, ports => {}, hosts => {} };
+ my (%top, %dir);
+
+ my $subsystem = sub($nqn) {
+ return $state->{subsystems}->{$nqn} //= { acl => {}, namespaces => {} };
+ };
+ my $namespace = sub($nqn, $nsid) {
+ return $subsystem->($nqn)->{namespaces}->{$nsid} //= {};
+ };
+ my $port = sub($id) { return $state->{ports}->{$id} //= { links => {} } };
+ my $host = sub($hostnqn) { return $state->{hosts}->{$hostnqn} //= { key_sha256 => undef } };
+ my $set = sub($object, $attr, $value) {
+ die "duplicate NVMe target configfs attribute\n" if exists($object->{$attr});
+ $object->{$attr} = $value;
+ };
+
+ for my $line (split /\n/, $text) {
+ if ($line =~ $RE_CFS_TOP) {
+ $top{ $+{top} // 'root' } = 1;
+ } elsif ($line =~ $RE_CFS_SUBSYS_DIR) {
+ my $nqn = $+{nqn};
+ $subsystem->($nqn);
+ $dir{"subsystem $nqn"} = 1;
+ } elsif ($line =~ $RE_CFS_SUBSYS_GROUP || $line =~ $RE_CFS_PORT_GROUP) {
+ # default groups, always present with their parent
+ } elsif ($line =~ $RE_CFS_NS_DIR) {
+ my ($nqn, $nsid) = @+{qw(nqn nsid)};
+ $namespace->($nqn, $nsid);
+ $dir{"namespace $nqn/$nsid"} = 1;
+ } elsif ($line =~ $RE_CFS_PORT_DIR) {
+ my $id = $+{port};
+ $port->($id);
+ $dir{"port $id"} = 1;
+ } elsif ($line =~ $RE_CFS_HOST_DIR) {
+ my $hostnqn = $+{host};
+ $host->($hostnqn);
+ $dir{"host $hostnqn"} = 1;
+ } elsif ($line =~ $RE_CFS_PORT_LINK) {
+ my ($id, $nqn) = @+{qw(port nqn)};
+ $port->($id)->{links}->{$nqn} = 1;
+ } elsif ($line =~ $RE_CFS_ACL_LINK) {
+ my ($nqn, $hostnqn) = @+{qw(nqn host)};
+ $subsystem->($nqn)->{acl}->{$hostnqn} = 1;
+ } elsif ($line =~ $RE_CFS_OTHER_ENTRY) {
+ # objects of a shape the plugin does not use
+ } elsif ($line =~ $RE_CFS_NS_ATTR) {
+ my ($nqn, $nsid, $attr, $value) = @+{qw(nqn nsid attr value)};
+ $set->($namespace->($nqn, $nsid), $attr, $value);
+ } elsif ($line =~ $RE_CFS_SUBSYS_ATTR) {
+ my ($nqn, $attr, $value) = @+{qw(nqn attr value)};
+ $set->($subsystem->($nqn), $attr, $value);
+ } elsif ($line =~ $RE_CFS_PORT_ATTR) {
+ my ($id, $attr, $value) = @+{qw(port attr value)};
+ $set->($port->($id), $attr, $value);
+ } elsif ($line =~ $RE_CFS_KEY_DIGEST) {
+ my ($sha, $hostnqn) = @+{qw(sha host)};
+ my $object = $host->($hostnqn);
+ die "duplicate DH-HMAC-CHAP key digest" . nvmet_label($hostnqn) . "\n"
+ if defined($object->{key_sha256});
+ $object->{key_sha256} = $sha;
+ } elsif ($line =~ $RE_CFS_OTHER_ATTR) {
+ # attribute of an object shape the plugin does not use
+ } else {
+ die "unexpected NVMe target configfs line\n";
+ }
+ }
+
+ for my $name (qw(root hosts ports subsystems)) {
+ die "NVMe target configfs is unavailable\n" if !$top{$name};
+ }
+ for my $nqn (keys $state->{subsystems}->%*) {
+ my $subsys = $state->{subsystems}->{$nqn};
+ die "incomplete NVMe subsystem" . nvmet_label($nqn) . "\n"
+ if !$dir{"subsystem $nqn"}
+ || grep { !defined($subsys->{$_}) } qw(attr_model attr_serial attr_allow_any_host);
+ for my $nsid (keys $subsys->{namespaces}->%*) {
+ my $ns = $subsys->{namespaces}->{$nsid};
+ die "incomplete NVMe namespace '$nsid' of subsystem" . nvmet_label($nqn) . "\n"
+ if !$dir{"namespace $nqn/$nsid"}
+ || grep { !defined($ns->{$_}) } qw(enable device_path device_uuid buffered_io);
+ }
+ }
+ for my $id (keys $state->{ports}->%*) {
+ my $object = $state->{ports}->{$id};
+ my @attrs = qw(addr_trtype addr_adrfam addr_traddr addr_trsvcid);
+ die "incomplete NVMe port '$id'\n"
+ if !$dir{"port $id"} || grep { !defined($object->{$_}) } @attrs;
+ }
+ for my $hostnqn (keys $state->{hosts}->%*) {
+ die "DH-HMAC-CHAP key digest for unknown NVMe host" . nvmet_label($hostnqn) . "\n"
+ if !$dir{"host $hostnqn"};
+ }
+ return $state;
+}
+
+sub _nvmet_parse_mounts($text) {
+ for my $line (split /\n/, $text) {
+ my (undef, $mountpoint, $type) = split / /, $line;
+ return 1 if ($mountpoint // '') eq '/sys/kernel/config' && ($type // '') eq 'configfs';
+ }
+ return 0;
+}
+
+sub _nvmet_serial($nqn) {
+ return 'PVEZFS' . substr(sha256_hex($nqn), 0, 14);
+}
+
+sub _nvmet_template_name($dataset) {
+ die "only VM zvols can become templates\n"
+ if $dataset !~ $RE_NVMET_TEMPLATE_ZVOL || $+{type} ne 'vm';
+ return nvmet_template_twin($dataset);
+}
+
+# refuses a volume whose identity another owned volume duplicates anywhere in the pool
+sub _nvmet_owned_identity($inv, $nqn, $dataset) {
+ my $type = $inv->{types}->{$dataset} // die "ZFS volume '$dataset' does not exist\n";
+ die "'$dataset' is not a ZFS volume\n" if $type ne 'volume';
+ my $row = $inv->{volumes}->{$dataset};
+ die "ZFS volume '$dataset' is not owned by NVMe subsystem '$nqn'\n" if $row->{nqn} ne $nqn;
+ my $nsid = nvmet_nsid($row->{nsid}) // die "invalid NSID on '$dataset'\n";
+ my $uuid = nvmet_uuid($row->{uuid}) // die "invalid namespace UUID on '$dataset'\n";
+ for my $other (keys $inv->{volumes}->%*) {
+ next if $other eq $dataset;
+ my $identity = $inv->{volumes}->{$other};
+ next if $identity->{nqn} ne $nqn;
+ die "duplicate NVMe identity on '$dataset'\n"
+ if $identity->{nsid} eq $nsid || $identity->{uuid} eq $uuid;
+ }
+ return ($nsid, $uuid);
+}
+
+# validates every owned volume first, so a bad identity refuses the whole plan before any change
+sub _nvmet_desired_namespaces($inv, $nqn) {
+ my (%desired, %uuids);
+ for my $dataset (sort keys $inv->{volumes}->%*) {
+ my $row = $inv->{volumes}->{$dataset};
+ next if $row->{nqn} ne $nqn;
+ my $nsid = nvmet_nsid($row->{nsid}) // die "invalid NSID on '$dataset'\n";
+ my $uuid = nvmet_uuid($row->{uuid}) // die "invalid namespace UUID on '$dataset'\n";
+ die "duplicate NSID '$nsid'\n" if $desired{$nsid};
+ die "duplicate namespace UUID '$uuid'\n" if $uuids{ lc($uuid) }++;
+ $desired{$nsid} = [$uuid, "/dev/zvol/$dataset"];
+ }
+ return \%desired;
+}
+
+# NSIDs grow past the last one handed out in the pool, so a host that missed a namespace removal
+# never sees a new volume at an old NSID. Only when they run out is the lowest free one used.
+sub _nvmet_allocate_nsid($inv, $cfs, $nqn) {
+ my %used;
+ for my $row (values $inv->{volumes}->%*) {
+ $used{ $row->{nsid} } = 1 if $row->{nqn} eq $nqn && defined(nvmet_nsid($row->{nsid}));
+ }
+ $used{$_} = 1 for keys nvmet_namespaces($cfs, $nqn)->%*;
+
+ my $highest = max(0, $inv->{last_nsid} // 0, keys %used);
+ return $highest + 1 if $highest < $nvmet_max_nsid;
+ my $nsid = 1;
+ $nsid++ while $used{$nsid};
+ die "no free namespace ID\n" if $nsid > $nvmet_max_nsid;
+ return $nsid;
+}
+
+# The state is present, disabled, absent, incomplete (a disabled namespace with another identity,
+# for example one being built), stale (enabled on the other template name of the zvol) or nosubsys.
+sub _nvmet_export_state($cfs, $nqn, $nsid, $uuid, $dev) {
+ return 'nosubsys' if !$cfs->{subsystems}->{$nqn};
+ my $namespaces = nvmet_namespaces($cfs, $nqn);
+ for my $id (keys $namespaces->%*) {
+ next if $id eq $nsid;
+ die "namespace UUID '$uuid' is already in use\n"
+ if $namespaces->{$id}->{device_uuid} eq $uuid;
+ }
+ my $ns = $namespaces->{$nsid} // return 'absent';
+ if ($ns->{device_uuid} eq $uuid && $ns->{device_path} eq $dev) {
+ return $ns->{enable} eq '1' ? 'present' : 'disabled';
+ }
+ # A template conversion or its undo that ssh gave up on can rename the zvol on the target after
+ # an activation exported it under its old name.
+ my $twin = nvmet_template_twin($dev);
+ return 'stale'
+ if $ns->{enable} eq '1'
+ && $ns->{device_uuid} eq $uuid
+ && $twin ne ''
+ && $ns->{device_path} eq $twin;
+ die "NVMe namespace ID '$nsid' has a different identity; refusing to replace it\n"
+ if $ns->{enable} ne '0';
+ return 'incomplete';
+}
+
+# A disabled namespace with another identity, or a stale one (of a template or a failed conversion,
+# so no guest uses it), is rebuilt, which is only correct under the target lock.
+sub _nvmet_plan_export($cfs, $nqn, $nsid, $uuid, $dev) {
+ die "NVMe subsystem does not exist\n" if !$cfs->{subsystems}->{$nqn};
+ my $state = _nvmet_export_state($cfs, $nqn, $nsid, $uuid, $dev);
+ return ([nvmet_build_unit($nqn, $nsid, $uuid, $dev)], 'absent') if $state eq 'absent';
+ return ([], 'present') if $state eq 'present';
+ return ([nvmet_enable_unit($nqn, $nsid, $dev)], 'disabled') if $state eq 'disabled';
+ my $unexport = nvmet_unexport_unit($nqn, $nsid, $state eq 'stale');
+ my $build = nvmet_build_unit($nqn, $nsid, $uuid, $dev);
+ return ([[$unexport->@*, $build->@*]], $state eq 'stale' ? 'stale' : 'reclaim');
+}
+
+sub _nvmet_plan_unexport($cfs, $nqn, $uuid) {
+ my $namespaces = nvmet_namespaces($cfs, $nqn);
+ my @matches = grep { $namespaces->{$_}->{device_uuid} eq $uuid }
+ sort { $a <=> $b } keys $namespaces->%*;
+ die "duplicate namespace UUID '$uuid'\n" if @matches > 1;
+ return ([], undef) if !@matches;
+ my $enabled = $namespaces->{ $matches[0] }->{enable} eq '1';
+ return (
+ [nvmet_unexport_unit($nqn, $matches[0], $enabled)],
+ { nsid => $matches[0], enabled => $enabled },
+ );
+}
+
+# among matching ports the one linked to $nqn wins, then the lowest id, incomplete ports never match
+sub _nvmet_find_port($cfs, $nqn, $portal) {
+ my $wanted = nvmet_canonical_address($portal->{address});
+ my @matches = grep {
+ my $port = $cfs->{ports}->{$_};
+ $port->{addr_trtype} eq 'tcp'
+ && $port->{addr_adrfam} eq $portal->{family}
+ && $port->{addr_traddr} ne ''
+ && $port->{addr_trsvcid} eq "$portal->{port}"
+ && nvmet_canonical_address($port->{addr_traddr}) eq $wanted
+ } sort {
+ $a <=> $b
+ } keys $cfs->{ports}->%*;
+ my @linked = grep { nvmet_port_linked($cfs, $_, $nqn) } @matches;
+ return $linked[0] // $matches[0];
+}
+
+sub _nvmet_plan_activation($inv, $cfs, $conf) {
+ my ($nqn, $keysha) = $conf->@{qw(nqn keysha)};
+ my $desired = _nvmet_desired_namespaces($inv, $nqn); # refuse before any unit
+ my $subsys_path = nvmet_subsys_path($nqn);
+ my $subsys = $cfs->{subsystems}->{$nqn};
+ my (@objects, @key_hosts, @acls, @namespaces, %port_ids);
+
+ if (!$subsys) {
+ push @objects,
+ [
+ ['mkdir', $subsys_path],
+ nvmet_write("$subsys_path/attr_model", $nvmet_model),
+ nvmet_write("$subsys_path/attr_serial", _nvmet_serial($nqn)),
+ nvmet_write("$subsys_path/attr_allow_any_host", 0),
+ ];
+ } else {
+ my $serial = _nvmet_serial($nqn);
+ my @attrs;
+ if ($subsys->{attr_model} ne $nvmet_model || $subsys->{attr_serial} ne $serial) {
+ die "refusing to take over existing NVMe subsystem '$nqn': it was not created by"
+ . " Proxmox VE; remove it on the target or use another NQN\n"
+ if !nvmet_unfinished_subsystem($cfs, $nqn);
+ push @attrs, nvmet_write("$subsys_path/attr_serial", $serial);
+ }
+ push @attrs, nvmet_write("$subsys_path/attr_allow_any_host", 0)
+ if $subsys->{attr_allow_any_host} ne '0';
+ push @objects, [@attrs] if @attrs;
+ }
+
+ my %taken = map { $_ => 1 } keys $cfs->{ports}->%*;
+ for my $portal ($conf->{portals}->@*) {
+ my $id = _nvmet_find_port($cfs, $nqn, $portal);
+ if (!defined($id)) {
+ $id = 1;
+ $id++ while $taken{$id};
+ $taken{$id} = 1;
+ my $port_path = nvmet_port_path($id);
+ push @objects,
+ [
+ ['mkdir', $port_path],
+ nvmet_write("$port_path/addr_trtype", 'tcp'),
+ nvmet_write("$port_path/addr_adrfam", $portal->{family}),
+ nvmet_write("$port_path/addr_traddr", $portal->{address}),
+ nvmet_write("$port_path/addr_trsvcid", $portal->{port}),
+ ];
+ }
+ $port_ids{$id} = 1;
+ }
+
+ # nvmet keeps the key on the global host object. A key that differs from ours is only replaced
+ # while no subsystem links the host.
+ my $linked = nvmet_linked_hosts($cfs);
+ for my $hostnqn ($conf->{hostnqns}->@*) {
+ my $host_path = nvmet_host_path($hostnqn);
+ if (my $host = $cfs->{hosts}->{$hostnqn}) {
+ my $sha = $host->{key_sha256}
+ // die "NVMe target does not expose a DH-HMAC-CHAP key for host '$hostnqn'\n";
+ if ($sha ne $keysha) {
+ # a subsystem left behind by a removed storage or a failed add still links the host
+ if (defined(my $holder = $linked->{$hostnqn})) {
+ my $label = nvmet_label($holder);
+ die "refusing to replace an in-use DH-HMAC-CHAP key for '$hostnqn': "
+ . ($label ne '' ? "subsystem$label" : 'another subsystem')
+ . " still allows this host. Remove it on the target first\n";
+ }
+ push @key_hosts, $host_path;
+ }
+ } else {
+ push @objects, [['mkdir', $host_path]];
+ push @key_hosts, $host_path;
+ }
+ push @acls, [['ln', '-s', $host_path, "$subsys_path/allowed_hosts/$hostnqn"]]
+ if !$subsys || !($subsys->{acl} // {})->{$hostnqn};
+ }
+ # nvmet creates the key attributes world-readable. The chmod before the write keeps later opens
+ # from reading the key, but a descriptor opened earlier is not affected.
+ my @keys;
+ if (@key_hosts) {
+ my @attrs = map { ("$_/dhchap_key", "$_/dhchap_ctrl_key") } @key_hosts;
+ @keys = ([['chmod', '0600', @attrs], { key => [map { "$_/dhchap_key" } @key_hosts] }]);
+ }
+
+ my $current = { subsystems => { $nqn => $subsys // { acl => {}, namespaces => {} } } };
+ for my $nsid (sort { $a <=> $b } keys $desired->%*) {
+ my ($units) = _nvmet_plan_export($current, $nqn, $nsid, $desired->{$nsid}->@*);
+ push @namespaces, $units->@*;
+ }
+ my $existing = nvmet_namespaces($cfs, $nqn);
+ for my $nsid (sort { $a <=> $b } keys $existing->%*) {
+ next if $desired->{$nsid};
+ push @namespaces, nvmet_unexport_unit($nqn, $nsid, $existing->{$nsid}->{enable} eq '1');
+ }
+
+ return {
+ prepublish => [@objects, @keys, @acls, @namespaces],
+ port_ids => [sort { $a <=> $b } keys %port_ids],
+ };
+}
+
+# One call per port: each link repeats the guards, so it only succeeds while the subsystem denies
+# unknown hosts and every configured host has its ACL, which only a manager of the target outside
+# this cluster can change after the verify read.
+sub _nvmet_plan_publish($cfs, $nqn, $port_ids, $hostnqns) {
+ my $subsys_path = nvmet_subsys_path($nqn);
+ my %wanted = map { $_ => 1 } $port_ids->@*;
+ my @guards = (
+ ['grep', '-qx', '0', "$subsys_path/attr_allow_any_host"],
+ map { ['test', '-L', "$subsys_path/allowed_hosts/$_"] } $hostnqns->@*,
+ );
+
+ my @units;
+ for my $id ($port_ids->@*) {
+ next if nvmet_port_linked($cfs, $id, $nqn);
+ my $link = ['ln', '-s', $subsys_path, nvmet_port_path($id) . "/subsystems/$nqn"];
+ push @units, { port => $id, action => 'link', steps => [@guards, $link] };
+ }
+ for my $id (sort { $a <=> $b } keys $cfs->{ports}->%*) {
+ next if $wanted{$id} || !nvmet_port_linked($cfs, $id, $nqn);
+ my $unlink = ['rm', nvmet_port_path($id) . "/subsystems/$nqn"];
+ push @units, { port => $id, action => 'unlink', steps => [$unlink] };
+ }
+ return \@units;
+}
+
+1;
--
2.54.0.windows.1
^ permalink raw reply related [relevance 11%]
* [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin
@ 2026-11-26 15:09 13% Joaquin Varela
2026-11-26 15:09 11% ` [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning Joaquin Varela
` (8 more replies)
0 siblings, 9 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:09 UTC (permalink / raw)
To: pve-devel
Hi,
this is v5 of the zfsnvme backend, rebased on current master for Proxmox VE
9.3. v4 was never sent, so the changes below are against v3.
The new nvmeof storage connects to namespaces that an array already serves.
zfsnvme creates and manages the zvols on a Linux ZFS host and exports them
with the kernel nvmet target, with DH-HMAC-CHAP, snapshots and clones. So the
two complement each other. zfsnvme now uses the nvmeof helpers where they fit:
the host lock, host_identity and parse_portal. It keeps its own connect, which
writes /dev/nvme-fabrics, so the DH-HMAC-CHAP secret never shows up in argv.
Changes since v3:
- storage API 17: isolated properties, a sensitive dhchap-key, titles,
advanced and hidden properties, vm-vol and vm-state content
- volume names use the same character set as ZFS over iSCSI
- the delete hook only removes the key file, so it does no remote work
while the storage.cfg lock is held. The subsystem stays on the target
until the admin removes it, as the docs describe.
- the plugin is taint safe for pvedaemon and pveproxy, with a perl -T test
- the plugin loads nvme-tcp on the nodes
- deactivation checks the users of a namespace with the Diskmanage helpers
and only deletes controllers it still owns, checked under the host lock
- the old 3/4, the fencing of abandoned target commands, is dropped. It was
the only shell control flow on the target.
- patch 5 lets the SAN view, the wipe check and the controller list count a
zfsnvme storage as the owner of its subsystem. The cluster multipath
status still lists only nvmeof namespaces.
- patch 6 checks the cluster version before the first zfsnvme storage, like
for nvmeof. The version there, 9.3.2, is a guess. Please adapt it to the
first pve-manager that will depend on this.
- smaller patches, so none hits the size limit of the list, and fewer
comments
Patch 5 would also fit the hook that Dirk Nehring proposed for SAN LUNs of
other plugins [0]. zfsnvme could then answer that hook instead of the type
check.
Every patch builds and passes make test on a PVE 9.3 node. On a lab cluster
with two PVE 9.3 nodes, a Linux nvmet target and two paths, the series passed
adding the storage over the API (also a failed add and its retry), volume
allocation, live migration both ways, snapshot and rollback (also with RAM
state), template and linked clone, resize, a target reboot and the loss of one
path with a running guest, and an nvmeof storage on the same target. The SAN
guards held as well: a node where the guest does not run refused to wipe its
namespace and to disconnect its last path.
The docs and manager patches follow in this thread.
v3: https://lore.proxmox.com/pve-devel/20261005002609.571-1-joaquinvarela@neatech.ar/
[0]: https://lore.proxmox.com/pve-devel/20261124200340.380381-1-dnehring@marcant.net/
Joaquin Varela (13):
zfsnvme: add target state parsing and planning
zfsnvme: add the target transactions
zfsnvme: add storage configuration and volume methods
zfsnvme: connect the nodes and register the plugin
api: san luns: count zfsnvme storages as owners of their subsystem
api: config: check the cluster version before the first zfsnvme
storage
test: zfsnvme: add configuration and volume tests
test: zfsnvme: add node side tests
test: zfsnvme: add an in-memory nvmet target
test: zfsnvme: test the target parsers and planners
test: zfsnvme: test the target flows
test: zfsnvme: add a fault sweep, renderer and taint tests
zfsnvme: wait up to 30 seconds for the shared storage lock
src/PVE/API2/NVMeOF.pm | 7 +-
src/PVE/API2/SAN/Cluster.pm | 6 +-
src/PVE/API2/SAN/Node.pm | 5 +-
src/PVE/API2/Storage/Config.pm | 13 +-
src/PVE/CLI/pvesm.pm | 21 +-
src/PVE/NVMeOF.pm | 6 +
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/NVMeOFPlugin.pm | 4 +-
src/PVE/Storage/Plugin.pm | 12 +-
src/PVE/Storage/SAN.pm | 16 +-
src/PVE/Storage/ZFSNVMePlugin.pm | 2947 +++++++++++
src/test/Makefile | 4 +
src/test/run_nvmeof_api_tests.pl | 16 +-
src/test/run_nvmeof_tests.pl | 47 +
src/test/run_plugin_tests.pl | 2 +
src/test/run_san_lun_scan_tests.pl | 11 +
src/test/run_san_nvme_tests.pl | 4 +
src/test/run_zfsnvme_taint_tests.pl | 988 ++++
.../zfsnvme_fixtures/configfs_snapshot.txt | 38 +
src/test/zfsnvme_fixtures/zfs_inventory.txt | 15 +
src/test/zfsnvme_target_test.pm | 4514 +++++++++++++++++
src/test/zfsnvme_test.pm | 2881 +++++++++++
23 files changed, 11535 insertions(+), 25 deletions(-)
create mode 100644 src/PVE/Storage/ZFSNVMePlugin.pm
create mode 100755 src/test/run_zfsnvme_taint_tests.pl
create mode 100644 src/test/zfsnvme_fixtures/configfs_snapshot.txt
create mode 100644 src/test/zfsnvme_fixtures/zfs_inventory.txt
create mode 100644 src/test/zfsnvme_target_test.pm
create mode 100644 src/test/zfsnvme_test.pm
base-commit: 3ac027fd9fcd8fdfe6bb3acb1e4b58e8cd1cfde8
--
2.54.0.windows.1
^ permalink raw reply [relevance 13%]
* [PATCH storage v5 03/13] zfsnvme: add storage configuration and volume methods
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-11-26 15:09 11% ` [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning Joaquin Varela
@ 2026-11-26 15:09 15% ` Joaquin Varela
2026-11-26 15:09 16% ` [PATCH storage v5 04/13] zfsnvme: connect the nodes and register the plugin Joaquin Varela
` (6 subsequent siblings)
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:09 UTC (permalink / raw)
To: pve-devel
Add the storage schema and config checks, the ZFS helpers and the
volume methods of the storage API. Volume names are checked and follow
the other ZFS plugins, raw carries no extension, and portals go through
PVE::NVMeOF::parse_portal as for nvmeof. The plugin isolates its
properties. A new storage cannot take the subsystem NQN of an nvmeof
storage.
Each storage needs its own NVMe/TCP listener, as nvmet answers a
connect to a listener that does not publish the subsystem yet with DNR
and a shared one could lose its paths after a restart. The DH-HMAC-CHAP
key is stored in /etc/pve/priv/storage and reaches the target on stdin.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
src/PVE/Storage/ZFSNVMePlugin.pm | 798 ++++++++++++++++++++++++++++++-
1 file changed, 797 insertions(+), 1 deletion(-)
diff --git a/src/PVE/Storage/ZFSNVMePlugin.pm b/src/PVE/Storage/ZFSNVMePlugin.pm
index 1892bd21..1f95f8c5 100644
--- a/src/PVE/Storage/ZFSNVMePlugin.pm
+++ b/src/PVE/Storage/ZFSNVMePlugin.pm
@@ -17,6 +17,7 @@ use PVE::Cluster;
use PVE::File;
use PVE::JSONSchema;
use PVE::Network;
+use PVE::NVMeOF;
use PVE::RESTEnvironment qw(log_warn);
use PVE::RPCEnvironment;
use PVE::SysFSTools;
@@ -105,7 +106,10 @@ my $RE_TRSVCID = qr{(?: \A | ,) trsvcid=(?<value>[^,]+)}nxx;
my $RE_HOST_IFACE_ADDRESS = qr{(?: \A | ,) host_iface=(?<value>[^,]+)}nxx;
# no ':' like ZFSPlugin, and anchor with \z as $ also accepts a trailing newline
my $RE_ZVOL_SUFFIX = qr{[a-zA-Z0-9_.-]+}nxx;
-my $RE_ZVOL_OWNER = qr{\A (?:vm|base|subvol|basevol)- (?<owner>\d+) - $RE_ZVOL_SUFFIX \z}nxx;
+my $RE_ZVOL_OWNER = qr{
+ \A (?<name> (?:vm|base|subvol|basevol)- (?<owner>\d+) - $RE_ZVOL_SUFFIX) \z
+}nxx;
+my $RE_ZVOL_ORIGIN = qr{\A (?<origin> [A-Za-z0-9] [A-Za-z0-9_.:/-]* \@ [A-Za-z0-9_.:-]+) \z}nxx;
my $RE_VOLNAME = qr{
\A
(?: (?<base> (?:base|basevol)- (?<base_vmid>\d+) - $RE_ZVOL_SUFFIX) /)?
@@ -1567,4 +1571,796 @@ my sub nvmet_resize_volume($scfg, $name, $size) {
return;
}
+sub parse_nvme_portals($value, $noerr = undef) {
+ my $result = [];
+ my $seen = {};
+
+ for my $entry (split(/,/, $value // '')) {
+ $entry = trim($entry);
+ # parse_portal refuses the same addresses as the nvmeof storage and maps an IPv4-mapped
+ # IPv6 address to IPv4. It takes an IPv4 address in brackets, this storage does not.
+ my $portal = PVE::NVMeOF::parse_portal($entry);
+ if (!$portal || $entry =~ m/\A\[[^\]:]*\]/) {
+ return undef if $noerr;
+ die "invalid NVMe/TCP portal '$entry'\n";
+ }
+ my ($address, $port) = $portal->@{qw(traddr trsvcid)};
+ if ($seen->{"$address\0$port"}++) {
+ return undef if $noerr;
+ die "duplicate NVMe/TCP portal '$entry'\n";
+ }
+ push $result->@*,
+ {
+ address => $address,
+ port => $port,
+ family => index($address, ':') < 0 ? 'ipv4' : 'ipv6',
+ };
+ if (scalar($result->@*) > $max_paths) {
+ return undef if $noerr;
+ die "at most $max_paths NVMe/TCP portals are supported\n";
+ }
+ }
+
+ if (!$result->@*) {
+ return undef if $noerr;
+ die "at least one NVMe/TCP portal is required\n";
+ }
+
+ return $result;
+}
+
+my sub verify_nvme_portals($value, $noerr = undef) {
+ return undef if !parse_nvme_portals($value, $noerr);
+ return $value;
+}
+
+sub parse_nvme_host_ifaces($value, $noerr = undef) {
+ my $result = [];
+
+ for my $iface (split(/,/, $value // '')) {
+ $iface = trim($iface);
+ # the kernel never names an interface '.' or '..'
+ if (
+ length($iface) < 1
+ || length($iface) > 15
+ || $iface !~ $RE_HOST_IFACE
+ || $iface eq '.'
+ || $iface eq '..'
+ ) {
+ return undef if $noerr;
+ die "invalid NVMe/TCP host interface '$iface'\n";
+ }
+ push $result->@*, $iface;
+ }
+
+ if (!$result->@*) {
+ return undef if $noerr;
+ die "at least one NVMe/TCP host interface is required\n";
+ }
+
+ return $result;
+}
+
+my sub verify_nvme_host_ifaces($value, $noerr = undef) {
+ return undef if !parse_nvme_host_ifaces($value, $noerr);
+ return $value;
+}
+
+my sub verify_nvme_host_nqns($value, $noerr = undef) {
+ return undef if !parse_nvme_host_nqns($value, $noerr);
+ return $value;
+}
+
+sub _configured_portals($scfg) {
+ my $portals = parse_nvme_portals($scfg->{'nvme-portals'});
+ my $ifaces = parse_nvme_host_ifaces($scfg->{'nvme-host-ifaces'});
+ die "nvme-host-ifaces must contain one interface for each nvme-portals entry\n"
+ if scalar($ifaces->@*) != scalar($portals->@*);
+
+ for (my $i = 0; $i < scalar($portals->@*); $i++) {
+ $portals->[$i]->{host_iface} = $ifaces->[$i];
+ }
+ return $portals;
+}
+
+sub _local_iface_exists($iface) {
+ return -d "/sys/class/net/$iface";
+}
+
+sub _validate_local_ifaces($portals) {
+ for my $portal ($portals->@*) {
+ my $iface = $portal->{host_iface};
+ die "NVMe/TCP host interface '$iface' does not exist on this node\n"
+ if !_local_iface_exists($iface);
+ }
+}
+
+PVE::JSONSchema::register_format('pve-storage-nvme-nqn', \&verify_nvme_nqn);
+PVE::JSONSchema::register_format('pve-storage-nvme-portals', \&verify_nvme_portals);
+PVE::JSONSchema::register_format('pve-storage-nvme-host-ifaces', \&verify_nvme_host_ifaces);
+PVE::JSONSchema::register_format('pve-storage-nvme-host-nqns', \&verify_nvme_host_nqns);
+
+sub type($class) {
+ return 'zfsnvme';
+}
+
+sub plugindata($class) {
+ return {
+ content => [{ images => 1, 'vm-vol' => 1, 'vm-state' => 1 }, { images => 1 }],
+ 'isolate-properties' => 1,
+ 'advanced-properties' => {
+ 'nvme-iopolicy' => 1,
+ 'nvme-keep-alive-tmo' => 1,
+ 'nvme-reconnect-delay' => 1,
+ 'nvme-ctrl-loss-tmo' => 1,
+ 'nvme-fast-io-fail-tmo' => 1,
+ 'nvme-nr-io-queues' => 1,
+ },
+ 'hidden-properties' => {
+ bwlimit => 1,
+ content => 1,
+ },
+ 'sensitive-properties' => { 'dhchap-key' => 1 },
+ };
+}
+
+# The plugin isolates its properties, so it declares the ones it shares with other plugins itself.
+sub properties($class) {
+ return {
+ server => {
+ title => "Server",
+ description => "IP address or hostname of the ZFS target.",
+ type => 'string',
+ format => 'pve-storage-server',
+ },
+ pool => {
+ title => "Pool",
+ description => "ZFS pool on the target.",
+ type => 'string',
+ },
+ blocksize => {
+ title => "Block Size",
+ description => "ZFS block size.",
+ type => 'string',
+ format => 'pve-storage-zfs-blocksize',
+ format_description => 'a power of 2 with optional k or m suffix',
+ },
+ sparse => {
+ title => "Thin Provision",
+ description => "Use sparse (thin-provisioned) volumes.",
+ type => 'boolean',
+ },
+ subsysnqn => {
+ title => "Subsystem NQN",
+ description => "NVMe subsystem qualified name.",
+ type => 'string',
+ format => 'pve-storage-nvme-nqn',
+ },
+ 'nvme-portals' => {
+ title => "Portals",
+ description =>
+ "Comma-separated NVMe/TCP target IP addresses, at most 16. Put IPv6 addresses in"
+ . " brackets. The default TCP port is 4420.",
+ type => 'string',
+ format => 'pve-storage-nvme-portals',
+ maxLength => 2048,
+ },
+ 'nvme-host-ifaces' => {
+ title => "Host Interfaces",
+ description =>
+ "Comma-separated local interfaces, in portal order. Interface names must be"
+ . " identical on every cluster node.",
+ type => 'string',
+ format => 'pve-storage-nvme-host-ifaces',
+ maxLength => 512,
+ },
+ 'nvme-host-nqns' => {
+ title => "Host NQNs",
+ description =>
+ "Comma-separated /etc/nvme/hostnqn values for every cluster node allowed to use"
+ . " this storage, at most 64. Host NQNs can only be added.",
+ type => 'string',
+ format => 'pve-storage-nvme-host-nqns',
+ maxLength => 8192,
+ },
+ 'dhchap-key' => {
+ title => "DH-HMAC-CHAP Key",
+ description =>
+ "NVMe DH-HMAC-CHAP key in secret representation format (DHHC-1). Required when the"
+ . " storage is created. It cannot be changed.",
+ type => 'string',
+ maxLength => 256,
+ sensitive => 1,
+ },
+ 'nvme-iopolicy' => {
+ title => "I/O Policy",
+ description => "Native NVMe multipath I/O policy.",
+ type => 'string',
+ enum => ['numa', 'round-robin', 'queue-depth'],
+ default => 'round-robin',
+ },
+ 'nvme-keep-alive-tmo' => {
+ title => "Keep-Alive Timeout (s)",
+ description => "NVMe keep-alive timeout in seconds.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 120,
+ default => 5,
+ },
+ 'nvme-reconnect-delay' => {
+ title => "Reconnect Delay (s)",
+ description => "Delay between NVMe reconnect attempts in seconds.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 120,
+ default => 2,
+ },
+ 'nvme-ctrl-loss-tmo' => {
+ title => "Controller Loss Timeout (s)",
+ description => "Time to keep retrying a lost NVMe controller in seconds.",
+ type => 'integer',
+ minimum => -1,
+ maximum => 86400,
+ default => 600,
+ },
+ 'nvme-fast-io-fail-tmo' => {
+ title => "Fast I/O Fail Timeout (s)",
+ description =>
+ "Optional time before failing I/O on a reconnecting NVMe controller. Unset queues"
+ . " I/O until controller loss timeout.",
+ type => 'integer',
+ minimum => 0,
+ maximum => 86400,
+ optional => 1,
+ },
+ 'nvme-nr-io-queues' => {
+ title => "I/O Queues",
+ description => "Number of NVMe/TCP I/O queues per controller.",
+ type => 'integer',
+ minimum => 1,
+ maximum => 1024,
+ optional => 1,
+ },
+ };
+}
+
+sub options($class) {
+ return {
+ server => { fixed => 1 },
+ subsysnqn => { fixed => 1 },
+ 'nvme-portals' => { fixed => 1 },
+ 'nvme-host-ifaces' => {},
+ 'nvme-host-nqns' => {},
+ pool => { fixed => 1 },
+ blocksize => { fixed => 1 },
+ sparse => { optional => 1 },
+ 'dhchap-key' => { optional => 1 },
+ 'nvme-iopolicy' => { optional => 1 },
+ 'nvme-keep-alive-tmo' => { optional => 1 },
+ 'nvme-reconnect-delay' => { optional => 1 },
+ 'nvme-ctrl-loss-tmo' => { optional => 1 },
+ 'nvme-fast-io-fail-tmo' => { optional => 1 },
+ 'nvme-nr-io-queues' => { optional => 1 },
+ nodes => { optional => 1 },
+ disable => { optional => 1 },
+ content => { optional => 1 },
+ bwlimit => { optional => 1 },
+ };
+}
+
+sub _validate_fail_fast_timeout($config, $default_ctrl_loss_tmo = undef) {
+ my $fast = $config->{'nvme-fast-io-fail-tmo'};
+ return if !defined($fast);
+
+ my $ctrl = $config->{'nvme-ctrl-loss-tmo'};
+ $ctrl = $default_ctrl_loss_tmo if !defined($ctrl);
+ return if !defined($ctrl) || $ctrl < 0;
+
+ die "nvme-fast-io-fail-tmo must not exceed nvme-ctrl-loss-tmo\n"
+ if $fast > $ctrl;
+}
+
+# no defaults are injected here, as this also runs when storage.cfg is parsed
+sub check_config($class, $section_id, $config, $create, $skip_schema_check = undef) {
+ nvmet_pool($config) if defined($config->{pool});
+ verify_nvme_nqn($config->{subsysnqn}) if defined($config->{subsysnqn});
+ parse_nvme_portals($config->{'nvme-portals'}) if defined($config->{'nvme-portals'});
+ if (defined($config->{'nvme-host-ifaces'}) && defined($config->{'nvme-portals'})) {
+ _configured_portals($config);
+ } elsif (defined($config->{'nvme-host-ifaces'})) {
+ parse_nvme_host_ifaces($config->{'nvme-host-ifaces'});
+ }
+ parse_nvme_host_nqns($config->{'nvme-host-nqns'})
+ if defined($config->{'nvme-host-nqns'});
+ _validate_fail_fast_timeout($config, $create ? 600 : undef);
+ return $class->SUPER::check_config($section_id, $config, $create, $skip_schema_check);
+}
+
+my sub zfs_request($scfg, $timeout, $method, @args) {
+ $timeout = PVE::RPCEnvironment->is_worker() ? 60 * 60 : 10 if !$timeout;
+ my $change = $method ne 'get' && $method ne 'list';
+ my $res = nvmet_exec(
+ $scfg, [['zfs', $method, @args]],
+ op => "zfs $method",
+ timeout => $timeout,
+ change => $change,
+ );
+ die "zfs error on '" . nvmet_server($scfg) . "': $res->{err}\n" if $res->{rc};
+ return nvmet_output($res);
+}
+
+# the plugin creates and owns zvols only, a filesystem child still holds its name
+my sub zfs_parse_zvol_list($text, $pool) {
+ my $list = [];
+ for my $line (split /\n/, $text // '') {
+ my ($dataset, $size, $origin, $type) = split(/\s+/, $line);
+ next if !defined($type) || ($type ne 'volume' && $type ne 'filesystem');
+ my @parts = split /\//, $dataset;
+ next if @parts < 2;
+ my $name = pop @parts;
+ next if join('/', @parts) ne $pool;
+ next if $name !~ $RE_ZVOL_OWNER;
+ my ($zvol, $owner) = @+{qw(name owner)};
+ my $volume = $type eq 'volume';
+ # A size or an origin of another form stays as the target sent it. The sum has a statement
+ # of its own, as a statement that reads a tainted value taints the sums in it.
+ $size = (nvmet_uint($size) // $size) + 0 if $volume;
+ $origin = $+{origin} if $origin =~ $RE_ZVOL_ORIGIN;
+ push $list->@*,
+ {
+ name => $zvol,
+ owner => $owner,
+ type => $type,
+ ($volume ? (size => $size) : ()),
+ ($origin ne '-' ? (origin => $origin) : ()),
+ };
+ }
+ return $list;
+}
+
+my sub zfs_list_zvol($scfg, $owned_only) {
+ my $pool = nvmet_pool($scfg);
+ my $text = zfs_request(
+ $scfg,
+ 10,
+ 'list',
+ '-o',
+ 'name,volsize,origin,type',
+ '-t',
+ 'volume,filesystem',
+ '-d1',
+ '-Hp',
+ $pool,
+ );
+ my $list = {};
+ my $prefix = "$pool/";
+ for my $zvol (zfs_parse_zvol_list($text, $pool)->@*) {
+ next if $owned_only && $zvol->{type} ne 'volume';
+ my $parent = $zvol->{origin};
+ $parent = substr($parent, length($prefix)) if $parent && index($parent, $prefix) == 0;
+ $list->{ $zvol->{name} } = {
+ name => $zvol->{name},
+ size => $zvol->{size},
+ parent => $parent,
+ format => 'raw',
+ vmid => $zvol->{owner},
+ };
+ }
+ return $list if !$owned_only;
+
+ my $properties = zfs_request(
+ $scfg,
+ 10,
+ 'get',
+ '-H',
+ '-d',
+ '1',
+ '-o',
+ 'name,value,source',
+ 'proxmox:nvme-subsys',
+ $pool,
+ );
+ my $owned = {};
+ for my $line (split(/\n/, $properties)) {
+ my ($dataset, $nqn, $source) = split(/\t/, $line, 3);
+ next if !defined($source) || ($source ne 'local' && $source ne 'received');
+ next if !defined($nqn) || $nqn ne $scfg->{subsysnqn};
+ next if index($dataset, $prefix) != 0;
+ $owned->{ substr($dataset, length($prefix)) } = 1;
+ }
+ for my $name (keys $list->%*) {
+ delete $list->{$name} if !$owned->{$name};
+ }
+ return $list;
+}
+
+my sub zfs_get_properties($scfg, $properties, $dataset, $timeout = undef) {
+ my $text = zfs_request($scfg, $timeout, 'get', '-o', 'value', '-Hp', $properties, $dataset);
+ my @values = split /\n/, $text;
+ return wantarray ? @values : $values[0];
+}
+
+my sub zfs_get_sorted_snapshot_list($scfg, $name, $sort_params) {
+ # a name of another form stays as the target sent it
+ return [
+ map {
+ my $snap = s/^.*\@//r;
+ $snap =~ $RE_NVMET_SNAPSHOT ? $+{snap} : $snap
+ } split /\n/,
+ zfs_request(
+ $scfg,
+ undef,
+ 'list',
+ '-H',
+ '-r',
+ '-t',
+ 'snapshot',
+ '-o',
+ 'name',
+ $sort_params->@*,
+ nvmet_dataset($scfg, $name),
+ ),
+ ];
+}
+
+sub parse_volname($class, $volname) {
+ if ($volname =~ $RE_VOLNAME) {
+ my $format = ($+{type} eq 'subvol' || $+{type} eq 'basevol') ? 'subvol' : 'raw';
+ my $is_base = $+{type} eq 'base' || $+{type} eq 'basevol';
+ my $vtype = $class->guest_volume_vtype($format, $+{name});
+ return ($vtype, $+{name}, $+{vmid}, $+{base}, $+{base_vmid}, $is_base, $format);
+ }
+ die "unable to parse zfs volume name '$volname'\n";
+}
+
+use constant FORMAT_EXTENSION => { raw => '' };
+
+sub get_parsed_format($class, $name) {
+ return ($class->parse_volname($name))[6];
+}
+
+sub list_images($class, $storeid, $scfg, $vmid = undef, $vollist = undef, $cache = undef) {
+ my $res = [];
+ for my $info (values zfs_list_zvol($scfg, 1)->%*) {
+ my $volname =
+ $info->{parent} && $info->{parent} =~ $RE_BASE_SNAPSHOT
+ ? "$storeid:$+{base}/$info->{name}"
+ : "$storeid:$info->{name}";
+ next
+ if $vollist
+ ? !grep { $_ eq $volname } $vollist->@*
+ : defined($vmid) && $info->{vmid} ne $vmid;
+ $info->{volid} = $volname;
+ push $res->@*, $info;
+ }
+ return $res;
+}
+
+# names are allocated against every direct child of the pool, also leftovers that list_images hides
+sub find_free_diskname($class, $storeid, $scfg, $vmid, $fmt = undef, $add_fmt_suffix = undef) {
+ my $disk_list = [map { "$storeid:$_" } sort keys zfs_list_zvol($scfg, 0)->%*];
+ return PVE::Storage::Plugin::get_next_vm_diskname(
+ $disk_list, $storeid, $vmid, $fmt, $scfg, $add_fmt_suffix,
+ );
+}
+
+sub status($class, $storeid, $scfg, $cache = undef) {
+ my ($available, $used) =
+ eval { zfs_get_properties($scfg, 'available,used', nvmet_pool($scfg)) };
+ if (my $err = $@) {
+ warn "storage '$storeid': $err";
+ return (0, 0, 0, 0);
+ }
+ ($available, $used) = (nvmet_uint($available), nvmet_uint($used));
+ if (!defined($available) || !defined($used)) {
+ warn "unexpected ZFS pool usage for storage '$storeid'\n";
+ return (0, 0, 0, 0);
+ }
+ return ($available + $used, $available, $used, 1);
+}
+
+sub volume_size_info($class, $scfg, $storeid, $volname, $timeout = undef) {
+ my (undef, $name, undef, $parent, undef, undef, $format) = $class->parse_volname($volname);
+ die "volume_size_info requires a ZFS volume\n" if $format ne 'raw';
+ my ($size, $used) = zfs_get_properties(
+ $scfg, 'volsize,usedbydataset', nvmet_dataset($scfg, $name), $timeout,
+ );
+ $size = nvmet_uint($size);
+ die "Could not get zfs volume size\n" if !defined($size);
+ $used = (nvmet_uint($used) // 0) + 0;
+ return wantarray ? ($size + 0, 'raw', $used, $parent) : $size + 0;
+}
+
+sub volume_snapshot($class, $scfg, $storeid, $volname, $snap) {
+ my (undef, $name, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
+ die "volume_snapshot requires a ZFS volume\n" if $format ne 'raw';
+ my $snapshot = nvmet_snapshot($scfg, $name, $snap);
+ nvmet_locked($scfg, sub { zfs_request($scfg, undef, 'snapshot', $snapshot) });
+ return;
+}
+
+sub volume_snapshot_delete($class, $scfg, $storeid, $volname, $snap, $running = undef) {
+ my $name = ($class->parse_volname($volname))[1];
+ my $snapshot = nvmet_snapshot($scfg, $name, $snap);
+ nvmet_locked($scfg, sub { zfs_request($scfg, undef, 'destroy', $snapshot) });
+ return;
+}
+
+sub volume_rollback_is_possible($class, $scfg, $storeid, $volname, $snap, $blockers = undef) {
+ my $name = ($class->parse_volname($volname))[1];
+ nvmet_snapshot($scfg, $name, $snap); # validation only
+ my $found;
+ $blockers //= [];
+ for my $snapshot (zfs_get_sorted_snapshot_list($scfg, $name, ['-s', 'creation'])->@*) {
+ $found = 1 if $snapshot eq $snap;
+ push $blockers->@*, $snapshot if $found && $snapshot ne $snap;
+ }
+ die "can't rollback, snapshot '$snap' does not exist on '${storeid}:${volname}'\n" if !$found;
+ die "can't rollback, '$snap' is not most recent snapshot on '${storeid}:${volname}'\n"
+ if $blockers->@*;
+ return 1;
+}
+
+sub volume_snapshot_rollback($class, $scfg, $storeid, $volname, $snap) {
+ my (undef, $name, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
+ die "snapshot rollback requires a ZFS volume\n" if $format ne 'raw';
+ nvmet_rollback_volume($scfg, $name, $snap);
+}
+
+sub volume_snapshot_info($class, $scfg, $storeid, $volname) {
+ my $name = ($class->parse_volname($volname))[1];
+ my $info = {};
+ my $text = zfs_request(
+ $scfg,
+ undef,
+ 'list',
+ '-Hp',
+ '-r',
+ '-t',
+ 'snapshot',
+ '-o',
+ 'name,guid,creation',
+ nvmet_dataset($scfg, $name),
+ );
+ for my $line (split /\n/, $text) {
+ my ($snapshot, $guid, $creation) = split /\s+/, $line;
+ $snapshot =~ s/^.*\@//;
+ $info->{$snapshot} =
+ { id => nvmet_uint($guid) // $guid, timestamp => nvmet_uint($creation) // $creation };
+ }
+ return $info;
+}
+
+sub free_image($class, $storeid, $scfg, $volname, $is_base = undef, $format = undef) {
+ my (undef, $name, undef, undef, undef, undef, $volformat) = $class->parse_volname($volname);
+ die "free_image requires a ZFS volume\n" if $volformat ne 'raw';
+ nvmet_destroy_volume($scfg, $name);
+ return undef;
+}
+
+sub create_base($class, $storeid, $scfg, $volname) {
+ my (undef, $name, undef, $basename, undef, $is_base, $format) = $class->parse_volname($volname);
+ die "create_base not possible with base image\n" if $is_base;
+ die "create_base requires a ZFS volume\n" if $format ne 'raw';
+ my $newname = $name =~ s/^vm-/base-/r;
+ nvmet_template_volume($scfg, $name);
+ return $basename ? "$basename/$newname" : $newname;
+}
+
+sub clone_image($class, $scfg, $storeid, $volname, $vmid, $snap = undef) {
+ $snap ||= '__base__';
+ my (undef, $basename, undef, undef, undef, $is_base, $format) = $class->parse_volname($volname);
+ die "clone_image only works on base images\n" if !$is_base;
+ die "clone_image requires a ZFS volume\n" if $format ne 'raw';
+ my $origin = nvmet_snapshot($scfg, $basename, $snap);
+ my $name = $class->find_free_diskname($storeid, $scfg, $vmid, $format);
+ nvmet_create_volume($scfg, $name, origin => $origin);
+ return "$basename/$name";
+}
+
+sub alloc_image($class, $storeid, $scfg, $vmid, $fmt, $name, $size) {
+ die "unsupported format '$fmt'" if $fmt ne 'raw';
+ die "illegal name '$name' - should be 'vm-$vmid-*'\n"
+ if $name && index($name, "vm-$vmid-") != 0;
+ my $volname = $name || $class->find_free_diskname($storeid, $scfg, $vmid, $fmt);
+ $volname = $class->volname_for_format($volname, $fmt, 0);
+ $size += (1024 - $size % 1024) % 1024;
+ nvmet_create_volume($scfg, $volname, size => $size);
+ return $volname;
+}
+
+sub volume_resize($class, $scfg, $storeid, $volname, $size, $running = undef, $snapname = undef) {
+ # The plugin cannot yet wait for the local namespace to report the new size, so refuse online
+ # resize before changing the zvol, as a running VM must not see a different size.
+ die "online resize is not supported for NVMe/TCP block devices; stop the VM first\n"
+ if $running;
+ die "resizing a snapshot is not supported for $class\n" if $snapname;
+ my $new_size = int($size / 1024);
+ $new_size += (1024 - $new_size % 1024) % 1024;
+ my $name = ($class->parse_volname($volname))[1];
+ nvmet_resize_volume($scfg, $name, $new_size);
+ return $new_size;
+}
+
+sub volume_has_feature(
+ $class, $scfg, $feature, $storeid, $volname,
+ $snapname = undef,
+ $running = undef,
+ $opts = undef,
+) {
+ my $features = {
+ snapshot => { current => 1, snap => 1 },
+ clone => { base => 1 },
+ template => { current => 1 },
+ copy => { base => 1, current => 1 },
+ };
+ my $is_base = ($class->parse_volname($volname))[5];
+ my $key = $snapname ? 'snap' : $is_base ? 'base' : 'current';
+ return $features->{$feature}->{$key};
+}
+
+# the storage has no path, so the base class offers no export or import format either
+sub volume_export($class, @args) {
+ die "ZFS stream export is not supported for NVMe/TCP storage\n";
+}
+
+sub volume_import($class, @args) {
+ die "ZFS stream import is not supported for NVMe/TCP storage\n";
+}
+
+sub rename_volume($class, @args) {
+ die "renaming volumes is not supported for NVMe/TCP storage\n";
+}
+
+sub rename_snapshot($class, @args) {
+ die "rename_snapshot is not supported for $class";
+}
+
+# Each storage needs its own listener, also a disabled one: nvmet answers a connect to a listener
+# that does not publish the subsystem yet with DNR, and the host then deletes the controller. After
+# a target restart the storage published second would lose its paths. Storages that reach the same
+# data address must spell the server alike, as it names the target lock.
+sub _assert_unique_target($storeid, $scfg, $cfg = undef) {
+ $cfg //= PVE::Storage::config();
+ my (%listeners, %addresses);
+ for my $portal (parse_nvme_portals($scfg->{'nvme-portals'})->@*) {
+ $listeners{"$portal->{address}\0$portal->{port}"} = 1;
+ $addresses{ $portal->{address} } = 1;
+ }
+ my $ids = $cfg->{ids} // {};
+ for my $other_id (sort keys $ids->%*) {
+ next if $other_id eq $storeid;
+ my $other = $ids->{$other_id};
+ next if ($other->{type} // '') ne 'zfsnvme';
+
+ die "NVMe subsystem NQN is already used by storage '$other_id'\n"
+ if ($other->{subsysnqn} // '') eq $scfg->{subsysnqn};
+ my $other_server = $other->{server} // '';
+ # a storage whose portals do not parse cannot be activated
+ for my $portal ((parse_nvme_portals($other->{'nvme-portals'}, 1) // [])->@*) {
+ die "NVMe/TCP portal '$portal->{address}' port $portal->{port} is already used by"
+ . " storage '$other_id'; give each storage its own address or port\n"
+ if $listeners{"$portal->{address}\0$portal->{port}"};
+ die "storage '$other_id' reaches target address '$portal->{address}' through server"
+ . " '$other_server'; use the same server value for both storages\n"
+ if $addresses{ $portal->{address} } && $other_server ne $scfg->{server};
+ }
+ next if $other_server ne $scfg->{server};
+ my ($pool, $other_pool) = ($scfg->{pool}, $other->{pool} // '');
+ die "ZFS pool '$pool' on '$scfg->{server}' is already used by storage '$other_id'\n"
+ if $other_pool eq $pool;
+ die "ZFS pool '$pool' on '$scfg->{server}' overlaps the pool of storage '$other_id'\n"
+ if index("$other_pool/", "$pool/") == 0 || index("$pool/", "$other_pool/") == 0;
+ }
+}
+
+# nvmet keeps one key per host NQN, so storages of a target that share a host NQN need the same key
+sub _assert_shared_host_key($storeid, $scfg, $key, $cfg = undef) {
+ $cfg //= PVE::Storage::config();
+ my %hosts = map { $_ => 1 } (parse_nvme_host_nqns($scfg->{'nvme-host-nqns'}, 1) // [])->@*;
+ my $ids = $cfg->{ids} // {};
+ for my $other_id (sort keys $ids->%*) {
+ next if $other_id eq $storeid;
+ my $other = $ids->{$other_id};
+ next if ($other->{type} // '') ne 'zfsnvme';
+ next if ($other->{server} // '') ne ($scfg->{server} // '');
+ my $other_hosts = parse_nvme_host_nqns($other->{'nvme-host-nqns'}, 1) // [];
+ next if !grep { $hosts{$_} } $other_hosts->@*;
+ my $other_key = file_read_firstline(secret_path($other_id));
+ die "storage '$other_id' uses a different DH-HMAC-CHAP key for the same NVMe host NQNs"
+ . " on '$scfg->{server}'\n"
+ if defined($other_key) && $other_key ne $key;
+ }
+}
+
+# DHHC-1:<hash>:<base64 of key and its little-endian CRC-32>: as generated by `nvme gen-dhchap-key`.
+# Messages never contain the key.
+sub _validate_secret($key) {
+ die "missing NVMe DH-HMAC-CHAP key\n" if !defined($key) || $key eq '';
+ my $invalid = "invalid NVMe DH-HMAC-CHAP key representation\n";
+ die $invalid if $key !~ $RE_DHCHAP_KEY;
+ my ($valid, $hash, $encoded) = @+{qw(key hash secret)};
+ die $invalid if length($encoded) % 4;
+ my $decoded = decode_base64($encoded);
+ my $length = length($decoded) - 4;
+ my %lengths = ('00' => [32, 48, 64], '01' => [32], '02' => [48], '03' => [64]);
+ die $invalid if !grep { $_ == $length } $lengths{$hash}->@*;
+ die $invalid if pack('V', crc32(substr($decoded, 0, $length))) ne substr($decoded, $length);
+ return $valid;
+}
+
+my sub set_secret($storeid, $key) {
+ _validate_secret($key);
+ make_path($secret_dir, { mode => 0700 });
+ file_set_contents(secret_path($storeid), "$key\n", 0600);
+}
+
+my sub get_secret($storeid) {
+ my $key = file_read_firstline(secret_path($storeid));
+ return _validate_secret($key);
+}
+
+sub _unlink_file($path) {
+ return unlink($path);
+}
+
+my sub delete_secret($storeid) {
+ _unlink_file(secret_path($storeid));
+}
+
+# An nvmeof storage lists the namespaces of its subsystem as its own, like a new storage of this
+# type would. Only a new storage checks it, so a storage that exists keeps working.
+my sub assert_not_used_by_nvmeof($storeid, $scfg) {
+ my $ids = PVE::Storage::config()->{ids} // {};
+ for my $other_id (sort keys $ids->%*) {
+ next if $other_id eq $storeid || ($ids->{$other_id}->{type} // '') ne 'nvmeof';
+ die "NVMe subsystem NQN is already used by storage '$other_id'\n"
+ if ($ids->{$other_id}->{subsysnqn} // '') eq $scfg->{subsysnqn};
+ }
+}
+
+sub on_add_hook($class, $storeid, $scfg, %sensitive) {
+ _configured_portals($scfg);
+ parse_nvme_host_nqns($scfg->{'nvme-host-nqns'});
+ _assert_unique_target($storeid, $scfg);
+ assert_not_used_by_nvmeof($storeid, $scfg);
+ my $key = _validate_secret($sensitive{'dhchap-key'});
+ _assert_shared_host_key($storeid, $scfg, $key);
+ set_secret($storeid, $key);
+ return;
+}
+
+sub on_update_hook_full($class, $storeid, $scfg, $update, $delete = undef, $sensitive = undef) {
+ $sensitive //= {};
+ my %prospective = ($scfg->%*, $update->%*);
+ delete @prospective{ $delete->@* } if $delete;
+ verify_nvme_nqn($prospective{subsysnqn});
+ _configured_portals(\%prospective);
+ my $new_hostnqns = parse_nvme_host_nqns($prospective{'nvme-host-nqns'});
+ my %new_hosts = map { $_ => 1 } $new_hostnqns->@*;
+ for my $old_hostnqn (parse_nvme_host_nqns($scfg->{'nvme-host-nqns'})->@*) {
+ die "removing NVMe host NQN '$old_hostnqn' is not supported; move every volume off"
+ . " the storage and recreate it with a new subsystem NQN and a new DH-HMAC-CHAP"
+ . " key\n"
+ if !$new_hosts{$old_hostnqn};
+ }
+ _validate_fail_fast_timeout(\%prospective, 600);
+ _assert_unique_target($storeid, \%prospective);
+
+ my $old_key = file_read_firstline(secret_path($storeid));
+ my $key = exists($sensitive->{'dhchap-key'}) ? $sensitive->{'dhchap-key'} : $old_key;
+ _validate_secret($key);
+
+ # nvmet stores authentication on the global host NQN object, which several subsystems can share.
+ # Replacing an active key in place can make unrelated storages unrecoverable on their next
+ # reconnect, so fail until PVE can coordinate a rolling rotation on every node.
+ die "NVMe DH-HMAC-CHAP key rotation is not supported; create a new storage with a new"
+ . " subsystem NQN\n"
+ if defined($old_key) && $key ne $old_key;
+ _assert_shared_host_key($storeid, \%prospective, $key);
+
+ set_secret($storeid, $key) if exists($sensitive->{'dhchap-key'});
+ return;
+}
+
1;
--
2.54.0.windows.1
^ permalink raw reply related [relevance 15%]
* [PATCH storage v5 04/13] zfsnvme: connect the nodes and register the plugin
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-11-26 15:09 11% ` [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning Joaquin Varela
2026-11-26 15:09 15% ` [PATCH storage v5 03/13] zfsnvme: add storage configuration and volume methods Joaquin Varela
@ 2026-11-26 15:09 16% ` Joaquin Varela
2026-11-26 15:09 11% ` [PATCH storage v5 07/13] test: zfsnvme: add configuration and volume tests Joaquin Varela
` (5 subsequent siblings)
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:09 UTC (permalink / raw)
To: pve-devel
Connect the nodes with native NVMe multipath. One write to
/dev/nvme-fabrics creates each controller, in a bounded child that
holds the PVE::NVMeOF host lock, so the key never shows up on a
command line. activate_volume checks the namespace identity.
The host NQN and ID come from nvme-cli, which is recommended already.
Register the 'zfsnvme' type, add it to @SHARED_STORAGE and let 'pvesm
add' and 'pvesm set' read --dhchap-key from a file. The delete hook
only removes the key file, as it runs under the storage.cfg lock. The
subsystem stays on the target, so a new key for its host NQNs is
refused until it is removed there.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
src/PVE/CLI/pvesm.pm | 21 +-
src/PVE/Storage.pm | 2 +
src/PVE/Storage/Makefile | 1 +
src/PVE/Storage/Plugin.pm | 12 +-
src/PVE/Storage/ZFSNVMePlugin.pm | 575 +++++++++++++++++++++++++++++++
5 files changed, 608 insertions(+), 3 deletions(-)
diff --git a/src/PVE/CLI/pvesm.pm b/src/PVE/CLI/pvesm.pm
index 05da60d8..33272fad 100755
--- a/src/PVE/CLI/pvesm.pm
+++ b/src/PVE/CLI/pvesm.pm
@@ -79,12 +79,29 @@ sub param_mapping {
},
};
+ my $dhchap_key_map = {
+ name => 'dhchap-key',
+ desc => 'a file containing the NVMe DH-HMAC-CHAP key',
+ func => sub {
+ my ($value) = @_;
+ # never repeat a key passed in place of the file name
+ die "dhchap-key expects the path of a file containing the key\n"
+ if $value =~ /^DHHC-1:/i || -d $value;
+ my ($key) = split(/\n/, PVE::Tools::file_get_contents($value), 2);
+ $key = PVE::Tools::trim($key // '');
+ die "DH-HMAC-CHAP key file '$value' is empty\n" if $key eq '';
+ return $key;
+ },
+ };
+
my $mapping = {
'cifsscan' => [$password_map],
'cifs' => [$password_map],
'pbs' => [$password_map],
- 'create' => [$password_map, $enc_key_map, $master_key_map, $keyring_map],
- 'update' => [$password_map, $enc_key_map, $master_key_map, $keyring_map],
+ 'create' =>
+ [$password_map, $enc_key_map, $master_key_map, $keyring_map, $dhchap_key_map],
+ 'update' =>
+ [$password_map, $enc_key_map, $master_key_map, $keyring_map, $dhchap_key_map],
};
return $mapping->{$name};
}
diff --git a/src/PVE/Storage.pm b/src/PVE/Storage.pm
index c77a6755..df4c6943 100755
--- a/src/PVE/Storage.pm
+++ b/src/PVE/Storage.pm
@@ -39,6 +39,7 @@ use PVE::Storage::CephFSPlugin;
use PVE::Storage::ISCSIDirectPlugin;
use PVE::Storage::ZFSPoolPlugin;
use PVE::Storage::ZFSPlugin;
+use PVE::Storage::ZFSNVMePlugin;
use PVE::Storage::PBSPlugin;
use PVE::Storage::BTRFSPlugin;
use PVE::Storage::ESXiPlugin;
@@ -65,6 +66,7 @@ PVE::Storage::CephFSPlugin->register();
PVE::Storage::ISCSIDirectPlugin->register();
PVE::Storage::ZFSPoolPlugin->register();
PVE::Storage::ZFSPlugin->register();
+PVE::Storage::ZFSNVMePlugin->register();
PVE::Storage::PBSPlugin->register();
PVE::Storage::BTRFSPlugin->register();
PVE::Storage::ESXiPlugin->register();
diff --git a/src/PVE/Storage/Makefile b/src/PVE/Storage/Makefile
index 7f2ff6c8..553f65a3 100644
--- a/src/PVE/Storage/Makefile
+++ b/src/PVE/Storage/Makefile
@@ -12,6 +12,7 @@ SOURCES= \
ISCSIDirectPlugin.pm \
ZFSPoolPlugin.pm \
ZFSPlugin.pm \
+ ZFSNVMePlugin.pm \
PBSPlugin.pm \
BTRFSPlugin.pm \
LvmThinPlugin.pm \
diff --git a/src/PVE/Storage/Plugin.pm b/src/PVE/Storage/Plugin.pm
index 998bc68a..60207301 100644
--- a/src/PVE/Storage/Plugin.pm
+++ b/src/PVE/Storage/Plugin.pm
@@ -42,7 +42,17 @@ our @COMMON_TAR_FLAGS = qw(
);
our @SHARED_STORAGE = (
- 'iscsi', 'nfs', 'cifs', 'rbd', 'cephfs', 'iscsidirect', 'zfs', 'drbd', 'pbs', 'nvmeof',
+ 'iscsi',
+ 'nfs',
+ 'cifs',
+ 'rbd',
+ 'cephfs',
+ 'iscsidirect',
+ 'zfs',
+ 'zfsnvme',
+ 'drbd',
+ 'pbs',
+ 'nvmeof',
);
our $QCOW2_PREALLOCATION = {
diff --git a/src/PVE/Storage/ZFSNVMePlugin.pm b/src/PVE/Storage/ZFSNVMePlugin.pm
index 1f95f8c5..4d2eaf7e 100644
--- a/src/PVE/Storage/ZFSNVMePlugin.pm
+++ b/src/PVE/Storage/ZFSNVMePlugin.pm
@@ -14,6 +14,7 @@ use Socket qw(AF_INET6 inet_ntop inet_pton);
use Time::HiRes;
use PVE::Cluster;
+use PVE::Diskmanage;
use PVE::File;
use PVE::JSONSchema;
use PVE::Network;
@@ -2363,4 +2364,578 @@ sub on_update_hook_full($class, $storeid, $scfg, $update, $delete = undef, $sens
return;
}
+my %slow_path_last; # time of the last slow-path activation, by storeid
+
+sub _block_device($path) {
+ return -b $path;
+}
+
+sub _link_target($path) {
+ return readlink($path);
+}
+
+sub _fabrics_device() {
+ return '/dev/nvme-fabrics';
+}
+
+sub _nvme_tcp_loaded() {
+ return -e '/sys/module/nvme_tcp';
+}
+
+sub _partitions($device) {
+ return glob("${device}p[0-9]*");
+}
+
+# Runs $code in a child under the host lock of PVE::NVMeOF, which the nvmeof storage and the
+# controller API share. with_lock kills the child at its limit, which also frees the lock. The limit
+# is $timeout plus the lock wait in all, counted from the start of the call. The bound is not hard:
+# a child stuck in the kernel (a write or delete in D state) is only reaped once the kernel returns,
+# and a timeout does not mean that the operation did not happen. $code must not take locks or call
+# run_locked.
+#
+# A stopped task (TERM, HUP, INT and QUIT) stays pending in the parent while the child runs, and
+# the child inherits the mask. So a connect still creates its controller and restricts the secret
+# attributes before the stop takes effect, unless PVE escalates to KILL after 5 seconds. That ends
+# both processes and leaves the attributes world-readable until the next activation. Once the child
+# is reaped, the worker handler dies with the task marker, also over a result or an error of the
+# child. ALRM, the timeout, is not blocked.
+my sub run_locked($timeout, $what, $code) {
+ my $limit = $timeout + $PVE::NVMeOF::LOCK_WAIT;
+ my $previous = POSIX::SigSet->new();
+ sigprocmask(SIG_BLOCK, POSIX::SigSet->new(SIGHUP, SIGINT, SIGQUIT, SIGTERM), $previous)
+ or die "cannot block signals: $!\n";
+ my $outer_warn = $SIG{__WARN__};
+ my $res = eval {
+ # with_lock only warns in the parent when its child leaves no result, which dies below.
+ # The child keeps the handler of the caller, so its warnings reach the task log.
+ local $SIG{__WARN__} = sub($message) { };
+ PVE::NVMeOF::with_lock(
+ sub {
+ local $SIG{__WARN__} = $outer_warn;
+ return $code->();
+ },
+ $limit,
+ );
+ };
+ my $error = $@;
+ sigprocmask(SIG_SETMASK, $previous) or die "cannot restore signals: $!\n";
+ if ($error) {
+ rethrow_task_interrupt($error);
+ die "$what did not complete within $limit seconds\n" if $error eq $PVE::NVMeOF::TIMED_OUT;
+ die $error;
+ }
+ die "$what left no result\n" if !defined($res);
+ return $res;
+}
+
+# the values are validated by the caller, the kernel reads each one up to the next ','
+sub _fabrics_options($scfg, $portal, $hostnqn, $hostid, $key) {
+ my @options = (
+ [transport => 'tcp'],
+ [traddr => $portal->{address}],
+ [trsvcid => $portal->{port}],
+ [host_iface => $portal->{host_iface}],
+ [nqn => $scfg->{subsysnqn}],
+ [hostnqn => $hostnqn],
+ [hostid => $hostid],
+ [dhchap_secret => $key],
+ [keep_alive_tmo => $scfg->{'nvme-keep-alive-tmo'} // 5],
+ [reconnect_delay => $scfg->{'nvme-reconnect-delay'} // 2],
+ [ctrl_loss_tmo => $scfg->{'nvme-ctrl-loss-tmo'} // 600],
+ );
+ # unlike unset, which leaves fast I/O failure off, 0 is a real timeout
+ push @options, [fast_io_fail_tmo => $scfg->{'nvme-fast-io-fail-tmo'}]
+ if defined($scfg->{'nvme-fast-io-fail-tmo'});
+ push @options, [nr_io_queues => $scfg->{'nvme-nr-io-queues'}]
+ if defined($scfg->{'nvme-nr-io-queues'});
+ for my $option (@options) {
+ die "internal error: invalid NVMe connect option '$option->[0]'\n"
+ if !defined($option->[1]) || $option->[1] !~ $RE_FABRICS_VALUE;
+ }
+ return (join(',', map { "$_->[0]=$_->[1]" } @options), [map { $_->[0] } @options]);
+}
+
+# One write of $options creates exactly one controller. It is never repeated, because the kernel
+# may have created the controller even when it reports an error. Errors carry the errno text and
+# never the options, which hold the key.
+sub _fabrics_connect($options, $names) {
+ my $device = _fabrics_device();
+ my $probe;
+ if (!sysopen($probe, $device, O_RDONLY | O_NOFOLLOW)) {
+ die "'$device' does not exist; load the nvme-tcp kernel module\n" if $! == ENOENT;
+ die "cannot open '$device': $!\n";
+ }
+ my @stat = stat($probe);
+ die "'$device' is not a character device\n" if !@stat || !S_ISCHR($stat[2]);
+ # without a controller, a read lists the supported options as patterns
+ my $supported = '';
+ sysread($probe, $supported, 4096) // die "cannot read '$device': $!\n";
+ close($probe);
+ my %supported = map { s/=.*//r => 1 } split(/,/, $supported =~ s/\n\z//r);
+ for my $name ($names->@*) {
+ die "the running kernel does not support the NVMe connect option '$name'\n"
+ if !$supported{$name};
+ }
+
+ # Not PVE::SysFSTools::file_write: the kernel returns the instance of the new controller on a
+ # read of the file descriptor that wrote the options.
+ sysopen(my $fh, $device, O_RDWR | O_NOFOLLOW) or die "cannot open '$device': $!\n";
+ my $written = _fabrics_write($fh, $options);
+ die "connect failed: $!\n" if !defined($written);
+ die "connect failed: short write\n" if $written != length($options);
+ my $result = '';
+ sysread($fh, $result, 128) // die "cannot read the connect result: $!\n";
+ die "unexpected connect result\n" if $result !~ $RE_FABRICS_RESULT;
+ my $instance = int($+{instance});
+ # The kernel creates the secret attributes world-readable. The caller keeps a stopped task from
+ # interrupting before this, short of a KILL.
+ _restrict_attr("/sys/class/nvme/nvme$instance/$_") for qw(dhchap_secret dhchap_ctrl_secret);
+ close($fh);
+ return $instance;
+}
+
+sub _fabrics_write($fh, $options) {
+ return syswrite($fh, $options);
+}
+
+# PVE::SysFSTools::file_write returns undef without a warning when the open fails, leaving its
+# errno in $!, and 0 after warning "error writing ...: <errno text>" when the write fails, which is
+# not passed on. With $missing_ok, an attribute that went away with its controller is no failure.
+my sub write_attribute($path, $value, $missing_ok = 0) {
+ my $warning;
+ my $written = do {
+ local $SIG{__WARN__} = sub($message) { $warning = $message };
+ PVE::SysFSTools::file_write($path, $value);
+ };
+ return if $written;
+ return if !defined($warning) && $missing_ok && $! == ENOENT;
+ return "$!" if !defined($warning);
+ return $warning =~ s/\A.*: //sr =~ s/\n\z//r;
+}
+
+# runs in a child, as the deletion can block in the kernel
+sub _delete_controllers($controllers) {
+ for my $controller ($controllers->@*) {
+ my $path = "/sys/class/nvme/$controller->{name}/delete_controller";
+ my $error = write_attribute($path, '1', 1) // next;
+ die "cannot delete NVMe controller '$controller->{name}': $error\n";
+ }
+ return scalar($controllers->@*);
+}
+
+my sub nvme_controllers($nqn) {
+ my $controllers = [];
+ PVE::File::dir_glob_foreach(
+ '/sys/class/nvme',
+ $RE_NVME_CONTROLLER,
+ sub($entry) {
+ my $base = "/sys/class/nvme/$entry";
+ my $subsys = file_read_firstline("$base/subsysnqn");
+ return if !defined($subsys) || $subsys ne $nqn;
+ my $address = file_read_firstline("$base/address") // '';
+ my $traddr = $address =~ $RE_TRADDR ? $+{value} : undef;
+ my $trsvcid = $address =~ $RE_TRSVCID ? $+{value} : undef;
+ my $host_iface = $address =~ $RE_HOST_IFACE_ADDRESS ? $+{value} : undef;
+ push $controllers->@*,
+ {
+ name => $entry,
+ state => file_read_firstline("$base/state") // 'unknown',
+ traddr => nvmet_canonical_address($traddr),
+ trsvcid => $trsvcid,
+ host_iface => $host_iface,
+ };
+ },
+ );
+ return $controllers;
+}
+
+# a portal has more than one controller while its path moves to another interface
+my sub controller_states($nqn) {
+ my $states = {};
+ for my $controller (nvme_controllers($nqn)->@*) {
+ next if !defined($controller->{traddr}) || !defined($controller->{trsvcid});
+ push $states->{"$controller->{traddr}:$controller->{trsvcid}"}->@*, $controller;
+ }
+ return $states;
+}
+
+# The kernel reuses the name of a controller that is gone, and the wait for the host lock can be
+# long, so the name of a listed controller can belong to another one by the time it is deleted. A
+# dead controller must still be dead, as it can recover meanwhile.
+my sub same_controller($listed, $now) {
+ return 0 if !$now;
+ for my $key (qw(traddr trsvcid host_iface)) {
+ return 0 if ($now->{$key} // '') ne ($listed->{$key} // '');
+ }
+ return $listed->{state} ne 'dead' || $now->{state} eq 'dead';
+}
+
+# runs in a child under the host lock, and deletes the listed controllers that are still the same
+my sub delete_listed($nqn, $listed) {
+ my %now = map { $_->{name} => $_ } nvme_controllers($nqn)->@*;
+ return _delete_controllers([grep { same_controller($_, $now{ $_->{name} }) } $listed->@*]);
+}
+
+# What keeps the namespaces of the subsystem from going away, as PVE::NVMeOF::disconnect_guarded
+# checks it. A swap area claims its device like a mount does, so the claim covers it.
+sub _namespace_users($nqn) {
+ my @users;
+ for my $head (sort keys PVE::NVMeOF::namespaces($nqn)->%*) {
+ my $device = "/dev/$head";
+ my @devices = ($device, _partitions($device));
+ if (defined(my $mounted = PVE::Diskmanage::is_mounted($device))) {
+ push @users, "'$mounted' is mounted";
+ } elsif (defined(my $held = PVE::Diskmanage::has_holder($device))) {
+ push @users, "'$held' has a holder";
+ } elsif (my ($claimed) = grep { PVE::NVMeOF::is_claimed($_) } @devices) {
+ push @users, "'$claimed' is claimed, for example by a swap area";
+ } else {
+ # retry briefly to ignore transient openers like LVM status scans
+ my $opener;
+ for my $try (1 .. 4) {
+ _sleep(0.3) if $try > 1;
+ $opener = PVE::Diskmanage::device_opener(@devices);
+ last if !defined($opener);
+ }
+ push @users, "process $opener has namespace '$head' open" if defined($opener);
+ }
+ }
+ return \@users;
+}
+
+my sub portal_reachable($portal) {
+ return PVE::Network::tcp_ping($portal->{address}, $portal->{port}, 2) // 0;
+}
+
+# with $any_iface, a live controller on any interface counts, as such a path carries I/O
+sub _live_portal_count($states, $portals, $any_iface = 0) {
+ my $live = 0;
+ for my $portal ($portals->@*) {
+ my $id = "$portal->{address}:$portal->{port}";
+ $live++ if grep {
+ $_->{state} eq 'live'
+ && ($any_iface || ($_->{host_iface} // '') eq $portal->{host_iface})
+ } ($states->{$id} // [])->@*;
+ }
+ return $live;
+}
+
+# Gives up after 10 seconds plus the lock wait in all, counted from the start of the call. Returns
+# -1 if the portal got a controller on its interface meanwhile, as another activation can run at
+# the same time.
+sub _connect_portal($scfg, $portal, $hostnqn, $hostid, $key) {
+ my ($options, $names) = _fabrics_options($scfg, $portal, $hostnqn, $hostid, $key);
+ my $id = "$portal->{address}:$portal->{port}";
+ return run_locked(
+ 10,
+ 'NVMe/TCP connect',
+ sub {
+ my $states = controller_states($scfg->{subsysnqn});
+ return -1
+ if grep {
+ ($_->{host_iface} // '') eq $portal->{host_iface} && $_->{state} ne 'dead'
+ } ($states->{$id} // [])->@*;
+ return _fabrics_connect($options, $names);
+ },
+ );
+}
+
+my sub set_iopolicy($nqn, $policy) {
+ PVE::File::dir_glob_foreach(
+ '/sys/class/nvme-subsystem',
+ $RE_NVME_SUBSYSTEM,
+ sub($entry) {
+ my $base = "/sys/class/nvme-subsystem/$entry";
+ my $subsys = file_read_firstline("$base/subsysnqn");
+ return if !defined($subsys) || $subsys ne $nqn;
+ my $error = write_attribute("$base/iopolicy", "$policy\n");
+ die "unable to set NVMe multipath policy: $error\n" if defined($error);
+ },
+ );
+}
+
+# Connected controllers keep the values of their connect unless this writes them. sysfs shows "off"
+# for -1 and the loss timeout rounded up to a multiple of the reconnect delay.
+my sub set_tunables($scfg) {
+ my $delay = $scfg->{'nvme-reconnect-delay'} // 2;
+ my $loss = $scfg->{'nvme-ctrl-loss-tmo'} // 600;
+ my $fast = $scfg->{'nvme-fast-io-fail-tmo'};
+ my $shown_loss = $loss < 0 ? 'off' : int(($loss + $delay - 1) / $delay) * $delay;
+ my $shown_fast = defined($fast) && $fast >= 0 ? $fast : 'off';
+
+ for my $controller (nvme_controllers($scfg->{subsysnqn})->@*) {
+ my $base = "/sys/class/nvme/$controller->{name}";
+ my $current_delay = file_read_firstline("$base/reconnect_delay") // next;
+ my $write = sub($attr, $value) {
+ my $error = write_attribute("$base/$attr", "$value\n") // return;
+ log_warn("cannot set $attr of NVMe controller '$controller->{name}': $error");
+ };
+ my $delay_changed = $current_delay ne "$delay";
+ $write->('reconnect_delay', $delay) if $delay_changed;
+ $write->('ctrl_loss_tmo', $loss < 0 ? -1 : $loss)
+ if $delay_changed
+ || (file_read_firstline("$base/ctrl_loss_tmo") // '') ne "$shown_loss";
+ $write->('fast_io_fail_tmo', $shown_fast eq 'off' ? -1 : $fast)
+ if (file_read_firstline("$base/fast_io_fail_tmo") // '') ne "$shown_fast";
+ }
+}
+
+sub _restrict_attr($path) {
+ my @stat = stat($path);
+ if (!@stat) {
+ log_warn("cannot stat NVMe controller attribute '$path': $!") if $! != ENOENT;
+ return;
+ }
+ return if !($stat[2] & 077);
+ chmod(0600, $path) or log_warn("cannot restrict permissions of '$path': $!");
+}
+
+my sub restrict_secret_attrs($nqn) {
+ for my $controller (nvme_controllers($nqn)->@*) {
+ _restrict_attr("/sys/class/nvme/$controller->{name}/$_")
+ for qw(dhchap_secret dhchap_ctrl_secret);
+ }
+}
+
+my sub rescan_namespaces($nqn) {
+ for my $controller (nvme_controllers($nqn)->@*) {
+ next if $controller->{state} ne 'live';
+ my $path = "/sys/class/nvme/$controller->{name}/rescan_controller";
+ my $error = write_attribute($path, "1\n", 1) // next;
+ log_warn("cannot rescan NVMe controller '$controller->{name}': $error");
+ }
+}
+
+# the activation reconnects or keeps the path either way, so a failure only warns
+my sub disconnect_controller($nqn, $controller) {
+ my $name = $controller->{name};
+ eval {
+ run_locked(
+ 5,
+ "deleting NVMe controller '$name'",
+ sub { return delete_listed($nqn, [$controller]) },
+ );
+ };
+ if (my $error = $@) {
+ rethrow_task_interrupt($error);
+ log_warn($error);
+ }
+}
+
+my sub wait_for_live_path($nqn, $portal) {
+ for (my $attempt = 0; $attempt < 40; $attempt++) {
+ return 1 if _live_portal_count(controller_states($nqn), [$portal]);
+ _sleep(0.25);
+ }
+ return 0;
+}
+
+# A path connected on another interface moves make-before-break: its old controller is only
+# disconnected once the new one is live, so a changed mapping never takes away a path with I/O.
+my sub connect_portals($scfg, $portals, $hostnqn, $hostid, $key) {
+ my $nqn = $scfg->{subsysnqn};
+ for my $portal ($portals->@*) {
+ my $id = "$portal->{address}:$portal->{port}";
+ my $iface = $portal->{host_iface};
+ my @controllers = (controller_states($nqn)->{$id} // [])->@*;
+ my ($configured) = grep { ($_->{host_iface} // '') eq $iface } @controllers;
+ my @moved = grep { ($_->{host_iface} // '') ne $iface } @controllers;
+
+ if (!$configured || $configured->{state} eq 'dead') {
+ disconnect_controller($nqn, $configured) if $configured;
+ if (!portal_reachable($portal)) {
+ log_warn("NVMe/TCP portal '$id' is unreachable");
+ next;
+ }
+ eval { _connect_portal($scfg, $portal, $hostnqn, $hostid, $key) };
+ my $connect_error = $@;
+ # A failed or timed-out connect can still have created a controller.
+ eval { restrict_secret_attrs($nqn); 1 };
+ if (my $error = $@) {
+ rethrow_task_interrupt($error);
+ log_warn("cannot restrict NVMe controller attributes for '$nqn'");
+ }
+ rethrow_task_interrupt($connect_error) if $connect_error;
+ if ($connect_error) {
+ log_warn("$id: $connect_error");
+ next;
+ }
+ }
+ next if !@moved;
+ if (!wait_for_live_path($nqn, $portal)) {
+ log_warn("NVMe/TCP portal '$id' is not live on '$iface' yet; keeping its path on"
+ . " another interface");
+ next;
+ }
+ disconnect_controller($nqn, $_) for @moved;
+ }
+}
+
+sub activate_storage($class, $storeid, $scfg, $cache = undef) {
+ $cache //= {};
+ my $nqn = $scfg->{subsysnqn};
+ # first, whatever the rest of the activation does, also for controllers connected by hand
+ restrict_secret_attrs($nqn);
+
+ # as PVE::NVMeOF::assert_support, which also wants the nvme binary that this plugin never runs
+ run_command(['modprobe', 'nvme-tcp'], timeout => 10) if !_nvme_tcp_loaded();
+ my $multipath = file_read_firstline('/sys/module/nvme_core/parameters/multipath') // '';
+ die "native NVMe multipath is disabled in the running kernel\n" if $multipath ne 'Y';
+
+ my $portals = _configured_portals($scfg);
+ verify_nvme_nqn($nqn);
+ _validate_local_ifaces($portals);
+ _assert_unique_target($storeid, $scfg);
+ my $host = PVE::NVMeOF::host_identity();
+ my $hostnqn = $host->{nqn};
+ my $hostnqns = parse_nvme_host_nqns($scfg->{'nvme-host-nqns'});
+ die "local NVMe host NQN '$hostnqn' is missing from nvme-host-nqns\n"
+ if !grep { $_ eq $hostnqn } $hostnqns->@*;
+ my $policy = $scfg->{'nvme-iopolicy'} // 'round-robin';
+ my $force_reconcile = delete($cache->{'zfsnvme-force-reconcile'}->{$storeid}) // 0;
+ my $states = controller_states($nqn);
+ my $healthy = _live_portal_count($states, $portals);
+ my $usable = _live_portal_count($states, $portals, 1);
+ my $last = $slow_path_last{$storeid};
+ my $recent = defined($last) && _now() - $last < $slow_path_backoff;
+
+ # This runs in the periodic status loop. Once every configured path is live, lifecycle
+ # operations keep the target converged, so no remote call is needed. A degraded storage retries
+ # the target at most once a minute. In between, one with a live path is usable and one
+ # without fails at once. Missing namespaces force the slow path.
+ if (!$force_reconcile && ($healthy == scalar($portals->@*) || $recent)) {
+ die "no live NVMe/TCP path for storage '$storeid'\n" if !$usable;
+ die "missing NVMe DH-HMAC-CHAP key\n"
+ if (file_read_firstline(secret_path($storeid)) // '') eq '';
+ set_iopolicy($nqn, $policy);
+ set_tunables($scfg);
+ return 1;
+ }
+
+ $slow_path_last{$storeid} = _now();
+ my $hostid = $host->{id};
+ my $key = get_secret($storeid);
+ for my $name (qw(keep-alive-tmo reconnect-delay ctrl-loss-tmo fast-io-fail-tmo nr-io-queues)) {
+ my $value = $scfg->{"nvme-$name"};
+ die "invalid NVMe connection parameter '$name'\n"
+ if defined($value) && $value !~ $RE_CONFIG_INT;
+ }
+ _nvmet_activate_target($storeid, $scfg, $portals, $hostnqns, $key);
+ connect_portals($scfg, $portals, $hostnqn, $hostid, $key);
+
+ # after a restart controllers can sit in their kernel reconnect delay, so wait, do not duplicate
+ for (my $attempt = 0; $attempt < 60; $attempt++) {
+ $states = controller_states($nqn);
+ last if _live_portal_count($states, $portals, 1);
+ _sleep(0.25);
+ }
+ die "no live NVMe/TCP path for storage '$storeid'\n"
+ if !_live_portal_count($states, $portals, 1);
+ $healthy = _live_portal_count($states, $portals);
+ log_warn("storage '$storeid' is degraded: $healthy/" . scalar($portals->@*) . " paths live")
+ if $healthy < scalar($portals->@*);
+
+ set_iopolicy($nqn, $policy);
+ set_tunables($scfg);
+ return 1;
+}
+
+sub deactivate_storage($class, $storeid, $scfg, $cache = undef) {
+ my $nqn = $scfg->{subsysnqn};
+ my $users = _namespace_users($nqn);
+ die "refusing to disconnect NVMe storage '$storeid': " . join(', ', $users->@*) . "\n"
+ if $users->@*;
+
+ return 1 if !nvme_controllers($nqn)->@*;
+ # One child deletes the controllers that it finds once it has the lock. It gives up after 15
+ # seconds plus the lock wait in all, counted from the start of the call. Then the remaining
+ # controllers stay and the deactivation fails.
+ run_locked(
+ 15,
+ "disconnecting NVMe subsystem '$nqn'",
+ sub { return _delete_controllers(nvme_controllers($nqn)) },
+ );
+ return 1;
+}
+
+# The core runs this inside the storage.cfg lock of the cluster, so it only touches local state.
+# The subsystem stays on the target and the controllers of the nodes stay connected.
+sub on_delete_hook($class, $storeid, $scfg) {
+ # A storage that is added again under this ID is a new one. Adding a storage removes it again
+ # when its activation fails, and a long running worker would keep the backoff of that failure.
+ delete $slow_path_last{$storeid};
+ delete_secret($storeid);
+ return;
+}
+
+sub path($class, $scfg, $volname, $storeid, $snapname = undef) {
+ die "direct access to snapshots not implemented\n" if defined($snapname);
+ my ($vtype, $name, $vmid) = $class->parse_volname($volname);
+ my $uuid = _nvmet_volume_uuid($scfg, $name);
+ my $path = "/dev/disk/by-id/nvme-uuid.$uuid";
+ return ($path, $vmid, $vtype);
+}
+
+sub qemu_blockdev_options(
+ $class, $scfg, $storeid, $volname,
+ $machine_version = undef,
+ $options = undef,
+) {
+ die "direct access to snapshots not implemented\n" if $options->{'snapshot-name'};
+ my ($path) = $class->path($scfg, $volname, $storeid);
+ return { driver => 'host_device', filename => $path };
+}
+
+# a UUID claimed by another subsystem must never reach a guest
+sub _nvmet_local_namespace_ok($path, $nqn, $nsid, $uuid) {
+ my $link = _link_target($path) // return 0;
+ my $device = (split m{/}, $link)[-1];
+ return 0 if !defined($device) || $device !~ $RE_NVME_NAMESPACE;
+ my $sys = "/sys/block/$+{device}";
+ return 0 if lc(file_read_firstline("$sys/uuid") // '') ne lc($uuid);
+ return 0 if (file_read_firstline("$sys/nsid") // '') ne "$nsid";
+ return 0 if (file_read_firstline("$sys/device/subsysnqn") // '') ne $nqn;
+ return 1;
+}
+
+sub activate_volume(
+ $class, $storeid, $scfg, $volname,
+ $snapname = undef,
+ $cache = undef,
+ $hints = undef,
+) {
+ die "unable to activate snapshot from remote zfs storage\n" if $snapname;
+ my (undef, $name) = $class->parse_volname($volname);
+ my $nqn = nvmet_nqn($scfg);
+ my $dataset = nvmet_dataset($scfg, $name);
+
+ my ($inv, $cfs) = nvmet_read($scfg);
+ my ($nsid, $uuid) = _nvmet_owned_identity($inv, $nqn, $dataset);
+ my $state = _nvmet_export_state($cfs, $nqn, $nsid, $uuid, "/dev/zvol/$dataset");
+ my $path = "/dev/disk/by-id/nvme-uuid.$uuid";
+ my $ok = sub {
+ return _block_device($path) && _nvmet_local_namespace_ok($path, $nqn, $nsid, $uuid);
+ };
+ return 1 if $state eq 'present' && $ok->();
+
+ $cache //= {};
+ $cache->{'zfsnvme-force-reconcile'}->{$storeid} = 1;
+ $class->activate_storage($storeid, $scfg, $cache);
+ for (my $attempt = 0; $attempt < 40 && !_block_device($path); $attempt++) {
+ # a host can miss the change notice, and rescanning is harmless
+ rescan_namespaces($nqn) if $attempt % 8 == 0;
+ _sleep(0.25);
+ }
+ die "NVMe namespace for '$volname' did not appear\n" if !_block_device($path);
+ die "NVMe namespace for '$volname' has an unexpected identity\n" if !$ok->();
+ return 1;
+}
+
+sub deactivate_volume(
+ $class, $storeid, $scfg, $volname, $snapname = undef, $cache = undef,
+) {
+ die "unable to deactivate snapshot from remote zfs storage\n" if $snapname;
+ return 1;
+}
+
1;
--
2.54.0.windows.1
^ permalink raw reply related [relevance 16%]
* [PATCH storage v5 07/13] test: zfsnvme: add configuration and volume tests
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
` (2 preceding siblings ...)
2026-11-26 15:09 16% ` [PATCH storage v5 04/13] zfsnvme: connect the nodes and register the plugin Joaquin Varela
@ 2026-11-26 15:09 11% ` Joaquin Varela
2026-11-26 15:09 10% ` [PATCH storage v5 08/13] test: zfsnvme: add node side tests Joaquin Varela
` (4 subsequent siblings)
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:09 UTC (permalink / raw)
To: pve-devel
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 <joaquinvarela@neatech.ar>
---
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:<hash>:<base64 of the key and its little-endian CRC-32>:
+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
^ permalink raw reply related [relevance 11%]
* [PATCH storage v5 08/13] test: zfsnvme: add node side tests
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
` (3 preceding siblings ...)
2026-11-26 15:09 11% ` [PATCH storage v5 07/13] test: zfsnvme: add configuration and volume tests Joaquin Varela
@ 2026-11-26 15:09 10% ` Joaquin Varela
2026-11-26 15:09 8% ` [PATCH storage v5 09/13] test: zfsnvme: add an in-memory nvmet target Joaquin Varela
` (3 subsequent siblings)
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:09 UTC (permalink / raw)
To: pve-devel
Test the /dev/nvme-fabrics options, the connect child against a
pseudoterminal that answers like the fabrics device (skipped without
/dev/ptmx) and that a connect which times out gives up the host lock.
Also test rescans, the namespace checks of a deactivation, the deletion
of controllers and its re-check under the lock, loading nvme-tcp, path
selection and storage activation.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
src/test/zfsnvme_test.pm | 1584 +++++++++++++++++++++++++++++++++++++-
1 file changed, 1583 insertions(+), 1 deletion(-)
diff --git a/src/test/zfsnvme_test.pm b/src/test/zfsnvme_test.pm
index 41991649..4f27f38b 100644
--- a/src/test/zfsnvme_test.pm
+++ b/src/test/zfsnvme_test.pm
@@ -11,7 +11,7 @@ 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 Fcntl qw(:flock O_NOCTTY O_RDWR);
use File::Temp qw(tempdir);
use MIME::Base64 qw(encode_base64);
use POSIX qw(
@@ -1261,6 +1261,1588 @@ subtest 'vdisk_alloc dispatches under the shared storage lock' => sub {
$parent_mock->unmock('lookup');
};
+{
+ my $portal = { address => '192.0.2.22', port => 4420, host_iface => 'ens21' };
+ my $options = sub($scfg) {
+ return nv(
+ '_fabrics_options', $scfg, $portal, $hostnqn_a, $UUID, $KEY,
+ );
+ };
+ my ($string, $names) = $options->({ subsysnqn => $NQN });
+ is(
+ $string,
+ "transport=tcp,traddr=192.0.2.22,trsvcid=4420,host_iface=ens21,nqn=$NQN,"
+ . "hostnqn=$hostnqn_a,hostid=$UUID,dhchap_secret=$KEY,keep_alive_tmo=5,"
+ . 'reconnect_delay=2,ctrl_loss_tmo=600',
+ 'the portal, the identities, the key and the default timeouts',
+ );
+ is_deeply(
+ $names,
+ [
+ qw(transport traddr trsvcid host_iface nqn hostnqn hostid dhchap_secret),
+ qw(keep_alive_tmo reconnect_delay ctrl_loss_tmo),
+ ],
+ 'with the names of the options',
+ );
+ my $tuned = {
+ subsysnqn => $NQN,
+ 'nvme-keep-alive-tmo' => 10,
+ 'nvme-reconnect-delay' => 5,
+ 'nvme-ctrl-loss-tmo' => 60,
+ 'nvme-fast-io-fail-tmo' => 15,
+ 'nvme-nr-io-queues' => 4,
+ };
+ ($string, $names) = $options->($tuned);
+ my $tail = 'keep_alive_tmo=10,reconnect_delay=5,ctrl_loss_tmo=60,'
+ . 'fast_io_fail_tmo=15,nr_io_queues=4';
+ like($string, qr/,\Q$tail\E\z/, 'the configured timeouts and queues');
+ is_deeply([$names->@[-2, -1]], ['fast_io_fail_tmo', 'nr_io_queues'], 'are named too');
+ ($string) = $options->({ $tuned->%*, 'nvme-fast-io-fail-tmo' => 0 });
+ like($string, qr/,fast_io_fail_tmo=0,/, 'a fast I/O fail timeout of 0 is a real value');
+ ($string) = $options->({ $tuned->%*, 'nvme-ctrl-loss-tmo' => -1 });
+ like($string, qr/,ctrl_loss_tmo=-1,/, 'an infinite loss timeout');
+
+ for my $value ('6 0', '60,duplicate_connect', "60\x00", '') {
+ eval { $options->({ $tuned->%*, 'nvme-ctrl-loss-tmo' => $value }) };
+ is(
+ $@,
+ "internal error: invalid NVMe connect option 'ctrl_loss_tmo'\n",
+ 'a value that would end the option early is refused without echoing it',
+ );
+ }
+}
+
+# The connect runs in a child bounded by 10 seconds plus 10 for the host lock. Its result and
+# errors pass through, a stopped task and a timeout have their own message.
+{
+ my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+ my $connect = sub($child) {
+ local @FORKS = ();
+ $nvme_mock->redefine(_fabrics_connect => $child);
+ my $res = eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY); };
+ my $error = $@;
+ $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+ return ($res, $error, [@FORKS]);
+ };
+ @LOCKS = ();
+ my ($res, $error, $forks) = $connect->(sub($options, $names) { return 7 });
+ is($res, 7, 'returns the instance of the new controller');
+ is_deeply($forks, [20], 'from a child bounded by 10 seconds and 10 for the host lock');
+ is_deeply(\@LOCKS, ['enter', 'leave'], 'that takes the host lock of PVE::NVMeOF');
+ my $held;
+ $connect->(sub(@args) {
+ $held = $LOCK_HELD;
+ return 7;
+ });
+ ok($held, 'and creates the controller while it holds it');
+ for my $exception ("received interrupt\n", "interrupted by unexpected signal\n") {
+ (undef, $error) = $connect->(sub(@args) {
+ die $exception;
+ });
+ is($error, "received interrupt\n", 'a stopped task dies with the task marker');
+ }
+ my @warnings;
+ local $SIG{__WARN__} = sub($warning) { push @warnings, $warning };
+ $nvmeof_mock->redefine(with_lock => sub($code, $limit = undef) { die $PVE::NVMeOF::TIMED_OUT });
+ (undef, $error) = $connect->(sub(@args) {
+ return 7;
+ });
+ is($error, "NVMe/TCP connect did not complete within 20 seconds\n", 'a timeout');
+ $nvmeof_mock->redefine(
+ with_lock => sub($code, $limit = undef) {
+ warn "malformed JSON string\n"; # what a child that died without a result leaves
+ return undef;
+ },
+ );
+ (undef, $error) = $connect->(sub(@args) {
+ return 7;
+ });
+ is($error, "NVMe/TCP connect left no result\n", 'a child without a result');
+ is_deeply(\@warnings, [], 'without the warning of with_lock in the task log');
+ $nvmeof_mock->redefine(with_lock => $lock_inline);
+}
+
+# The host lock is shared with the nvmeof storage and the controller API, and another activation
+# of the same storage can run at the same time, so the portal is checked again under the lock.
+{
+ reset_host();
+ my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+ my $connect = sub() {
+ my $res = eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY); };
+ return ($res, $@);
+ };
+ my $created = 0;
+ $nvme_mock->redefine(_fabrics_connect => sub(@args) { $created++; return 7 });
+
+ local $LOCK_BUSY = 1;
+ my ($res, $error) = $connect->();
+ is(
+ $error,
+ "NVMe over Fabrics is busy - another operation is still running\n",
+ 'a busy host lock fails the connect',
+ );
+ is($created, 0, 'before anything is created');
+ $LOCK_BUSY = 0;
+
+ # [name, controller, expected result]
+ for my $case (
+ ['a live controller on the interface', ['nvme5', 'live', 'ens19'], -1],
+ ['a controller that is still connecting', ['nvme5', 'connecting', 'ens19'], -1],
+ ['a dead controller', ['nvme5', 'dead', 'ens19'], 7],
+ ['a controller on another interface', ['nvme5', 'live', 'ens20'], 7],
+ ['no controller', undef, 7],
+ ) {
+ my ($name, $controller, $expected) = $case->@*;
+ reset_host();
+ $created = 0;
+ if ($controller) {
+ my ($controller_name, $state, $iface) = $controller->@*;
+ add_controller($controller_name, '192.0.2.21', 4420, $iface, $state);
+ }
+ ($res, $error) = $connect->();
+ is($res, $expected, "with $name the result is $expected");
+ is($error, '', "and there is no error");
+ is($created, $expected == 7 ? 1 : 0, "and the controller is created or not accordingly");
+ }
+ $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+}
+
+my %signal = (HUP => SIGHUP, INT => SIGINT, QUIT => SIGQUIT, TERM => SIGTERM, ALRM => SIGALRM);
+
+sub blocked_signals() {
+ my $mask = POSIX::SigSet->new();
+ sigprocmask(SIG_BLOCK, POSIX::SigSet->new(), $mask) or die "sigprocmask: $!\n";
+ return join(',', grep { $mask->ismember($signal{$_}) } sort keys %signal);
+}
+
+# The child itself: a real fork under the real with_lock, on a lock file of its own.
+subtest 'the connect child' => sub {
+ $nvmeof_mock->unmock('with_lock');
+ local $PVE::NVMeOF::RUN_DIR = tempdir(CLEANUP => 1);
+ my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+ my $connect = sub() {
+ my $res = eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY); };
+ return ($res, $@);
+ };
+ $nvme_mock->redefine(_fabrics_connect => sub(@args) { return 7 });
+ my ($res, $error) = $connect->();
+ is($res, 7, 'the result of the child reaches the parent');
+ is(blocked_signals(), '', 'and the signal mask is restored');
+ $nvme_mock->redefine(
+ _fabrics_connect => sub(@args) { die "connect failed: Connection refused\n" },
+ );
+ (undef, $error) = $connect->();
+ is($error, "connect failed: Connection refused\n", 'and so does its error');
+ is(blocked_signals(), '', 'with the signal mask restored');
+
+ my $dir = tempdir(CLEANUP => 1);
+ $nvme_mock->redefine(_fabrics_connect => sub(@args) { warn "child warning\n"; return 7 });
+ open(my $saved, '>&', \*STDERR) or die "cannot save STDERR: $!\n";
+ open(STDERR, '>', "$dir/stderr") or die "cannot redirect STDERR: $!\n";
+ ($res, $error) = $connect->();
+ open(STDERR, '>&', $saved) or die "cannot restore STDERR: $!\n";
+ is($res, 7, 'a child that warns');
+ open(my $fh, '<', "$dir/stderr") or die "cannot read '$dir/stderr': $!\n";
+ is(join('', <$fh>), "child warning\n", 'is heard');
+ close($fh);
+
+ # the signal stays pending while the child runs, then the worker handler dies with the marker
+ for my $name (qw(TERM QUIT INT)) {
+ pipe(my $from_child, my $to_parent) or die "pipe: $!\n";
+ $nvme_mock->redefine(
+ _fabrics_connect => sub(@args) {
+ kill($name, getppid()) or die "kill: $!\n";
+ print {$to_parent} "$$ " . blocked_signals() . "\n";
+ close($to_parent);
+ return 7;
+ },
+ );
+ my $seen;
+ local $SIG{$name} = sub { # as in a PVE worker
+ chomp(my $report = <$from_child> // '');
+ my ($pid, $blocked) = split(/ /, $report, 2);
+ $seen = { blocked => $blocked, reaped => $pid && waitpid($pid, WNOHANG) == -1 };
+ die "received interrupt\n";
+ };
+ ($res, $error) = $connect->();
+ close($to_parent);
+ close($from_child);
+ is($error, "received interrupt\n", "$name stops the task with the task marker");
+ is(
+ $seen->{blocked},
+ 'HUP,INT,QUIT,TERM',
+ 'once the child, with the inherited mask, is done',
+ );
+ ok($seen->{reaped}, 'and reaped');
+ is(blocked_signals(), '', 'and the signal mask is restored');
+ }
+ $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+ $nvmeof_mock->redefine(with_lock => $lock_inline);
+};
+
+# with_lock kills its child at the limit, so a stalled connect only keeps the host lock until the
+# caller gives up. A child inside that child would run on and keep the lock.
+subtest 'a connect that times out gives up the host lock' => sub {
+ $nvmeof_mock->unmock('with_lock');
+ my $dir = tempdir(CLEANUP => 1);
+ local $PVE::NVMeOF::RUN_DIR = $dir;
+ local $PVE::NVMeOF::LOCK_WAIT = 0;
+ # the real run_fork_with_timeout, with one second instead of the limit of the plugin
+ my $fork = \&PVE::Tools::run_fork_with_timeout;
+ my @limits;
+ $tools_mock->redefine(
+ run_fork_with_timeout => sub($limit, @rest) {
+ push @limits, $limit;
+ return $fork->($limit == 10 ? 1 : $limit, @rest);
+ },
+ );
+ my $marker = "$dir/marker";
+ $nvme_mock->redefine(
+ _fabrics_connect => sub(@args) {
+ sleep(2);
+ open(my $fh, '>', $marker) or die "cannot create '$marker': $!\n";
+ close($fh);
+ return 7;
+ },
+ );
+ my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+ eval { nv('_connect_portal', scfg(), $portal, $hostnqn_a, $UUID, $KEY) };
+ is($@, "NVMe/TCP connect did not complete within 10 seconds\n", 'the caller gives up');
+ is_deeply(\@limits, [10], 'at the limit that it passes to with_lock');
+ open(my $lock, '>>', "$dir/fabrics.lock") or die "cannot open the lock file: $!\n";
+ ok(flock($lock, LOCK_EX | LOCK_NB), 'and the host lock is free at once');
+ close($lock);
+ sleep(2);
+ ok(!-e $marker, 'as the connect was stopped and not left to run to its end');
+ $tools_mock->unmock('run_fork_with_timeout');
+ $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+ $nvmeof_mock->redefine(with_lock => $lock_inline);
+};
+
+# The body of the connect child, inline. A pseudoterminal stands in for the fabrics device, a
+# character device that answers reads with the lines the test writes to the master.
+subtest 'the connect child body' => sub {
+ my $body = $nvme_mock->original('_fabrics_connect');
+ my $portal = { address => '192.0.2.21', port => 4420, host_iface => 'ens19' };
+ my ($options, $names) = nv('_fabrics_options', scfg(), $portal, $hostnqn_a, $UUID, $KEY);
+ my $tokens = sub(@names) {
+ return join(',', map { "$_=%s" } @names) . "\n";
+ };
+ # a body that waits for a line the test did not write must not hang the suite
+ local $SIG{ALRM} = sub { die "the child body did not finish\n" };
+ my $run = sub() {
+ @RESTRICTED = ();
+ alarm(30);
+ my $res = eval { $body->($options, $names) };
+ alarm(0);
+ return ($res, $@);
+ };
+ my $dir = tempdir(CLEANUP => 1);
+ my $file = "$dir/file";
+ open(my $fh, '>', $file) or die "cannot create '$file': $!\n";
+ close($fh);
+ for my $case (
+ [
+ 'a missing device',
+ "$dir/missing",
+ qr/\A'\Q$dir\E\/missing' does not exist; load the nvme-tcp kernel module\n\z/,
+ ],
+ ['a regular file', $file, qr/\A'\Q$file\E' is not a character device\n\z/],
+ [
+ 'a device without the option list',
+ '/dev/null',
+ qr/\Athe running kernel does not support the NVMe connect option 'transport'\n\z/,
+ ],
+ ) {
+ my ($name, $device, $expected) = $case->@*;
+ $nvme_mock->redefine(_fabrics_device => sub () { return $device });
+ my (undef, $error) = $run->();
+ like($error, $expected, "$name is refused");
+ unlike($error, qr/\Q$KEY\E/, 'without the key in the error');
+ }
+ is(-s $file, 0, 'and nothing is written before the device is checked');
+
+ my $pty = sub() {
+ # TIOCSPTLCK and TIOCGPTN are only known for these architectures
+ return if $Config{archname} !~ m/\A(?:x86_64|i[3-6]86|aarch64|arm|riscv64)-linux/;
+ sysopen(my $master, '/dev/ptmx', O_RDWR | O_NOCTTY) or return;
+ my $zero = pack('i', 0);
+ ioctl($master, 0x40045431, $zero) or return;
+ my $number = pack('i', 0);
+ ioctl($master, 0x80045430, $number) or return;
+ my $slave = '/dev/pts/' . unpack('i', $number);
+ # keeps the line discipline: canonical reads, no echo, no translation
+ sysopen(my $keep, $slave, O_RDWR | O_NOCTTY) or return;
+ my $termios = POSIX::Termios->new();
+ $termios->getattr(fileno($keep)) or die "tcgetattr: $!\n";
+ $termios->setlflag(($termios->getlflag() & ~(ECHO | ECHONL)) | ICANON);
+ $termios->setoflag($termios->getoflag() & ~OPOST);
+ $termios->setattr(fileno($keep), TCSANOW) or die "tcsetattr: $!\n";
+ return ($master, $slave, $keep);
+ };
+ my $received = sub($master) {
+ my $readable = '';
+ vec($readable, fileno($master), 1) = 1;
+ return '' if !select($readable, undef, undef, 0.1);
+ sysread($master, my $buffer, 65536) // die "cannot read the pseudoterminal: $!\n";
+ return $buffer;
+ };
+ my ($master, $slave, $keep) = $pty->();
+ SKIP: {
+ skip 'no pseudoterminal available', 25 if !$master;
+ $nvme_mock->redefine(_fabrics_device => sub () { return $slave });
+
+ my ($res, $error);
+ for my $instance (3, 12) {
+ syswrite($master, $tokens->($names->@*, 'tls'));
+ syswrite($master, "instance=$instance,cntlid=1\n");
+ ($res, $error) = $run->();
+ is($error, '', "a connect (instance $instance)");
+ is($res, $instance, 'returns the instance of the controller');
+ is($received->($master), $options, 'after exactly one write of the options');
+ my $attrs = "/sys/class/nvme/nvme$instance";
+ is_deeply(
+ \@RESTRICTED,
+ ["$attrs/dhchap_secret", "$attrs/dhchap_ctrl_secret"],
+ 'and restricts the secret attributes of that controller',
+ );
+ }
+
+ for my $missing (qw(host_iface nqn)) {
+ syswrite($master,
+ $tokens->(map { $_ eq $missing ? "${_}_suffix" : $_ } $names->@*));
+ ($res, $error) = $run->();
+ is(
+ $error,
+ "the running kernel does not support the NVMe connect option '$missing'\n",
+ "an option the kernel does not list ($missing)",
+ );
+ is($received->($master), '', 'is found before anything is written');
+ }
+
+ for my $result ("garbage\n", "instance=3,cntlid=1,garbage\n") {
+ syswrite($master, $tokens->($names->@*));
+ syswrite($master, $result);
+ ($res, $error) = $run->();
+ is($error, "unexpected connect result\n", 'an unexpected result is refused');
+ is($received->($master), $options, 'after the one write');
+ is_deeply(\@RESTRICTED, [], 'and nothing is restricted');
+ }
+
+ symlink($slave, "$dir/link") or die "symlink: $!\n";
+ $nvme_mock->redefine(_fabrics_device => sub () { return "$dir/link" });
+ ($res, $error) = $run->();
+ is(
+ $error,
+ "cannot open '$dir/link': Too many levels of symbolic links\n",
+ 'a symbolic link to the device is not followed',
+ );
+ $nvme_mock->redefine(_fabrics_device => sub () { return $slave });
+
+ # A failed write: the error has the errno text and never the options.
+ my $writes = 0;
+ $nvme_mock->redefine(
+ _fabrics_write => sub($fh, $data) { $writes++; $! = ECONNREFUSED; return undef },
+ );
+ syswrite($master, $tokens->($names->@*));
+ ($res, $error) = $run->();
+ is(
+ $error,
+ "connect failed: Connection refused\n",
+ 'a refused connect has the errno text',
+ );
+ is($writes, 1, 'after one write, which is not repeated');
+ is_deeply(\@RESTRICTED, [], 'and nothing is restricted');
+ $writes = 0;
+ $nvme_mock->redefine(
+ _fabrics_write => sub($fh, $data) { $writes++; return length($data) - 1 });
+ syswrite($master, $tokens->($names->@*));
+ syswrite($master, "instance=3,cntlid=1\n"); # never read: a short write ends the connect
+ ($res, $error) = $run->();
+ is($error, "connect failed: short write\n", 'a short write');
+ is($writes, 1, 'is not completed');
+ is_deeply(\@RESTRICTED, [], 'and restricts nothing');
+ $nvme_mock->unmock('_fabrics_write');
+ }
+ $nvme_mock->unmock('_fabrics_device');
+};
+
+# no namespace of the subsystem on this node, unless a test says otherwise
+my $no_namespaces = sub($nqn) { return {} };
+$nvmeof_mock->redefine(namespaces => $no_namespaces);
+
+{
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ add_controller('nvme3', '192.0.2.23', 4420, 'ens21', 'live', $OTHER_NQN);
+ my $opened = "process 123 (qemu-system-x86_64) has namespace 'nvme0n1' open";
+ $nvme_mock->redefine(_namespace_users => sub($nqn) { return [$opened] });
+ eval { $PLUGIN->deactivate_storage('nvmetest', scfg()) };
+ is(
+ $@,
+ "refusing to disconnect NVMe storage 'nvmetest': $opened\n",
+ 'deactivation refuses a namespace opened by a VM',
+ );
+ is_deeply(\@DELETED, [], 'and deletes nothing');
+ $nvme_mock->redefine(_namespace_users => sub($nqn) { return [] });
+ is($PLUGIN->deactivate_storage('nvmetest', scfg()), 1, 'an unused storage is deactivated');
+ is_deeply(\@DELETED, ['nvme1', 'nvme2'], 'by deleting the controllers of its subsystem');
+ is_deeply(\@FORKS, [25], 'in one child bounded by 15 seconds and 10 for the host lock');
+ is_deeply($DIRS{'/sys/class/nvme'}, ['nvme3'], 'the controllers of other subsystems stay');
+ is($PLUGIN->deactivate_storage('nvmetest', scfg()), 1, 'a storage without controllers');
+ is_deeply(\@FORKS, [25], 'needs no child');
+ $nvme_mock->unmock('_namespace_users');
+
+ my $delete = $nvme_mock->original('_delete_controllers');
+ @SYSFS_WRITES = ();
+ is($delete->([{ name => 'nvme1' }, { name => 'nvme2' }]), 2, 'the child deletes each one');
+ is_deeply(
+ \@SYSFS_WRITES,
+ [map { ["/sys/class/nvme/$_/delete_controller", '1'] } qw(nvme1 nvme2)],
+ 'through sysfs',
+ );
+ # the stock file_write: a failed write warns with the errno text, a failed open does not
+ my $file_write = $sysfs_mock->original('file_write');
+ my $dir = tempdir(CLEANUP => 1);
+ my @warnings;
+ local $SIG{__WARN__} = sub($warning) { push @warnings, $warning };
+ for my $case (['/dev/full', 'No space left on device'], [$dir, 'Is a directory']) {
+ my ($path, $reason) = $case->@*;
+ $sysfs_mock->redefine(file_write => sub($file, @args) { $file_write->($path, @args) });
+ eval { $delete->([{ name => 'nvme1' }, { name => 'nvme2' }]) };
+ is(
+ $@,
+ "cannot delete NVMe controller 'nvme1': $reason\n",
+ "a failed delete names the controller and the errno text ($reason)",
+ );
+ }
+ $sysfs_mock->redefine(file_write => sub($file, @args) { $file_write->("$dir/a/b", @args) });
+ is(
+ $delete->([{ name => 'nvme1' }, { name => 'nvme2' }]),
+ 2,
+ 'a controller that went away since it was listed counts as deleted',
+ );
+ $sysfs_mock->redefine(
+ file_write => sub($path, $data, @rest) {
+ warn "error writing '$data' to '$path': Device or resource busy\n";
+ $! = 0;
+ return 0;
+ },
+ );
+ eval { $delete->([{ name => 'nvme1' }]) };
+ is(
+ $@,
+ "cannot delete NVMe controller 'nvme1': Device or resource busy\n",
+ 'the errno text of a failed write is the one of the warning',
+ );
+ is_deeply(\@warnings, [], 'which is not passed on');
+ $sysfs_mock->redefine(file_write => $sysfs_write);
+}
+
+# What keeps a namespace from going away comes from the helpers of PVE::Diskmanage and PVE::NVMeOF,
+# as in disconnect_guarded. They are mocked here, so each case sets what one device answers.
+subtest 'users of the namespaces' => sub {
+ my $disk_mock = Test::MockModule->new('PVE::Diskmanage');
+ my (@heads, @asked, @claims, %mounted, %held, %claimed, %opener, %partitions);
+ $nvmeof_mock->redefine(
+ namespaces => sub($nqn) {
+ die "test error: namespaces of '$nqn'\n" if $nqn ne $NQN;
+ return { map { $_ => {} } @heads };
+ },
+ );
+ $nvmeof_mock->redefine(
+ is_claimed => sub($device) {
+ push @claims, $device;
+ return $claimed{$device};
+ },
+ );
+ $disk_mock->redefine(is_mounted => sub($device) { return $mounted{$device} });
+ $disk_mock->redefine(has_holder => sub($device) { return $held{$device} });
+ $disk_mock->redefine(
+ device_opener => sub(@devices) {
+ push @asked, [@devices];
+ return shift(($opener{ $devices[0] } //= [])->@*); # one answer for each try
+ },
+ );
+ $nvme_mock->redefine(
+ _partitions => sub($device) { return ($partitions{$device} // [])->@* });
+ my $reset = sub(@names) {
+ @heads = @names;
+ @asked = @claims = ();
+ %mounted = %held = %claimed = %opener = %partitions = ();
+ reset_host();
+ };
+
+ $reset->();
+ is_deeply(nv('_namespace_users', $NQN), [], 'no namespace, no users');
+ is_deeply([\@claims, \@asked], [[], []], 'and nothing is asked');
+
+ $reset->('nvme7n1');
+ $partitions{'/dev/nvme7n1'} = ['/dev/nvme7n1p1', '/dev/nvme7n1p2'];
+ is_deeply(nv('_namespace_users', $NQN), [], 'a namespace that nothing uses');
+ is_deeply(
+ \@claims,
+ ['/dev/nvme7n1', '/dev/nvme7n1p1', '/dev/nvme7n1p2'],
+ 'is checked for a claim on the namespace and on each partition',
+ );
+ is_deeply(
+ \@asked,
+ [['/dev/nvme7n1', '/dev/nvme7n1p1', '/dev/nvme7n1p2']],
+ 'and for openers of all three at once',
+ );
+
+ $reset->('nvme7n1');
+ $mounted{'/dev/nvme7n1'} = '/dev/nvme7n1p1';
+ is_deeply(
+ nv('_namespace_users', $NQN),
+ ["'/dev/nvme7n1p1' is mounted"],
+ 'a mounted partition is a user',
+ );
+ is_deeply([\@claims, \@asked], [[], []], 'which ends the check of the namespace');
+
+ $reset->('nvme7n1');
+ $held{'/dev/nvme7n1'} = '/dev/nvme7n1p2';
+ is_deeply(
+ nv('_namespace_users', $NQN),
+ ["'/dev/nvme7n1p2' has a holder"],
+ 'so is a partition with a holder, like a volume group',
+ );
+
+ # a swap area claims the device like a mount, and is neither mounted nor held
+ $reset->('nvme7n1');
+ $partitions{'/dev/nvme7n1'} = ['/dev/nvme7n1p1'];
+ $claimed{'/dev/nvme7n1p1'} = 1;
+ is_deeply(
+ nv('_namespace_users', $NQN),
+ ["'/dev/nvme7n1p1' is claimed, for example by a swap area"],
+ 'a partition that is claimed, which is how a swap area looks',
+ );
+ is_deeply(\@asked, [], 'before anyone looks for openers');
+
+ $reset->('nvme7n1');
+ my $before = $NOW;
+ $partitions{'/dev/nvme7n1'} = ['/dev/nvme7n1p1'];
+ $opener{'/dev/nvme7n1'} = [('200 (mkfs.ext4)') x 5];
+ is_deeply(
+ nv('_namespace_users', $NQN),
+ ["process 200 (mkfs.ext4) has namespace 'nvme7n1' open"],
+ 'a process that keeps a partition open is a user',
+ );
+ is(scalar(@asked), 4, 'after four tries');
+ is(sprintf('%.1f', $NOW - $before), '0.9', 'with 0.3 seconds between them');
+
+ $reset->('nvme7n1');
+ $opener{'/dev/nvme7n1'} = ['4 (udevd)'];
+ is_deeply(nv('_namespace_users', $NQN), [], 'a process that lets go meanwhile is not');
+ is(scalar(@asked), 2, 'after the second try');
+
+ $reset->('nvme7n2', 'nvme7n1');
+ $mounted{'/dev/nvme7n2'} = '/dev/nvme7n2';
+ is_deeply(
+ nv('_namespace_users', $NQN),
+ ["'/dev/nvme7n2' is mounted"],
+ 'of two namespaces only the one in use is named',
+ );
+ is_deeply(\@asked, [['/dev/nvme7n1']], 'while the other one was checked');
+
+ # a namespace that cannot be read must not look like one that is gone
+ $nvmeof_mock->redefine(
+ namespaces => sub($nqn) { die "cannot read the WWID of namespace 'nvme7n1'\n" },
+ );
+ $reset->();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ eval { $PLUGIN->deactivate_storage('nvmetest', scfg()) };
+ is($@, "cannot read the WWID of namespace 'nvme7n1'\n", 'the deactivation fails with it');
+ is_deeply(\@DELETED, [], 'and deletes nothing');
+
+ # the whole deactivation on top of the real check
+ $nvmeof_mock->redefine(namespaces => sub($nqn) { return { nvme7n1 => {} } });
+ $mounted{'/dev/nvme7n1'} = '/dev/nvme7n1p1';
+ eval { $PLUGIN->deactivate_storage('nvmetest', scfg()) };
+ is(
+ $@,
+ "refusing to disconnect NVMe storage 'nvmetest': '/dev/nvme7n1p1' is mounted\n",
+ 'a deactivation refuses a mounted partition',
+ );
+ is_deeply(\@DELETED, [], 'and deletes nothing');
+ delete $mounted{'/dev/nvme7n1'};
+ is($PLUGIN->deactivate_storage('nvmetest', scfg()), 1, 'and goes ahead once it is free');
+ is_deeply(\@DELETED, ['nvme1'], 'by deleting the controller');
+
+ $nvmeof_mock->redefine(namespaces => $no_namespaces);
+ $nvmeof_mock->unmock('is_claimed');
+ $nvme_mock->unmock('_partitions');
+};
+
+{
+ my $link = "/dev/disk/by-id/nvme-uuid.$UUID";
+ my $check = sub($target, %files) {
+ local %LINKS = (defined($target) ? ($link => $target) : ());
+ local %FILES = (
+ '/sys/block/nvme3n1/uuid' => uc($UUID),
+ '/sys/block/nvme3n1/nsid' => '7',
+ '/sys/block/nvme3n1/device/subsysnqn' => $NQN,
+ %files,
+ );
+ my $ok = nv('_nvmet_local_namespace_ok', $link, $NQN, 7, $UUID);
+ return $ok ? 1 : 0;
+ };
+ my $device = '../../nvme3n1';
+ is($check->($device), 1, 'accepts the namespace of the subsystem, whatever the UUID case');
+ is($check->($device, '/sys/block/nvme3n1/nsid' => '8'), 0, 'refuses another NSID');
+ is(
+ $check->($device, '/sys/block/nvme3n1/device/subsysnqn' => $OTHER_NQN),
+ 0,
+ 'another subsystem',
+ );
+ is(
+ $check->($device, '/sys/block/nvme3n1/uuid' => '22345678-1234-1234-1234-123456789abc'),
+ 0,
+ 'another UUID',
+ );
+ is($check->($device, '/sys/block/nvme3n1/uuid' => undef), 0, 'an unreadable device');
+ is($check->(undef), 0, 'a missing link');
+
+ for my $target ('../../nvme3c1n1', '../../nvme3n1p1', '../../sda') {
+ is($check->($target), 0, "a link to $target");
+ }
+
+ my $dir = tempdir(CLEANUP => 1);
+ symlink('../../nvme3n1', "$dir/link") or die "symlink: $!\n";
+ is($nvme_mock->original('_link_target')->("$dir/link"), '../../nvme3n1', 'read, not followed');
+}
+
+my $activate = sub($storeid, $scfg, $cache = undef) {
+ local $FILES{"/etc/pve/priv/storage/$storeid.nvme-dhchap"} = $KEY;
+ local %CONFIG = (%CONFIG, $storeid => $scfg);
+ @ACTIVATIONS = ();
+ $nvme_mock->redefine(
+ _nvmet_activate_target => sub(@args) { push @ACTIVATIONS, [@args]; return },
+ );
+ my $res = eval { $PLUGIN->activate_storage($storeid, $scfg, $cache) };
+ my $error = $@;
+ $nvme_mock->unmock('_nvmet_activate_target');
+ return ($res, $error);
+};
+my $forced = sub($storeid) { return { 'zfsnvme-force-reconcile' => { $storeid => 1 } } };
+
+subtest 'activation preconditions' => sub {
+ my $file = sub($path, $value) {
+ return sub() { $FILES{$path} = $value }
+ };
+ my $missing_iface = sub() {
+ $nvme_mock->redefine(_local_iface_exists => sub($iface) { return $iface ne 'ens20' });
+ };
+ my $other_storage = sub(%override) {
+ return sub() { $CONFIG{other} = scfg(subsysnqn => $OTHER_NQN, %override) };
+ };
+ my $fabrics_injection = 'traddr=198.51.100.9';
+ for my $case (
+ [
+ 'a kernel without native NVMe multipath',
+ $file->('/sys/module/nvme_core/parameters/multipath', undef),
+ qr/native NVMe multipath is disabled/,
+ ],
+ [
+ 'multipath disabled',
+ $file->('/sys/module/nvme_core/parameters/multipath', 'N'),
+ qr/native NVMe multipath is disabled/,
+ ],
+ [
+ 'no host NQN',
+ $file->('/etc/nvme/hostnqn', undef),
+ qr/invalid or missing NVMe host NQN in '\/etc\/nvme\/hostnqn'/,
+ ],
+ [
+ 'a host NQN with a connect option',
+ $file->('/etc/nvme/hostnqn', "$hostnqn_a,$fabrics_injection"),
+ qr/invalid or missing NVMe host NQN in '\/etc\/nvme\/hostnqn'/,
+ ],
+ [
+ 'a host that is not allowed',
+ $file->(
+ '/etc/nvme/hostnqn',
+ 'nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-00000000dead',
+ ),
+ qr/local NVMe host NQN .* is missing from nvme-host-nqns/,
+ ],
+ [
+ 'no host ID',
+ $file->('/etc/nvme/hostid', undef),
+ qr/invalid or missing NVMe host ID in '\/etc\/nvme\/hostid'/,
+ ],
+ [
+ 'the zero host ID',
+ $file->('/etc/nvme/hostid', '00000000-0000-0000-0000-000000000000'),
+ qr/invalid or missing NVMe host ID in '\/etc\/nvme\/hostid'/,
+ ],
+ [
+ 'a host ID with a connect option',
+ $file->('/etc/nvme/hostid', "$UUID,$fabrics_injection"),
+ qr/invalid or missing NVMe host ID in '\/etc\/nvme\/hostid'/,
+ ],
+ [
+ 'a host ID with a newline',
+ $file->('/etc/nvme/hostid', "$UUID\n"),
+ qr/invalid or missing NVMe host ID in '\/etc\/nvme\/hostid'/,
+ ],
+ [
+ 'a connection parameter that is not a number',
+ sub() { },
+ qr/invalid NVMe connection parameter 'reconnect-delay'/,
+ 'nvme-reconnect-delay' => "2,$fabrics_injection",
+ ],
+ [
+ 'a missing local interface',
+ $missing_iface,
+ qr/interface 'ens20' does not exist on this node/,
+ ],
+ [
+ 'a pool shared with another storage',
+ $other_storage->('nvme-portals' => '192.0.2.31,192.0.2.32'),
+ qr/ZFS pool 'tank' on '192\.0\.2\.10' is already used by storage 'other'/,
+ ],
+ [
+ 'a listener shared with another storage',
+ $other_storage->(pool => 'data', 'nvme-portals' => '192.0.2.31,192.0.2.22'),
+ qr/portal '192\.0\.2\.22' port 4420 is already used by storage 'other'/,
+ ],
+ ) {
+ my ($name, $setup, $error, %override) = $case->@*;
+ reset_host();
+ local %CONFIG = ();
+ $nvme_mock->redefine(_local_iface_exists => sub($iface) { return 1 });
+ $setup->();
+ my (undef, $got) = $activate->('zfsnvme-unit-s', scfg(%override));
+ like($got, $error, "refuses $name");
+ is_deeply([@ACTIVATIONS, @CONNECTS, @SYSFS_WRITES], [], 'and does nothing');
+ }
+ $nvme_mock->redefine(_local_iface_exists => sub($iface) { return 1 });
+};
+
+# As PVE::NVMeOF does, so that a node without local NVMe disks can use the storage after a reboot
+subtest 'loading the nvme-tcp module' => sub {
+ my $multipath = '/sys/module/nvme_core/parameters/multipath';
+ my @commands;
+ local $COMMAND = sub($cmd, %opts) {
+ push @commands, [$cmd, $opts{timeout}];
+ return 0;
+ };
+ reset_host();
+ my (undef, $err) = $activate->('zfsnvme-module', scfg());
+ is($err, '', 'a node that has the module activates the storage');
+ is_deeply(\@commands, [], 'without a command');
+
+ reset_host();
+ $TCP_LOADED = 0;
+ delete $FILES{$multipath}; # the module brings nvme_core with it
+ local $COMMAND = sub($cmd, %opts) {
+ push @commands, [$cmd, $opts{timeout}];
+ $FILES{$multipath} = 'Y';
+ return 0;
+ };
+ (undef, $err) = $activate->('zfsnvme-module', scfg());
+ is($err, '', 'a node without it loads it and activates the storage');
+ is_deeply(
+ \@commands,
+ [[['modprobe', 'nvme-tcp'], 10]],
+ 'with modprobe, for 10 seconds at most',
+ );
+
+ reset_host();
+ $TCP_LOADED = 0;
+ @commands = ();
+ local $COMMAND =
+ sub($cmd, %opts) { die "command 'modprobe nvme-tcp' failed: exit code 1\n" };
+ (undef, $err) = $activate->('zfsnvme-module', scfg());
+ is($err, "command 'modprobe nvme-tcp' failed: exit code 1\n",
+ 'a module that does not load');
+ is_deeply([@ACTIVATIONS, @CONNECTS, @SYSFS_WRITES], [], 'fails before anything is done');
+
+ reset_host();
+ $TCP_LOADED = 0;
+ local $COMMAND = sub($cmd, %opts) { return 0 };
+ $FILES{$multipath} = 'N';
+ (undef, $err) = $activate->('zfsnvme-module', scfg());
+ like($err, qr/native NVMe multipath is disabled/,
+ 'a kernel with multipath off still fails');
+};
+
+subtest 'a stopped task ends the activation at the connect' => sub {
+ for my $case (
+ ["received interrupt\n", 1],
+ ["interrupted by unexpected signal\n", 1],
+ ["connect failed: Connection refused\n", 0],
+ ["NVMe/TCP connect did not complete within 10 seconds\n", 0],
+ ) {
+ my ($exception, $cancelled) = $case->@*;
+ reset_host();
+ my $calls = 0;
+ $nvme_mock->redefine(
+ _fabrics_connect => sub($options, $names) {
+ my %option = map { split(/=/, $_, 2) } split(/,/, $options);
+ ++$calls;
+ # cancellation must escape even if the write created a live path
+ add_controller("nvme$calls", $option{traddr}, 4420, $option{host_iface})
+ if $cancelled || $calls > 1;
+ die $exception if $calls == 1;
+ return $calls;
+ },
+ );
+ my ($res, $err) = $activate->('zfsnvme-cancel', scfg());
+ is($err, $cancelled ? "received interrupt\n" : '', 'only a stopped task escapes');
+ is($res, $cancelled ? undef : 1, 'an ordinary failure still permits a degraded path');
+ is($calls, $cancelled ? 1 : 2, 'a stopped task never attempts the next portal');
+ unlike($err . join('', @WARNINGS), qr/\Q$KEY\E/, 'errors and warnings hide the key');
+ }
+ $nvme_mock->redefine(_fabrics_connect => $connect_mock);
+
+ reset_host();
+ no warnings 'redefine';
+ local *PVE::Storage::ZFSNVMePlugin::_restrict_attr =
+ sub($path) { die "received interrupt\n" };
+ my ($res, $err) = $activate->('zfsnvme-cancel-scan', scfg());
+ is($err, "received interrupt\n",
+ 'cancellation in the post-connect permission scan escapes');
+ is(scalar(@CONNECTS), 1, 'no next portal after a cancelled permission scan');
+};
+
+# A dead path is deleted in a bounded child, 5 seconds during an activation, which goes on, and 15
+# for a deactivation, which fails. Each gets 10 more seconds for the host lock. Only a stopped task
+# escapes an activation.
+subtest 'deleting a controller is bounded and keeps a stopped task' => sub {
+ my $interrupt = "received interrupt\n";
+ my $failed = "cannot delete NVMe controller 'nvme1'\n";
+ # [label, what the child does, activation error, deactivation error]
+ for my $case (
+ ['a stopped task', $interrupt, $interrupt, $interrupt],
+ ['a signalled child', "interrupted by unexpected signal\n", $interrupt, $interrupt],
+ ['a failed deletion', $failed, '', $failed],
+ [
+ 'a timeout',
+ undef,
+ '',
+ "disconnecting NVMe subsystem '$NQN' did not complete within 25 seconds\n",
+ ],
+ ) {
+ my ($label, $exception, $activation_error, $deactivation_error) = $case->@*;
+ $nvmeof_mock->redefine(
+ with_lock => sub($code, $limit = undef) {
+ # without an exception, the deletion times out
+ if (!defined($exception) && $limit != 20) {
+ push @FORKS, $limit;
+ die $PVE::NVMeOF::TIMED_OUT;
+ }
+ return $lock_inline->($code, $limit);
+ },
+ );
+ $nvme_mock->redefine(_delete_controllers => sub($controllers) { die $exception })
+ if defined($exception);
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+ my ($res, $err) = $activate->('zfsnvme-delete', scfg());
+ is($err, $activation_error, "$label while a dead path is deleted");
+ is($FORKS[0], 15, 'in a child bounded by 5 seconds and 10 for the host lock');
+ is(scalar(@CONNECTS), $activation_error ? 0 : 2, 'only a failure goes on to connect');
+ my $warned = $exception
+ // "deleting NVMe controller 'nvme1' did not complete within 15 seconds\n";
+ like(join("\n", @WARNINGS), qr/\Q$warned\E/, 'and is warned about')
+ if !$activation_error;
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ eval { $PLUGIN->deactivate_storage('zfsnvme-delete', scfg()) };
+ is($@, $deactivation_error, "$label fails the deactivation");
+ is_deeply(\@FORKS, [25], 'in a child bounded by 15 seconds and 10 for the host lock');
+ $nvme_mock->redefine(_delete_controllers => $delete_mock);
+ }
+ $nvmeof_mock->redefine(with_lock => $lock_inline);
+};
+
+# connecting and deleting controllers take the host lock one at a time, never twice
+subtest 'the host lock of the controllers' => sub {
+ my $busy = "NVMe over Fabrics is busy - another operation is still running\n";
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+ my ($res, $err) = $activate->('zfsnvme-lock', scfg());
+ is($err, '', 'an activation that replaces a dead path and adds one');
+ is_deeply(
+ \@LOCKS,
+ [('enter', 'leave') x 3],
+ 'takes the lock for the deletion and for each connect, one after the other',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+ $LOCK_BUSY = 1;
+ ($res, $err) = $activate->('zfsnvme-lock', scfg());
+ like(
+ $err,
+ qr/^no live NVMe\/TCP path for storage 'zfsnvme-lock'/,
+ 'a busy lock leaves an activation without a live path to fail',
+ );
+ is_deeply([\@DELETED, \@CONNECTS], [[], []], 'after it deleted and connected nothing');
+ like(join("\n", @WARNINGS), qr/\Q$busy\E/, 'and warned about the lock');
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ $LOCK_BUSY = 1;
+ eval { $PLUGIN->deactivate_storage('zfsnvme-lock', scfg()) };
+ is($@, $busy, 'a busy lock fails the deactivation');
+ is_deeply(\@DELETED, [], 'which keeps the controllers');
+ $LOCK_BUSY = 0;
+ is($PLUGIN->deactivate_storage('zfsnvme-lock', scfg()), 1, 'and succeeds when it is free');
+ is_deeply(\@LOCKS, ['enter', 'leave'], 'under the lock');
+
+ # Another activation connects the second portal after this one checked its controllers.
+ reset_host();
+ my $meanwhile;
+ $network_mock->redefine(
+ tcp_ping => sub($host, $port, $timeout = undef) {
+ add_controller('nvme9', $host, $port, 'ens20')
+ if $host eq '192.0.2.22' && !$meanwhile++;
+ return 1;
+ },
+ );
+ ($res, $err) = $activate->('zfsnvme-lock', scfg());
+ is($err, '', 'an activation whose portal got a controller meanwhile succeeds');
+ is_deeply(\@CONNECTS, ['192.0.2.21@ens19'], 'and does not connect that portal twice');
+ $network_mock->redefine(tcp_ping => sub($host, $port, $timeout = undef) { return 1 });
+};
+
+# The kernel reuses the name of a controller that is gone, and another process can run while this
+# one waits for the host lock. So a delete looks at the controller again once it has the lock, and
+# a deactivation lists the controllers there. $ON_LOCK runs when the lock is taken for the nth time.
+subtest 'controllers are checked again under the host lock' => sub {
+ my $path = '/sys/class/nvme/nvme1';
+ my $other_subsystem = sub() { $FILES{"$path/subsysnqn"} = $OTHER_NQN };
+ my $live_again = sub() { $FILES{"$path/state"} = 'live' };
+ my $other_address = sub() {
+ $FILES{"$path/address"} = 'traddr=192.0.2.23,trsvcid=4420,host_iface=ens19';
+ };
+ my $dead = ['dead', 'ens19'];
+ my $moved = ['live', 'ens20'];
+ # [label, state and interface of the controller, change, nth lock, deleted, connects]
+ for my $case (
+ ['dead, unchanged', $dead, sub() { }, 1, ['nvme1'], 2],
+ ['dead, name reused by another subsystem', $dead, $other_subsystem, 1, [], 2],
+ ['dead, then live again', $dead, $live_again, 1, [], 1],
+ ['dead, name reused with another address', $dead, $other_address, 1, [], 2],
+ ['moved, unchanged', $moved, sub() { }, 2, ['nvme1'], 2],
+ ['moved, name reused by another subsystem', $moved, $other_subsystem, 2, [], 2],
+ ) {
+ my ($label, $controller, $change, $nth, $deleted, $connects) = $case->@*;
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, $controller->[1], $controller->[0]);
+ local $ON_LOCK = sub($entry) { $change->() if $entry == $nth };
+ my ($res, $err) = $activate->('zfsnvme-recheck', scfg());
+ is($err, '', "$label: the activation succeeds");
+ is_deeply(\@DELETED, $deleted, 'and deletes what it found, not what the name is now');
+ is(scalar(@CONNECTS), $connects, 'and connects the portals that need it');
+ }
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'dead');
+ local $ON_LOCK = sub($entry) { $other_subsystem->() };
+ $activate->('zfsnvme-recheck', scfg());
+ is(
+ $FILES{"$path/subsysnqn"},
+ $OTHER_NQN,
+ 'the controller of the other subsystem is left alone',
+ );
+ is_deeply($DIRS{'/sys/class/nvme'}, ['nvme1', 'nvme71', 'nvme72'], 'and still there');
+
+ # the list of a deactivation is the one under the lock
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ local $ON_LOCK = sub($entry) {
+ $other_subsystem->();
+ add_controller('nvme4', '192.0.2.21', 4420, 'ens20');
+ };
+ is($PLUGIN->deactivate_storage('zfsnvme-recheck', scfg()), 1, 'a deactivation succeeds');
+ is_deeply(
+ \@DELETED,
+ ['nvme2', 'nvme4'],
+ 'and deletes the controllers of the subsystem then',
+ );
+ is(
+ $FILES{"$path/subsysnqn"},
+ $OTHER_NQN,
+ 'not the one that got another subsystem meanwhile',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ local $ON_LOCK = sub($entry) { $DIRS{'/sys/class/nvme'} = [] };
+ is($PLUGIN->deactivate_storage('zfsnvme-recheck', scfg()), 1, 'and one without any left');
+ is_deeply(\@DELETED, [], 'deletes none');
+};
+
+# the core runs the hook inside the storage.cfg lock of the cluster
+subtest 'deleting a storage only touches local files' => sub {
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ @TARGET_CALLS = ();
+ $PLUGIN->on_delete_hook('zfsnvme-delete', scfg());
+ is_deeply(
+ \@UNLINKED,
+ ['/etc/pve/priv/storage/zfsnvme-delete.nvme-dhchap'],
+ 'the key file is removed',
+ );
+ is_deeply(
+ [\@TARGET_CALLS, \@DELETED, \@SYSFS_WRITES, \@FORKS, \@LOCKS, \@WARNINGS],
+ [[], [], [], [], [], []],
+ 'and nothing else: no target call, no lock, the controllers stay connected',
+ );
+};
+
+subtest 'slow-path backoff' => sub {
+ reset_host();
+ local %REFUSE = ('192.0.2.22' => 1);
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ my $scfg = scfg();
+ my ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is($error, '', 'a degraded storage activates');
+ is(scalar(@ACTIVATIONS), 1, 'through the target');
+ is_deeply(
+ [$ACTIVATIONS[0]->@[0, 2 .. 4]],
+ [
+ 'zfsnvme-unit-a',
+ [
+ map { {
+ family => 'ipv4',
+ address => "192.0.2.2$_",
+ port => 4420,
+ host_iface => 'ens' . (18 + $_),
+ } } 1,
+ 2,
+ ],
+ [$hostnqn_a, $hostnqn_b],
+ $KEY,
+ ],
+ 'with the storage, its parsed portals, hosts and key',
+ );
+ like(
+ join("\n", @WARNINGS),
+ qr/storage 'zfsnvme-unit-a' is degraded: 1\/2 paths live/,
+ 'and warns',
+ );
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is($error, '', 'within a minute, a live path takes the fast path');
+ is(scalar(@ACTIVATIONS), 0, 'without a target call');
+ {
+ local $NOW = $NOW + 61;
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is(scalar(@ACTIVATIONS), 1, 'a minute later the target is tried again');
+ }
+ my $cache = $forced->('zfsnvme-unit-a');
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg, $cache);
+ is(scalar(@ACTIVATIONS), 1, 'a forced activation always reaches the target');
+ ok(!$cache->{'zfsnvme-force-reconcile'}->{'zfsnvme-unit-a'}, 'and consumes the request');
+ $FILES{'/sys/class/nvme/nvme1/state'} = 'dead';
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is(
+ $error,
+ "no live NVMe/TCP path for storage 'zfsnvme-unit-a'\n",
+ 'within a minute, without a live path the activation fails at once',
+ );
+ is_deeply([@ACTIVATIONS, @DELETED], [], 'without a target call or a reconnect');
+ {
+ local $NOW = $NOW + 61;
+ ($res, $error) = $activate->('zfsnvme-unit-a', $scfg);
+ is(scalar(@ACTIVATIONS), 1, 'a minute later the target is tried');
+ is_deeply(\@DELETED, ['nvme1'], 'and the dead path is reconnected');
+ }
+
+ reset_host();
+ local %REFUSE = ('192.0.2.22' => 1);
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ local $NOW = 30; # the monotonic clock shortly after boot
+ ($res, $error) = $activate->('zfsnvme-unit-b', $scfg);
+ is(scalar(@ACTIVATIONS), 1, 'a storage that was never activated is not in its backoff');
+
+ # a storage without any path waits for one once per backoff period, not on every status update
+ reset_host();
+ local %REFUSE = ('192.0.2.21' => 1, '192.0.2.22' => 1);
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+ is($error, "no live NVMe/TCP path for storage 'zfsnvme-unit-d'\n", 'no path, no storage');
+ is_deeply(
+ [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+ [1, 2],
+ 'after the target and each portal',
+ );
+ @CONNECTS = ();
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+ is(
+ $error,
+ "no live NVMe/TCP path for storage 'zfsnvme-unit-d'\n",
+ 'within a minute it fails',
+ );
+ is_deeply([@ACTIVATIONS, @CONNECTS], [], 'at once, without a target call or a connect');
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg, $forced->('zfsnvme-unit-d'));
+ is_deeply(
+ [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+ [1, 2],
+ 'a forced activation tries again',
+ );
+ {
+ local $NOW = $NOW + 61;
+ @CONNECTS = ();
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+ is_deeply(
+ [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+ [1, 2],
+ 'so does one a minute later',
+ );
+ }
+
+ # Adding a storage activates it right away, and removes it again if that fails. A new storage
+ # with the same ID must not inherit the backoff of the one that was removed.
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+ is($error, "no live NVMe/TCP path for storage 'zfsnvme-unit-d'\n", 'in its backoff again');
+ $PLUGIN->on_delete_hook('zfsnvme-unit-d', $scfg);
+ @CONNECTS = ();
+ ($res, $error) = $activate->('zfsnvme-unit-d', $scfg);
+ is_deeply(
+ [scalar(@ACTIVATIONS), scalar(@CONNECTS)],
+ [1, 2],
+ 'after its removal, the same ID reaches the target and the portals again',
+ );
+
+ # A slow path whose target call fails starts the backoff as well.
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ local $FILES{'/etc/pve/priv/storage/zfsnvme-unit-t.nvme-dhchap'} = $KEY;
+ local %CONFIG = ('zfsnvme-unit-t' => $scfg);
+ my $calls = 0;
+ $nvme_mock->redefine(
+ _nvmet_activate_target => sub(@args) {
+ $calls++;
+ die "NVMe target '192.0.2.10' is unreachable: timeout\n";
+ },
+ );
+ eval { $PLUGIN->activate_storage('zfsnvme-unit-t', $scfg) };
+ like($@, qr/is unreachable/, 'an unreachable target fails the slow path');
+ eval { $PLUGIN->activate_storage('zfsnvme-unit-t', $scfg) };
+ is($@, '', 'within a minute the live path takes the fast path');
+ is($calls, 1, 'without another target call');
+ $nvme_mock->unmock('_nvmet_activate_target');
+};
+
+subtest 'connecting the paths' => sub {
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ $network_mock->redefine(
+ tcp_ping => sub($host, $port, $timeout = undef) { return $host ne '192.0.2.22' },
+ );
+ my (undef, $error) = $activate->('zfsnvme-unit-v', scfg(), $forced->('zfsnvme-unit-v'));
+ is_deeply(\@CONNECTS, [], 'an unreachable portal is not connected');
+ like(join("\n", @WARNINGS), qr/'192\.0\.2\.22:4420' is unreachable/, 'but warned about');
+ $network_mock->redefine(tcp_ping => sub($host, $port, $timeout = undef) { return 1 });
+
+ # After a target restart, the kernel reconnects its controllers itself.
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'connecting');
+ local %REFUSE = ('192.0.2.22' => 1);
+ my $sleeps = 0;
+ $nvme_mock->redefine(
+ _sleep => sub($seconds) {
+ $NOW += $seconds;
+ $FILES{'/sys/class/nvme/nvme1/state'} = 'live' if ++$sleeps == 3;
+ return;
+ },
+ );
+ (undef, $error) = $activate->('zfsnvme-unit-w', scfg());
+ is($error, '', 'an activation waits for a controller that reconnects');
+ is($sleeps, 3, 'until it is live');
+ $nvme_mock->redefine(_sleep => sub($seconds) { $NOW += $seconds; return });
+};
+
+subtest 'moving a path to its configured interface' => sub {
+ my $single = scfg('nvme-portals' => '192.0.2.21', 'nvme-host-ifaces' => 'ens19');
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+ my ($res, $error) = $activate->('zfsnvme-unit-c', scfg());
+ is($error, '', 'a storage whose only live path uses another interface');
+ is_deeply(\@CONNECTS, ['192.0.2.21@ens19', '192.0.2.22@ens20'], 'connects both paths');
+ is_deeply(\@DELETED, ['nvme1'], 'and then disconnects the old one');
+ is_deeply(\@WARNINGS, [], 'the storage is healthy');
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+ local %CONNECT_STATE = ('192.0.2.21' => 'connecting');
+ my $start = $NOW;
+ ($res, $error) = $activate->('zfsnvme-unit-g', $single);
+ is($error, '', 'a new path that does not become live');
+ is_deeply(\@DELETED, [], 'keeps the old path');
+ like(
+ join("\n", @WARNINGS),
+ qr/'192\.0\.2\.21:4420' is not live on 'ens19' yet; keeping its path on another interface/,
+ 'and warns',
+ );
+ like(join("\n", @WARNINGS), qr/is degraded: 0\/1 paths live/, 'the storage is degraded');
+ is($NOW - $start, 10, 'after waiting 10 seconds for the new path');
+ ($res, $error) = $activate->('zfsnvme-unit-g', $single);
+ ok(!$error && !@ACTIVATIONS, 'within a minute, the old path takes the fast path');
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+ local %REFUSE = ('192.0.2.21' => 1);
+ ($res, $error) = $activate->('zfsnvme-unit-h', $single);
+ is($error, '', 'a new path that cannot connect');
+ is_deeply(\@DELETED, [], 'keeps the old path too');
+ like(
+ join("\n", @WARNINGS),
+ qr/192\.0\.2\.21:4420: connect failed: Connection refused/,
+ 'and warns',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'eth9');
+ my $connect = $PLUGIN->can('_connect_portal');
+ {
+ no warnings 'redefine';
+ local %REFUSE = ();
+ local *PVE::Storage::ZFSNVMePlugin::_connect_portal = sub($scfg, $portal, @ids) {
+ $connect->($scfg, $portal, @ids);
+ die "connection failed after creation\n";
+ };
+ ($res, $error) = $activate->('zfsnvme-unit-h-partial', $single);
+ }
+ ok(!$error && $res == 1, 'a partially successful connect leaves the storage usable');
+ is($FILES{'/sys/class/nvme/nvme71/state'}, 'live', 'a live replacement was created');
+ is_deeply(\@DELETED, [], 'the connect error still preserves the old interface path');
+ like(
+ join("\n", @WARNINGS),
+ qr/192\.0\.2\.21:4420: connection failed after creation/,
+ 'and preserves the original connect warning',
+ );
+};
+
+subtest 'reconnect timeouts reach connected controllers' => sub {
+ my $sysfs = sub () {
+ return [
+ map { [$_->[0] =~ s{\A/sys/class/nvme/}{}r, $_->[1] =~ s/\n\z//r] }
+ grep { $_->[0] =~ m{\A/sys/class/nvme/} } @SYSFS_WRITES
+ ];
+ };
+ my $case = sub($storeid, $scfg, %current) {
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ for my $name (qw(nvme1 nvme2)) {
+ $FILES{"/sys/class/nvme/$name/$_"} = $current{$_} for keys %current;
+ }
+ my ($res, $error) = $activate->($storeid, $scfg, $forced->($storeid));
+ is($error, '', "activation of $storeid");
+ return $sysfs->();
+ };
+ my $timeouts = scfg(
+ 'nvme-reconnect-delay' => 5,
+ 'nvme-ctrl-loss-tmo' => 60,
+ 'nvme-fast-io-fail-tmo' => 10,
+ );
+ my $written = [
+ map { (
+ ["$_/reconnect_delay", 5], ["$_/ctrl_loss_tmo", 60], ["$_/fast_io_fail_tmo", 10],
+ ) } qw(nvme1 nvme2)
+ ];
+ is_deeply($case->('zfsnvme-unit-i', $timeouts), $written, 'changes reach every controller');
+ is_deeply(
+ [grep { $_->[0] =~ /iopolicy/ } @SYSFS_WRITES],
+ [['/sys/class/nvme-subsystem/nvme-subsys7/iopolicy', "round-robin\n"]],
+ 'with the multipath policy',
+ );
+ my %current = (reconnect_delay => '5', ctrl_loss_tmo => '60', fast_io_fail_tmo => '10');
+ is_deeply(
+ $case->('zfsnvme-unit-j', $timeouts, %current),
+ [],
+ 'unchanged ones are not written',
+ );
+ is_deeply(
+ $case->('zfsnvme-unit-k', scfg('nvme-ctrl-loss-tmo' => -1)),
+ [map { ["$_/ctrl_loss_tmo", -1] } qw(nvme1 nvme2)],
+ 'an infinite loss timeout',
+ );
+ is_deeply(
+ $case->('zfsnvme-unit-l', scfg('nvme-ctrl-loss-tmo' => 7), ctrl_loss_tmo => '8'),
+ [],
+ 'the loss timeout the kernel rounds up to the reconnect delay',
+ );
+ is_deeply(
+ $case->('zfsnvme-unit-m', scfg(), fast_io_fail_tmo => '5'),
+ [map { ["$_/fast_io_fail_tmo", -1] } qw(nvme1 nvme2)],
+ 'an unset fast I/O fail timeout is turned off',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ my ($res, $error) = $activate->('zfsnvme-unit-n', $timeouts);
+ ok(!$error && $res == 1, 'a healthy storage activates on the fast path');
+ is(scalar(@ACTIVATIONS) + scalar(@CONNECTS), 0, 'without a target call or connect');
+ is_deeply($sysfs->(), $written, 'which also writes changed timeouts');
+ is_deeply(
+ [grep { $_->[0] =~ /iopolicy/ } @SYSFS_WRITES],
+ [['/sys/class/nvme-subsystem/nvme-subsys7/iopolicy', "round-robin\n"]],
+ 'and the multipath policy',
+ );
+ delete $FILES{'/etc/pve/priv/storage/zfsnvme-unit-n.nvme-dhchap'};
+ $res = eval {
+ local %CONFIG = ('zfsnvme-unit-n' => $timeouts);
+ $PLUGIN->activate_storage('zfsnvme-unit-n', $timeouts);
+ };
+ is($@, "missing NVMe DH-HMAC-CHAP key\n", 'the fast path needs the key file');
+
+ # file_write warns about a failed write and is silent about a failed open, errno stays in $!
+ my @perl_warnings;
+ local $SIG{__WARN__} = sub($warning) { push @perl_warnings, $warning };
+ my $failing = sub($pattern, $errno, $warn) {
+ $sysfs_mock->redefine(
+ file_write => sub($path, $data, @rest) {
+ return $sysfs_write->($path, $data) if $path !~ $pattern;
+ $! = $errno;
+ return undef if !$warn;
+ warn "error writing '$data' to '$path': $!\n";
+ $! = ENOENT; # not the reason: file_write closed the file since
+ return 0;
+ },
+ );
+ };
+ my $reason = sub($errno) { local $! = $errno; return "$!" };
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $failing->(qr{/nvme1/ctrl_loss_tmo\z}, EINVAL, 1);
+ ($res, $error) = $activate->('zfsnvme-unit-e', $timeouts);
+ is($error, '', 'a timeout that cannot be written does not fail the activation');
+ my $einval = $reason->(EINVAL);
+ is_deeply(
+ [@WARNINGS, @perl_warnings],
+ ["cannot set ctrl_loss_tmo of NVMe controller 'nvme1': $einval"],
+ 'and is reported once, as a task warning with the reason',
+ );
+ reset_host();
+ @perl_warnings = ();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $failing->(qr{/nvme2/ctrl_loss_tmo\z}, EACCES, 0);
+ ($res, $error) = $activate->('zfsnvme-unit-tmo-open', $timeouts);
+ is($error, '', 'a timeout that cannot be opened does not fail the activation');
+ is_deeply(
+ [@WARNINGS, @perl_warnings],
+ ["cannot set ctrl_loss_tmo of NVMe controller 'nvme2': " . $reason->(EACCES)],
+ 'and is reported once, with the reason',
+ );
+ reset_host();
+ @perl_warnings = ();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $failing->(qr{/iopolicy\z}, EACCES, 0);
+ ($res, $error) = $activate->('zfsnvme-unit-f', $timeouts);
+ is(
+ $error,
+ 'unable to set NVMe multipath policy: ' . $reason->(EACCES) . "\n",
+ 'a policy that cannot be set fails the activation',
+ );
+ is_deeply([@WARNINGS, @perl_warnings], [], 'with the reason in the error only');
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $failing->(qr{/iopolicy\z}, EINVAL, 1);
+ ($res, $error) = $activate->('zfsnvme-unit-policy-write', $timeouts);
+ is(
+ $error,
+ "unable to set NVMe multipath policy: $einval\n",
+ 'a policy that cannot be written fails the activation',
+ );
+ is_deeply([@WARNINGS, @perl_warnings], [],
+ 'and the warning of file_write is not passed on');
+
+ # The stock file_write on an attribute that does not exist: unlike a deletion or a rescan,
+ # setting a timeout or the policy treats the failed open (ENOENT) as a failure like any other.
+ my $file_write = $sysfs_mock->original('file_write');
+ my $missing = tempdir(CLEANUP => 1) . '/a/b';
+ my $absent = sub($pattern) {
+ $sysfs_mock->redefine(
+ file_write => sub($path, $data, @rest) {
+ return $sysfs_write->($path, $data) if $path !~ $pattern;
+ return $file_write->($missing, $data, @rest);
+ },
+ );
+ };
+ my $enoent = $reason->(ENOENT);
+ reset_host();
+ @perl_warnings = ();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $absent->(qr{/nvme1/reconnect_delay\z});
+ ($res, $error) = $activate->('zfsnvme-unit-tmo-missing', $timeouts);
+ is($error, '', 'a missing timeout attribute does not fail the activation');
+ is_deeply(
+ [@WARNINGS, @perl_warnings],
+ ["cannot set reconnect_delay of NVMe controller 'nvme1': $enoent"],
+ 'but is reported once, as a task warning with the reason',
+ );
+ reset_host();
+ @perl_warnings = ();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ $absent->(qr{/iopolicy\z});
+ ($res, $error) = $activate->('zfsnvme-unit-policy-missing', $timeouts);
+ is(
+ $error,
+ "unable to set NVMe multipath policy: $enoent\n",
+ 'a missing policy attribute fails the activation',
+ );
+ is_deeply([@WARNINGS, @perl_warnings], [], 'with the reason in the error only');
+ $sysfs_mock->redefine(file_write => $sysfs_write);
+};
+
+subtest 'the key attributes of the controllers are private' => sub {
+ my $attrs = sub(@names) {
+ my @attrs = qw(dhchap_secret dhchap_ctrl_secret);
+ return [
+ map {
+ my $name = $_;
+ map { "/sys/class/nvme/$name/$_" } @attrs
+ } @names
+ ];
+ };
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ add_controller('nvme2', '192.0.2.22', 4420, 'ens20');
+ add_controller('nvme3', '192.0.2.23', 4420, 'ens21', 'live', $OTHER_NQN);
+ my ($res, $error) = $activate->('zfsnvme-unit-o', scfg());
+ is($error, '', 'a healthy storage');
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme1', 'nvme2'),
+ 'restricts its controllers on the fast path',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19');
+ ($res, $error) = $activate->('zfsnvme-unit-p', scfg(), $forced->('zfsnvme-unit-p'));
+ is($error, '', 'a forced activation');
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme1', 'nvme1', 'nvme71'),
+ 'restricts those of the existing controllers first, then those of new ones',
+ );
+
+ reset_host();
+ local %CONNECT_STATE = map { ($_ => 'connecting') } '192.0.2.21', '192.0.2.22';
+ ($res, $error) = $activate->('zfsnvme-unit-q', scfg());
+ is(
+ $error,
+ "no live NVMe/TCP path for storage 'zfsnvme-unit-q'\n",
+ 'an activation that fails',
+ );
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme71', 'nvme71', 'nvme72'),
+ 'each one after its connect',
+ );
+
+ reset_host();
+ add_controller('nvme1', '192.0.2.21', 4420, 'ens19', 'connecting');
+ $nvme_mock->redefine(_nvmet_activate_target => sub(@args) { die "unreachable\n" });
+ $res = eval {
+ local $FILES{'/etc/pve/priv/storage/zfsnvme-unit-x.nvme-dhchap'} = $KEY;
+ local %CONFIG = ('zfsnvme-unit-x' => scfg());
+ $PLUGIN->activate_storage('zfsnvme-unit-x', scfg());
+ };
+ is($@, "unreachable\n", 'a slow path that fails at the target');
+ is_deeply(\@RESTRICTED, $attrs->('nvme1'), 'still restricts the existing controllers');
+ $nvme_mock->unmock('_nvmet_activate_target');
+
+ # the first connect fails after it created a live controller, in the second case the permission
+ # scan after it fails too
+ my $connect = $PLUGIN->can('_connect_portal');
+ my $connect_error = "connection failed after creation\n";
+ for my $scan_error (0, 1) {
+ reset_host();
+ my $scan_failed = 0;
+ {
+ no warnings 'redefine';
+ local *PVE::Storage::ZFSNVMePlugin::_connect_portal = sub($scfg, $portal, @ids) {
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme71'),
+ 'a failed connect restricts both attributes before the next connect',
+ ) if @CONNECTS == 1 && !$scan_error;
+ $connect->($scfg, $portal, @ids);
+ die $connect_error if @CONNECTS == 1;
+ };
+ local *PVE::Storage::ZFSNVMePlugin::_restrict_attr = sub($path) {
+ push @RESTRICTED, $path;
+ eval { 1 }; # A permission helper must not erase the saved connect error.
+ die "permission scan failed\n" if $scan_error && !$scan_failed++;
+ return;
+ };
+ ($res, $error) = $activate->("zfsnvme-unit-secret-failure-$scan_error", scfg());
+ }
+ is($error, '', 'a connect error does not discard its live controller');
+ ok(
+ scalar(grep { $_ eq "192.0.2.21:4420: $connect_error" } @WARNINGS),
+ 'and warns about it',
+ );
+ if ($scan_error) {
+ ok(
+ scalar(
+ grep { $_ eq "cannot restrict NVMe controller attributes for '$NQN'" }
+ @WARNINGS
+ ),
+ 'the scan failure has its own warning',
+ );
+ unlike(join("\n", @WARNINGS), qr/permission scan failed/, 'without its exception');
+ } else {
+ is_deeply(
+ \@RESTRICTED,
+ $attrs->('nvme71', 'nvme71', 'nvme72'),
+ 'each attempt restricts the controllers, including a failed last connect',
+ );
+ }
+ }
+
+ my $dir = tempdir(CLEANUP => 1);
+ my $restrict = $nvme_mock->original('_restrict_attr');
+ for my $mode (0644, 0640, 0600, 0400) {
+ my $file = sprintf('%s/attr-%o', $dir, $mode);
+ open(my $fh, '>', $file) or die "open: $!\n";
+ close($fh);
+ chmod($mode, $file);
+ $restrict->($file);
+ is(
+ (stat($file))[2] & 07777,
+ $mode & 077 ? 0600 : $mode,
+ sprintf('an attribute with mode %o', $mode),
+ );
+ }
+ @WARNINGS = ();
+ $restrict->("$dir/missing");
+ is_deeply(\@WARNINGS, [], 'a missing attribute is skipped');
+ my $not_directory = "$dir/attr-600/child";
+ $restrict->($not_directory);
+ like(join("\n", @WARNINGS), qr/\Q$not_directory\E/, 'another stat failure warns');
+};
+
+subtest 'controllers match IPv6 portals in any spelling' => sub {
+ reset_host();
+ add_controller('nvme1', '2001:db8:0:0::11', 4420, 'ens19');
+ add_controller('nvme2', '2001:DB8::12', 4420, 'ens20');
+ my $scfg = scfg('nvme-portals' => '[2001:db8::11],[2001:db8::0:12]');
+ my ($res, $error) = $activate->('zfsnvme-unit-r', $scfg);
+ is($error, '', 'both paths are live');
+ is(scalar(@ACTIVATIONS) + scalar(@CONNECTS), 0, 'without a target call or connect');
+};
+
+is_deeply(\@COMMANDS, [], 'the host side ran no command');
+
done_testing();
1;
--
2.54.0.windows.1
^ permalink raw reply related [relevance 10%]
* [PATCH storage v5 09/13] test: zfsnvme: add an in-memory nvmet target
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
` (4 preceding siblings ...)
2026-11-26 15:09 10% ` [PATCH storage v5 08/13] test: zfsnvme: add node side tests Joaquin Varela
@ 2026-11-26 15:09 8% ` Joaquin Varela
2026-11-26 15:09 9% ` [PATCH storage v5 12/13] test: zfsnvme: add a fault sweep, renderer and taint tests Joaquin Varela
` (2 subsequent siblings)
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:09 UTC (permalink / raw)
To: pve-devel
Add zfsnvme_target_test.pm with FakeTarget, an in-memory target that
runs exactly the commands the plugin sends and records anything else as
a protocol violation, and check it against fixture reads of a real
target (Linux 6.8, ZFS 2.2, documentation addresses).
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
src/test/run_plugin_tests.pl | 1 +
.../zfsnvme_fixtures/configfs_snapshot.txt | 38 +
src/test/zfsnvme_fixtures/zfs_inventory.txt | 15 +
src/test/zfsnvme_target_test.pm | 1578 +++++++++++++++++
4 files changed, 1632 insertions(+)
create mode 100644 src/test/zfsnvme_fixtures/configfs_snapshot.txt
create mode 100644 src/test/zfsnvme_fixtures/zfs_inventory.txt
create mode 100644 src/test/zfsnvme_target_test.pm
diff --git a/src/test/run_plugin_tests.pl b/src/test/run_plugin_tests.pl
index 19465c25..99ea2f46 100755
--- a/src/test/run_plugin_tests.pl
+++ b/src/test/run_plugin_tests.pl
@@ -26,6 +26,7 @@ my $res = $harness->runtests(
"plugin_load_test.pm",
"plugin_properties_test.pm",
"zfsnvme_test.pm",
+ "zfsnvme_target_test.pm",
);
exit -1 if !$res || $res->{failed} || $res->{parse_errors};
diff --git a/src/test/zfsnvme_fixtures/configfs_snapshot.txt b/src/test/zfsnvme_fixtures/configfs_snapshot.txt
new file mode 100644
index 00000000..1b7672a0
--- /dev/null
+++ b/src/test/zfsnvme_fixtures/configfs_snapshot.txt
@@ -0,0 +1,38 @@
+D /sys/kernel/config/nvmet
+D /sys/kernel/config/nvmet/hosts
+D /sys/kernel/config/nvmet/hosts/nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a
+D /sys/kernel/config/nvmet/hosts/nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b
+D /sys/kernel/config/nvmet/ports
+D /sys/kernel/config/nvmet/ports/2
+D /sys/kernel/config/nvmet/ports/2/subsystems
+D /sys/kernel/config/nvmet/ports/1
+D /sys/kernel/config/nvmet/ports/1/subsystems
+D /sys/kernel/config/nvmet/subsystems
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5
+L /sys/kernel/config/nvmet/ports/2/subsystems/nqn.2026-01.com.example:zfsnvme
+L /sys/kernel/config/nvmet/ports/1/subsystems/nqn.2026-01.com.example:zfsnvme
+L /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts/nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a
+L /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts/nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b
+/sys/kernel/config/nvmet/ports/2/addr_trtype:tcp
+/sys/kernel/config/nvmet/ports/2/addr_trsvcid:4420
+/sys/kernel/config/nvmet/ports/2/addr_traddr:192.0.2.22
+/sys/kernel/config/nvmet/ports/2/addr_adrfam:ipv4
+/sys/kernel/config/nvmet/ports/1/addr_trtype:tcp
+/sys/kernel/config/nvmet/ports/1/addr_trsvcid:4420
+/sys/kernel/config/nvmet/ports/1/addr_traddr:192.0.2.21
+/sys/kernel/config/nvmet/ports/1/addr_adrfam:ipv4
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/buffered_io:0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/enable:1
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/device_uuid:0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/device_path:/dev/zvol/tank/vm-100-cloudinit
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/buffered_io:0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/enable:1
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/device_uuid:0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/device_path:/dev/zvol/tank/vm-100-disk-0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_model:Proxmox ZFS NVMe
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_serial:PVEZFS51b2c3c90ea254
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_allow_any_host:0
diff --git a/src/test/zfsnvme_fixtures/zfs_inventory.txt b/src/test/zfsnvme_fixtures/zfs_inventory.txt
new file mode 100644
index 00000000..69ba9238
--- /dev/null
+++ b/src/test/zfsnvme_fixtures/zfs_inventory.txt
@@ -0,0 +1,15 @@
+tank type filesystem -
+tank proxmox:nvme-subsys - -
+tank proxmox:nvme-nsid - -
+tank proxmox:nvme-uuid - -
+tank proxmox:nvme-last-nsid - -
+tank/vm-100-cloudinit type volume -
+tank/vm-100-cloudinit proxmox:nvme-subsys nqn.2026-01.com.example:zfsnvme local
+tank/vm-100-cloudinit proxmox:nvme-nsid 6 local
+tank/vm-100-cloudinit proxmox:nvme-uuid 0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d local
+tank/vm-100-cloudinit proxmox:nvme-last-nsid - -
+tank/vm-100-disk-0 type volume -
+tank/vm-100-disk-0 proxmox:nvme-subsys nqn.2026-01.com.example:zfsnvme local
+tank/vm-100-disk-0 proxmox:nvme-nsid 5 local
+tank/vm-100-disk-0 proxmox:nvme-uuid 0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c local
+tank/vm-100-disk-0 proxmox:nvme-last-nsid - -
diff --git a/src/test/zfsnvme_target_test.pm b/src/test/zfsnvme_target_test.pm
new file mode 100644
index 00000000..22b9585b
--- /dev/null
+++ b/src/test/zfsnvme_target_test.pm
@@ -0,0 +1,1578 @@
+# Target side of the zfsnvme plugin: the parsers and planners on the fixture reads, the command
+# renderer and every target flow against an in-memory NVMe target (FakeTarget) that interprets
+# exactly the commands the plugin sends. Nothing here opens a connection or touches local devices.
+
+use v5.36;
+
+use lib qw(..);
+
+use Compress::Zlib qw(crc32);
+use Digest::SHA qw(sha256_hex);
+use File::Temp qw(tempdir);
+use FindBin;
+use IPC::Open3;
+use MIME::Base64 qw(encode_base64);
+use POSIX ();
+use Storable qw(dclone freeze);
+use Symbol qw(gensym);
+use Test::MockModule;
+use Test::More;
+
+use PVE::Cluster;
+use PVE::NVMeOF;
+use PVE::Storage;
+use PVE::Storage::ZFSNVMePlugin;
+
+my $PLUGIN = 'PVE::Storage::ZFSNVMePlugin';
+my $ROOT = '/sys/kernel/config/nvmet';
+my $MARKER = 'ZFSNVME-CONFIGFS';
+my $MODEL = 'Proxmox ZFS NVMe';
+my $FIXTURES = "$FindBin::Bin/zfsnvme_fixtures";
+my $UUID_RE = qr/\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/i;
+my $EMPTY_KEY_SHA = sha256_hex("\n");
+
+# The fixtures are the ZFS inventory and the configfs read of a target (Linux 6.8 nvmet, ZFS 2.2)
+# that serves one subsystem with two namespaces to two cluster nodes, as the plugin reads them.
+my $FIXTURE_NQN = 'nqn.2026-01.com.example:zfsnvme';
+my @FIXTURE_HOSTS = (
+ 'nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a',
+ 'nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b',
+);
+my $FIXTURE_UUID5 = '0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c';
+my $FIXTURE_UUID6 = '0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d';
+
+my $NQN = 'nqn.2026-01.com.example:zfsnvme-test';
+my $FOREIGN_NQN = 'nqn.2026-01.com.example:foreign';
+my @HOSTS =
+ map { sprintf('nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-%012d', $_) } 1, 2;
+
+sub portal($family, $address, $port) {
+ return { family => $family, address => $address, port => $port };
+}
+my $PORTALS = [portal('ipv4', '192.0.2.21', 4420), portal('ipv4', '192.0.2.22', 4420)];
+my %U = map {
+ my $d = $_;
+ ($d => join('-', $d x 8, $d x 4, '4' . $d x 3, '8' . $d x 3, $d x 12))
+} 1 .. 9;
+
+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);
+my $KEY_SHA = sha256_hex("$KEY\n");
+
+sub scfg(%override) {
+ return {
+ type => 'zfsnvme',
+ server => '192.0.2.10',
+ pool => 'tank',
+ subsysnqn => $NQN,
+ blocksize => '16k',
+ sparse => 1,
+ 'nvme-portals' => '192.0.2.21,192.0.2.22',
+ 'nvme-host-ifaces' => 'ens19,ens20',
+ 'nvme-host-nqns' => join(',', @HOSTS),
+ %override,
+ };
+}
+
+sub slurp($path) {
+ open(my $fh, '<', $path) or die "cannot open '$path': $!\n";
+ local $/;
+ return scalar(<$fh>);
+}
+
+# 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);
+}
+
+sub same($x, $y) {
+ local $Storable::canonical = 1;
+ return freeze([$x]) eq freeze([$y]);
+}
+
+# Mocks: the only way to the target is _nvmet_run, and it reaches $FAKE. The pmxcfs lock, quorum,
+# clock, waits, UUID source, local files and local devices are mocked, waits advance $NOW.
+
+our $FAKE;
+our $NOW = 1_000_000;
+our $SLEPT = 0;
+our $QUORATE = 1;
+our $LOCK_HOOK;
+our (%LOCK_HELD, @LOCKS, @NESTED_LOCKS, @QUORUM, @WARNINGS, @SYSFS_WRITES, %FILES, %CONFIG);
+our (%CORPUS, @VIOLATIONS, @WRITES, %BLOCK, @UUIDS);
+
+my $uuid_seq = 0;
+
+sub lock_id($scfg) {
+ return 'zfsnvme-' . ($scfg->{server} =~ s/[^A-Za-z0-9.-]/_/gr);
+}
+
+sub lock_held($scfg) {
+ return (($LOCK_HELD{ lock_id($scfg) } // 0) == $$) ? 1 : 0;
+}
+
+# by the vocabulary of the fake target, independently of the plugin
+sub step_is($step, @prefix) {
+ return
+ ref($step) eq 'ARRAY'
+ && $step->@* >= @prefix
+ && join("\0", $step->@[0 .. $#prefix]) eq join("\0", @prefix);
+}
+
+sub write_to($step, $suffix, $value = undef) {
+ return
+ ref($step) eq 'HASH'
+ && exists($step->{write})
+ && $step->{write} =~ m{\Q$suffix\E\z}
+ && (!defined($value) || $step->{value} eq $value);
+}
+
+sub mutating_step($step) {
+ return 1 if ref($step) ne 'ARRAY';
+ my ($command, $subcommand) = $step->@*;
+ return 0 if grep { $command eq $_ } qw(test grep cat printf env);
+ return 0 if $command eq 'zfs' && ($subcommand eq 'get' || $subcommand eq 'list');
+ return 1;
+}
+
+# Whether steps change the target, not counting the module load of a locked read.
+sub changing($steps) {
+ return scalar(grep { mutating_step($_) && !step_is($_, 'modprobe') } $steps->@*);
+}
+
+my $plugin_mock = Test::MockModule->new($PLUGIN);
+my $cluster_mock = Test::MockModule->new('PVE::Cluster');
+my $storage_mock = Test::MockModule->new('PVE::Storage');
+my $sysfs_mock = Test::MockModule->new('PVE::SysFSTools');
+my $tools_mock = Test::MockModule->new('PVE::Tools');
+
+$plugin_mock->redefine(
+ _nvmet_run => sub($scfg, $steps, %opts) {
+ die "test error: no fake target\n" if !$FAKE;
+ my $rendered = nv('_nvmet_render', $steps);
+ $CORPUS{$rendered} //= $opts{op} // '';
+ return $FAKE->run($scfg, $steps, $rendered, %opts);
+ },
+);
+# The target is the only place that runs commands, and only through _nvmet_run.
+# A command is also a violation, in case the caller handles the error.
+my $no_command = sub($cmd, %opts) {
+ my $what = 'unexpected command ' . (ref($cmd) ? $cmd->[0] : $cmd);
+ push @VIOLATIONS, $what;
+ die "test error: $what\n";
+};
+$plugin_mock->redefine(run_command => $no_command);
+$tools_mock->redefine(run_command => $no_command);
+$plugin_mock->redefine(_now => sub () { return $NOW });
+$plugin_mock->redefine(
+ _sleep => sub($seconds) {
+ $NOW += $seconds;
+ $SLEPT += $seconds;
+ return;
+ },
+);
+$plugin_mock->redefine(_block_device => sub($path) { return $BLOCK{$path} });
+$plugin_mock->redefine(log_warn => sub($message) { push @WARNINGS, $message; return });
+my $sysfs_write = sub($path, $data, $allow_existing = undef) {
+ push @SYSFS_WRITES, [$path, $data];
+ return 1;
+};
+$sysfs_mock->redefine(file_write => $sysfs_write);
+# UUIDs come from @UUIDS first, then from a sequence.
+$plugin_mock->redefine(
+ file_read_firstline => sub($path) {
+ if ($path eq '/proc/sys/kernel/random/uuid') {
+ return shift(@UUIDS) if @UUIDS;
+ $uuid_seq++;
+ return sprintf('%08x-7e57-4000-8000-%012x', $uuid_seq, $uuid_seq);
+ }
+ return $FILES{$path};
+ },
+);
+$plugin_mock->redefine(
+ file_set_contents => sub($path, $data, $perm = undef, @rest) {
+ push @WRITES, { path => $path, data => $data, perm => $perm };
+ return;
+ },
+);
+$plugin_mock->redefine(make_path => sub(@args) { push @WRITES, { make_path => [@args] }; return });
+
+$cluster_mock->redefine(
+ check_cfs_quorum => sub($noerr = undef) {
+ push @QUORUM, $noerr;
+ die "cluster not ready - no quorum?\n" if !$QUORATE && !$noerr;
+ return $QUORATE;
+ },
+);
+# Keeps the cfs_lock contract: the result of the code with $@ cleared, or undef with $@ set. pmxcfs
+# locks are not re-entrant, so a second request for a held lock times out like a mkdir on
+# /etc/pve/priv/lock would.
+$cluster_mock->redefine(
+ cfs_lock_domain => sub($name, $timeout, $code, @param) {
+ push @LOCKS, { name => $name, timeout => $timeout, pid => $$, now => $NOW };
+ if ($LOCK_HELD{$name}) {
+ push @NESTED_LOCKS, $name;
+ $@ = "cfs-lock 'domain-$name' error: got lock request timeout\n";
+ return undef;
+ }
+ if (my $hook = $LOCK_HOOK) {
+ local $LOCK_HOOK;
+ $hook->($name);
+ }
+ local $LOCK_HELD{$name} = $$;
+ my $res = eval { $code->(@param) };
+ my $err = $@;
+ if ($err) {
+ $@ = $err;
+ return undef;
+ }
+ $@ = undef;
+ return $res;
+ },
+);
+$storage_mock->redefine(config => sub () { return { ids => {%CONFIG} } });
+
+# FakeTarget: ZFS datasets and an nvmet configfs tree with the kernel rules the plugin depends on.
+# It accepts only the command vocabulary of the plugin, anything else is a protocol violation.
+
+package FakeTarget {
+ use Digest::SHA qw(sha256_hex);
+ use Storable qw(dclone);
+
+ my $RR = quotemeta($ROOT);
+
+ # The option fail is a list of [$match, $error, $times]. The steps that match (an argv prefix, a
+ # hash with write and value, or a sub of the step) fail $times times with $error.
+ sub new($class, %opts) {
+ my $pools = delete($opts{pools}) // ['tank'];
+ if (my $fail = delete($opts{fail})) {
+ my ($match, $error, $times) = $fail->@*;
+ my $matches =
+ ref($match) eq 'CODE' ? $match
+ : ref($match) eq 'HASH'
+ ? sub($step) { main::write_to($step, $match->{write}, $match->{value}) }
+ : sub($step) { main::step_is($step, $match->@*) };
+ my $count = 0;
+ $opts{step_fault} = sub($step, $call) {
+ return undef if !$matches->($step) || $count >= ($times // 99);
+ $count++;
+ return $error;
+ };
+ }
+ my $self = bless {
+ m => {
+ ds => {},
+ snaps => {},
+ seq => 0,
+ subsystems => {},
+ ports => {},
+ hosts => {},
+ mounted => 1,
+ loaded => 1,
+ available => '1073741824',
+ used => '1048576',
+ },
+ calls => [],
+ violations => [],
+ faults => {}, # by call index: before, after, late, cut:<step> or lost:<step>
+ late => [], # calls that ssh gave up on, applied by land()
+ # a hash with after (call index) and mode (before, unreachable or failed)
+ read_fault => undef,
+ step_fault => undef, # sub ($step, $call) returning an error text
+ before_call => undef,
+ after_call => undef,
+ udev_delay => 0, # failing `test -b` polls after a zvol (re)appears
+ unbindable => {}, # port ids whose address is missing on the target
+ unreachable => 0,
+ secrets => [$KEY, $KEY_B],
+ %opts,
+ }, $class;
+ $self->{m}->{ds}->{$_} = { type => 'filesystem', props => {} } for $pools->@*;
+ return $self;
+ }
+
+ sub from_state($class, $state, %opts) {
+ my $self = $class->new(%opts);
+ $self->{m} = dclone($state);
+ return $self;
+ }
+
+ sub add_zvol($self, $name, %o) {
+ my %props;
+ @props{qw(proxmox:nvme-subsys proxmox:nvme-nsid proxmox:nvme-uuid)} = $o{identity}->@*
+ if $o{identity};
+ $self->{m}->{ds}->{$name} = {
+ type => 'volume',
+ props => \%props,
+ volsize => $o{volsize} // 1073741824,
+ origin => $o{origin} // '-',
+ devwait => 0,
+ };
+ return $self;
+ }
+
+ sub add_snapshot($self, $snapshot, %o) {
+ my ($name) = split /\@/, $snapshot;
+ my $ds = $self->{m}->{ds}->{$name};
+ $self->{m}->{snaps}->{$snapshot} = {
+ props => $o{props} // dclone($ds->{props}),
+ volsize => $ds->{volsize},
+ seq => ++$self->{m}->{seq},
+ };
+ return $self;
+ }
+
+ sub add_subsystem($self, $nqn, %o) {
+ $self->{m}->{subsystems}->{$nqn} = {
+ attr => {
+ attr_model => $o{model} // $MODEL,
+ attr_serial => $o{serial} // PVE::Storage::ZFSNVMePlugin::_nvmet_serial($nqn),
+ attr_allow_any_host => $o{allow_any_host} // '0',
+ },
+ acl => { map { $_ => 1 } ($o{acl} // [])->@* },
+ ns => {},
+ };
+ return $self;
+ }
+
+ sub add_namespace($self, $nqn, $nsid, $uuid, $dev, $enable = 1) {
+ $self->{m}->{subsystems}->{$nqn}->{ns}->{$nsid} = {
+ enable => "$enable",
+ device_path => $dev,
+ device_uuid => $uuid,
+ buffered_io => '0',
+ };
+ return $self;
+ }
+
+ sub add_port($self, $id, $address, $service, %o) {
+ $self->{m}->{ports}->{$id} = {
+ attr => {
+ addr_trtype => 'tcp',
+ addr_adrfam => $o{family} // 'ipv4',
+ addr_traddr => $address,
+ addr_trsvcid => "$service",
+ },
+ links => { map { $_ => 1 } ($o{links} // [])->@* },
+ };
+ return $self;
+ }
+
+ # nvmet creates the key attributes of a host world-readable
+ sub host_entry($key = undef) {
+ return { key => $key, mode => { map { $_ => '0644' } qw(dhchap_key dhchap_ctrl_key) } };
+ }
+
+ sub add_host($self, $hostnqn, $key = undef) {
+ $self->{m}->{hosts}->{$hostnqn} = host_entry($key);
+ return $self;
+ }
+
+ # a target restart: configfs is empty and, unless $loaded, nvmet is not loaded yet
+ sub reboot($self, $loaded = 0) {
+ my $m = $self->{m};
+ $m->{$_} = {} for qw(subsystems ports hosts);
+ $m->{loaded} = $loaded;
+ $_->{devwait} = 0 for grep { $_->{type} eq 'volume' } values $m->{ds}->%*;
+ return $self;
+ }
+
+ sub run($self, $scfg, $steps, $rendered, %opts) {
+ my $call = {
+ index => scalar($self->{calls}->@*),
+ op => $opts{op},
+ steps => dclone($steps),
+ rendered => $rendered,
+ timeout => $opts{timeout},
+ input => defined($opts{input}) ? 1 : 0,
+ locked => main::lock_held($scfg),
+ mutating => (grep { main::mutating_step($_) } $steps->@*) ? 1 : 0,
+ changing => main::changing($steps),
+ now => $main::NOW,
+ };
+ push $self->{calls}->@*, $call;
+ $self->audit($call, $opts{input});
+ $self->{before_call}->($self, $call) if $self->{before_call};
+ my $res = $self->execute($call, $steps, $opts{input});
+ $call->{rc} = $res->{rc};
+ $call->{err} = $res->{err};
+ $self->audit_text($call, $res->{err}, $res->{out}->@*);
+ $self->{after_call}->($self, $call) if $self->{after_call};
+ return $res;
+ }
+
+ # violations are recorded for the fake and for the whole run, which the last subtest checks
+ sub flag($self, @what) {
+ push $self->{violations}->@*, @what;
+ push @main::VIOLATIONS, @what;
+ }
+
+ sub violation($self, $what) {
+ $self->flag($what);
+ die "FAKEERR:protocol violation: $what\n";
+ }
+
+ sub err($message) {
+ die "FAKEERR:$message\n";
+ }
+
+ sub audit($self, $call, $input) {
+ my @bad;
+ my $op = $call->{op} // '';
+ push @bad, 'call without an operation label' if $op eq '';
+ for my $secret ($self->{secrets}->@*) {
+ push @bad, "key in the command of '$op'" if index($call->{rendered}, $secret) >= 0;
+ }
+ my $keys = grep { ref($_) eq 'HASH' && exists($_->{key}) } $call->{steps}->@*;
+ push @bad, "key write without stdin in '$op'" if $keys && !defined($input);
+ push @bad, "stdin without a key write in '$op'" if defined($input) && !$keys;
+ push @bad, "stdin is not a configured key in '$op'"
+ if defined($input) && !grep { $input eq "$_\n" } $self->{secrets}->@*;
+ push @bad, "target change without the target lock in '$op'"
+ if $call->{mutating} && !$call->{locked};
+ $self->flag(@bad);
+ }
+
+ sub audit_text($self, $call, @texts) {
+ for my $text (grep { defined } @texts) {
+ for my $secret ($self->{secrets}->@*) {
+ $self->flag("key in the output of '$call->{op}'") if index($text, $secret) >= 0;
+ }
+ }
+ }
+
+ # applies the calls that ssh gave up on, each chain stops at its first failing step
+ sub land($self) {
+ for my $late (splice($self->{late}->@*)) {
+ for my $step ($late->{steps}->@*) {
+ last if !eval { $self->step($step, $late->{input}); 1 };
+ }
+ }
+ return $self;
+ }
+
+ # A fault mode fails a call before it runs (rc 1), after it ran (the connection breaks, 255), at
+ # one of its steps (cut: the remote shell stops, lost: the rest of the chain still runs later),
+ # or ssh gives up on it while it runs to its end later (late, -1).
+ sub execute($self, $call, $steps, $input) {
+ my $closed = 'Connection to 192.0.2.10 closed by remote host.';
+ my $broken = { rc => 255, out => [], err => $closed };
+ my $no_route = 'ssh: connect to host 192.0.2.10: No route to host';
+ return { rc => 255, out => [], err => $no_route } if $self->{unreachable};
+ my $read_fault = $self->{read_fault};
+ if ($read_fault && !$call->{mutating} && $call->{index} > $read_fault->{after}) {
+ $self->{read_fault} = undef;
+ $call->{fault} = "read $read_fault->{mode}";
+ return { rc => 255, out => [], err => $no_route }
+ if $read_fault->{mode} eq 'unreachable';
+ return { rc => -1, out => [], err => 'ssh failed' } if $read_fault->{mode} eq 'failed';
+ return { rc => 1, out => [], err => 'injected read failure' };
+ }
+ my $mode = $self->{faults}->{ $call->{index} } // '';
+ $call->{fault} = $mode if $mode;
+ return { rc => 1, out => [], err => 'injected failure' } if $mode eq 'before';
+ if ($mode eq 'late') {
+ push $self->{late}->@*, { steps => dclone($steps), input => $input };
+ return { rc => -1, out => [], err => 'timeout' };
+ }
+ my ($cut) = $mode =~ /\Acut:([0-9]+)\z/;
+ my ($lost) = $mode =~ /\Alost:([0-9]+)\z/;
+ my @out;
+ for my $index (0 .. $steps->$#*) {
+ return $broken if defined($cut) && $index == $cut;
+ if (defined($lost) && $index == $lost) {
+ my @rest = $steps->@[$index .. $steps->$#*];
+ push $self->{late}->@*, { steps => dclone(\@rest), input => $input };
+ return $broken;
+ }
+ my $step = $steps->[$index];
+ my $error = $self->{step_fault} ? $self->{step_fault}->($step, $call) : undef;
+ if (!defined($error)) {
+ my @lines = eval { $self->step($step, $input) };
+ my $e = $@;
+ if (!$e) {
+ push @out, @lines;
+ next;
+ }
+ if ($e !~ s/\AFAKEERR://) {
+ $self->flag("fake target error: $e");
+ return { rc => 2, out => \@out, err => 'fake target error' };
+ }
+ chomp($error = $e);
+ }
+ return { rc => 1, out => \@out, err => $error eq '' ? 'exit code 1' : $error };
+ }
+ return $broken if $mode eq 'after';
+ return { rc => 0, out => \@out, err => '' };
+ }
+
+ sub step($self, $step, $input) {
+ if (ref($step) eq 'HASH' && exists($step->{write})) {
+ $self->write_attr($step->{write}, $step->{value});
+ return ();
+ }
+ if (ref($step) eq 'HASH') {
+ err('dd: error reading standard input') if !defined($input);
+ (my $key = $input) =~ s/\n\z//;
+ my @failed;
+ for my $path ($step->{key}->@*) {
+ eval { $self->write_key($path, $key) };
+ push @failed, $@ if $@;
+ }
+ die $failed[0] if @failed;
+ return ();
+ }
+ my ($command, @args) = $step->@*;
+ my $method = "cmd_$command";
+ $self->violation("command '$command'") if !$self->can($method);
+ return $self->$method(@args);
+ }
+
+ sub available($self) {
+ err("find: '$ROOT': No such file or directory")
+ if !$self->{m}->{mounted} || !$self->{m}->{loaded};
+ }
+
+ sub parts($self, $path) {
+ return () if $path !~ m{\A$RR/(.+)\z};
+ return split m{/}, $1;
+ }
+
+ sub zvol_name($self, $dev) {
+ return $dev =~ m{\A/dev/zvol/(.+)\z} ? $1 : undef;
+ }
+
+ sub block_device($self, $dev, $poll) {
+ my $name = $self->zvol_name($dev) // return 0;
+ my $ds = $self->{m}->{ds}->{$name} // return 0;
+ return 0 if $ds->{type} ne 'volume';
+ if ($ds->{devwait} > 0) {
+ $ds->{devwait}-- if $poll;
+ return 0;
+ }
+ return 1;
+ }
+
+ sub busy($self, $name) {
+ for my $subsys (values $self->{m}->{subsystems}->%*) {
+ return 1
+ if grep { $_->{enable} eq '1' && $_->{device_path} eq "/dev/zvol/$name" }
+ values $subsys->{ns}->%*;
+ }
+ return 0;
+ }
+
+ sub new_uuid($self) {
+ my $seq = ++$self->{m}->{seq};
+ return sprintf('%08x-dead-4000-8000-%012x', $seq, $seq);
+ }
+
+ sub write_attr($self, $path, $value) {
+ $self->available;
+ my @p = $self->parts($path) or $self->violation("write '$path'");
+ my $m = $self->{m};
+ if ($p[0] eq 'subsystems' && @p == 3) {
+ my $subsys = $m->{subsystems}->{ $p[1] } // err("$path: No such file or directory");
+ $self->violation("write '$path'")
+ if $p[2] !~ /\A(?:attr_model|attr_serial|attr_allow_any_host)\z/;
+ if ($p[2] eq 'attr_allow_any_host') {
+ err("$path: Invalid argument") if $value !~ /\A[01]\z/;
+ err("$path: Invalid argument") if $value eq '1' && $subsys->{acl}->%*;
+ }
+ $subsys->{attr}->{ $p[2] } = "$value";
+ } elsif ($p[0] eq 'subsystems' && @p == 5 && $p[2] eq 'namespaces') {
+ my $subsys = $m->{subsystems}->{ $p[1] } // err("$path: No such file or directory");
+ my $ns = $subsys->{ns}->{ $p[3] } // err("$path: No such file or directory");
+ my $attr = $p[4];
+ if ($attr eq 'enable') {
+ err("$path: Invalid argument") if $value !~ /\A[01]\z/;
+ err("$path: No such device")
+ if $value eq '1'
+ && $ns->{enable} ne '1'
+ && !$self->block_device($ns->{device_path}, 0);
+ $ns->{enable} = "$value";
+ } elsif ($attr =~ /\A(?:device_path|device_uuid|buffered_io)\z/) {
+ err("$path: Device or resource busy") if $ns->{enable} eq '1';
+ if ($attr eq 'device_uuid') {
+ err("$path: Invalid argument") if $value !~ $UUID_RE;
+ $value = lc($value);
+ }
+ $ns->{$attr} = "$value";
+ } elsif ($attr eq 'revalidate_size') {
+ err("$path: Invalid argument") if $ns->{enable} ne '1' || $value ne '1';
+ $self->{revalidated}->{"$p[1]/$p[3]"}++;
+ } else {
+ $self->violation("write '$path'");
+ }
+ } elsif ($p[0] eq 'ports' && @p == 3) {
+ my $port = $m->{ports}->{ $p[1] } // err("$path: No such file or directory");
+ $self->violation("write '$path'")
+ if $p[2] !~ /\Aaddr_(?:trtype|adrfam|traddr|trsvcid)\z/;
+ err("$path: Permission denied") if $port->{links}->%*;
+ $port->{attr}->{ $p[2] } = "$value";
+ } else {
+ $self->violation("write '$path'");
+ }
+ }
+
+ sub write_key($self, $path, $key) {
+ $self->available;
+ my @p = $self->parts($path);
+ $self->violation("key write to '$path'")
+ if @p != 3 || $p[0] ne 'hosts' || $p[2] ne 'dhchap_key';
+ my $host = $self->{m}->{hosts}->{ $p[1] } // err("tee: $path: No such file or directory");
+ err("tee: $path: Invalid argument") if $key !~ /\ADHHC-1:/;
+ $self->violation("key write to the world-readable '$path'")
+ if ($host->{mode}->{ $p[2] } // '') ne '0600';
+ $host->{key} = $key;
+ }
+
+ sub cmd_mkdir($self, @paths) {
+ $self->available;
+ my $m = $self->{m};
+ for my $path (@paths) {
+ my @p = $self->parts($path) or $self->violation("mkdir '$path'");
+ my $exists = "mkdir: cannot create directory '$path': File exists";
+ my $missing = "mkdir: cannot create directory '$path': No such file or directory";
+ if ($p[0] eq 'subsystems' && @p == 2) {
+ err($exists) if $m->{subsystems}->{ $p[1] };
+ $m->{subsystems}->{ $p[1] } = {
+ attr => {
+ attr_model => 'Linux',
+ attr_serial => substr(sha256_hex("serial $p[1]"), 0, 16),
+ attr_allow_any_host => '0',
+ },
+ acl => {},
+ ns => {},
+ };
+ } elsif ($p[0] eq 'subsystems' && @p == 4 && $p[2] eq 'namespaces') {
+ my $subsys = $m->{subsystems}->{ $p[1] } // err($missing);
+ err("mkdir: cannot create directory '$path': Invalid argument")
+ if $p[3] !~ /\A[0-9]+\z/ || $p[3] == 0 || $p[3] > 0xfffffffe;
+ err($exists) if $subsys->{ns}->{ $p[3] };
+ $subsys->{ns}->{ $p[3] } = {
+ enable => '0',
+ device_path => '(null)',
+ device_uuid => $self->new_uuid,
+ buffered_io => '0',
+ };
+ } elsif ($p[0] eq 'ports' && @p == 2 && $p[1] =~ /\A[0-9]+\z/) {
+ err($exists) if $m->{ports}->{ $p[1] };
+ $m->{ports}->{ $p[1] } = {
+ attr => { map { ("addr_$_" => '') } qw(trtype adrfam traddr trsvcid) },
+ links => {},
+ };
+ } elsif ($p[0] eq 'hosts' && @p == 2) {
+ err($exists) if $m->{hosts}->{ $p[1] };
+ $m->{hosts}->{ $p[1] } = host_entry();
+ } else {
+ $self->violation("mkdir '$path'");
+ }
+ }
+ return ();
+ }
+
+ sub cmd_chmod($self, $mode, @paths) {
+ $self->available;
+ $self->violation("chmod '$mode'") if $mode ne '0600';
+ for my $path (@paths) {
+ my @p = $self->parts($path);
+ $self->violation("chmod '$path'")
+ if @p != 3 || $p[0] ne 'hosts' || $p[2] !~ /\Adhchap_(?:ctrl_)?key\z/;
+ my $host = $self->{m}->{hosts}->{ $p[1] }
+ // err("chmod: cannot access '$path': No such file or directory");
+ $host->{mode}->{ $p[2] } = $mode;
+ }
+ return ();
+ }
+
+ sub cmd_rmdir($self, @paths) {
+ $self->available;
+ my $m = $self->{m};
+ my @errors;
+ for my $path (@paths) {
+ my @p = $self->parts($path) or $self->violation("rmdir '$path'");
+ my $fail = sub($why) { push @errors, "rmdir: failed to remove '$path': $why" };
+ if ($p[0] eq 'subsystems' && @p == 4 && $p[2] eq 'namespaces') {
+ my $subsys = $m->{subsystems}->{ $p[1] };
+ $fail->('No such file or directory')
+ if !$subsys || !delete($subsys->{ns}->{ $p[3] });
+ } elsif ($p[0] eq 'subsystems' && @p == 2) {
+ my $subsys = $m->{subsystems}->{ $p[1] };
+ if (!$subsys) {
+ $fail->('No such file or directory');
+ } elsif ($subsys->{ns}->%* || $subsys->{acl}->%*) {
+ $fail->('Directory not empty');
+ } elsif (grep { $_->{links}->{ $p[1] } } values $m->{ports}->%*) {
+ $fail->('Device or resource busy');
+ } else {
+ delete $m->{subsystems}->{ $p[1] };
+ }
+ } elsif ($p[0] eq 'hosts' && @p == 2) {
+ if (!$m->{hosts}->{ $p[1] }) {
+ $fail->('No such file or directory');
+ } elsif (grep { $_->{acl}->{ $p[1] } } values $m->{subsystems}->%*) {
+ $fail->('Device or resource busy');
+ } else {
+ delete $m->{hosts}->{ $p[1] };
+ }
+ } else {
+ $self->violation("rmdir '$path'");
+ }
+ }
+ err($errors[0]) if @errors;
+ return ();
+ }
+
+ sub cmd_rm($self, @paths) {
+ $self->available;
+ my $m = $self->{m};
+ my @errors;
+ for my $path (@paths) {
+ my @p = $self->parts($path);
+ my $missing = "rm: cannot remove '$path': No such file or directory";
+ if (@p == 4 && $p[0] eq 'ports' && $p[2] eq 'subsystems') {
+ my $port = $m->{ports}->{ $p[1] };
+ push @errors, $missing if !$port || !delete($port->{links}->{ $p[3] });
+ } elsif (@p == 4 && $p[0] eq 'subsystems' && $p[2] eq 'allowed_hosts') {
+ my $subsys = $m->{subsystems}->{ $p[1] };
+ push @errors, $missing if !$subsys || !delete($subsys->{acl}->{ $p[3] });
+ } else {
+ $self->violation("rm '$path'");
+ }
+ }
+ err($errors[0]) if @errors;
+ return ();
+ }
+
+ sub cmd_ln($self, $flag, $target, $link) {
+ $self->available;
+ my $m = $self->{m};
+ my @t = $self->parts($target);
+ my @l = $self->parts($link);
+ my $fail = sub($why) { err("ln: failed to create symbolic link '$link': $why") };
+ if (@l == 4 && $l[0] eq 'ports' && $l[2] eq 'subsystems') {
+ $self->violation("ln '$target' '$link'")
+ if @t != 2 || $t[0] ne 'subsystems' || $t[1] ne $l[3];
+ my $port = $m->{ports}->{ $l[1] } // $fail->('No such file or directory');
+ $fail->('No such file or directory') if !$m->{subsystems}->{ $t[1] };
+ $fail->('File exists') if $port->{links}->{ $l[3] };
+ my $a = $port->{attr};
+ $fail->('Invalid argument')
+ if $a->{addr_trtype} ne 'tcp'
+ || $a->{addr_adrfam} !~ /\Aipv[46]\z/
+ || $a->{addr_traddr} eq ''
+ || $a->{addr_trsvcid} eq '';
+ if (!$port->{links}->%*) { # the first link enables the port
+ $fail->('Cannot assign requested address') if $self->{unbindable}->{ $l[1] };
+ my @fields = qw(addr_trtype addr_adrfam addr_traddr addr_trsvcid);
+ my $address = join(' ', $a->@{@fields});
+ for my $id (keys $m->{ports}->%*) {
+ my $other = $m->{ports}->{$id};
+ next if $id eq $l[1] || !$other->{links}->%*;
+ $fail->('Address already in use')
+ if join(' ', $other->{attr}->@{@fields}) eq $address;
+ }
+ }
+ $port->{links}->{ $l[3] } = 1;
+ } elsif (@l == 4 && $l[0] eq 'subsystems' && $l[2] eq 'allowed_hosts') {
+ $self->violation("ln '$target' '$link'")
+ if @t != 2 || $t[0] ne 'hosts' || $t[1] ne $l[3];
+ my $subsys = $m->{subsystems}->{ $l[1] } // $fail->('No such file or directory');
+ $fail->('No such file or directory') if !$m->{hosts}->{ $t[1] };
+ $fail->('Invalid argument') if $subsys->{attr}->{attr_allow_any_host} eq '1';
+ $fail->('File exists') if $subsys->{acl}->{ $l[3] };
+ $subsys->{acl}->{ $l[3] } = 1;
+ } else {
+ $self->violation("ln '$target' '$link'");
+ }
+ return ();
+ }
+
+ sub cmd_test($self, $flag, $path) {
+ if ($flag eq '-b') {
+ err('') if !$self->block_device($path, 1);
+ return ();
+ }
+ $self->available;
+ my $m = $self->{m};
+ my @p = $self->parts($path);
+ my $found;
+ if (@p == 4 && $p[0] eq 'subsystems' && $p[2] eq 'allowed_hosts') {
+ $found = ($m->{subsystems}->{ $p[1] } // {})->{acl}->{ $p[3] };
+ } elsif (@p == 4 && $p[0] eq 'ports' && $p[2] eq 'subsystems') {
+ $found = ($m->{ports}->{ $p[1] } // {})->{links}->{ $p[3] };
+ } else {
+ $self->violation("test $flag '$path'");
+ }
+ err('') if !$found;
+ return ();
+ }
+
+ sub cmd_grep($self, $flag, $value, $path) {
+ $self->available;
+ my @p = $self->parts($path);
+ $self->violation("grep '$path'")
+ if @p != 3 || $p[0] ne 'subsystems' || $p[2] ne 'attr_allow_any_host';
+ my $subsys = $self->{m}->{subsystems}->{ $p[1] }
+ // err("grep: $path: No such file or directory");
+ err('') if $subsys->{attr}->{attr_allow_any_host} ne $value;
+ return ();
+ }
+
+ sub cmd_cat($self, $path) {
+ $self->violation("cat '$path'") if $path ne '/proc/mounts';
+ return (
+ 'sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0',
+ 'proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0',
+ (
+ $self->{m}->{mounted}
+ ? ('configfs /sys/kernel/config configfs rw,relatime 0 0')
+ : ()
+ ),
+ );
+ }
+
+ sub cmd_mount($self, @args) {
+ err('mount: /sys/kernel/config: none already mounted on /sys/kernel/config.')
+ if $self->{m}->{mounted};
+ $self->{m}->{mounted} = 1;
+ return ();
+ }
+
+ sub cmd_modprobe($self, $module) {
+ $self->violation("modprobe '$module'") if $module ne 'nvmet_tcp';
+ $self->{m}->{loaded} = 1;
+ return ();
+ }
+
+ sub cmd_printf($self, @args) {
+ $self->violation('printf') if @args != 2 || $args[0] ne '%s\n' || $args[1] ne $MARKER;
+ return ($MARKER);
+ }
+
+ # the configfs read, the golden commands test pins its argv
+ sub cmd_env($self, @args) {
+ my @hosts = map { $args[$_ + 1] =~ m{\A$RR/hosts/([^/]+)/dhchap_key\z} ? ($1) : () }
+ grep { $args[$_] eq '-path' } 0 .. $#args;
+ $self->available;
+ return $self->configfs_lines(\@hosts);
+ }
+
+ sub configfs_lines($self, $hosts) {
+ my $m = $self->{m};
+ my (@dirs, @links, @attrs, @digests);
+ push @dirs, "D $ROOT", map { "D $ROOT/$_" } qw(hosts ports subsystems);
+ push @dirs, map { "D $ROOT/hosts/$_" } sort keys $m->{hosts}->%*;
+ for my $id (sort { $a <=> $b } keys $m->{ports}->%*) {
+ my $port = $m->{ports}->{$id};
+ push @dirs, "D $ROOT/ports/$id", "D $ROOT/ports/$id/subsystems";
+ push @links, map { "L $ROOT/ports/$id/subsystems/$_" } sort keys $port->{links}->%*;
+ push @attrs,
+ map { "$ROOT/ports/$id/$_:$port->{attr}->{$_}" } sort keys $port->{attr}->%*;
+ }
+ for my $nqn (sort keys $m->{subsystems}->%*) {
+ my $subsys = $m->{subsystems}->{$nqn};
+ my $S = "$ROOT/subsystems/$nqn";
+ push @dirs, "D $S", "D $S/allowed_hosts", "D $S/namespaces";
+ push @links, map { "L $S/allowed_hosts/$_" } sort keys $subsys->{acl}->%*;
+ push @attrs, map { "$S/$_:$subsys->{attr}->{$_}" } sort keys $subsys->{attr}->%*;
+ for my $id (sort { $a <=> $b } keys $subsys->{ns}->%*) {
+ my $ns = $subsys->{ns}->{$id};
+ push @dirs, "D $S/namespaces/$id";
+ push @attrs,
+ map { "$S/namespaces/$id/$_:$ns->{$_}" }
+ qw(buffered_io enable device_uuid device_path);
+ }
+ }
+ for my $hostnqn ($hosts->@*) {
+ my $host = $m->{hosts}->{$hostnqn} // next;
+ push @digests,
+ sha256_hex(($host->{key} // '') . "\n") . " $ROOT/hosts/$hostnqn/dhchap_key";
+ }
+ return (@dirs, @links, @attrs, @digests);
+ }
+
+ sub cmd_zfs($self, $subcommand, @args) {
+ my $method = "zfs_$subcommand";
+ $self->violation("zfs $subcommand") if !$self->can($method);
+ return $self->$method(@args);
+ }
+
+ # Options with values are listed with 1, flags with 0.
+ sub options($self, $args, %spec) {
+ my %o;
+ my @rest = $args->@*;
+ while (@rest && $rest[0] =~ /\A-/) {
+ my $option = shift @rest;
+ if ($option eq '-Hp') {
+ $o{H} = $o{p} = 1;
+ next;
+ }
+ if ($option =~ /\A-d([0-9]+)\z/) {
+ $o{d} = [$1];
+ next;
+ }
+ my $name = substr($option, 1);
+ $self->violation("zfs option '$option'") if !exists($spec{$name});
+ if ($spec{$name}) {
+ push $o{$name}->@*, shift(@rest);
+ } else {
+ $o{$name} = 1;
+ }
+ }
+ return (\%o, @rest);
+ }
+
+ sub properties_of($self, $assignments) {
+ my %props;
+ for my $assignment (($assignments // [])->@*) {
+ $self->violation("zfs property '$assignment'") if $assignment !~ /\A([^=]+)=(.*)\z/;
+ $props{$1} = $2;
+ }
+ return \%props;
+ }
+
+ sub datasets_under($self, $target, $depth) {
+ my $m = $self->{m};
+ return () if !$m->{ds}->{$target};
+ return sort grep {
+ my $name = $_;
+ $name eq $target
+ || (index($name, "$target/") == 0
+ && (() = substr($name, length($target)) =~ m{/}g) <= $depth)
+ } keys $m->{ds}->%*;
+ }
+
+ sub property($self, $name, $prop) {
+ my $m = $self->{m};
+ my $ds = $m->{ds}->{$name};
+ return ($ds->{type}, '-') if $prop eq 'type';
+ if ($prop =~ /:/) {
+ return ($ds->{props}->{$prop}, 'local') if defined($ds->{props}->{$prop});
+ my $parent = $name;
+ while ($parent =~ s{/[^/]+\z}{}) {
+ my $value = ($m->{ds}->{$parent} // last)->{props}->{$prop};
+ return ($value, "inherited from $parent") if defined($value);
+ }
+ return ('-', '-');
+ }
+ return ($m->{available}, '-') if $prop eq 'available';
+ return ($m->{used}, '-') if $prop eq 'used';
+ return ($ds->{volsize} // '-', '-') if $prop eq 'volsize';
+ return ('4096', '-') if $prop eq 'usedbydataset';
+ $self->violation("zfs property '$prop'");
+ }
+
+ sub zfs_get($self, @args) {
+ my ($o, $props, @targets) = $self->options(\@args, H => 0, p => 0, d => 1, t => 1, o => 1);
+ $self->violation('zfs get') if @targets != 1 || !$o->{H};
+ $self->violation('zfs get inventory')
+ if $props =~ /\Atype,proxmox:/
+ && !main::same(['get', @args], main::expected_inventory_read($targets[0]));
+ my $target = $targets[0];
+ my @fields = split /,/, ($o->{o} // ['name,property,value,source'])->[0];
+ my %types = map { $_ => 1 } split /,/, ($o->{t} // ['filesystem,volume'])->[0];
+ my @datasets = $self->datasets_under($target, $o->{d} ? $o->{d}->[0] : 0)
+ or err("cannot open '$target': dataset does not exist");
+ my @out;
+
+ for my $name (grep { $types{ $self->{m}->{ds}->{$_}->{type} } } @datasets) {
+ for my $prop (split /,/, $props) {
+ my ($value, $source) = $self->property($name, $prop);
+ my %row = (name => $name, property => $prop, value => $value, source => $source);
+ push @out, join("\t", map { $row{$_} } @fields);
+ }
+ }
+ return @out;
+ }
+
+ sub list_field($self, $row, $field) {
+ my $m = $self->{m};
+ return $row if $field eq 'name';
+ if (my $snap = $m->{snaps}->{$row}) {
+ return 1000 + $snap->{seq} if $field eq 'guid';
+ return 1700000000 + $snap->{seq} if $field eq 'creation';
+ $self->violation("zfs list snapshot field '$field'");
+ }
+ my $ds = $m->{ds}->{$row};
+ return $ds->{type} eq 'volume' ? $ds->{volsize} : '-' if $field eq 'volsize';
+ return $ds->{origin} // '-' if $field eq 'origin';
+ return $ds->{type} if $field eq 'type';
+ $self->violation("zfs list field '$field'");
+ }
+
+ sub zfs_list($self, @args) {
+ my ($o, @targets) =
+ $self->options(\@args, H => 0, p => 0, r => 0, d => 1, t => 1, o => 1, s => 1);
+ $self->violation('zfs list') if @targets != 1 || !$o->{H};
+ my $m = $self->{m};
+ my $target = $targets[0];
+ my @fields = split /,/, ($o->{o} // ['name'])->[0];
+ my %types = map { $_ => 1 } split /,/, ($o->{t} // ['filesystem,volume'])->[0];
+ my @rows;
+ if ($target =~ /\@/) {
+ err("cannot open '$target': dataset does not exist") if !$m->{snaps}->{$target};
+ @rows = ($target);
+ } else {
+ my $depth = $o->{d} ? $o->{d}->[0] : $o->{r} ? 1000 : 0;
+ my @datasets = $self->datasets_under($target, $depth)
+ or err("cannot open '$target': dataset does not exist");
+ if ($types{snapshot}) {
+ my %under = map { $_ => 1 } @datasets;
+ push @rows, sort { $m->{snaps}->{$a}->{seq} <=> $m->{snaps}->{$b}->{seq} }
+ grep { $under{ (split /\@/)[0] } } keys $m->{snaps}->%*;
+ }
+ push @rows, grep { $types{ $m->{ds}->{$_}->{type} } } @datasets;
+ }
+ return map {
+ my $row = $_;
+ join("\t", map { $self->list_field($row, $_) } @fields)
+ } @rows;
+ }
+
+ sub zfs_create($self, @args) {
+ my ($o, @targets) = $self->options(\@args, s => 0, b => 1, o => 1, V => 1);
+ $self->violation('zfs create') if @targets != 1 || !$o->{V};
+ my $m = $self->{m};
+ my $name = $targets[0];
+ my ($parent) = $name =~ m{\A(.+)/[^/]+\z} or $self->violation('zfs create name');
+ $self->violation('zfs create size') if $o->{V}->[0] !~ /\A([0-9]+)k\z/;
+ my $size = $1 * 1024;
+ err("cannot create '$name': parent does not exist") if !$m->{ds}->{$parent};
+ err("cannot create '$name': dataset already exists") if $m->{ds}->{$name};
+ $m->{ds}->{$name} = {
+ type => 'volume',
+ props => $self->properties_of($o->{o}),
+ volsize => $size,
+ origin => '-',
+ devwait => $self->{udev_delay},
+ sparse => $o->{s} ? 1 : 0,
+ blocksize => $o->{b} ? $o->{b}->[0] : undef,
+ };
+ return ();
+ }
+
+ sub zfs_clone($self, @args) {
+ my ($o, $origin, $name, @extra) = $self->options(\@args, o => 1);
+ $self->violation('zfs clone') if @extra || !defined($name);
+ my $m = $self->{m};
+ my $snap = $m->{snaps}->{$origin} // err("cannot open '$origin': dataset does not exist");
+ err("cannot create '$name': dataset already exists") if $m->{ds}->{$name};
+ $m->{ds}->{$name} = {
+ type => 'volume',
+ props => $self->properties_of($o->{o}),
+ volsize => $snap->{volsize},
+ origin => $origin,
+ devwait => $self->{udev_delay},
+ };
+ return ();
+ }
+
+ sub zfs_destroy($self, @args) {
+ my ($o, $target, @extra) = $self->options(\@args, r => 0);
+ $self->violation('zfs destroy') if @extra || !defined($target);
+ my $m = $self->{m};
+ my $clones = sub($snapshot) {
+ return grep { ($_->{origin} // '-') eq $snapshot } values $m->{ds}->%*;
+ };
+ if ($target =~ /\@/) {
+ $self->violation('zfs destroy -r of a snapshot') if $o->{r};
+ err("could not find any snapshots to destroy; check snapshot names.")
+ if !$m->{snaps}->{$target};
+ err("cannot destroy snapshot $target: snapshot has dependent clones")
+ if $clones->($target);
+ delete $m->{snaps}->{$target};
+ return ();
+ }
+ $self->violation('zfs destroy without -r') if !$o->{r};
+ err("cannot open '$target': dataset does not exist") if !$m->{ds}->{$target};
+ err("cannot destroy '$target': dataset is busy") if $self->busy($target);
+ my @snaps = grep { index($_, "$target\@") == 0 } keys $m->{snaps}->%*;
+ err("cannot destroy '$target': filesystem has dependent clones")
+ if grep { $clones->($_) } @snaps;
+ delete $m->{snaps}->{$_} for @snaps;
+ delete $m->{ds}->{$target};
+ return ();
+ }
+
+ # Stricter than ZFS: user properties revert to their value at snapshot
+ # time, so the plugin must set the identity again after a rollback.
+ sub zfs_rollback($self, @args) {
+ $self->violation('zfs rollback') if @args != 1 || $args[0] !~ /\@/;
+ my $m = $self->{m};
+ my ($name) = split /\@/, $args[0];
+ my $snap = $m->{snaps}->{ $args[0] }
+ // err("cannot open '$args[0]': dataset does not exist");
+ err("cannot rollback to '$args[0]': more recent snapshots or bookmarks exist")
+ if grep { index($_, "$name\@") == 0 && $m->{snaps}->{$_}->{seq} > $snap->{seq} }
+ keys $m->{snaps}->%*;
+ err("cannot rollback '$name': dataset is busy") if $self->busy($name);
+ my $ds = $m->{ds}->{$name};
+ $ds->{props} = dclone($snap->{props});
+ $ds->{volsize} = $snap->{volsize};
+ $ds->{devwait} = $self->{udev_delay};
+ return ();
+ }
+
+ sub zfs_set($self, @args) {
+ my $target = pop @args;
+ $self->violation('zfs set') if !@args;
+ my $m = $self->{m};
+ my $object = $target =~ /\@/ ? $m->{snaps}->{$target} : $m->{ds}->{$target};
+ err("cannot open '$target': dataset does not exist") if !$object;
+ for my $assignment (@args) {
+ $self->violation("zfs set '$assignment'") if $assignment !~ /\A([^=]+)=(.*)\z/;
+ my ($prop, $value) = ($1, $2);
+ if ($prop eq 'volsize') {
+ $self->violation('zfs set volsize') if $value !~ /\A([0-9]+)k\z/;
+ $object->{volsize} = $1 * 1024;
+ } elsif ($prop =~ /:/) {
+ $object->{props}->{$prop} = $value;
+ } else {
+ $self->violation("zfs set '$prop'");
+ }
+ }
+ return ();
+ }
+
+ # Like OpenZFS, which renames the minor of a zvol that is open: an
+ # exported zvol is renamed under its namespace.
+ sub zfs_rename($self, @args) {
+ $self->violation('zfs rename') if @args != 2;
+ my ($old, $new) = @args;
+ my $m = $self->{m};
+ err("cannot open '$old': dataset does not exist") if !$m->{ds}->{$old};
+ err("cannot rename to '$new': dataset already exists") if $m->{ds}->{$new};
+ $m->{ds}->{$new} = delete $m->{ds}->{$old};
+ for my $snap (grep { index($_, "$old\@") == 0 } keys $m->{snaps}->%*) {
+ my $renamed = $new . substr($snap, length($old));
+ $m->{snaps}->{$renamed} = delete $m->{snaps}->{$snap};
+ for my $ds (values $m->{ds}->%*) {
+ $ds->{origin} = $renamed if ($ds->{origin} // '-') eq $snap;
+ }
+ }
+ $m->{ds}->{$new}->{devwait} = $self->{udev_delay};
+ return ();
+ }
+
+ sub zfs_snapshot($self, @args) {
+ $self->violation('zfs snapshot') if @args != 1 || $args[0] !~ /\A([^@]+)\@(.+)\z/;
+ my ($name, $snap) = ($1, $2);
+ err("cannot create snapshot '$args[0]': invalid character in name")
+ if $snap !~ /\A[A-Za-z0-9_.: -]+\z/;
+ my $m = $self->{m};
+ my $ds = $m->{ds}->{$name} // err("cannot open '$name': dataset does not exist");
+ err("cannot create snapshot '$args[0]': dataset already exists")
+ if $m->{snaps}->{ $args[0] };
+ $m->{snaps}->{ $args[0] } =
+ { props => dclone($ds->{props}), volsize => $ds->{volsize}, seq => ++$m->{seq} };
+ return ();
+ }
+}
+
+# The inventory read written down independently of the plugin code.
+my $INVENTORY_PROPS =
+ 'type,proxmox:nvme-subsys,proxmox:nvme-nsid,proxmox:nvme-uuid,proxmox:nvme-last-nsid';
+
+sub expected_inventory_read($pool) {
+ return [
+ 'get',
+ '-H',
+ '-p',
+ '-d',
+ '1',
+ '-t',
+ 'filesystem,volume',
+ '-o',
+ 'name,property,value,source',
+ $INVENTORY_PROPS,
+ $pool,
+ ];
+}
+
+sub secret_file($storeid) {
+ return "/etc/pve/priv/storage/$storeid.nvme-dhchap";
+}
+
+# The target part of a storage activation, with the key stored for the storage.
+sub activate($scfg = scfg(), $key = $KEY, $hostnqns = [@HOSTS], $portals = $PORTALS) {
+ local $FILES{ secret_file('st') } = $key;
+ return nv('_nvmet_activate_target', 'st', $scfg, $portals, $hostnqns, $key);
+}
+
+sub flow($fake, $code) {
+ local $FAKE = $fake;
+ local @LOCKS = ();
+ local @NESTED_LOCKS = ();
+ local @WARNINGS = ();
+ local @SYSFS_WRITES = ();
+
+ my $start = scalar($fake->{calls}->@*);
+ my $result = eval { $code->() };
+ my $error = $@;
+ my @calls = $fake->{calls}->@*;
+ return {
+ error => $error,
+ result => $result,
+ calls => [@calls[$start .. $#calls]],
+ locks => [@LOCKS],
+ nested => [@NESTED_LOCKS],
+ warnings => [@WARNINGS],
+ sysfs_writes => [@SYSFS_WRITES],
+ };
+}
+
+sub ops($res) {
+ return [map { $_->{op} } $res->{calls}->@*];
+}
+
+sub changes($res) {
+ return scalar(grep { $_->{changing} } $res->{calls}->@*);
+}
+
+# Our subsystem published on two ports to two hosts, no volumes yet.
+sub target_fake(%opts) {
+ my $fake = FakeTarget->new(pools => ['tank', 'other'], %opts);
+ $fake->add_host($_, $KEY) for @HOSTS;
+ $fake->add_subsystem($NQN, acl => [@HOSTS]);
+ $fake->add_port(1, '192.0.2.21', 4420, links => [$NQN]);
+ $fake->add_port(2, '192.0.2.22', 4420, links => [$NQN]);
+ return $fake;
+}
+
+sub add_volume($fake, $name, $nsid, $uuid, %o) {
+ $fake->add_zvol("tank/$name", identity => [$NQN, $nsid, $uuid]);
+ $fake->add_namespace($NQN, $nsid, $uuid, "/dev/zvol/tank/$name", $o{enable} // 1)
+ if !$o{unexported};
+ return $fake;
+}
+
+# A converged target with three owned volumes, an unowned leftover, a volume of another subsystem
+# in our pool, and a foreign subsystem that shares the first host and port 1.
+sub lifecycle_fake(%opts) {
+ my $fake = target_fake(%opts);
+ add_volume($fake, 'vm-100-disk-0', 1, $U{1});
+ add_volume($fake, 'vm-101-disk-0', 2, $U{2});
+ add_volume($fake, 'base-102-disk-0', 3, $U{3});
+ $fake->add_snapshot('tank/vm-100-disk-0@snap1');
+ $fake->add_snapshot('tank/base-102-disk-0@__base__');
+ $fake->add_zvol('tank/vm-900-disk-0');
+ $fake->add_zvol('tank/vm-901-disk-0', identity => [$FOREIGN_NQN, 7, $U{7}]);
+ $fake->add_zvol('other/foreign-disk', identity => [$FOREIGN_NQN, 1, $U{8}]);
+ $fake->add_subsystem(
+ $FOREIGN_NQN,
+ model => 'Linux',
+ serial => '0123456789abcdef',
+ acl => [$HOSTS[0]],
+ );
+ $fake->add_namespace($FOREIGN_NQN, 1, $U{8}, '/dev/zvol/other/foreign-disk');
+ $fake->{m}->{ports}->{1}->{links}->{$FOREIGN_NQN} = 1;
+ return $fake;
+}
+
+sub owned_volumes($m, $nqn = $NQN, $pool = 'tank') {
+ my %owned;
+ for my $name (sort keys $m->{ds}->%*) {
+ my $ds = $m->{ds}->{$name};
+ next if $ds->{type} ne 'volume' || $name !~ m{\A\Q$pool\E/[^/]+\z};
+ next if ($ds->{props}->{'proxmox:nvme-subsys'} // '') ne $nqn;
+ $owned{$name} = [map { $ds->{props}->{"proxmox:nvme-$_"} } qw(nsid uuid)];
+ }
+ return \%owned;
+}
+
+# Everything on the target that does not belong to the storage under test.
+# The last NSID handed out, on its pool, belongs to the storage.
+sub foreign_view($m, $port_ids, $nqn, $hostnqns, $pool = 'tank') {
+ my %ours = map { $_ => 1 } $hostnqns->@*;
+ my $dataset = sub($name) {
+ my $ds = $m->{ds}->{$name};
+ return $ds if $name ne $pool;
+ my %props = $ds->{props}->%*;
+ delete $props{'proxmox:nvme-last-nsid'};
+ return { $ds->%*, props => \%props };
+ };
+ return {
+ subsystems =>
+ { map { $_ => $m->{subsystems}->{$_} } grep { $_ ne $nqn } keys $m->{subsystems}->%* },
+ datasets => {
+ map { $_ => $dataset->($_) }
+ grep { ($m->{ds}->{$_}->{props}->{'proxmox:nvme-subsys'} // '') ne $nqn }
+ keys $m->{ds}->%*
+ },
+ hosts => { map { $_ => $m->{hosts}->{$_} } grep { !$ours{$_} } keys $m->{hosts}->%* },
+ ports => {
+ map {
+ my $port = $m->{ports}->{$_};
+ my @links = $port ? sort grep { $_ ne $nqn } keys $port->{links}->%* : ();
+ ($_ => $port ? [$port->{attr}, \@links] : undef)
+ } $port_ids->@*
+ },
+ };
+}
+
+# (i), (ii), (v) and (vi), checked after every call.
+sub online_violations($fake, $ctx) {
+ my $m = $fake->{m};
+ my $nqn = $ctx->{nqn};
+ my @bad;
+ if (my $subsys = $m->{subsystems}->{$nqn}) {
+ my $owned = owned_volumes($m, $nqn, $ctx->{pool});
+ my %identity = map { ("/dev/zvol/$_" => $owned->{$_}) } keys $owned->%*;
+ my %seen;
+ for my $id (sort keys $subsys->{ns}->%*) {
+ my $ns = $subsys->{ns}->{$id};
+ push @bad, "(ii) UUID $ns->{device_uuid} used by two namespaces"
+ if $seen{ lc($ns->{device_uuid}) }++;
+ next if $ns->{enable} ne '1';
+ my $want = $identity{ $ns->{device_path} };
+ push @bad, "(i) namespace $id exports $ns->{device_path} under another identity"
+ if !$want || $want->[0] ne $id || lc($want->[1]) ne lc($ns->{device_uuid});
+ }
+ if (grep { $_->{links}->{$nqn} } values $m->{ports}->%*) {
+ push @bad, '(v) published while any host may connect'
+ if $subsys->{attr}->{attr_allow_any_host} ne '0';
+ for my $hostnqn ($ctx->{hosts}->@*) {
+ push @bad, "(v) published without the ACL of $hostnqn"
+ if !$subsys->{acl}->{$hostnqn};
+ push @bad, "(v) published without the key of $hostnqn"
+ if (($m->{hosts}->{$hostnqn} // {})->{key} // '') ne $ctx->{key};
+ }
+ }
+ }
+ push @bad,
+ '(vi) objects of other storages changed'
+ if !same(
+ foreign_view($m, $ctx->{port_ids}, $nqn, $ctx->{hosts}, $ctx->{pool}),
+ $ctx->{foreign},
+ );
+ return @bad;
+}
+
+# (iii): owned identities stay valid, unique and attached to their volume.
+sub identity_violations($m, $ctx) {
+ my @bad;
+ my $owned = owned_volumes($m, $ctx->{nqn}, $ctx->{pool});
+ my (%nsids, %uuids);
+ for my $name (sort keys $owned->%*) {
+ my ($nsid, $uuid) = $owned->{$name}->@*;
+ push @bad, "(iii) invalid identity on $name"
+ if ($nsid // '') !~ /\A[1-9][0-9]*\z/ || ($uuid // '') !~ $UUID_RE;
+ push @bad, "(iii) NSID $nsid on two volumes" if $nsids{ $nsid // '' }++;
+ push @bad, "(iii) UUID $uuid on two volumes" if $uuids{ lc($uuid // '') }++;
+ }
+ for my $name (sort keys $ctx->{initial_owned}->%*) {
+ my $identity = join('/', $ctx->{initial_owned}->{$name}->@*);
+ my @holders = grep { join('/', $owned->{$_}->@*) eq $identity } keys $owned->%*;
+ next if !@holders && ($ctx->{may_vanish} // '') eq $name;
+ my %allowed = map { $_ => 1 } $name, ($ctx->{renames}->{$name} // ());
+ push @bad, "(iii) identity of $name lost" if @holders != 1 || !$allowed{ $holders[0] };
+ }
+ return @bad;
+}
+
+# A creation cut right after its mkdir leaves an unused subsystem with the
+# kernel's default model, which another tool could have created as well.
+# Activation refuses it until an administrator removes it.
+sub default_subsystem($m, $nqn) {
+ my $subsys = $m->{subsystems}->{$nqn} // return 0;
+ return
+ $subsys->{attr}->{attr_model} eq 'Linux'
+ && !$subsys->{ns}->%*
+ && !$subsys->{acl}->%*
+ && !grep { $_->{links}->{$nqn} } values $m->{ports}->%*;
+}
+
+# (iv): one more activation exports every owned volume exactly once.
+sub convergence_violations($fake, $ctx) {
+ my $res = flow($fake, sub { activate($ctx->{scfg}, $ctx->{key}, $ctx->{hosts}) });
+ if (my $error = $res->{error}) {
+ return ()
+ if $error =~ /not created by Proxmox VE/ && default_subsystem($fake->{m}, $ctx->{nqn});
+ return "(iv) activation afterwards failed: $error";
+ }
+ my $m = $fake->{m};
+ my $owned = owned_volumes($m, $ctx->{nqn}, $ctx->{pool});
+ my $subsys = $m->{subsystems}->{ $ctx->{nqn} } // return '(iv) subsystem missing';
+ my %want = map { $owned->{$_}->[0] => ["/dev/zvol/$_", lc($owned->{$_}->[1]), '1'] }
+ keys $owned->%*;
+ my %have = map {
+ my $ns = $subsys->{ns}->{$_};
+ ($_ => [$ns->{device_path}, lc($ns->{device_uuid}), $ns->{enable}])
+ } keys $subsys->{ns}->%*;
+ my @bad;
+ push @bad, '(iv) exported namespaces differ from the owned volumes' if !same(\%want, \%have);
+ # an interrupted port creation leaves an incomplete port that is ignored, a new one serves it
+ for my $portal ($PORTALS->@*) {
+ my ($address, $service) = $portal->@{qw(address port)};
+ push @bad, "(iv) not published on $address"
+ if !grep {
+ $_->{links}->{ $ctx->{nqn} }
+ && $_->{attr}->{addr_traddr} eq $address
+ && $_->{attr}->{addr_trsvcid} eq "$service"
+ } values $m->{ports}->%*;
+ }
+ return @bad;
+}
+
+sub run_case($initial, $ctx, $faults, $read_fault = undef) {
+ my $fake = FakeTarget->from_state($initial);
+ $fake->{faults} = $faults;
+ $fake->{read_fault} = $read_fault;
+ my @online;
+ $fake->{after_call} = sub($f, $call) {
+ push @online,
+ map { "call $call->{index} ($call->{op}): $_" } online_violations($f, $ctx);
+ };
+ my $res = flow($fake, $ctx->{action});
+ $res->{fake} = $fake;
+ $res->{online} = \@online;
+ $res->{faults} = { $faults->%*, ($read_fault ? (read => $read_fault->{mode}) : ()) };
+ return $res;
+}
+
+sub case_violations($ctx, $res) {
+ my $fake = $res->{fake};
+ my @bad;
+ push @bad, 'domain lock taken ' . scalar($res->{locks}->@*) . ' times'
+ if $res->{locks}->@* > 1;
+ push @bad, 'nested domain lock request' if $res->{nested}->@*;
+ push @bad, 'key in the error text' if grep { index($res->{error}, $_) >= 0 } $KEY, $KEY_B;
+
+ # The result must match the outcome: success only when the goal is reached. A flow whose only
+ # faults are lost replies (create and clone, which cannot settle one with a read) may fail after
+ # reaching its goal, but only with an unknown target state.
+ my @missing = $ctx->{done}->($fake->{m}, $res);
+ push @bad, map { "success without reaching the goal: $_" } @missing if $res->{error} eq '';
+ my @modes = values $res->{faults}->%*;
+ push @bad, "failure after reaching the goal: $res->{error}"
+ if $ctx->{lost_replies}
+ && $res->{error} ne ''
+ && $res->{error} !~ /the target state is unknown\n\z/
+ && !@missing
+ && @modes
+ && !grep { $_ ne 'after' } @modes;
+
+ # A call that ssh gave up on completes on the target afterwards. When the
+ # rest of it changes the target, the outcome was unknown.
+ if ($fake->{late}->@*) {
+ if (
+ grep {
+ grep { mutating_step($_) } $_->{steps}->@*
+ } $fake->{late}->@*
+ ) {
+ push @bad, "late call after a success" if $res->{error} eq '';
+ push @bad, "late call reported without an unknown state: $res->{error}"
+ if $res->{error} !~ /the target state is unknown\n\z/;
+ }
+ $fake->land;
+ push @bad, map { "after the late call: $_" } online_violations($fake, $ctx);
+ }
+ push @bad, identity_violations($fake->{m}, $ctx);
+ $fake->{faults} = {};
+ $fake->{read_fault} = undef;
+ push @bad, convergence_violations($fake, $ctx);
+ push @bad, $res->{online}->@*;
+ push @bad, map { "protocol: $_" } $fake->{violations}->@*;
+ return @bad;
+}
+
+# Fault sweep: every mutating call of a flow fails, and then every later mutating call of that run
+# fails as well, or the first read after it. After each run: (i) every enabled namespace of the
+# subsystem exports the zvol of its identity, (ii) no UUID is used twice, (iii) owned identities
+# are kept and unique, (iv) one more activation converges, (v) the subsystem is never published
+# before its ACLs, keys and allow_any_host=0, (vi) nothing of other storages changes, every change
+# ran under one domain lock and the result matches the outcome. (i), (ii), (v) and (vi) are checked
+# after every call, refusals have their own tests.
+sub sweep($name, $ctx) {
+ my $initial = dclone($ctx->{setup}->()->{m});
+ $ctx->{nqn} //= $NQN;
+ $ctx->{pool} //= 'tank';
+ $ctx->{hosts} //= [@HOSTS];
+ $ctx->{key} //= $KEY;
+ $ctx->{scfg} //= scfg();
+ $ctx->{initial_owned} = owned_volumes($initial, $ctx->{nqn}, $ctx->{pool});
+ $ctx->{port_ids} = [sort keys $initial->{ports}->%*];
+ $ctx->{foreign} =
+ foreign_view($initial, $ctx->{port_ids}, $ctx->{nqn}, $ctx->{hosts}, $ctx->{pool});
+
+ my $baseline = run_case($initial, $ctx, {});
+ is($baseline->{error}, '', "$name: succeeds without faults");
+ is_deeply([$ctx->{done}->($baseline->{fake}->{m}, $baseline)], [], "$name: reaches its goal");
+ is_deeply([case_violations($ctx, $baseline)], [], "$name: invariants hold without faults");
+
+ # A call fails in each mode of FakeTarget::execute, at each step of its chain. A second
+ # failure, in the compensation or the next round, is one that fails before or after its call,
+ # or the first read after the first failure fails or finds the target unreachable.
+ my $modes = sub($call) {
+ my @steps = 1 .. $call->{steps}->$#*;
+ return ('before', 'after', 'late', (map { "cut:$_" } @steps), map { "lost:$_" } @steps);
+ };
+ my @first = grep { $_->{mutating} } $baseline->{calls}->@*;
+ ok(scalar(@first), "$name: changes the target");
+ my ($runs, @failures) = (0);
+ for my $first (@first) {
+ my $k = $first->{index};
+ for my $mode ($modes->($first)) {
+ my $res = run_case($initial, $ctx, { $k => $mode });
+ $runs++;
+ my @later = grep { $_->{mutating} && $_->{index} > $k } $res->{calls}->@*;
+ push @failures, map { "call $k $mode: $_" } case_violations($ctx, $res);
+ for my $second (@later) {
+ my $j = $second->{index};
+ for my $again_mode (qw(before after)) {
+ my $again = run_case($initial, $ctx, { $k => $mode, $j => $again_mode });
+ $runs++;
+ push @failures,
+ map { "call $k $mode, call $j $again_mode: $_" }
+ case_violations($ctx, $again);
+ }
+ }
+ for my $read_mode (qw(before unreachable)) {
+ my $read_fault = { after => $k, mode => $read_mode };
+ my $again = run_case($initial, $ctx, { $k => $mode }, $read_fault);
+ $runs++;
+ push @failures,
+ map { "call $k $mode, next read $read_mode: $_" } case_violations($ctx, $again);
+ }
+ }
+ }
+ ok(!@failures, "$name: the invariants hold in $runs fault injections")
+ or diag(join("\n", @failures));
+}
+
+my $FIXTURE_ZFS = slurp("$FIXTURES/zfs_inventory.txt");
+my $FIXTURE_CFS = slurp("$FIXTURES/configfs_snapshot.txt");
+my $FIXTURE_DIGESTS = join('', map { "$KEY_SHA $ROOT/hosts/$_/dhchap_key\n" } @FIXTURE_HOSTS);
+
+sub fixture_fake() {
+ my $fake = FakeTarget->new(pools => ['tank']);
+ $fake->add_host($_) for @FIXTURE_HOSTS;
+ $fake->add_subsystem($FIXTURE_NQN, acl => [@FIXTURE_HOSTS]);
+ $fake->add_port($_, "192.0.2.2$_", 4420, links => [$FIXTURE_NQN]) for 1, 2;
+ $fake->add_zvol('tank/vm-100-disk-0', identity => [$FIXTURE_NQN, 5, $FIXTURE_UUID5]);
+ $fake->add_zvol('tank/vm-100-cloudinit', identity => [$FIXTURE_NQN, 6, $FIXTURE_UUID6]);
+ $fake->add_namespace($FIXTURE_NQN, 5, $FIXTURE_UUID5, '/dev/zvol/tank/vm-100-disk-0');
+ $fake->add_namespace($FIXTURE_NQN, 6, $FIXTURE_UUID6, '/dev/zvol/tank/vm-100-cloudinit');
+ return $fake;
+}
+
+subtest 'the fake target answers in the formats of the fixture target' => sub {
+ my $fake = fixture_fake();
+ my @zfs = $fake->zfs_get(expected_inventory_read('tank')->@[1 .. 10]);
+ is(join('', map { "$_\n" } @zfs), $FIXTURE_ZFS, 'the ZFS inventory equals the fixture');
+ my $cfs = join('', map { "$_\n" } $fake->configfs_lines([]));
+ is_deeply(
+ nv('_nvmet_parse_configfs', $cfs),
+ nv('_nvmet_parse_configfs', $FIXTURE_CFS),
+ 'the configfs read parses to the fixture',
+ );
+};
+
+done_testing();
--
2.54.0.windows.1
^ permalink raw reply related [relevance 8%]
* [PATCH storage v5 12/13] test: zfsnvme: add a fault sweep, renderer and taint tests
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
` (5 preceding siblings ...)
2026-11-26 15:09 8% ` [PATCH storage v5 09/13] test: zfsnvme: add an in-memory nvmet target Joaquin Varela
@ 2026-11-26 15:09 9% ` Joaquin Varela
2026-11-26 15:10 20% ` [PATCH docs v5] storage: document ZFS over NVMe/TCP Joaquin Varela
2026-11-26 15:11 21% ` [PATCH manager v5] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:09 UTC (permalink / raw)
To: pve-devel
The fault sweep fails every mutating call of every flow in each way an
SSH call can fail, and checks that identities stay unique, other
storages stay untouched and the next activation converges. The rendered
command chains also run with /bin/sh on a configfs stand-in, which
checks the quoting.
run_zfsnvme_taint_tests.pl runs under perl -T against a small model of
the target and a directory in place of sysfs. What the target answers
and what the plugin reads from files is tainted, as in the daemons,
while the commands, file names and sysfs writes are real. It covers the
activation, adding, cloning and removing a disk, rollback, templates
and the node side. It also covers a resize and a disk move that take
their size from the target, the sizes, names, snapshot names and
storage IDs that an internal caller passes, and the rows that the
methods return.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
src/test/Makefile | 4 +
src/test/run_zfsnvme_taint_tests.pl | 988 ++++++++++++++++++++++++++++
src/test/zfsnvme_target_test.pm | 766 +++++++++++++++++++++
3 files changed, 1758 insertions(+)
create mode 100755 src/test/run_zfsnvme_taint_tests.pl
diff --git a/src/test/Makefile b/src/test/Makefile
index eab91494..33ac5d17 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -28,8 +28,12 @@ test: \
test_sensitive_properties \
test_storage_create \
test_volume_access \
+ test_zfsnvme_taint \
test_zfspoolplugin \
+test_zfsnvme_taint: run_zfsnvme_taint_tests.pl
+ perl -T ./run_zfsnvme_taint_tests.pl
+
test_zfspoolplugin: run_test_zfspoolplugin.pl
./run_test_zfspoolplugin.pl
diff --git a/src/test/run_zfsnvme_taint_tests.pl b/src/test/run_zfsnvme_taint_tests.pl
new file mode 100755
index 00000000..bdc4a0de
--- /dev/null
+++ b/src/test/run_zfsnvme_taint_tests.pl
@@ -0,0 +1,988 @@
+#!/usr/bin/perl -T
+
+# The zfsnvme plugin in taint mode, as pvedaemon, pveproxy and pvesr run it. A model of the target
+# answers the commands that the plugin sends over SSH, and the files that the plugin reads and
+# writes live in a temporary directory. What the model answers and what the plugin reads from files
+# is tainted like the read of a file or a pipe. Every command also runs for real, as true with the
+# same arguments, and the file names and sysfs writes are real, so a tainted word fails them as it
+# would in a daemon. The test checks every command with Scalar::Util::tainted as well.
+
+use v5.36;
+use lib qw(..);
+
+use Compress::Zlib qw(crc32);
+use Digest::SHA qw(sha256_hex);
+use File::Path qw(make_path);
+use File::Temp qw(tempdir);
+use MIME::Base64 qw(encode_base64);
+use Scalar::Util qw(tainted);
+use Test::MockModule;
+use Test::More;
+
+use PVE::File;
+use PVE::NVMeOF;
+use PVE::Storage;
+use PVE::Storage::ZFSNVMePlugin;
+use PVE::SysFSTools;
+use PVE::Tools qw(file_get_contents file_set_contents);
+
+my $PLUGIN = 'PVE::Storage::ZFSNVMePlugin';
+my $ROOT = '/sys/kernel/config/nvmet';
+my $NQN = 'nqn.2026-01.com.example:zfsnvme-test';
+my @HOSTS =
+ map { sprintf('nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-%012d', $_) } 1, 2;
+my %UUID = (
+ 5 => '0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c',
+ 6 => '0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d',
+ new => '7e57c0de-1111-4000-8000-000000000001',
+);
+my @PROPERTIES = qw(proxmox:nvme-subsys proxmox:nvme-nsid proxmox:nvme-uuid proxmox:nvme-last-nsid);
+my $RAW = join('', map { chr(($_ * 131 + 17) % 256) } 1 .. 32);
+my $KEY = 'DHHC-1:00:' . encode_base64($RAW . pack('V', crc32($RAW)), '') . ':';
+
+$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
+delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
+
+# The parts of the file system that the plugin reads and writes live below $root.
+my $dir = tempdir('zfsnvme-taint-XXXX', DIR => '.', CLEANUP => 1);
+my $root = "$dir/root";
+
+sub fs($path) {
+ return "$root$path";
+}
+
+sub put($path, $content, $mode = undef) {
+ make_path(fs($path) =~ s{/[^/]*\z}{}r);
+ file_set_contents(fs($path), $content);
+ chmod($mode, fs($path)) if defined($mode);
+}
+
+# The lines as the read of a file or a pipe returns them.
+sub as_read(@lines) {
+ file_set_contents("$dir/read", join('', map { "$_\n" } @lines));
+ open(my $fh, '<', "$dir/read") or die "cannot read back the lines: $!\n";
+ chomp(my @read = <$fh>);
+ close($fh);
+ return @read;
+}
+
+# Every tainted value in what a method returns.
+sub tainted_values(@data) {
+ return map {
+ ref($_) eq 'ARRAY' ? tainted_values($_->@*)
+ : ref($_) eq 'HASH' ? tainted_values(values $_->%*)
+ : tainted($_) ? ($_)
+ : ()
+ } @data;
+}
+
+# The target: ZFS datasets and the nvmet configfs, with only what the plugin uses of both.
+
+my %T;
+my $seq = 0;
+
+sub new_uuid() {
+ $seq++;
+ return sprintf('%08x-dead-4000-8000-%012x', $seq, $seq);
+}
+
+sub add_volume($name, $nsid, $uuid) {
+ $T{ds}->{$name} = {
+ type => 'volume',
+ size => 1024**3,
+ origin => '-',
+ props => {
+ 'proxmox:nvme-subsys' => $NQN,
+ 'proxmox:nvme-nsid' => $nsid,
+ 'proxmox:nvme-uuid' => $uuid,
+ },
+ };
+}
+
+# A target with two volumes of an earlier life, exported unless the target restarted since.
+sub seed($exported) {
+ %T = (
+ ds => { tank => { type => 'filesystem', props => { 'proxmox:nvme-last-nsid' => 6 } } },
+ snaps => {},
+ subsystems => {},
+ ports => {},
+ hosts => {},
+ );
+ add_volume('tank/vm-100-disk-0', 5, $UUID{5});
+ add_volume('tank/vm-100-cloudinit', 6, $UUID{6});
+ return if !$exported;
+ $T{subsystems}->{$NQN} = {
+ attr => {
+ attr_model => 'Proxmox ZFS NVMe',
+ attr_serial => PVE::Storage::ZFSNVMePlugin::_nvmet_serial($NQN),
+ attr_allow_any_host => '0',
+ },
+ acl => { map { $_ => 1 } @HOSTS },
+ ns => {
+ map {
+ my $name = $_;
+ my $props = $T{ds}->{$name}->{props};
+ (
+ $props->{'proxmox:nvme-nsid'} => {
+ enable => '1',
+ device_path => "/dev/zvol/$name",
+ device_uuid => $props->{'proxmox:nvme-uuid'},
+ buffered_io => '0',
+ },
+ )
+ } grep {
+ $T{ds}->{$_}->{type} eq 'volume'
+ } keys $T{ds}->%*
+ },
+ };
+ $T{hosts}->{$_} = { key => "$KEY\n" } for @HOSTS;
+ my $id = 0;
+ for my $address ('192.0.2.21', '192.0.2.22') {
+ $T{ports}->{ ++$id } = {
+ attr => {
+ addr_trtype => 'tcp',
+ addr_adrfam => 'ipv4',
+ addr_traddr => $address,
+ addr_trsvcid => '4420',
+ },
+ links => { $NQN => 1 },
+ };
+ }
+}
+
+sub parts($path) {
+ return $path =~ m{\A\Q$ROOT\E/(.+)\z} ? split(m{/}, $1) : ('');
+}
+
+sub inventory($pool) {
+ my @rows;
+ for my $name (sort grep { $_ eq $pool || m{\A\Q$pool\E/[^/]+\z} } keys $T{ds}->%*) {
+ my $ds = $T{ds}->{$name};
+ push @rows, join("\t", $name, 'type', $ds->{type}, '-');
+ for my $prop (@PROPERTIES) {
+ my $value = $ds->{props}->{$prop};
+ push @rows, join("\t", $name, $prop, defined($value) ? ($value, 'local') : ('-', '-'));
+ }
+ }
+ return @rows;
+}
+
+sub configfs($hosts) {
+ my (@dirs, @links, @attrs, @digests);
+ push @dirs, "D $ROOT", map { "D $ROOT/$_" } qw(hosts ports subsystems);
+ push @dirs, map { "D $ROOT/hosts/$_" } sort keys $T{hosts}->%*;
+ for my $id (sort { $a <=> $b } keys $T{ports}->%*) {
+ my $port = $T{ports}->{$id};
+ push @dirs, "D $ROOT/ports/$id", "D $ROOT/ports/$id/subsystems";
+ push @links, map { "L $ROOT/ports/$id/subsystems/$_" } sort keys $port->{links}->%*;
+ push @attrs, map { "$ROOT/ports/$id/$_:$port->{attr}->{$_}" } sort keys $port->{attr}->%*;
+ }
+ for my $nqn (sort keys $T{subsystems}->%*) {
+ my ($subsys, $S) = ($T{subsystems}->{$nqn}, "$ROOT/subsystems/$nqn");
+ push @dirs, "D $S", "D $S/allowed_hosts", "D $S/namespaces";
+ push @links, map { "L $S/allowed_hosts/$_" } sort keys $subsys->{acl}->%*;
+ push @attrs, map { "$S/$_:$subsys->{attr}->{$_}" } sort keys $subsys->{attr}->%*;
+ for my $id (sort { $a <=> $b } keys $subsys->{ns}->%*) {
+ my $ns = $subsys->{ns}->{$id};
+ push @dirs, "D $S/namespaces/$id";
+ push @attrs, map { "$S/namespaces/$id/$_:$ns->{$_}" } sort keys $ns->%*;
+ }
+ }
+ for my $hostnqn ($hosts->@*) {
+ push @digests,
+ sha256_hex($T{hosts}->{$hostnqn}->{key} // "\n") . " $ROOT/hosts/$hostnqn/dhchap_key";
+ }
+ return (@dirs, @links, @attrs, @digests);
+}
+
+sub device_exists($dev) {
+ return $dev =~ m{\A/dev/zvol/(.+)\z} && $T{ds}->{$1} ? 1 : 0;
+}
+
+sub write_attr($path, $value) {
+ my @p = parts($path);
+ if ($p[0] eq 'subsystems' && @p == 3) {
+ $T{subsystems}->{ $p[1] }->{attr}->{ $p[2] } = $value;
+ } elsif ($p[0] eq 'subsystems' && @p == 5 && $p[2] eq 'namespaces') {
+ my $ns = $T{subsystems}->{ $p[1] }->{ns}->{ $p[3] } // die "no such namespace\n";
+ die "no such device\n" if $p[4] eq 'enable' && $value && !device_exists($ns->{device_path});
+ $ns->{ $p[4] } = $value if $p[4] ne 'revalidate_size';
+ } elsif ($p[0] eq 'ports' && @p == 3) {
+ $T{ports}->{ $p[1] }->{attr}->{ $p[2] } = $value;
+ } else {
+ die "write to '$path'\n";
+ }
+}
+
+sub assignments(@list) {
+ return map { /\A([^=]+)=(.*)\z/ ? ($1 => $2) : die "assignment '$_'\n" } @list;
+}
+
+sub columns(@args) {
+ return split(/,/, (map { $args[$_ + 1] } grep { $args[$_] eq '-o' } 0 .. $#args)[0]);
+}
+
+my %zfs = (
+ # the inventory, the usage of a dataset, or the owner of every dataset
+ get => sub(@args) {
+ my ($property, $name) = @args[-2, -1];
+ my @columns = columns(@args);
+ return inventory($name) if grep { $_ eq 'property' } @columns;
+ my %usage = (
+ available => 100 * 1024**3,
+ used => 3 * 1024**3,
+ volsize => $T{ds}->{$name}->{size},
+ usedbydataset => 1024**2,
+ );
+ return map { $usage{$_} // die "zfs get $_\n" } split(/,/, $property)
+ if $columns[0] eq 'value';
+ return map {
+ my $value = $T{ds}->{$_}->{props}->{$property};
+ join("\t", $_, defined($value) ? ($value, 'local') : ('-', '-'));
+ } sort grep {
+ $_ eq $name || m{\A\Q$name\E/[^/]+\z}
+ } keys $T{ds}->%*;
+ },
+ list => sub(@args) {
+ my $pool = $args[-1];
+ if (grep { $_ eq 'snapshot' } @args) {
+ my @columns = columns(@args);
+ return map {
+ my %row = (name => $_, $T{snaps}->{$_}->%{qw(guid creation)});
+ join("\t", @row{@columns});
+ } sort {
+ $T{snaps}->{$a}->{creation} <=> $T{snaps}->{$b}->{creation}
+ } grep {
+ index($_, "$pool\@") == 0
+ } keys $T{snaps}->%*;
+ }
+ return map {
+ my $ds = $T{ds}->{$_};
+ join("\t",
+ $_,
+ $ds->{type} eq 'volume' ? $ds->{size} : '-',
+ $ds->{origin} // '-',
+ $ds->{type});
+ } sort grep {
+ $_ eq $pool || m{\A\Q$pool\E/[^/]+\z}
+ } keys $T{ds}->%*;
+ },
+ create => sub(@args) {
+ my (%o, @props);
+ while (@args > 1) {
+ my $option = shift @args;
+ if ($option eq '-o') {
+ push @props, shift @args;
+ } elsif ($option eq '-V' || $option eq '-b') {
+ $o{$option} = shift @args;
+ } elsif ($option eq '-s') {
+ $o{$option} = 1;
+ } else {
+ die "zfs create option '$option'\n";
+ }
+ }
+ die "zfs create size\n" if ($o{'-V'} // '') !~ /\A([0-9]+)k\z/;
+ my $size = $1 * 1024;
+ $T{ds}->{ $args[0] } =
+ { type => 'volume', size => $size, origin => '-', props => { assignments(@props) } };
+ return ();
+ },
+ clone => sub(@args) {
+ my @props;
+ while ($args[0] eq '-o') {
+ shift @args;
+ push @props, shift @args;
+ }
+ my ($origin, $name) = @args;
+ my $snap = $T{snaps}->{$origin} // die "no snapshot '$origin'\n";
+ $T{ds}->{$name} = {
+ type => 'volume',
+ size => $snap->{size},
+ origin => $origin,
+ props => { assignments(@props) },
+ };
+ return ();
+ },
+ destroy => sub(@args) {
+ my $name = pop @args;
+ if ($name =~ /\@/) {
+ delete $T{snaps}->{$name};
+ } else {
+ die "cannot destroy '$name': dataset is busy\n" if $T{busy}->{$name};
+ delete $T{snaps}->{$_} for grep { index($_, "$name\@") == 0 } keys $T{snaps}->%*;
+ delete $T{ds}->{$name};
+ }
+ return ();
+ },
+ set => sub(@args) {
+ my $name = pop @args;
+ my $object = $name =~ /\@/ ? $T{snaps}->{$name} : $T{ds}->{$name};
+ my %set = assignments(@args);
+ for my $key (keys %set) {
+ if ($key eq 'volsize') {
+ $object->{size} = $set{$key} =~ s/k\z//r * 1024;
+ } else {
+ $object->{props}->{$key} = $set{$key};
+ }
+ }
+ return ();
+ },
+ rename => sub($old, $new) {
+ $T{ds}->{$new} = delete $T{ds}->{$old};
+ for my $snap (grep { index($_, "$old\@") == 0 } keys $T{snaps}->%*) {
+ $T{snaps}->{ $new . substr($snap, length($old)) } = delete $T{snaps}->{$snap};
+ }
+ return ();
+ },
+ snapshot => sub($snapshot) {
+ my ($name) = split /\@/, $snapshot;
+ my $ds = $T{ds}->{$name} // die "no dataset '$name'\n";
+ $seq++;
+ $T{snaps}->{$snapshot} = {
+ size => $ds->{size},
+ props => { $ds->{props}->%* },
+ guid => 4_000_000_000_000_000_000 + $seq,
+ creation => 1_700_000_000 + $seq,
+ };
+ return ();
+ },
+ # a rollback also brings back the properties of the snapshot
+ rollback => sub($snapshot) {
+ my ($name) = split /\@/, $snapshot;
+ my $snap = $T{snaps}->{$snapshot} // die "no snapshot '$snapshot'\n";
+ $T{ds}->{$name}->{props} = { $snap->{props}->%* };
+ $T{ds}->{$name}->{size} = $snap->{size};
+ return ();
+ },
+);
+
+my %command = (
+ modprobe => sub(@args) { return () },
+ chmod => sub(@args) { return () },
+ mount => sub(@args) { return () },
+ cat => sub($file) { return ('configfs /sys/kernel/config configfs rw,relatime 0 0') },
+ printf => sub($format, $text) { return ($text) },
+ test => sub($flag, $path) {
+ if ($flag eq '-b') {
+ die "not a block device\n" if !device_exists($path);
+ return ();
+ }
+ my @p = parts($path);
+ my $found =
+ $p[0] eq 'subsystems'
+ ? $T{subsystems}->{ $p[1] }->{acl}->{ $p[3] }
+ : $T{ports}->{ $p[1] }->{links}->{ $p[3] };
+ die "no such link\n" if !$found;
+ return ();
+ },
+ grep => sub($flag, $value, $path) {
+ my @p = parts($path);
+ die "other value\n" if $T{subsystems}->{ $p[1] }->{attr}->{ $p[2] } ne $value;
+ return ();
+ },
+ mkdir => sub($path) {
+ my @p = parts($path);
+ if ($p[0] eq 'subsystems' && @p == 2) {
+ $T{subsystems}->{ $p[1] } = {
+ attr => {
+ attr_model => 'Linux',
+ attr_serial => '0123456789abcdef',
+ attr_allow_any_host => '1',
+ },
+ acl => {},
+ ns => {},
+ };
+ } elsif ($p[0] eq 'subsystems' && @p == 4 && $p[2] eq 'namespaces') {
+ $T{subsystems}->{ $p[1] }->{ns}->{ $p[3] } = {
+ enable => '0',
+ device_path => '(null)',
+ device_uuid => new_uuid(),
+ buffered_io => '0',
+ };
+ } elsif ($p[0] eq 'ports' && @p == 2) {
+ $T{ports}->{ $p[1] } = {
+ attr => { map { ("addr_$_" => '') } qw(trtype adrfam traddr trsvcid) },
+ links => {},
+ };
+ } elsif ($p[0] eq 'hosts' && @p == 2) {
+ $T{hosts}->{ $p[1] } = {};
+ } else {
+ die "mkdir '$path'\n";
+ }
+ return ();
+ },
+ rmdir => sub($path) {
+ my @p = parts($path);
+ die "rmdir '$path'\n" if $p[0] ne 'subsystems' || @p != 4 || $p[2] ne 'namespaces';
+ delete $T{subsystems}->{ $p[1] }->{ns}->{ $p[3] } or die "no such namespace\n";
+ return ();
+ },
+ rm => sub($path) {
+ my @p = parts($path);
+ die "rm '$path'\n" if $p[0] ne 'ports' || @p != 4;
+ delete $T{ports}->{ $p[1] }->{links}->{ $p[3] };
+ return ();
+ },
+ ln => sub($flag, $target, $link) {
+ my @p = parts($link);
+ if ($p[0] eq 'ports' && @p == 4) {
+ $T{ports}->{ $p[1] }->{links}->{ $p[3] } = 1;
+ } elsif ($p[0] eq 'subsystems' && @p == 4) {
+ $T{subsystems}->{ $p[1] }->{acl}->{ $p[3] } = 1;
+ } else {
+ die "ln '$link'\n";
+ }
+ return ();
+ },
+ env => sub(@args) {
+ my @hosts = map { $args[$_ + 1] =~ m{/hosts/([^/]+)/dhchap_key\z} ? ($1) : () }
+ grep { $args[$_] eq '-path' } 0 .. $#args;
+ return configfs(\@hosts);
+ },
+ zfs => sub($verb, @args) {
+ return ($zfs{$verb} // die "zfs $verb\n")->(@args);
+ },
+);
+
+sub run_step($step, $input) {
+ if (ref($step) eq 'HASH' && exists($step->{write})) {
+ write_attr($step->{write}, $step->{value});
+ return ();
+ }
+ if (ref($step) eq 'HASH') {
+ for my $path ($step->{key}->@*) {
+ my @p = parts($path);
+ ($T{hosts}->{ $p[1] } // die "no such host\n")->{key} = $input;
+ }
+ return ();
+ }
+ my ($name, @args) = $step->@*;
+ return ($command{$name} // die "command '$name'\n")->(@args);
+}
+
+# What reaches a command or a file system call is checked here and by the real calls below.
+
+my @violations;
+my $steps_sent;
+my $now = 1_000_000;
+my @warnings;
+
+my $real = {
+ file_write => PVE::SysFSTools->can('file_write'),
+ dir_glob_foreach => PVE::File->can('dir_glob_foreach'),
+ restrict_attr => $PLUGIN->can('_restrict_attr'),
+ render => $PLUGIN->can('_nvmet_render'),
+};
+
+my $plugin = Test::MockModule->new($PLUGIN);
+$plugin->redefine(
+ # Every command is a real exec of true in taint mode, the plugin then gets the model's answer.
+ run_command => sub($cmd, %opts) {
+ push @violations, "a tainted word in the command '$cmd->[0]'"
+ if grep { tainted($_) } $cmd->@*;
+ push @violations, "tainted input for the command '$cmd->[0]'" if tainted($opts{input});
+ PVE::Tools::run_command(['/usr/bin/true', $cmd->@*], timeout => 10);
+ return 0 if $cmd->[0] ne '/usr/bin/ssh';
+
+ my @out = eval {
+ map { run_step($_, $opts{input}) } $steps_sent->@*;
+ };
+ if (my $error = $@) {
+ chomp($error);
+ $opts{errfunc}->($error);
+ die "command 'ssh' failed: exit code 1\n";
+ }
+ $opts{outfunc}->($_) for as_read(@out);
+ return 0;
+ },
+ _nvmet_render => sub($steps) {
+ $steps_sent = $steps;
+ return $real->{render}->($steps);
+ },
+ file_read_firstline => sub($path) { return PVE::File::file_read_first_line(fs($path)) },
+ file_set_contents =>
+ sub($path, @rest) { return PVE::File::file_set_contents(fs($path), @rest) },
+ make_path => sub($path, @rest) { return File::Path::make_path(fs($path), @rest) },
+ _unlink_file => sub($path) { return unlink(fs($path)) },
+ _restrict_attr => sub($path) { return $real->{restrict_attr}->(fs($path)) },
+ # a file stands in for the link, as the read of either is tainted
+ _link_target => sub($path) { return PVE::File::file_read_first_line(fs($path)) },
+ _block_device => sub($path) { return -e fs($path) },
+ _local_iface_exists => sub($iface) { return 1 },
+ _nvme_tcp_loaded => sub() { return 1 },
+ _namespace_users => sub($nqn) { return [] },
+ _now => sub() { return $now },
+ _sleep => sub($seconds) { $now += $seconds; return },
+ log_warn => sub($message) { push @warnings, $message; return },
+);
+my $file = Test::MockModule->new('PVE::File');
+$file->redefine(
+ dir_glob_foreach => sub($path, $regex, $func) {
+ return $real->{dir_glob_foreach}->(fs($path), $regex, $func);
+ },
+);
+my $sysfs = Test::MockModule->new('PVE::SysFSTools');
+$sysfs->redefine(
+ file_write => sub($path, @rest) { return $real->{file_write}->(fs($path), @rest) });
+my $nvmeof = Test::MockModule->new('PVE::NVMeOF');
+$nvmeof->redefine(with_lock => sub($code, $limit = undef) { return $code->() });
+my $cluster = Test::MockModule->new('PVE::Cluster');
+$cluster->redefine(
+ check_cfs_quorum => sub($noerr = undef) { return 1 },
+ cfs_lock_domain => sub($name, $timeout, $code, @param) {
+ my $res = eval { $code->(@param) };
+ my $error = $@;
+ $@ = $error;
+ return $error ? undef : $res;
+ },
+);
+
+# the storage as a node reads it: the text of storage.cfg is read from a file
+put('/etc/pve/storage.cfg', <<"EOF");
+zfsnvme: nvme1
+\tserver 192.0.2.10
+\tpool tank
+\tblocksize 16k
+\tsparse 1
+\tsubsysnqn $NQN
+\tnvme-portals 192.0.2.21,192.0.2.22
+\tnvme-host-ifaces ens19,ens20
+\tnvme-host-nqns @{[join(',', @HOSTS)]}
+\tnvme-keep-alive-tmo 5
+\tnvme-ctrl-loss-tmo 600
+
+EOF
+my $raw = file_get_contents(fs('/etc/pve/storage.cfg'));
+my $cfg = PVE::Storage::Plugin->parse_config('storage.cfg', $raw);
+my ($storeid) = grep { $_ eq 'nvme1' } keys $cfg->{ids}->%*;
+my $scfg = $cfg->{ids}->{$storeid};
+my $secret = "/etc/pve/priv/storage/$storeid.nvme-dhchap";
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->redefine(config => sub() { return $cfg });
+
+put('/etc/nvme/hostnqn', "$HOSTS[0]\n");
+put('/etc/nvme/hostid', "11111111-2222-4333-8444-555555555555\n");
+local $PVE::NVMeOF::HOSTNQN_FILE = fs('/etc/nvme/hostnqn');
+local $PVE::NVMeOF::HOSTID_FILE = fs('/etc/nvme/hostid');
+
+sub flow($name, $code) {
+ subtest $name => sub {
+ @violations = ();
+ @warnings = ();
+ my $res = eval { $code->() };
+ is($@, '', 'it completes in taint mode');
+ is_deeply(\@violations, [], 'nothing tainted reaches a command or a file system call');
+ is_deeply(\@warnings, [], 'without warnings');
+ return $res;
+ };
+}
+
+sub proc_uuid($uuid) {
+ put('/proc/sys/kernel/random/uuid', "$uuid\n");
+}
+
+sub ns_of($nsid) {
+ return $T{subsystems}->{$NQN}->{ns}->{$nsid};
+}
+
+sub identity($name) {
+ my $props = $T{ds}->{$name}->{props};
+ return [@{$props}{qw(proxmox:nvme-nsid proxmox:nvme-uuid)}];
+}
+
+ok(tainted(file_get_contents(fs('/etc/pve/storage.cfg'))), 'a file read is tainted');
+is(
+ scalar(grep { tainted($_) } $storeid, values $scfg->%*),
+ 0,
+ 'storage.cfg values and the storage ID come out of the parser untainted',
+);
+put($secret, "$KEY\n");
+proc_uuid($UUID{new});
+ok(tainted(PVE::File::file_read_first_line(fs('/proc/sys/kernel/random/uuid'))), 'so is the UUID');
+ok(tainted((as_read('a'))[0]), 'and the answer of the target');
+
+flow(
+ 'a ZFS inventory that comes back in several reads' => sub {
+ seed(1);
+ for my $i (1 .. 60) {
+ add_volume(
+ "tank/vm-$i-disk-0",
+ 10 + $i,
+ sprintf('%08x-aaaa-4000-8000-%012x', $i, $i),
+ );
+ }
+ # run_command passes on a last row without newline tainted, and so are the rows that
+ # span two reads of 4096 bytes
+ my $uuid_row = qr{\Atank/vm-9-disk-0\tproxmox:nvme-uuid\t};
+ my @rows = inventory('tank');
+ @rows = ((grep { $_ !~ $uuid_row } @rows), (grep { $_ =~ $uuid_row } @rows));
+ my $last = pop @rows;
+ file_set_contents("$dir/inventory", join('', map { "$_\n" } @rows) . $last);
+ my @lines;
+ PVE::Tools::run_command(
+ ['/bin/cat', "$dir/inventory"],
+ outfunc => sub($line) { push @lines, $line },
+ );
+ ok(tainted($lines[-1]), 'the row of a UUID is tainted');
+ my $text = join('', map { "$_\n" } @lines);
+ my $inv = PVE::Storage::ZFSNVMePlugin::_nvmet_parse_zfs_inventory($text, 'tank');
+ my @identity =
+ PVE::Storage::ZFSNVMePlugin::_nvmet_owned_identity($inv, $NQN, 'tank/vm-9-disk-0');
+ is_deeply(\@identity, [19, '00000009-aaaa-4000-8000-000000000009'], 'its identity');
+ is(scalar(grep { tainted($_) } @identity, $inv->{last_nsid}), 0, 'is untainted');
+ },
+);
+
+flow(
+ 'add and the first activation rebuild the namespaces after a restart' => sub {
+ seed(0);
+ $PLUGIN->on_add_hook($storeid, $scfg, 'dhchap-key' => $KEY);
+ is(file_get_contents(fs($secret)), "$KEY\n", 'the key file is written');
+ my $portals = PVE::Storage::ZFSNVMePlugin::_configured_portals($scfg);
+ my $hostnqns =
+ PVE::Storage::ZFSNVMePlugin::parse_nvme_host_nqns($scfg->{'nvme-host-nqns'});
+ my $key = PVE::Storage::ZFSNVMePlugin::_validate_secret(
+ PVE::File::file_read_first_line(fs($secret)),
+ );
+ ok(!tainted($key), 'the key is untainted');
+ PVE::Storage::ZFSNVMePlugin::_nvmet_activate_target(
+ $storeid, $scfg, $portals, $hostnqns, $key,
+ );
+ is_deeply(
+ [map { [@{ ns_of($_) }{qw(enable device_uuid device_path)}] } 5, 6],
+ [
+ ['1', $UUID{5}, '/dev/zvol/tank/vm-100-disk-0'],
+ ['1', $UUID{6}, '/dev/zvol/tank/vm-100-cloudinit'],
+ ],
+ 'the namespaces are rebuilt from the ZFS properties',
+ );
+ is_deeply(
+ [sort keys $T{subsystems}->{$NQN}->{acl}->%*],
+ [sort @HOSTS],
+ 'the hosts are allowed',
+ );
+ is(
+ scalar(grep { $_->{links}->{$NQN} } values $T{ports}->%*),
+ 2,
+ 'both ports publish it',
+ );
+ is($T{hosts}->{ $HOSTS[0] }->{key}, "$KEY\n", 'the key reached the host object');
+ },
+);
+
+flow(
+ 'add a disk' => sub {
+ seed(1);
+ proc_uuid($UUID{new});
+ my $name = $PLUGIN->alloc_image(
+ $storeid, $scfg, 101, 'raw', undef, 4 * 1024 * 1024,
+ );
+ is($name, 'vm-101-disk-0', 'the volume name');
+ is_deeply(
+ identity("tank/$name"),
+ [7, $UUID{new}],
+ 'the identity comes from the pool and /proc',
+ );
+ is($T{ds}->{tank}->{props}->{'proxmox:nvme-last-nsid'}, 7, 'the NSID is reserved');
+ is_deeply(
+ [@{ ns_of(7) }{qw(enable device_uuid)}],
+ ['1', $UUID{new}],
+ 'the namespace is exported',
+ );
+ },
+);
+
+flow(
+ 'convert to a template and clone it' => sub {
+ seed(1);
+ proc_uuid($UUID{new});
+ my $base = $PLUGIN->create_base($storeid, $scfg, 'vm-100-disk-0');
+ is($base, 'base-100-disk-0', 'the template name');
+ is_deeply(identity("tank/$base"), [5, $UUID{5}], 'the template keeps its identity');
+ is(ns_of(5)->{device_path}, '/dev/zvol/tank/base-100-disk-0', 'and its namespace');
+ my $clone = $PLUGIN->clone_image($scfg, $storeid, $base, 102);
+ is($clone, 'base-100-disk-0/vm-102-disk-0', 'the clone name');
+ is_deeply(
+ identity('tank/vm-102-disk-0'),
+ [7, $UUID{new}],
+ 'the clone has a new identity',
+ );
+ is(
+ $T{ds}->{'tank/vm-102-disk-0'}->{origin},
+ 'tank/base-100-disk-0@__base__',
+ 'and origin',
+ );
+ is(ns_of(7)->{enable}, '1', 'its namespace is exported');
+ },
+);
+
+flow(
+ 'snapshot, roll back and resize' => sub {
+ seed(1);
+ $PLUGIN->volume_snapshot($scfg, $storeid, 'vm-100-disk-0', 'before');
+ $PLUGIN->volume_snapshot_rollback($scfg, $storeid, 'vm-100-disk-0', 'before');
+ is_deeply(identity('tank/vm-100-disk-0'), [5, $UUID{5}], 'the identity is kept');
+ is_deeply(
+ [@{ ns_of(5) }{qw(enable device_uuid)}],
+ ['1', $UUID{5}],
+ 'the namespace is exported again',
+ );
+ is(
+ $PLUGIN->volume_resize($scfg, $storeid, 'vm-100-disk-0', 2 * 1024**3, 0),
+ 2097152,
+ 'resize',
+ );
+ is($T{ds}->{'tank/vm-100-disk-0'}->{size}, 2 * 1024**3, 'to the new size');
+ },
+);
+
+flow(
+ 'resize to the size that the target reports plus a delta' => sub {
+ seed(1);
+ my $size = $PLUGIN->volume_size_info($scfg, $storeid, 'vm-100-disk-0');
+ is($size, 1024**3, 'the size');
+ is(
+ $PLUGIN->volume_resize($scfg, $storeid, 'vm-100-disk-0', $size + 1024**3, 0),
+ 2097152,
+ 'resize',
+ );
+ is($T{ds}->{'tank/vm-100-disk-0'}->{size}, 2 * 1024**3, 'to the new size');
+ },
+);
+
+flow(
+ 'a disk move allocates the size of its source' => sub {
+ seed(1);
+ proc_uuid($UUID{new});
+ my ($size) = $PLUGIN->volume_size_info($scfg, $storeid, 'vm-100-disk-0');
+ my $name = $PLUGIN->alloc_image($storeid, $scfg, 101, 'raw', undef, $size / 1024);
+ is($T{ds}->{"tank/$name"}->{size}, 1024**3, 'the new disk has the size of the source');
+ },
+);
+
+# The daemons untaint what an API call passes, an internal caller (qemu-server, vzdump, the
+# replication) may pass values that it read from a file or a pipe.
+
+flow(
+ 'an internal caller passes a size that is tainted' => sub {
+ seed(1);
+ proc_uuid(new_uuid());
+ my ($size, $bytes) = as_read(4096, 5120 * 1024);
+ ok(tainted($size) && tainted($bytes), 'the sizes are tainted');
+ my $name = $PLUGIN->alloc_image($storeid, $scfg, 101, 'raw', undef, $size);
+ is($T{ds}->{"tank/$name"}->{size}, 4096 * 1024, 'add a disk');
+ $PLUGIN->volume_resize($scfg, $storeid, $name, $bytes, 0);
+ is($T{ds}->{"tank/$name"}->{size}, 5120 * 1024, 'resize');
+ },
+);
+
+flow(
+ 'an internal caller passes a VM ID and a name that are tainted' => sub {
+ seed(1);
+ my ($vmid, $name) = as_read(101, 'vm-101-disk-0');
+ ok(tainted($vmid) && tainted($name), 'they are tainted');
+ proc_uuid(new_uuid());
+ is(
+ $PLUGIN->alloc_image($storeid, $scfg, $vmid, 'raw', $name, 4096),
+ 'vm-101-disk-0',
+ 'add a disk with its name',
+ );
+ proc_uuid(new_uuid());
+ is(
+ $PLUGIN->alloc_image($storeid, $scfg, $vmid, 'raw', undef, 4096),
+ 'vm-101-disk-1',
+ 'and one with the name that the storage picks',
+ );
+ proc_uuid(new_uuid());
+ my ($base) = as_read('base-100-disk-0');
+ $PLUGIN->create_base($storeid, $scfg, 'vm-100-disk-0');
+ is(
+ $PLUGIN->clone_image($scfg, $storeid, $base, $vmid),
+ 'base-100-disk-0/vm-101-disk-2',
+ 'clone a template under the VM ID',
+ );
+ },
+);
+
+flow(
+ 'an internal caller passes snapshot names that are tainted' => sub {
+ seed(1);
+ proc_uuid(new_uuid());
+ my ($snap, $tag, $base) = as_read('before', '__base__', 'base-100-disk-0');
+ ok(tainted($snap) && tainted($tag), 'they are tainted');
+ $PLUGIN->volume_snapshot($scfg, $storeid, 'vm-100-disk-0', $snap);
+ ok($T{snaps}->{'tank/vm-100-disk-0@before'}, 'snapshot');
+ ok(
+ $PLUGIN->volume_rollback_is_possible($scfg, $storeid, 'vm-100-disk-0', $snap),
+ 'check',
+ );
+ $PLUGIN->volume_snapshot_rollback($scfg, $storeid, 'vm-100-disk-0', $snap);
+ $PLUGIN->volume_snapshot_delete($scfg, $storeid, 'vm-100-disk-0', $snap);
+ ok(!$T{snaps}->{'tank/vm-100-disk-0@before'}, 'delete');
+ $PLUGIN->create_base($storeid, $scfg, 'vm-100-disk-0');
+ is(
+ $PLUGIN->clone_image($scfg, $storeid, $base, 102, $tag),
+ 'base-100-disk-0/vm-102-disk-0',
+ 'clone a template from its snapshot',
+ );
+ },
+);
+
+flow(
+ 'the rows that the methods return are untainted' => sub {
+ seed(1);
+ proc_uuid($UUID{new});
+ $PLUGIN->volume_snapshot($scfg, $storeid, 'vm-100-disk-0', 'before');
+ $PLUGIN->volume_snapshot($scfg, $storeid, 'vm-100-disk-0', 'later');
+ $PLUGIN->create_base($storeid, $scfg, 'vm-100-cloudinit');
+ $PLUGIN->clone_image($scfg, $storeid, 'base-100-cloudinit', 102);
+
+ my $images = $PLUGIN->list_images($storeid, $scfg);
+ is_deeply(
+ [sort map { $_->{volid} } $images->@*],
+ [
+ "$storeid:base-100-cloudinit",
+ "$storeid:base-100-cloudinit/vm-102-disk-0",
+ "$storeid:vm-100-disk-0",
+ ],
+ 'the images',
+ );
+ my ($clone) = grep { $_->{name} eq 'vm-102-disk-0' } $images->@*;
+ is($clone->{parent}, 'base-100-cloudinit@__base__', 'the parent of a clone');
+ is_deeply([tainted_values($images)], [], 'list_images returns untainted rows');
+
+ my $snapshots = $PLUGIN->volume_snapshot_info($scfg, $storeid, 'vm-100-disk-0');
+ is_deeply([sort keys $snapshots->%*], ['before', 'later'], 'the snapshots');
+ is_deeply(
+ [tainted_values($snapshots)],
+ [],
+ 'volume_snapshot_info returns untainted rows',
+ );
+
+ my @blockers;
+ eval {
+ $PLUGIN->volume_rollback_is_possible(
+ $scfg, $storeid, 'vm-100-disk-0', 'before', \@blockers,
+ );
+ };
+ like($@, qr/is not most recent snapshot/, 'a rollback past a snapshot is refused');
+ is_deeply(\@blockers, ['later'], 'it names the snapshot in the way');
+ is_deeply([tainted_values(\@blockers)], [], 'untainted');
+
+ my @usage = $PLUGIN->status($storeid, $scfg);
+ is_deeply(
+ \@usage,
+ [103 * 1024**3, 100 * 1024**3, 3 * 1024**3, 1],
+ 'the usage of the pool',
+ );
+ is_deeply([tainted_values(\@usage)], [], 'status returns untainted values');
+
+ my @info = $PLUGIN->volume_size_info($scfg, $storeid, 'vm-100-disk-0');
+ is_deeply(\@info, [1024**3, 'raw', 1024**2, undef], 'the size info of a volume');
+ is_deeply([tainted_values(\@info)], [], 'volume_size_info returns untainted values');
+ },
+);
+
+flow(
+ 'remove a disk' => sub {
+ seed(1);
+ $PLUGIN->free_image($storeid, $scfg, 'vm-100-disk-0');
+ ok(!$T{ds}->{'tank/vm-100-disk-0'}, 'the zvol is gone');
+ ok(!ns_of(5), 'and its namespace');
+ ok(ns_of(6), 'the other namespace stays');
+ },
+);
+
+flow(
+ 'a busy zvol keeps its namespace' => sub {
+ seed(1);
+ $T{busy}->{'tank/vm-100-disk-0'} = 1;
+ eval { $PLUGIN->free_image($storeid, $scfg, 'vm-100-disk-0') };
+ like($@, qr/dataset is busy; namespace restored\n\z/, 'the removal is refused');
+ is_deeply(
+ [@{ ns_of(5) }{qw(enable device_uuid device_path)}],
+ ['1', $UUID{5}, '/dev/zvol/tank/vm-100-disk-0'],
+ 'the namespace is exported again as it was',
+ );
+ },
+);
+
+flow(
+ 'the path of a disk reaches a guest command line' => sub {
+ seed(1);
+ put("/dev/disk/by-id/nvme-uuid.$UUID{5}", "../../nvme0n1\n");
+ put('/sys/block/nvme0n1/uuid', "$UUID{5}\n");
+ put('/sys/block/nvme0n1/nsid', "5\n");
+ put('/sys/block/nvme0n1/device/subsysnqn', "$NQN\n");
+ my ($path) = $PLUGIN->path($scfg, 'vm-100-disk-0', $storeid);
+ is($path, "/dev/disk/by-id/nvme-uuid.$UUID{5}", 'the path');
+ my $options = $PLUGIN->qemu_blockdev_options($scfg, $storeid, 'vm-100-disk-0');
+ is(scalar(grep { tainted($_) } $path, $options->{filename}), 0, 'it is untainted');
+ is(
+ $PLUGIN->activate_volume($storeid, $scfg, 'vm-100-disk-0'),
+ 1,
+ 'the volume is active',
+ );
+ },
+);
+
+flow(
+ 'the node side reads sysfs and changes controllers' => sub {
+ for my $i (0, 1) {
+ my $c = "/sys/class/nvme/nvme$i";
+ put("$c/subsysnqn", "$NQN\n");
+ put(
+ "$c/address",
+ sprintf("traddr=192.0.2.2%d,trsvcid=4420,host_iface=ens%d\n", $i + 1, 19 + $i),
+ );
+ put("$c/state", "live\n");
+ put("$c/reconnect_delay", "7\n");
+ put("$c/ctrl_loss_tmo", "70\n");
+ put("$c/fast_io_fail_tmo", "off\n");
+ put("$c/dhchap_secret", "$KEY\n", 0644);
+ put("$c/dhchap_ctrl_secret", "\n", 0644);
+ }
+ put('/sys/class/nvme-subsystem/nvme-subsys0/subsysnqn', "$NQN\n");
+ put('/sys/class/nvme-subsystem/nvme-subsys0/iopolicy', "numa\n");
+ put('/sys/module/nvme_core/parameters/multipath', "Y\n");
+ is($PLUGIN->activate_storage($storeid, $scfg, {}), 1, 'activation');
+ is(
+ file_get_contents(fs('/sys/class/nvme-subsystem/nvme-subsys0/iopolicy')),
+ "round-robin\n",
+ 'policy',
+ );
+ is(file_get_contents(fs('/sys/class/nvme/nvme1/reconnect_delay')), "2\n", 'tunables');
+ is($PLUGIN->deactivate_storage($storeid, $scfg), 1, 'deactivation');
+ is(
+ join('',
+ map { file_get_contents(fs("/sys/class/nvme/nvme$_/delete_controller")) } 0,
+ 1),
+ '11',
+ 'both controllers are deleted',
+ );
+ },
+);
+
+flow(
+ 'remove the storage' => sub {
+ $PLUGIN->on_delete_hook($storeid, $scfg);
+ ok(!-e fs($secret), 'the key file is gone');
+ },
+);
+
+flow(
+ 'an internal caller names the storage with a tainted ID' => sub {
+ my ($id) = as_read($storeid);
+ ok(tainted($id), 'the ID is tainted');
+ $PLUGIN->on_add_hook($id, $scfg, 'dhchap-key' => $KEY);
+ is(file_get_contents(fs($secret)), "$KEY\n", 'the key file is written');
+ $PLUGIN->on_delete_hook($id, $scfg);
+ ok(!-e fs($secret), 'and removed');
+
+ my ($other) = as_read('../x');
+ eval { $PLUGIN->on_delete_hook($other, $scfg) };
+ is($@, "invalid storage ID\n", 'an ID that is not valid is refused');
+ },
+);
+
+done_testing();
diff --git a/src/test/zfsnvme_target_test.pm b/src/test/zfsnvme_target_test.pm
index 4ea7057b..687ba7fd 100644
--- a/src/test/zfsnvme_target_test.pm
+++ b/src/test/zfsnvme_target_test.pm
@@ -3745,4 +3745,770 @@ subtest 'target call timeouts' => sub {
$rpcenv_mock->unmock_all();
};
+# The goals of the swept flows. They only read the state: a lookup that
+# created a missing namespace would change the outcome of the next check.
+sub exported_ns($m, $nsid) {
+ my $subsys = $m->{subsystems}->{$NQN} // return undef;
+ return $subsys->{ns}->{$nsid};
+}
+
+sub template_done($m, $res) {
+ my $ds = owned_volumes($m)->{'tank/base-101-disk-0'} // return 'template missing';
+ my $ns = exported_ns($m, 2) // return 'template not exported';
+ return 'template not exported' if $ns->{device_path} ne '/dev/zvol/tank/base-101-disk-0';
+ return $m->{snaps}->{'tank/base-101-disk-0@__base__'} ? () : 'base snapshot missing';
+}
+
+sub new_volume_done($name) {
+ return sub($m, $res) {
+ my $owned = owned_volumes($m)->{"tank/$name"} // return "$name missing";
+ my $ns = exported_ns($m, $owned->[0]) // return "$name not exported";
+ return () if $ns->{enable} eq '1' && $ns->{device_uuid} eq $owned->[1];
+ return "$name not exported";
+ };
+}
+
+subtest 'fault sweep' => sub {
+ sweep(
+ 'create',
+ {
+ setup => \&lifecycle_fake,
+ lost_replies => 1,
+ action => $ACT{alloc},
+ done => new_volume_done('vm-200-disk-0'),
+ },
+ );
+ sweep(
+ 'clone',
+ {
+ setup => \&lifecycle_fake,
+ lost_replies => 1,
+ action => $ACT{clone},
+ done => new_volume_done('vm-201-disk-0'),
+ },
+ );
+ sweep(
+ 'destroy',
+ {
+ setup => \&lifecycle_fake,
+ action => $ACT{free},
+ may_vanish => 'tank/vm-101-disk-0',
+ done => sub($m, $res) { $m->{ds}->{'tank/vm-101-disk-0'} ? 'volume left' : () },
+ },
+ );
+ sweep(
+ 'rollback',
+ {
+ setup => \&lifecycle_fake,
+ action => $ACT{rollback},
+ done => sub($m, $res) {
+ my $ns = exported_ns($m, 1) // return 'not exported';
+ return $ns->{enable} eq '1' ? () : 'not exported';
+ },
+ },
+ );
+ sweep(
+ 'template',
+ {
+ setup => \&lifecycle_fake,
+ action => $ACT{template},
+ renames => { 'tank/vm-101-disk-0' => 'tank/base-101-disk-0' },
+ done => \&template_done,
+ },
+ );
+ sweep(
+ 'resize',
+ {
+ setup => \&lifecycle_fake,
+ action => $ACT{resize},
+ done => sub($m, $res) {
+ my $ds = $m->{ds}->{'tank/vm-100-disk-0'} // return 'volume missing';
+ return 'not resized' if $ds->{volsize} != 2 * 1024**3;
+ return $res->{fake}->{revalidated}->{"$NQN/1"} ? () : 'not revalidated';
+ },
+ },
+ );
+ sweep(
+ 'activation after a configfs loss',
+ {
+ setup => sub () { lifecycle_fake()->reboot(1) },
+ action => $ACT{activate},
+ done => sub($m, $res) { () },
+ },
+ );
+};
+
+subtest 'two storages on one target' => sub {
+ my $nqn_b = 'nqn.2026-01.com.example:zfsnvme-b';
+ my $scfg_a = scfg(pool => 'tank/a');
+ my $scfg_b = scfg(pool => 'tank/b', subsysnqn => $nqn_b);
+ my $new = sub () { FakeTarget->new(pools => [qw(tank tank/a tank/b)]) };
+
+ # B, with another key, takes the lock first, between A's lockless read and A's locked read
+ my $fake = $new->();
+ my ($res, $b_res);
+ {
+ local $LOCK_HOOK = sub($name) {
+ $b_res = flow($fake, sub { activate($scfg_b, $KEY_B) });
+ };
+ $res = flow($fake, sub { activate($scfg_a, $KEY) });
+ }
+ is($b_res->{error}, '', 'B configures the target first');
+ like($res->{error}, qr/in-use DH-HMAC-CHAP key/, 'A is refused by its locked read');
+ ok(!$fake->{m}->{subsystems}->{$NQN}, 'without creating anything');
+ is_deeply(
+ [map { $fake->{m}->{hosts}->{$_}->{key} } @HOSTS],
+ [$KEY_B, $KEY_B],
+ "B's key is kept",
+ );
+
+ # (a) a target restart between the verify read and the publish
+ for my $loaded (0, 1) {
+ $fake = FakeTarget->new(pools => ['tank']);
+ my $restarted = 0;
+ my @online;
+ my $ctx =
+ { nqn => $NQN, pool => 'tank', hosts => [@HOSTS], key => $KEY, port_ids => [] };
+ $ctx->{foreign} = foreign_view($fake->{m}, [], $NQN, [@HOSTS]);
+ $fake->{before_call} = sub($f, $call) {
+ $f->reboot($loaded) if $call->{op} =~ /\Alink / && !$restarted++;
+ };
+ $fake->{after_call} = sub($f, $call) { push @online, online_violations($f, $ctx) };
+ $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/cannot publish NVMe subsystem '\Q$NQN\E'/,
+ 'a restart before the publish fails it',
+ );
+ ok(!grep({ $_->{links}->%* } values $fake->{m}->{ports}->%*), 'nothing is linked');
+ $fake->{before_call} = undef;
+ $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'the next activation restores the target');
+ is_deeply(\@online, [], 'never published before the ACLs and keys');
+ ok(
+ $fake->{m}->{ports}->{1}->{links}->{$NQN}
+ && $fake->{m}->{ports}->{2}->{links}->{$NQN},
+ 'and publishes it',
+ );
+ }
+
+ # ports are shared, whoever creates them
+ $fake = $new->();
+ {
+ local $LOCK_HOOK = sub($name) {
+ $b_res = flow($fake, sub { activate($scfg_b, $KEY) });
+ };
+ $res = flow($fake, sub { activate($scfg_a, $KEY) });
+ }
+ ok(!$res->{error} && !$b_res->{error}, 'two storages with one key on the same portals');
+ is_deeply(
+ [sort map { $_->{attr}->{addr_traddr} } values $fake->{m}->{ports}->%*],
+ ['192.0.2.21', '192.0.2.22'],
+ 'share one port per address',
+ );
+ ok(
+ !grep({ !($_->{links}->{$NQN} && $_->{links}->{$nqn_b}) }
+ values $fake->{m}->{ports}->%*),
+ 'both subsystems are published on both',
+ );
+
+ # lifecycle operations of both storages
+ my ($a_vol, $b_vol);
+ {
+ local $LOCK_HOOK = sub($name) {
+ $b_vol = flow(
+ $fake, sub { $PLUGIN->alloc_image('b', $scfg_b, 300, 'raw', undef, 1024) },
+ );
+ };
+ $a_vol =
+ flow($fake, sub { $PLUGIN->alloc_image('a', $scfg_a, 300, 'raw', undef, 1024) });
+ }
+ is_deeply(
+ [$a_vol->{result}, $b_vol->{result}],
+ ['vm-300-disk-0', 'vm-300-disk-0'],
+ 'volumes in both pools',
+ );
+ is_deeply(
+ [
+ sort keys $fake->{m}->{subsystems}->{$NQN}->{ns}->%*,
+ sort keys $fake->{m}->{subsystems}->{$nqn_b}->{ns}->%*,
+ ],
+ [1, 1],
+ 'with independent namespace IDs',
+ );
+};
+
+subtest 'each port is published on its own' => sub {
+ my $fake = FakeTarget->new(pools => ['tank'], unbindable => { 2 => 1 });
+ my $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'a port that cannot bind its address');
+ like(
+ join("\n", $res->{warnings}->@*),
+ qr/cannot publish NVMe subsystem '\Q$NQN\E' on port 2: .*Cannot assign requested address/,
+ 'only warns',
+ );
+ ok(
+ $fake->{m}->{ports}->{1}->{links}->{$NQN} && !$fake->{m}->{ports}->{2}->{links}->{$NQN},
+ 'while the other port serves the subsystem',
+ );
+ $res = flow($fake, $ACT{activate});
+ ok(grep({ $_ eq 'link NVMe subsystem on port 2' } ops($res)->@*), 'and is retried');
+
+ $fake = FakeTarget->new(pools => ['tank'], unbindable => { 1 => 1, 2 => 1 });
+ $res = flow($fake, $ACT{activate});
+ like(
+ $res->{error},
+ qr/\Acannot publish NVMe subsystem '\Q$NQN\E': ln: .*Cannot assign requested address\n\z/,
+ 'without any port the activation fails',
+ );
+};
+
+subtest 'UUIDs are compared in lower case' => sub {
+ my $upper = uc($U{9} =~ tr/9/a/r);
+ my $lower = lc($upper);
+ is(
+ inventory(@POOL, zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $upper))->{volumes}
+ ->{'tank/vm-100-disk-0'}->{uuid},
+ $lower,
+ 'the inventory normalizes the UUID',
+ );
+ my $dup = inventory(
+ @POOL,
+ zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $upper),
+ zfs_rows('tank/vm-101-disk-0', 'volume', $NQN, 2, $lower),
+ );
+ eval { nv('_nvmet_owned_identity', $dup, $NQN, 'tank/vm-100-disk-0') };
+ like($@, qr/duplicate NVMe identity/, 'a UUID that differs only in case is a duplicate');
+
+ my $fake = target_fake();
+ $fake->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $upper]);
+ my $res = flow($fake, $ACT{activate});
+ is($res->{error}, '', 'the volume is exported');
+ ok(exported($fake, 1, $lower, '/dev/zvol/tank/vm-100-disk-0'), 'under its UUID');
+ $res = flow($fake, $ACT{activate});
+ is_deeply(ops($res), ['read target state'], 'which then is converged');
+};
+
+my $INVENTORY_TEXT = 'zfs get -H -p -d 1 -t filesystem,volume -o name,property,value,source'
+ . ' type,proxmox:nvme-subsys,proxmox:nvme-nsid,proxmox:nvme-uuid,proxmox:nvme-last-nsid tank';
+my $MARKER_TEXT = q{printf '%s\n' ZFSNVME-CONFIGFS};
+my $CONFIGFS_TEXT =
+ q{env 'LC_ALL=C' find /sys/kernel/config/nvmet}
+ . q{ '(' -path '/sys/kernel/config/nvmet/subsystems/*/passthru'}
+ . q{ -o -path '/sys/kernel/config/nvmet/ports/*/ana_groups'}
+ . q{ -o -path '/sys/kernel/config/nvmet/ports/*/referrals' ')' -type d -prune}
+ . q{ -o -type d -exec printf 'D %s\n' '{}' +}
+ . q{ -o -type l -exec printf 'L %s\n' '{}' +}
+ . q{ -o -type f '(' -name enable -o -name device_path -o -name device_uuid -o -name buffered_io}
+ . q{ -o -name attr_model -o -name attr_serial -o -name attr_allow_any_host}
+ . q{ -o -name addr_trtype -o -name addr_adrfam -o -name addr_traddr -o -name addr_trsvcid ')'}
+ . q{ -exec grep '' /dev/null '{}' +};
+my $CONFIGFS_KEYS_TEXT =
+ $CONFIGFS_TEXT
+ . q{ -o -type f '('}
+ . join(' -o', map { " -path $ROOT/hosts/$_/dhchap_key" } @HOSTS)
+ . q{ ')' -exec sha256sum '{}' +};
+my $STATE_TEXT = "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_TEXT";
+my $LOCKED_STATE_TEXT = "modprobe nvmet_tcp && $STATE_TEXT";
+
+sub w_text($path, $value) {
+ return "printf '%s\\n' $value > $path";
+}
+
+sub build_text($nsid, $uuid, $dev) {
+ my $ns = "$S/namespaces/$nsid";
+ return join(
+ ' && ',
+ "test -b $dev", "mkdir $ns",
+ w_text("$ns/device_path", $dev),
+ w_text("$ns/device_uuid", $uuid),
+ w_text("$ns/buffered_io", 0),
+ w_text("$ns/enable", 1),
+ );
+}
+
+sub rendered($res) {
+ return [map { $_->{rendered} } $res->{calls}->@*];
+}
+
+subtest 'golden commands' => sub {
+ my @H = map { "$ROOT/hosts/$_" } @HOSTS;
+ my $serial = 'PVEZFS' . substr(sha256_hex($NQN), 0, 14);
+ my $port = sub($id, $address) {
+ my $P = "$ROOT/ports/$id";
+ return join(
+ ' && ',
+ "mkdir $P",
+ w_text("$P/addr_trtype", 'tcp'),
+ w_text("$P/addr_adrfam", 'ipv4'),
+ w_text("$P/addr_traddr", $address),
+ w_text("$P/addr_trsvcid", 4420),
+ );
+ };
+ my $link = sub($id) {
+ return join(
+ ' && ',
+ "grep -qx 0 $S/attr_allow_any_host",
+ (map { "test -L $S/allowed_hosts/$_" } @HOSTS),
+ "ln -s $S $ROOT/ports/$id/subsystems/$NQN",
+ );
+ };
+
+ my $fake = FakeTarget->new(pools => ['tank']);
+ $fake->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $U{1}]);
+ is_deeply(
+ rendered(flow($fake, $ACT{activate})),
+ [
+ "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+ "modprobe nvmet_tcp && $INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+ join(
+ ' && ',
+ "mkdir $S",
+ w_text("$S/attr_model", q{'Proxmox ZFS NVMe'}),
+ w_text("$S/attr_serial", $serial),
+ w_text("$S/attr_allow_any_host", 0),
+ $port->(1, '192.0.2.21'),
+ $port->(2, '192.0.2.22'),
+ "mkdir $H[0]",
+ "mkdir $H[1]",
+ "chmod 0600 $H[0]/dhchap_key $H[0]/dhchap_ctrl_key $H[1]/dhchap_key"
+ . " $H[1]/dhchap_ctrl_key",
+ "dd ibs=4096 obs=8192 2>/dev/null | tee $H[0]/dhchap_key $H[1]/dhchap_key"
+ . ' >/dev/null',
+ "ln -s $H[0] $S/allowed_hosts/$HOSTS[0]",
+ "ln -s $H[1] $S/allowed_hosts/$HOSTS[1]",
+ build_text(1, $U{1}, '/dev/zvol/tank/vm-100-disk-0'),
+ ),
+ "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+ $link->(1),
+ $link->(2),
+ ],
+ 'read, configure with a key from stdin, verify and publish',
+ );
+ $fake = lifecycle_fake();
+ is_deeply(
+ rendered(flow($fake, sub { $PLUGIN->path(scfg(), 'vm-100-disk-0', 'st') })),
+ [$INVENTORY_TEXT],
+ 'the ZFS inventory',
+ );
+ my $res = flow($fake, sub { $PLUGIN->alloc_image('st', scfg(), 200, 'raw', undef, 1024) });
+ my $uuid = $fake->{m}->{ds}->{'tank/vm-200-disk-0'}->{props}->{'proxmox:nvme-uuid'};
+ is_deeply(
+ rendered($res),
+ [
+ 'zfs list -o name,volsize,origin,type -t volume,filesystem -d1 -Hp tank',
+ $LOCKED_STATE_TEXT,
+ "zfs set 'proxmox:nvme-last-nsid=4' tank",
+ "zfs create -s -b 16k -o 'proxmox:nvme-subsys=$NQN' -o 'proxmox:nvme-nsid=4'"
+ . " -o 'proxmox:nvme-uuid=$uuid' -V 1024k tank/vm-200-disk-0",
+ 'test -b /dev/zvol/tank/vm-200-disk-0',
+ build_text(4, $uuid, '/dev/zvol/tank/vm-200-disk-0'),
+ $STATE_TEXT,
+ ],
+ 'read, reserve, create, wait, export and verify',
+ );
+ is_deeply(
+ rendered(flow(
+ $fake,
+ sub { $PLUGIN->volume_resize(scfg(), 'st', 'vm-200-disk-0', 2 * 1024**3, 0) },
+ )),
+ [
+ $LOCKED_STATE_TEXT,
+ "zfs set 'volsize=2097152k' tank/vm-200-disk-0 && "
+ . w_text("$S/namespaces/4/revalidate_size", 1),
+ ],
+ 'read, then resize and revalidate',
+ );
+ is_deeply(
+ rendered(flow($fake, sub { $PLUGIN->free_image('st', scfg(), 'vm-101-disk-0') })),
+ [
+ $LOCKED_STATE_TEXT,
+ join(
+ ' && ',
+ w_text("$S/namespaces/2/enable", 0),
+ "rmdir $S/namespaces/2",
+ 'zfs destroy -r tank/vm-101-disk-0',
+ ),
+ ],
+ 'unexport and destroy',
+ );
+ is_deeply(
+ rendered(flow(
+ $fake,
+ sub { $PLUGIN->volume_snapshot_rollback(scfg(), 'st', 'vm-100-disk-0', 'snap1') },
+ )),
+ [
+ $LOCKED_STATE_TEXT,
+ join(' && ',
+ w_text("$S/namespaces/1/enable", 0),
+ "rmdir $S/namespaces/1",
+ 'zfs rollback tank/vm-100-disk-0@snap1',
+ "zfs set 'proxmox:nvme-subsys=$NQN' 'proxmox:nvme-nsid=1'"
+ . " 'proxmox:nvme-uuid=$U{1}' tank/vm-100-disk-0"),
+ 'test -b /dev/zvol/tank/vm-100-disk-0',
+ build_text(1, $U{1}, '/dev/zvol/tank/vm-100-disk-0'),
+ ],
+ 'unexport, roll back, write the identity and export again',
+ );
+ is_deeply(
+ rendered(flow($fake, sub { $PLUGIN->create_base('st', scfg(), 'vm-100-disk-0') })),
+ [
+ $LOCKED_STATE_TEXT,
+ join(' && ',
+ w_text("$S/namespaces/1/enable", 0),
+ "rmdir $S/namespaces/1",
+ 'zfs rename tank/vm-100-disk-0 tank/base-100-disk-0'),
+ 'test -b /dev/zvol/tank/base-100-disk-0',
+ build_text(1, $U{1}, '/dev/zvol/tank/base-100-disk-0')
+ . ' && zfs snapshot tank/base-100-disk-0@__base__',
+ ],
+ 'unexport, rename, export and snapshot',
+ );
+ $res = flow($fake, sub { $PLUGIN->clone_image(scfg(), 'st', 'base-102-disk-0', 201) });
+ $uuid = $fake->{m}->{ds}->{'tank/vm-201-disk-0'}->{props}->{'proxmox:nvme-uuid'};
+ is_deeply(
+ [map { $_->{rendered} } $res->{calls}->@[2, 3]],
+ [
+ "zfs set 'proxmox:nvme-last-nsid=5' tank",
+ "zfs clone -o 'proxmox:nvme-subsys=$NQN' -o 'proxmox:nvme-nsid=5'"
+ . " -o 'proxmox:nvme-uuid=$uuid' tank/base-102-disk-0\@__base__ tank/vm-201-disk-0",
+ ],
+ 'reserve and clone',
+ );
+
+ $fake = lifecycle_fake(
+ step_fault => sub($s, $c) { step_is($s, 'rmdir', "$S/namespaces/2") ? 'busy' : undef },
+ );
+ $res = flow($fake, sub { $PLUGIN->free_image('st', scfg(), 'vm-101-disk-0') });
+ is(
+ $res->{calls}->[-1]->{rendered},
+ 'test -b /dev/zvol/tank/vm-101-disk-0 && ' . w_text("$S/namespaces/2/enable", 1),
+ 'enable again',
+ );
+
+ $fake = FakeTarget->new(pools => ['tank']);
+ $fake->{m}->{mounted} = 0;
+ $res = flow($fake, $ACT{activate});
+ ok(grep({ $_ eq 'cat /proc/mounts' } rendered($res)->@*), 'the mount table');
+ ok(
+ grep({ $_ eq 'mount -t configfs none /sys/kernel/config' } rendered($res)->@*),
+ 'the mount',
+ );
+
+ $fake = target_fake();
+ $fake->add_port(5, '192.0.2.99', 4420, links => [$NQN]);
+ is(
+ rendered(flow($fake, $ACT{activate}))->[-1],
+ "rm $ROOT/ports/5/subsystems/$NQN",
+ 'unlink',
+ );
+
+ $fake = lifecycle_fake();
+ $fake->{m}->{subsystems}->{$NQN}->{attr}->{attr_allow_any_host} = '1';
+ $fake->{m}->{subsystems}->{$NQN}->{acl} = {};
+ is(
+ rendered(flow($fake, $ACT{activate}))->[2],
+ join(
+ ' && ',
+ w_text("$S/attr_allow_any_host", 0),
+ map { "ln -s $ROOT/hosts/$_ $S/allowed_hosts/$_" } @HOSTS,
+ ),
+ 'allow_any_host before the ACLs',
+ );
+
+ $fake = lifecycle_fake();
+ my @generic = (
+ [sub { [$PLUGIN->status('st', scfg())] }, 'zfs get -o value -Hp available,used tank'],
+ [
+ sub { $PLUGIN->volume_snapshot_info(scfg(), 'st', 'vm-100-disk-0') },
+ 'zfs list -Hp -r -t snapshot -o name,guid,creation tank/vm-100-disk-0',
+ ],
+ [
+ sub { $PLUGIN->volume_rollback_is_possible(scfg(), 'st', 'vm-100-disk-0', 'snap1') }
+ ,
+ 'zfs list -H -r -t snapshot -o name -s creation tank/vm-100-disk-0',
+ ],
+ [
+ sub { [$PLUGIN->volume_size_info(scfg(), 'st', 'vm-100-disk-0')] },
+ 'zfs get -o value -Hp volsize,usedbydataset tank/vm-100-disk-0',
+ ],
+ [
+ sub { $PLUGIN->volume_snapshot(scfg(), 'st', 'vm-100-disk-0', 'snap2') },
+ 'zfs snapshot tank/vm-100-disk-0@snap2',
+ ],
+ [
+ sub { $PLUGIN->volume_snapshot_delete(scfg(), 'st', 'vm-100-disk-0', 'snap2') },
+ 'zfs destroy tank/vm-100-disk-0@snap2',
+ ],
+ );
+
+ for my $case (@generic) {
+ is(rendered(flow($fake, $case->[0]))->[0], $case->[1], $case->[1]);
+ }
+ is(
+ rendered(flow($fake, sub { $PLUGIN->list_images('st', scfg()) }))->[1],
+ 'zfs get -H -d 1 -o name,value,source proxmox:nvme-subsys tank',
+ 'the ownership query',
+ );
+};
+
+sub sh($command, $input = undef) {
+ my $err = gensym;
+ my $pid = open3(my $in, my $out, $err, '/bin/sh', '-c', $command);
+ print {$in} $input if defined($input);
+ close($in);
+ my $stdout = do { local $/; <$out> }
+ // '';
+ my $stderr = do { local $/; <$err> }
+ // '';
+ waitpid($pid, 0) == $pid or die "wait for test shell: $!\n";
+ my $status = $?;
+ return ($status & 127 ? 128 + ($status & 127) : $status >> 8, $stdout, $stderr);
+}
+
+# The subtests that run rendered commands need these tools. A Debian build
+# has them, so a missing one is an error, never a silently skipped test.
+{
+ my @tools = qw(find grep sha256sum dd tee);
+ BAIL_OUT('needs /bin/sh with ' . join(', ', @tools))
+ if !-x '/bin/sh' || (sh('command -v ' . join(' ', @tools)))[0] != 0;
+}
+
+subtest 'quoting' => sub {
+ my $dir = tempdir(CLEANUP => 1);
+ for my $value (
+ 'a b',
+ q{it's},
+ "\$(touch $dir/pwned)",
+ "`touch $dir/pwned`",
+ '-n',
+ '*',
+ '%s\n',
+ q{"x"},
+ 'x;y',
+ 'a && b',
+ '|',
+ '~root',
+ "tab\there",
+ '',
+ '$HOME',
+ 'a\\b',
+ '#c',
+ ) {
+ my $file = "$dir/value";
+ my ($rc) = sh(nv('_nvmet_render', [write_step($file, $value)]));
+ is($rc . slurp($file), "0$value\n", 'a write keeps ' . ($value =~ s/\t/\\t/r));
+ my (undef, $out) = sh(nv('_nvmet_render', [['printf', '%s\n', $value]]));
+ is($out, "$value\n", 'an argument keeps ' . ($value =~ s/\t/\\t/r));
+ }
+ ok(!-e "$dir/pwned", 'no value is executed');
+};
+
+subtest 'renderer rejections' => sub {
+ for my $case (
+ ['a newline in a value', [write_step("$S/x", "a\nb")]],
+ ['a NUL in a value', [write_step("$S/x", "a\0b")]],
+ ['a CR in an argument', [['zfs', 'get', "a\rb"]]],
+ ['an undefined argument', [['zfs', 'get', undef]]],
+ ['an undefined value', [write_step("$S/x", undef)]],
+ ['a reference as argument', [['zfs', 'get', []]]],
+ ['a relative write', [write_step('x', 1)]],
+ ['a relative key path', [{ key => ['x'] }]],
+ ['an empty key step', [{ key => [] }]],
+ ['two key steps', [{ key => ['/a'] }, { key => ['/b'] }]],
+ ['bash', [['bash', '-c', 'true']]],
+ ['sh', [['sh', '-c', 'true']]],
+ ['perl', [['perl', '-e', '1']]],
+ ['an absolute command', [['/bin/rm', '/a']]],
+ ['an empty command', [[]]],
+ ['a write with extra keys', [{ write => '/a', value => 1, mode => 1 }]],
+ ['an unknown step', [{ run => '/a' }]],
+ ['a string step', ['mkdir /a']],
+ ['no steps', []],
+ ['a string', 'mkdir /a'],
+ ) {
+ eval { nv('_nvmet_render', $case->[1]) };
+ is($@, "internal error: invalid NVMe target step\n", "rejects $case->[0]");
+ }
+};
+
+subtest 'the rendered chains on a configfs stand-in' => sub {
+ my $dir = tempdir(CLEANUP => 1);
+ my $root = "$dir/nvmet";
+ mkdir($_) or die "mkdir $_: $!\n" for $root, map { "$root/$_" } qw(hosts ports subsystems);
+ my $device = "$dir/device";
+ symlink('/dev/null', $device) or die "symlink: $!\n";
+ my $box = sub($path) { $path =~ s{\A\Q$ROOT\E(?=/|\z)}{$root}r };
+ my $kind = sub($path) {
+ my $rel = substr($path, length($root) + 1);
+ return 'subsystem' if $rel =~ m{\Asubsystems/[^/]+\z};
+ return 'namespace' if $rel =~ m{\Asubsystems/[^/]+/namespaces/[0-9]+\z};
+ return 'port' if $rel =~ m{\Aports/[0-9]+\z};
+ return 'host' if $rel =~ m{\Ahosts/[^/]+\z};
+ die "unexpected directory $path\n";
+ };
+ my %attrs = (
+ subsystem => {
+ attr_model => 'Linux',
+ attr_serial => '0123456789abcdef',
+ attr_allow_any_host => 0,
+ },
+ namespace => {
+ enable => 0,
+ device_path => '(null)',
+ device_uuid => $U{9},
+ buffered_io => 0,
+ },
+ port => { addr_trtype => '', addr_adrfam => '', addr_traddr => '', addr_trsvcid => '' },
+ host => { dhchap_key => '', dhchap_ctrl_key => '' },
+ );
+ my %groups = (subsystem => ['namespaces', 'allowed_hosts'], port => ['subsystems']);
+ # configfs creates attributes and default groups with each directory and removes them with
+ # it, and the stand-in does both with the same commands.
+ my $shim = sub($steps) {
+ my @out;
+ for my $step ($steps->@*) {
+ if (ref($step) eq 'HASH' && exists($step->{write})) {
+ push @out, write_step($box->($step->{write}), $step->{value});
+ } elsif (ref($step) eq 'HASH') {
+ push @out, { key => [map { $box->($_) } $step->{key}->@*] };
+ } elsif ($step->[0] eq 'test' && $step->[1] eq '-b') {
+ push @out, ['test', '-L', $device];
+ } elsif ($step->[0] eq 'mkdir') {
+ for my $path (map { $box->($_) } $step->@[1 .. $step->$#*]) {
+ my $type = $kind->($path);
+ push @out, ['mkdir', $path, map { "$path/$_" } ($groups{$type} // [])->@*];
+ push @out, map { write_step("$path/$_", $attrs{$type}->{$_}) }
+ sort keys $attrs{$type}->%*;
+ }
+ } elsif ($step->[0] eq 'rmdir') {
+ for my $path (map { $box->($_) } $step->@[1 .. $step->$#*]) {
+ my $type = $kind->($path);
+ push @out, ['rm', map { "$path/$_" } sort keys $attrs{$type}->%*];
+ push @out, ['rmdir', map { "$path/$_" } $groups{$type}->@*]
+ if $groups{$type};
+ push @out, ['rmdir', $path];
+ }
+ } else {
+ push @out, [map { $box->($_) } $step->@*];
+ }
+ }
+ return \@out;
+ };
+ my $run = sub($steps, $input = undef) {
+ my ($rc, undef, $err) = sh(nv('_nvmet_render', $shim->($steps)), $input);
+ return ($rc, $err);
+ };
+
+ my $capture = FakeTarget->new(pools => ['tank']);
+ flow($capture, $ACT{activate});
+ my ($find) = grep { step_is($_, 'env') } $capture->{calls}->[0]->{steps}->@*;
+ my $read = sub () {
+ my ($rc, $out, $err) = sh(nv('_nvmet_render', $shim->([$find])));
+ die "configfs read failed: $err\n" if $rc;
+ $out =~ s{\Q$root\E}{$ROOT}g;
+ return nv('_nvmet_parse_configfs', $out);
+ };
+ my $inv = inventory(@POOL, @ONE);
+ my $conf = { nqn => $NQN, portals => $PORTALS, hostnqns => [@HOSTS], keysha => $KEY_SHA };
+ my $plan = nv('_nvmet_plan_activation', $inv, $read->(), $conf);
+ my ($rc, $err) = $run->([map { $_->@* } $plan->{prepublish}->@*], "$KEY\n");
+ is($rc, 0, 'the whole configuration runs as one chain') or diag($err);
+ my $cfs = $read->();
+ is_deeply(
+ nv('_nvmet_plan_activation', $inv, $cfs, $conf)->{prepublish},
+ [],
+ 'and converges',
+ );
+ is_deeply(
+ [map { $cfs->{hosts}->{$_}->{key_sha256} } @HOSTS],
+ [$KEY_SHA, $KEY_SHA],
+ 'the digests read back equal sha256 of the key and a newline',
+ );
+ is_deeply(
+ [map { (stat("$root/hosts/$_/dhchap_key"))[2] & 07777 } @HOSTS],
+ [0600, 0600],
+ 'and the key attributes are readable by their owner only',
+ );
+
+ # Only the kernel's own groups are skipped: the ACL of another tool's
+ # subsystem named like one of them is read and protects the key.
+ my $other = "$root/subsystems/referrals";
+ mkdir($_) or die "mkdir $_: $!\n" for $other, "$other/allowed_hosts", "$other/namespaces";
+ for my $attr (keys $attrs{subsystem}->%*) {
+ open(my $fh, '>', "$other/$attr") or die "open: $!\n";
+ print {$fh} "$attrs{subsystem}->{$attr}\n";
+ close($fh);
+ }
+ symlink("$root/hosts/$HOSTS[0]", "$other/allowed_hosts/$HOSTS[0]") or die "symlink: $!\n";
+ mkdir($_)
+ or die "mkdir $_: $!\n"
+ for "$root/ports/1/referrals", "$root/ports/1/referrals/r";
+ my (undef, $raw) = sh(nv('_nvmet_render', $shim->([$find])));
+ ok(
+ $read->()->{subsystems}->{referrals}->{acl}->{ $HOSTS[0] },
+ 'a subsystem named referrals',
+ );
+ unlike($raw, qr{/ports/1/referrals}, 'while the referrals of a port are skipped');
+ unlink("$other/allowed_hosts/$HOSTS[0]", map { "$other/$_" } keys $attrs{subsystem}->%*);
+ rmdir($_)
+ or die "rmdir $_: $!\n"
+ for "$other/allowed_hosts", "$other/namespaces", $other, "$root/ports/1/referrals/r",
+ "$root/ports/1/referrals";
+
+ for my $unit (nv('_nvmet_plan_publish', $cfs, $NQN, $plan->{port_ids}, [@HOSTS])->@*) {
+ ($rc) = $run->($unit->{steps});
+ is($rc, 0, "the guarded link to port $unit->{port}");
+ }
+ is_deeply(nv('_nvmet_plan_publish', $read->(), $NQN, [1, 2], [@HOSTS]), [], 'publishes');
+
+ unlink("$root/ports/1/subsystems/$NQN", "$root/subsystems/$NQN/allowed_hosts/$HOSTS[1]");
+ my ($unit) = nv('_nvmet_plan_publish', $read->(), $NQN, [1], [@HOSTS])->@*;
+ ($rc) = $run->($unit->{steps});
+ ok($rc && !-l "$root/ports/1/subsystems/$NQN", 'the guard blocks a link without every ACL');
+ symlink("$root/hosts/$HOSTS[1]", "$root/subsystems/$NQN/allowed_hosts/$HOSTS[1]") or die;
+ ($rc) = $run->([write_step("$ROOT/subsystems/$NQN/attr_allow_any_host", 1)]);
+ ($rc) = $run->($unit->{steps});
+ ok($rc && !-l "$root/ports/1/subsystems/$NQN", 'and while any host may connect');
+ $run->([write_step("$ROOT/subsystems/$NQN/attr_allow_any_host", 0)]);
+ ($rc) = $run->($unit->{steps});
+ ok(!$rc && -l "$root/ports/1/subsystems/$NQN", 'but links once both hold');
+
+ my ($units) = nv('_nvmet_plan_unexport', $read->(), $NQN, $U{1});
+ ($rc) = $run->([map { $_->@* } $units->@*]);
+ ok(!$rc && !-e "$root/subsystems/$NQN/namespaces/1", 'the unexport chain removes it');
+};
+
+# Last: every command rendered during this test run, and every protocol violation recorded (by a
+# fake target: a key on a command line or in output, a change without the lock, or a local command).
+subtest 'every rendered command is a POSIX command chain' => sub {
+ is_deeply(\@VIOLATIONS, [], 'no flow violated the target protocol');
+ my %shapes;
+ for my $command (keys %CORPUS) {
+ (my $shape = $command) =~ s/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/U/gi;
+ $shape =~ s/[0-9]+/N/g;
+ $shapes{$shape} //= $command;
+ }
+ ok(keys(%shapes) >= 40, 'the corpus covers ' . keys(%shapes) . ' command shapes');
+ my $meta = qr/[;&|<>`\$(){}\\*?\[\]~#!"]/;
+ my @bad;
+ for my $command (sort values %shapes) {
+ push @bad, "sh -n: $command" if system('/bin/sh', '-n', '-c', $command) != 0;
+ push @bad, "bash-ism: $command"
+ if $command =~ /\[\[|\$\(\(|<<<|\$'|pipefail|(?:\A|&& )(?:function|source|\.) /;
+ (my $bare = $command) =~ s/'[^']*'|\\'//g;
+ for my $segment (split / && /, $bare) {
+ next
+ if $segment =~ m{\Add\ ibs=4096\ obs=8192\ 2>/dev/null\ \|\ tee(?:\ /[^\s;&|<>]+)+
+ \ >/dev/null\z}x;
+ if ($segment =~ /\Aprintf +(\S*) +> (\S+)\z/) {
+ push @bad, "write: $segment" if "$1$2" =~ $meta;
+ next;
+ }
+ push @bad, "shell syntax: $segment" if $segment =~ $meta;
+ }
+ }
+ is_deeply(\@bad, [], 'every command is a plain POSIX command chain');
+};
+
done_testing();
--
2.54.0.windows.1
^ permalink raw reply related [relevance 9%]
* [PATCH docs v5] storage: document ZFS over NVMe/TCP
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
` (6 preceding siblings ...)
2026-11-26 15:09 9% ` [PATCH storage v5 12/13] test: zfsnvme: add a fault sweep, renderer and taint tests Joaquin Varela
@ 2026-11-26 15:10 20% ` Joaquin Varela
2026-11-26 15:11 21% ` [PATCH manager v5] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:10 UTC (permalink / raw)
To: pve-devel
Add a chapter for the zfsnvme storage type with its prerequisites,
properties, an example, what happens when all paths are down, how to
clean up after removing a storage and its limits. List the type in the
table of storage types and include the chapter in pvesm.
The chapter marks the type as a technology preview like the table does.
It says that Proxmox VE refuses to add the first storage of the type
until every node knows it, and how the type differs from NVMe over
Fabrics.
It also says that a removed storage or a failed add leaves its subsystem
on the target. Removing that subsystem is required before a key change,
the revocation of a node, or reusing its portals.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
pve-storage-zfsnvme.adoc | 210 +++++++++++++++++++++++++++++++++++++++
pvesm.adoc | 5 +
2 files changed, 215 insertions(+)
create mode 100644 pve-storage-zfsnvme.adoc
diff --git a/pve-storage-zfsnvme.adoc b/pve-storage-zfsnvme.adoc
new file mode 100644
index 0000000..7374cff
--- /dev/null
+++ b/pve-storage-zfsnvme.adoc
@@ -0,0 +1,210 @@
+[[storage_zfsnvme]]
+ZFS over NVMe/TCP Backend
+-------------------------
+ifdef::wiki[]
+:pve-toplevel:
+:title: Storage: ZFS over NVMe/TCP
+endif::wiki[]
+
+WARNING: ZFS over NVMe/TCP is currently a **technology preview** in {pve}.
+
+Storage pool type: `zfsnvme`
+
+This backend accesses a remote Linux machine with a ZFS pool and the kernel NVMe
+target via `ssh`. For each guest disk it creates a ZVOL and exports it as an
+NVMe namespace over TCP. The {pve} nodes connect with the native NVMe multipath
+of the Linux kernel.
+
+Unlike xref:storage_nvmeof[NVMe over Fabrics], which uses namespaces that a
+storage array already serves, this backend creates and manages the ZVOLs itself
+and exports them with the kernel `nvmet` target, with DH-HMAC-CHAP
+authentication, snapshots and clones.
+
+Prerequisites
+~~~~~~~~~~~~~
+
+. Upgrade all nodes to a {pve} version that includes this storage type, also
+ nodes that will not use it. A node without support removes such storages
+ when it writes the cluster-wide storage configuration, so adding the first
+ ZFS over NVMe/TCP storage is refused while a node is offline or runs an
+ older version.
+. The target needs OpenZFS, configfs, and the `nvmet` and `nvmet-tcp` kernel
+ modules with NVMe in-band authentication support. The plugin loads
+ `nvmet_tcp` and mounts configfs on the target when needed. Root needs a POSIX
+ compatible login shell. The target needs `zfs`, `modprobe`, `mount`, `find`,
+ `grep`, `dd`, `tee`, `sha256sum`, `cat`, `chmod`, `env`, `ln`, `mkdir`,
+ `printf`, `rm`, `rmdir` and `test`, but not Perl or Bash.
+. Configure root `ssh` access like for xref:storage_zfs[ZFS over iSCSI], with
+ the key at `/etc/pve/priv/zfs/<server>_id_rsa`.
+. Disable cloud-init on the target. It can otherwise take a guest disk with a
+ `cidata` file system for its own datasource at boot.
+. Install `nvme-cli` on every node. It creates the host NQN in
+ `/etc/nvme/hostnqn` and the host ID in `/etc/nvme/hostid`, which must be unique
+ for each node. The nodes also need native NVMe multipath, which is the kernel
+ default (`nvme_core.multipath=Y`). The plugin loads the `nvme-tcp` kernel
+ module when it activates a storage.
+
+Configuration
+~~~~~~~~~~~~~
+
+The backend supports the common storage properties `content`, `nodes`,
+`disable`, and the following ZFS over NVMe/TCP specific properties. The
+properties `server`, `pool`, `blocksize`, `subsysnqn` and `nvme-portals` cannot
+be changed after the storage is added. A change to `nvme-keep-alive-tmo` or
+`nvme-nr-io-queues` only applies to new connections.
+
+server:: Required. IP address or DNS name for the `ssh` connection to the
+ target. Guest I/O only uses the NVMe/TCP paths, but volume operations need
+ this connection. Use the same value in all storages on one target.
+
+pool:: Required. ZFS pool or child dataset on the target that holds the volumes.
+ It must not contain, or be contained in, the pool of another storage on the
+ same target.
+
+blocksize:: Required. ZFS volume block size, for example `16k`.
+
+sparse:: Use ZFS thin provisioning. Otherwise volumes reserve their full size.
+
+subsysnqn:: Required. NVMe qualified name of the subsystem. It must be unique in
+ the cluster.
+
+nvme-portals:: Required. Comma-separated IP addresses of the NVMe/TCP listeners
+ on the target, at most 16. The default port is `4420`. Put IPv6 addresses in
+ brackets, for example `[2001:db8::10]:4420`.
++
+Every storage needs its own listeners, which must not publish any other `nvmet`
+subsystem. If a listener does not publish the subsystem yet, for example while
+the target restores its configuration, `nvmet` rejects the connection in a way
+that makes the node delete the controller. Adding, updating or activating a
+storage fails if a portal has the address and port of another ZFS over NVMe/TCP
+storage, or an address that another storage reaches with a different `server`.
+
+nvme-host-ifaces:: Required. Comma-separated local interfaces, one for each
+ portal in the same order. Every node needs interfaces with these names. This
+ keeps a failed path from reconnecting over the management network.
+
+nvme-host-nqns:: Required. Comma-separated contents of `/etc/nvme/hostnqn` of
+ all nodes that may use the storage, at most 64. Activation fails on a node
+ whose host NQN is not listed, so add the NQN of a new node first. Host NQNs can
+ only be added.
+
+dhchap-key:: Required when the storage is added. NVMe DH-HMAC-CHAP secret in
+ `DHHC-1` format, for example from `nvme gen-dhchap-key`. It cannot be changed.
+ As a sensitive property it is stored below `/etc/pve/priv/storage/` and not in
+ `storage.cfg`. With `pvesm`, pass the path of a file that contains the key.
+ The target keeps one key for each host NQN, so storages on one target with
+ overlapping `nvme-host-nqns` need the same key.
+
+nvme-iopolicy:: Native multipath I/O policy: `round-robin` (default),
+ `queue-depth` or `numa`.
+
+nvme-keep-alive-tmo:: Keep-alive timeout in seconds. The default is 5.
+
+nvme-reconnect-delay:: Seconds between the attempts to reconnect a lost
+ controller. The default is 2.
+
+nvme-ctrl-loss-tmo:: Seconds that the kernel keeps reconnecting a lost
+ controller before it deletes it. The default is 600. With `-1` it retries
+ forever.
+
+nvme-fast-io-fail-tmo:: Optional. Seconds after which I/O to a reconnecting
+ controller fails. Without it, the kernel queues I/O until the controller is
+ lost. It must not exceed a finite `nvme-ctrl-loss-tmo`.
+
+nvme-nr-io-queues:: Optional number of I/O queues for each controller.
+
+.Configuration Example (`/etc/pve/storage.cfg`)
+----
+zfsnvme: nvme-shared
+ server 203.0.113.10
+ pool tank/pve-nvme
+ subsysnqn nqn.2026-01.com.example:pve-nvme
+ nvme-portals 192.0.2.10,198.51.100.10
+ nvme-host-ifaces ens1f0,ens1f1
+ nvme-host-nqns nqn.2014-08.org.nvmexpress:uuid:11111111-1111-1111-1111-111111111111,nqn.2014-08.org.nvmexpress:uuid:22222222-2222-2222-2222-222222222222
+ blocksize 16k
+ sparse 1
+ content images
+----
+
+The key is not part of `storage.cfg`. In the web interface, add the storage as
+*ZFS over NVMe/TCP* and enter the key there. With `pvesm`, save the key in a
+file with mode `0600` and pass its path as `--dhchap-key`, then remove the file.
+
+.Storage features for backend `zfsnvme`
+[width="100%",cols="m,m,3*d",options="header"]
+|==============================================================================
+|Content types |Image formats |Shared |Snapshots |Clones
+|images |raw |yes |yes |yes
+|==============================================================================
+
+Security and Availability
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The target allows only the host NQNs of `nvme-host-nqns`. All nodes share the
+DH-HMAC-CHAP key of the storage, so any holder of it can connect as any allowed
+host. The key only authenticates the hosts to the target. The target is not
+authenticated, and the data is not encrypted, so use isolated storage networks.
+The kernel exposes the key in sysfs on the nodes and in configfs on the target,
+so limit shell access on all of them to trusted administrators.
+
+The key cannot be rotated. To change it, or to revoke a node, remove the node
+from the cluster first. Every cluster member can read the keys below
+`/etc/pve/priv/`, which include the `ssh` keys of the targets, so replace those
+too. Then move all volumes off the storage, remove it, and remove its subsystem
+on the target as described under xref:storage_zfsnvme_limits[Limits]. This
+step is required. Until the subsystem is gone, the target still allows the
+revoked host NQN with the old key, and it refuses a new key for a host NQN that
+the subsystem still allows. Add a new storage with a new key and `subsysnqn`,
+without the revoked host NQN. Storages on one target with overlapping host NQNs
+share the key, so replace them together.
+
+Shared access relies on the cluster locking and fencing of {pve}, so test
+quorum and fencing before you place production guests on the storage. Make sure
+that the ZFS target is not a single point of failure. Changes to the target are
+serialized by a cluster-wide lock and need quorum. Do not use a target with more
+than one cluster.
+
+While all paths of a node are down, I/O is queued until a path returns, or
+fails after `nvme-fast-io-fail-tmo` if set. When they stay down longer than
+`nvme-ctrl-loss-tmo`, the kernel deletes the controllers and the multipath
+devices of the storage on that node. Running guests keep the removed device
+open, so stop and start them after the paths are back, for example with
+`qm stop <vmid>` and `qm start <vmid>`. A reboot inside the guest is not enough.
+A target that rejects a connection, for example for a wrong key, makes the
+kernel delete the controller regardless of the timeout. With `-1` the devices
+are kept, but guest I/O can block for the whole outage unless
+`nvme-fast-io-fail-tmo` is set. Choose these timeouts to fit the workload.
+
+[[storage_zfsnvme_limits]]
+Limits
+~~~~~~
+
+* Only VM disks and VM states are supported, not container volumes.
+* Online resize of a running guest disk is not supported. Stop the VM first.
+* Volumes cannot be renamed. `pvesm export` and `pvesm import` are not
+ supported, so remote migration cannot move disks of this storage. Migration
+ between nodes of the cluster works, as the storage is shared and no disk is
+ copied.
+* Removing a storage never deletes volumes. It only removes the key file of the
+ storage. The controllers stay connected on the nodes. Disconnect them on each
+ node under *NVMe over Fabrics* in its *SAN* panel, where they show no storage
+ once it is gone.
+* Removing a storage, or a failed add, leaves its subsystem on the target, with
+ its host objects and their key. Remove that subsystem before you add a storage
+ with another key for the same host NQNs, or reuse its portals. Otherwise the
+ target refuses the new key, or a portal publishes two subsystems. It is also
+ what ends the access of a revoked node. To do it, remove the port links,
+ the allowed host links, the namespaces and the subsystem directory under
+ `/sys/kernel/config/nvmet`, or use `nvmetcli`. After a plain removal with no
+ new storage it is optional. The `nvmet` configuration is not persistent unless
+ you save it, so a reboot of the target also drops it.
+
+ifdef::wiki[]
+
+See Also
+~~~~~~~~
+
+* link:/wiki/Storage[Storage]
+
+endif::wiki[]
diff --git a/pvesm.adoc b/pvesm.adoc
index ec2ef97..e40c16f 100644
--- a/pvesm.adoc
+++ b/pvesm.adoc
@@ -83,6 +83,7 @@ nodes that can be accessed as RBD (RADOS Block Device).
|FC/SAS |native^6^ |block |yes^3^|yes^4^ |yes
|Ceph/RBD |rbd |block |yes |yes |yes
|ZFS over iSCSI |zfs |block |yes |yes |yes
+|ZFS over NVMe/TCP|zfsnvme |block |yes |yes |TP^5^
|========================================================================
^1^: Disk images for VMs are stored in ZFS volume (zvol) datasets, which provide
@@ -539,6 +540,8 @@ See Also
* link:/wiki/Storage:_ZFS_over_ISCSI[Storage: ZFS over ISCSI]
+* link:/wiki/Storage:_ZFS_over_NVMe/TCP[Storage: ZFS over NVMe/TCP]
+
endif::wiki[]
ifndef::wiki[]
@@ -575,6 +578,8 @@ include::pve-storage-btrfs.adoc[]
include::pve-storage-zfs.adoc[]
+include::pve-storage-zfsnvme.adoc[]
+
ifdef::manvolnum[]
include::pve-copyright.adoc[]
base-commit: 0d8269d6c45caeffed7a6d71b695ad25217c4a4c
--
2.54.0.windows.1
^ permalink raw reply related [relevance 20%]
* [PATCH manager v5] ui: storage: add ZFS over NVMe/TCP editor
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
` (7 preceding siblings ...)
2026-11-26 15:10 20% ` [PATCH docs v5] storage: document ZFS over NVMe/TCP Joaquin Varela
@ 2026-11-26 15:11 21% ` Joaquin Varela
8 siblings, 0 replies; 43+ results
From: Joaquin Varela @ 2026-11-26 15:11 UTC (permalink / raw)
To: pve-devel
Add an input panel for the zfsnvme storage type and list it under SAN
in the Add dialog, with the subsystem NQN as its target.
The pool, block size and thin provision fields are those of ZFS over
iSCSI. Timeouts, I/O queues and the I/O policy use the plugin default
when left empty. Fixed properties are read-only when editing, host
NQNs can only be added and the DH-HMAC-CHAP key is only requested on
creation, as the plugin cannot rotate it.
The help button needs a pve-doc-generator with the storage_zfsnvme
section of the admin guide to generate OnlineHelpInfo.js.
Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
www/manager6/Makefile | 1 +
www/manager6/Utils.js | 6 +
www/manager6/dc/StorageView.js | 8 +
www/manager6/storage/ZFSNVMeEdit.js | 220 ++++++++++++++++++++++++++++
4 files changed, 235 insertions(+)
create mode 100644 www/manager6/storage/ZFSNVMeEdit.js
diff --git a/www/manager6/Makefile b/www/manager6/Makefile
index cdf222a2..b5c0f40e 100644
--- a/www/manager6/Makefile
+++ b/www/manager6/Makefile
@@ -389,6 +389,7 @@ JSSRC= \
storage/TemplateView.js \
storage/AddWizard.js \
storage/ZFSEdit.js \
+ storage/ZFSNVMeEdit.js \
storage/ZFSPoolEdit.js \
storage/ESXIEdit.js \
storage/wizard/Wizard.js \
diff --git a/www/manager6/Utils.js b/www/manager6/Utils.js
index fc3667f5..ae7079a7 100644
--- a/www/manager6/Utils.js
+++ b/www/manager6/Utils.js
@@ -924,6 +924,12 @@ Ext.define('PVE.Utils', {
faIcon: 'building',
backups: false,
},
+ zfsnvme: {
+ name: 'ZFS over NVMe/TCP',
+ ipanel: 'ZFSNVMeInputPanel',
+ faIcon: 'building',
+ backups: false,
+ },
zfspool: {
name: 'ZFS',
ipanel: 'ZFSPoolInputPanel',
diff --git a/www/manager6/dc/StorageView.js b/www/manager6/dc/StorageView.js
index 7f7d8bd0..11042236 100644
--- a/www/manager6/dc/StorageView.js
+++ b/www/manager6/dc/StorageView.js
@@ -78,6 +78,7 @@ Ext.define(
case 'zfspool':
return pool;
case 'nvmeof':
+ case 'zfsnvme':
return subsysnqn;
default:
return target || path;
@@ -224,6 +225,13 @@ Ext.define(
),
'lun target',
],
+ zfsnvme: [
+ 'san',
+ gettext(
+ 'Guest disks as ZFS volumes on a storage server that exports them over NVMe/TCP.',
+ ),
+ 'nvme tcp target subsystem',
+ ],
nfs: ['network', gettext('Mount an NFS export.'), 'nas share'],
cifs: ['network', gettext('Mount an SMB/CIFS share.'), 'nas samba windows'],
pbs: [
diff --git a/www/manager6/storage/ZFSNVMeEdit.js b/www/manager6/storage/ZFSNVMeEdit.js
new file mode 100644
index 00000000..5c5c1e45
--- /dev/null
+++ b/www/manager6/storage/ZFSNVMeEdit.js
@@ -0,0 +1,220 @@
+Ext.define('PVE.storage.ZFSNVMeInputPanel', {
+ extend: 'PVE.panel.StorageBase',
+
+ onlineHelp: 'storage_zfsnvme',
+
+ onGetValues: function (values) {
+ if (this.isCreate) {
+ values.content = 'images';
+ }
+ return this.callParent([values]);
+ },
+
+ initComponent: function () {
+ let me = this;
+
+ // the pool, block size and thin provision fields are those of ZFS over iSCSI
+ let zfs = PVE.storage.ZFSInputPanel.fields(me.isCreate);
+
+ let defaultCtrlLossTmo = 600;
+
+ let splitList = (value) =>
+ (value || '')
+ .split(',')
+ .map((item) => item.trim())
+ .filter((item) => item !== '');
+
+ // properties that are fixed after creation are read-only when editing
+ let fixedText = (config) => ({
+ xtype: me.isCreate ? 'textfield' : 'displayfield',
+ value: '',
+ allowBlank: false,
+ allowOnlyWhitespace: false,
+ ...config,
+ });
+
+ // left empty, the plugin default applies and nothing is stored
+ let optionalInt = (config) => ({
+ xtype: 'proxmoxintegerfield',
+ allowBlank: true,
+ deleteEmpty: !me.isCreate,
+ ...config,
+ });
+
+ me.column1 = [
+ fixedText({
+ name: 'server',
+ fieldLabel: gettext('SSH Server'),
+ emptyText: gettext('IP address or hostname'),
+ }),
+ { ...zfs.pool, allowOnlyWhitespace: false, emptyText: 'tank/pve-nvme' },
+ { ...zfs.blocksize, value: '16k' },
+ zfs.sparse,
+ ];
+
+ me.column2 = [
+ {
+ xtype: 'textfield',
+ name: 'nvme-host-ifaces',
+ fieldLabel: gettext('Host Interfaces'),
+ emptyText: 'ens1f0,ens1f1',
+ allowBlank: false,
+ allowOnlyWhitespace: false,
+ },
+ // The plugin cannot rotate the key. It is asked for on creation, never shown and never
+ // sent again, so that editing keeps it.
+ me.isCreate
+ ? {
+ xtype: 'textfield',
+ inputType: 'password',
+ name: 'dhchap-key',
+ fieldLabel: gettext('DH-HMAC-CHAP Key'),
+ emptyText: 'DHHC-1:xx:...:',
+ regex: /^DHHC-1:0[0-3]:[A-Za-z0-9+/]+={0,2}:$/,
+ regexText: gettext('Expected format: DHHC-1:xx:...:'),
+ allowBlank: false,
+ }
+ : {
+ xtype: 'displayfield',
+ fieldLabel: gettext('DH-HMAC-CHAP Key'),
+ value: gettext('Unchanged (rotation not supported)'),
+ },
+ ];
+
+ // NQNs and portal lists are longer than a column is wide
+ me.columnB = [
+ fixedText({
+ name: 'subsysnqn',
+ fieldLabel: gettext('Subsystem NQN'),
+ emptyText: 'nqn.2026-01.com.example:pve-nvme',
+ // an NQN wraps best at the line end, not at its first hyphen
+ fieldStyle: 'word-break: break-all;',
+ }),
+ fixedText({
+ name: 'nvme-portals',
+ fieldLabel: gettext('NVMe/TCP Portals'),
+ emptyText: '192.0.2.10,198.51.100.10',
+ fieldStyle: 'word-break: break-all;',
+ }),
+ {
+ xtype: 'textfield',
+ name: 'nvme-host-nqns',
+ fieldLabel: gettext('Allowed Host NQNs'),
+ emptyText: 'nqn.2014-08.org.nvmexpress:uuid:...',
+ allowBlank: false,
+ allowOnlyWhitespace: false,
+ validator: function (value) {
+ // the backend refuses to drop a host NQN from an existing storage
+ let current = splitList(value);
+ let removed = splitList(this.originalValue).filter(
+ (hostnqn) => !current.includes(hostnqn),
+ );
+ if (removed.length) {
+ return Ext.String.format(
+ gettext('Host NQN {0} cannot be removed from an existing storage'),
+ Ext.htmlEncode(removed[0]),
+ );
+ }
+ return true;
+ },
+ },
+ {
+ xtype: 'displayfield',
+ userCls: 'pmx-hint',
+ value: gettext(
+ 'List /etc/nvme/hostnqn from every allowed cluster node. Host interface names are matched to portals by position and must exist on every selected node.',
+ ),
+ },
+ ];
+
+ if (!me.isCreate) {
+ me.columnB.push({
+ xtype: 'displayfield',
+ userCls: 'pmx-hint',
+ value: gettext(
+ 'Host NQNs can only be added. Revoking a host requires a new storage with a new key.',
+ ),
+ });
+ }
+
+ me.advancedColumn1 = [
+ {
+ xtype: 'proxmoxKVComboBox',
+ name: 'nvme-iopolicy',
+ value: '__default__',
+ deleteEmpty: !me.isCreate,
+ fieldLabel: gettext('I/O Policy'),
+ comboItems: [
+ ['__default__', `${Proxmox.Utils.defaultText} (round-robin)`],
+ ['round-robin', 'round-robin'],
+ ['queue-depth', 'queue-depth'],
+ ['numa', 'numa'],
+ ],
+ },
+ optionalInt({
+ name: 'nvme-keep-alive-tmo',
+ minValue: 1,
+ maxValue: 120,
+ fieldLabel: gettext('Keep Alive Timeout (s)'),
+ emptyText: `${Proxmox.Utils.defaultText} (5)`,
+ }),
+ optionalInt({
+ name: 'nvme-reconnect-delay',
+ minValue: 1,
+ maxValue: 120,
+ fieldLabel: gettext('Reconnect Delay (s)'),
+ emptyText: `${Proxmox.Utils.defaultText} (2)`,
+ }),
+ optionalInt({
+ name: 'nvme-nr-io-queues',
+ minValue: 1,
+ maxValue: 1024,
+ fieldLabel: gettext('I/O Queues'),
+ emptyText: Proxmox.Utils.defaultText,
+ }),
+ ];
+
+ me.advancedColumn2 = [
+ optionalInt({
+ name: 'nvme-ctrl-loss-tmo',
+ minValue: -1,
+ maxValue: 86400,
+ fieldLabel: gettext('Controller Loss Timeout (s)'),
+ emptyText: `${Proxmox.Utils.defaultText} (${defaultCtrlLossTmo})`,
+ listeners: {
+ change: () => me.down('field[name=nvme-fast-io-fail-tmo]')?.validate(),
+ },
+ }),
+ optionalInt({
+ name: 'nvme-fast-io-fail-tmo',
+ minValue: 0,
+ maxValue: 86400,
+ fieldLabel: gettext('Fast I/O Fail Timeout (s)'),
+ emptyText: gettext('Off'),
+ validator: (value) => {
+ let ctrlLossTmo =
+ me.down('field[name=nvme-ctrl-loss-tmo]')?.getValue() ?? defaultCtrlLossTmo;
+ if (value === '' || ctrlLossTmo < 0) {
+ return true;
+ }
+ return (
+ Number(value) <= ctrlLossTmo ||
+ gettext('Must not exceed the Controller Loss Timeout')
+ );
+ },
+ }),
+ ];
+
+ me.advancedColumnB = [
+ {
+ xtype: 'displayfield',
+ userCls: 'pmx-hint',
+ value: gettext(
+ 'A Controller Loss Timeout of -1 retries forever. Leave Fast I/O Fail Timeout empty to queue I/O until the controller is lost.',
+ ),
+ },
+ ];
+
+ me.callParent();
+ },
+});
base-commit: 16611a25c07c72dccb65c1b95f52c2b847aa6b4b
--
2.54.0.windows.1
^ permalink raw reply related [relevance 21%]
Results 1-43 of 43 | reverse | options above
-- pct% links below jump to the message on this page, permalinks otherwise --
[not found] <20260130073139.248418-2-k.chai@proxmox.com>
2026-02-04 12:19 ` [PATCH proxmox-i18n v3] update Simplified Chinese translations Kefu Chai
2026-02-04 12:19 3% ` Kefu Chai
2026-07-15 16:23 [RFC] Native ZFS over NVMe/TCP storage backend for Proxmox VE Joaquin Varela
2026-07-21 11:45 9% ` Max R. Carrara
2026-08-02 3:20 15% ` Joaquin Varela
2026-08-07 9:46 6% ` Max R. Carrara
2026-08-02 3:31 15% [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend Joaquin Varela
2026-08-02 3:31 16% ` [PATCH storage v2 2/7] zfs: add native NVMe/TCP storage backend Joaquin Varela
2026-09-28 11:53 10% ` [PATCH storage v2 0/7] add native ZFS over NVMe/TCP backend Max R. Carrara
2026-10-05 0:27 15% ` Joaquin Varela
2026-10-21 8:06 6% ` Max R. Carrara
2026-08-28 22:22 8% qemu-img convert runs with cache=unsafe for every block storage except zfspool Ing. Alfonso Kuen Arroyo
2026-09-03 13:15 1% ` SPAM: " Fiona Ebner
2026-10-05 0:26 14% [PATCH storage v3 0/4] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-10-05 0:26 16% ` [PATCH storage v3 1/4] zfsnvme: " Joaquin Varela
2026-10-05 0:26 10% ` [PATCH storage v3 2/4] test: add zfsnvme plugin tests Joaquin Varela
2026-10-05 0:26 18% ` [PATCH docs v3] storage: document ZFS over NVMe/TCP Joaquin Varela
2026-10-05 0:26 22% ` [PATCH manager v3] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela
2026-11-05 23:30 6% [PATCH v3 proxmox,proxmox-perl-rs,cluster,storage,docs,manager 00/76] SAN: cluster-wide multipath, SAN views and a guided storage setup Thomas Lamprecht
2026-11-05 23:31 7% ` [PATCH v3 storage 41/76] api: disks: guard SAN wipes with stable identities and storage checks Thomas Lamprecht
2026-11-13 3:00 [PATCH v4 cluster,storage,docs,manager 00/36] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM Thomas Lamprecht
2026-11-13 3:00 11% ` [PATCH v4 storage 20/36] disks: lvm: allow volume groups on SAN LUNs and multipath maps Thomas Lamprecht
2026-11-13 3:04 [PATCH storage,docs,manager 00/17] NVMe over Fabrics storage Thomas Lamprecht
2026-11-13 3:04 20% ` [PATCH storage 02/17] nvmeof: add a storage for NVMe over Fabrics subsystems Thomas Lamprecht
2026-11-16 1:23 [PATCH v5 cluster,storage,docs,manager 00/36] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM Thomas Lamprecht
2026-11-16 1:23 10% ` [PATCH v5 storage 20/36] disks: lvm: allow volume groups on SAN LUNs and multipath maps Thomas Lamprecht
2026-11-18 6:52 7% [PATCH v6 cluster,storage,docs,manager 00/42] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM Thomas Lamprecht
2026-11-18 6:52 9% ` [PATCH v6 storage 22/42] disks: lvm: allow volume groups on SAN LUNs and multipath maps Thomas Lamprecht
2026-11-18 20:25 6% [PATCH v7 cluster,storage,docs,manager 00/43] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM Thomas Lamprecht
2026-11-18 20:26 9% ` [PATCH v7 storage 23/43] disks: lvm: allow volume groups on SAN LUNs and multipath maps Thomas Lamprecht
2026-11-18 20:42 [PATCH v2 storage,docs,manager 00/17] NVMe over Fabrics storage Thomas Lamprecht
2026-11-18 20:42 20% ` [PATCH v2 storage 02/17] nvmeof: add a storage for NVMe over Fabrics subsystems Thomas Lamprecht
2026-11-19 19:46 [PATCH v8 cluster,storage,docs,manager 00/43] SAN: cluster-wide multipath, SAN views and a guided setup for shared LVM Thomas Lamprecht
2026-11-19 19:46 9% ` [PATCH v8 storage 23/43] disks: lvm: allow volume groups on SAN LUNs and multipath maps Thomas Lamprecht
2026-11-22 1:25 10% [PATCH v3 storage,docs,manager 00/18] NVMe over Fabrics storage Thomas Lamprecht
2026-11-22 1:25 18% ` [PATCH v3 storage 02/18] nvmeof: add a storage for NVMe over Fabrics subsystems Thomas Lamprecht
2026-11-23 1:47 10% [PATCH v4 storage,docs,manager 00/25] NVMe over Fabrics storage Thomas Lamprecht
2026-11-23 1:47 17% ` [PATCH v4 storage 04/25] nvmeof: add a storage for NVMe over Fabrics subsystems Thomas Lamprecht
2026-11-23 13:31 10% applied: [PATCH v5 storage,docs,manager 00/26] NVMe over Fabrics storage Thomas Lamprecht
2026-11-23 13:31 17% ` [PATCH v5 storage 05/26] nvmeof: add a storage for NVMe over Fabrics subsystems Thomas Lamprecht
2026-11-26 15:09 13% [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-11-26 15:09 11% ` [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning Joaquin Varela
2026-11-26 15:09 15% ` [PATCH storage v5 03/13] zfsnvme: add storage configuration and volume methods Joaquin Varela
2026-11-26 15:09 16% ` [PATCH storage v5 04/13] zfsnvme: connect the nodes and register the plugin Joaquin Varela
2026-11-26 15:09 11% ` [PATCH storage v5 07/13] test: zfsnvme: add configuration and volume tests Joaquin Varela
2026-11-26 15:09 10% ` [PATCH storage v5 08/13] test: zfsnvme: add node side tests Joaquin Varela
2026-11-26 15:09 8% ` [PATCH storage v5 09/13] test: zfsnvme: add an in-memory nvmet target Joaquin Varela
2026-11-26 15:09 9% ` [PATCH storage v5 12/13] test: zfsnvme: add a fault sweep, renderer and taint tests Joaquin Varela
2026-11-26 15:10 20% ` [PATCH docs v5] storage: document ZFS over NVMe/TCP Joaquin Varela
2026-11-26 15:11 21% ` [PATCH manager v5] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox