From 685fb7d9e2c6ee31512aef0ccc2e21cbee709778 Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 08:01:14 +0000 Subject: [PATCH 01/10] Move in-band paths onto the current keys in place, without maintenance At each connect of a pool with in-band authentication, and at each host connect, a path that does not hold the host's current key (or, for two-way, its current controller key) is replaced: the agent makes a second controller to the same port with the keys (duplicate_connect), then disconnects the old one; native multipath keeps I/O on the other paths. If the new path cannot be made, the old one is kept and the next connect tries again. A host connect never adds a path to a port the host has none to. A VM-start lookup refused by the two-way check runs a (rate-limited) connect first. Turning inbandAuth or inbandAuthTwoWay on no longer needs the maintenance host order. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + INSTALL.md | 70 ++++---- docs/known-limitations-and-issues.md | 7 +- ...virtLightbitsGetHostNqnCommandWrapper.java | 14 ++ .../kvm/storage/LightbitsHostKey.java | 4 +- .../kvm/storage/LightbitsNvmeHost.java | 149 ++++++++++++++++-- .../kvm/storage/LightbitsStorageAdaptor.java | 55 ++++++- .../command/LightbitsGetHostNqnCommand.java | 23 +++ .../provider/LightbitsHostListener.java | 7 +- ...LightbitsGetHostNqnCommandWrapperTest.java | 51 ++++++ .../kvm/storage/LightbitsNvmeHostTest.java | 123 +++++++++++++++ .../storage/LightbitsStorageAdaptorTest.java | 62 +++++++- .../provider/LightbitsHostListenerTest.java | 6 + 13 files changed, 522 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5a8156..af64476 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] ### Changed +- Turning in-band authentication or two-way on no longer needs a maintenance cycle per host. + At each connect of an in-band pool, a path that does not hold the host's current key (or, + for two-way, its current controller key) is replaced in place: the agent makes a second path + to the same port with the keys, then disconnects the old one, and I/O continues on the other + paths. A reconnect of each host after turning the option on is enough, and an attach, VM + start or migration onto a host not yet reconnected moves its paths first. If the new path + cannot be made, the old one is kept and the next connect tries again (the agent log says why). - When a VM starts, each of its volumes' NQN ACL is set to the VM's host alone; NQNs of other hosts, including any added by hand on the cluster, are removed (with `ipAcl=true`, the IP ACL follows). Attach to a running VM and live migration still add the host and keep the others, diff --git a/INSTALL.md b/INSTALL.md index d65bb3d..b6a06c6 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -379,9 +379,8 @@ the host side: readiness line as needing a key rotation (see [Rotating the keys](#rotating-the-keys)) until it rotates. Key or configuration files not owned by root, or symbolic links, are deleted instead and new keys are made (the agent log says so); the host is not listed, but - must be reconnected (`cmk reconnect host id=`) to register the new key, and its - paths that still hold the old key keep it until they reconnect, so move it onto keyed paths - as in the rollout below before enforcement is on. + must be reconnected (`cmk reconnect host id=`) to register the new key; that + connect also moves its paths onto the new key (see [Moving paths in place](#moving-paths-in-place)). - On every host connect the agent sends the key to the management server over the agent channel. The management server registers the host as a trusted host of the pool's project (named `cs--host-`, label `cloudstack-host`) with the key as its @@ -411,30 +410,33 @@ the host side: below). Without the option the authentication is one-way: the cluster checks the host, the host does not check the cluster. A trusted host is shared by every pool of its project on the cluster, so a one-way pool keeps a target secret a two-way pool set. Make every pool of a cluster two-way, or - none: a one-way pool's paths hold the host key only, and its paths to the cluster's - subsystem also carry the two-way pool's volumes. Such a path stays until - it is disconnected by hand (`nvme disconnect -d `, as the refusal message says); - until then new handoffs of the two-way pool's volumes on that host are refused and the - readiness line lists the host. Readiness for a two-way pool also needs the - current controller key registered and on every path; move hosts onto new paths as in step - 4 after turning the option on. **Until a host is moved, new attaches, VM starts and - migrations onto it fail for this pool's volumes:** the agent refuses to hand a volume to a VM - while any path of the pool's subsystem lacks the host's current controller key, with a - message saying how to move the host; VMs already running keep working. **A VM that - maintenance cannot migrate is stopped by CloudStack**, so move the hosts in this order: - 1. Before turning two-way on, put one host of the pool in maintenance (its VMs migrate as - usual, the pool is still one-way). Wait until it is in Maintenance and runs no VMs, and - until nothing outside CloudStack on the host uses the cluster's volumes, then disconnect - it from the cluster's subsystem (`nvme disconnect -n `). - 2. Turn two-way on (`cmk update storagepool id= details[0].inbandAuthTwoWay=true`) - and reconnect the hosts that are not in maintenance (`cmk reconnect host id=`), - which registers their controller keys. - 3. Cancel maintenance on the first host and reconnect it: it is moved, and the readiness line - no longer lists it. - 4. For each further host, one at a time: first migrate its VMs to moved hosts - (`cmk migrate virtualmachine virtualmachineid= hostid=`), since - CloudStack may otherwise pick a host that is not moved yet, then put it in maintenance, - wait as in 1, disconnect it from the subsystem, cancel maintenance and reconnect it. + none: a one-way pool's new paths hold the host key only, and its paths to the cluster's + subsystem also carry the two-way pool's volumes. The two-way pool's next connect moves such + a path onto both keys; until then new handoffs of the two-way pool's volumes on that host + are refused and the readiness line lists the host. Readiness for a two-way pool also needs + the current controller key registered and on every path. + To turn two-way on, with VMs running: + 1. Turn it on (`cmk update storagepool id= details[0].inbandAuthTwoWay=true`). + 2. Reconnect every host (`cmk reconnect host id=`): each registers its controller + key, and its connect moves its paths onto both keys (see + [Moving paths in place](#moving-paths-in-place)). No maintenance is needed, and VMs keep + running. + 3. Check the readiness line (step 4 of the rollout below): it no longer lists the hosts. + An attach, VM start or migration onto a host that was not reconnected yet moves its paths + first. If a path cannot be moved, the agent refuses to hand the pool's volumes to a VM on + that host, with a message, and VMs already running keep working; the agent log says why the + path was not moved. + +#### Moving paths in place + +At each connect of a pool with in-band authentication, the agent checks the host's paths to +the ports it connects. A path that does not hold the host's current key (and, for two-way, +its current controller key) is replaced without a pause in I/O: the agent first makes a second +path to the same port with the keys, then disconnects the old one; the kernel's NVMe +multipath keeps the volumes on the other paths meanwhile. If the new path cannot be made (for +example, enforcement is on and the cluster does not have the new key yet), the old path is +kept and the next connect tries again; the agent log says so. A path on a kernel without +in-band authentication support cannot be checked and is left as it is. #### What two-way checks @@ -451,8 +453,6 @@ authentication enforcement on, so: keep the NVMe/TCP network isolated to the KVM hosts and the cluster (a dedicated VLAN or fabric), so no other machine can answer at the cluster's addresses. - The moved hosts need room for the VMs of the next host, as for any maintenance. - **Warning: turning enforcement on too early can freeze a host.** Once the cluster admin runs `lbcli enable in-band-auth`, any NVMe/TCP path that does not hold the host's current key (made before `inbandAuth=true`, or before the key was replaced) fails at its next reconnect, @@ -464,7 +464,7 @@ enforcement. In the lab this happened to a host that still had paths with an old recover, turn enforcement off (`lbcli disable in-band-auth`) and, on that host, reconnect the missing paths by hand (`nvme connect -t tcp -a -s 4420 -n ` for each node without a live path); the stuck I/O resumes and the host comes back Up. -Then move it onto keyed paths as in step 4. +Then reconnect the host (`cmk reconnect host id=`), which moves its paths onto the key. Turning in-band authentication on is a cluster-wide switch that only a cluster admin can flip, and a host without a registered key loses each path at its next reconnect. Follow @@ -481,12 +481,10 @@ this order: `the host(s) of pool are ready for in-band authentication` or `the hosts of pool are NOT ready`, with the hosts that are not registered and those with NVMe/TCP paths that do not hold the host's current key: paths made before the option was on hold none, - and paths made before a key was replaced hold an old one. Move each of those hosts onto keyed - paths: put it in maintenance (its VMs migrate away), wait until it is in Maintenance and - runs no VMs, and until nothing outside CloudStack on the host uses the cluster's volumes, - disconnect it from the cluster's subsystem (`nvme disconnect -n `, the - `nqn.2016-01.com.lightbitslabs:` entry of `nvme list-subsys`), and cancel maintenance; its - next connects use the key. + and paths made before a key was replaced hold an old one. A host's connect moves such paths + onto its current key (see [Moving paths in place](#moving-paths-in-place)), so the reconnect + of step 3 normally clears them; for a host still listed, the agent log says why a path was + not moved. Reconnect it again once the cause is fixed. 5. Enforcement is cluster-wide, and the readiness line covers only the hosts of one pool. Before the cluster admin turns it on, every host and client that uses the cluster must be ready: the hosts of every CloudStack pool on the cluster (each pool logs its own line, diff --git a/docs/known-limitations-and-issues.md b/docs/known-limitations-and-issues.md index f83e64c..fd9ce7b 100644 --- a/docs/known-limitations-and-issues.md +++ b/docs/known-limitations-and-issues.md @@ -72,11 +72,8 @@ Read INSTALL.md ("In-band authentication") before turning on enforcement on the host also accepts a target that does not ask for authentication, so two-way complements an isolated storage network rather than replacing it (INSTALL.md, "What two-way checks"). - **Two-way for all pools of a cluster, or none.** A one-way pool of the same cluster connects - with the host key only, and its paths also carry the two-way pool's volumes; the host is then - reported not ready for the two-way pool. -- **Turning two-way on with running VMs needs a host order.** A migration onto a host whose - paths do not yet hold its controller key is refused, so follow the host order in INSTALL.md: - empty one host before turning the option on, and migrate VMs by hand onto moved hosts. + new paths with the host key only, and its paths also carry the two-way pool's volumes; the + host is reported not ready for the two-way pool until that pool's next connect moves them. ## Known issues diff --git a/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapper.java b/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapper.java index f9715f1..3c88688 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapper.java +++ b/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapper.java @@ -80,6 +80,15 @@ public Answer execute(LightbitsGetHostNqnCommand command, LibvirtComputingResour answer.withRotation(false, e.getMessage()); } } + if (!command.isRotateKeys() && command.getMoveEndpoints() != null && !command.getMoveEndpoints().isEmpty()) { + try { + movePaths(command.getMoveEndpoints(), command.getKeyScope(), command.isMoveTwoWay()); + } catch (RuntimeException e) { + // the count below reports the paths that are left; the next connect tries again + LOG.warn("Lightbits: could not move this host's paths onto its current in-band authentication key(s): {}", + e.getMessage()); + } + } inbandAuth(answer, command.getKeyScope()); if (command.isTwoWay() && answer.getDhchapKey() != null) { ctrlKey(answer, command.getKeyScope()); @@ -184,6 +193,11 @@ protected int pathsWithoutCtrlKey(String currentCtrlKey, String scope) { : com.cloud.hypervisor.kvm.storage.LightbitsHostKey.pathsWithoutCtrlKey(currentCtrlKey, scope); } + /** Move this host's paths of the cluster that lack its current keys (see LightbitsStorageAdaptor#movePathsInPlace). */ + protected void movePaths(java.util.List endpoints, String scope, boolean twoWay) { + com.cloud.hypervisor.kvm.storage.LightbitsStorageAdaptor.movePathsInPlace(endpoints, scope, twoWay); + } + /** Rotate this host's keys for one cluster (null: the host-wide keys). */ protected void rotateKeys(String scope) { if (scope == null) { diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsHostKey.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsHostKey.java index 61944b3..fc20f5f 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsHostKey.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsHostKey.java @@ -488,7 +488,9 @@ public java.util.List targets(String poolUuid, java.ut String ctrl = twoWay ? ensureCtrlKey() : null; synchronized (LOCK) { try { - Files.deleteIfExists(twoWayConfigFile(poolUuid)); + if (poolUuid != null) { + Files.deleteIfExists(twoWayConfigFile(poolUuid)); + } String nqn = read(nvmeDir.resolve("hostnqn")); if (nqn == null || !HOST_NQN.matcher(nqn).matches()) { throw new CloudRuntimeException("Lightbits: this host's NQN (" + nvmeDir.resolve("hostnqn") + ") is missing or not an NQN"); diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java index 9dcaace..2ab46d2 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java @@ -307,18 +307,21 @@ boolean connectDirect(List endpoints, long endpointTimeoutMillis, failures.add(endpoint + " (its discovery log page lists no data port)"); continue; } - java.util.Set present = new java.util.HashSet<>(); - for (Path p : paths()) { - present.add(p.subsysNqn + " " + addressPart(p.address, "traddr") + ":" + addressPart(p.address, "trsvcid")); - } + java.util.Map> present = pathsByPort(); int connected = 0; List portFailures = new ArrayList<>(); // one time budget for all the endpoint's ports, as connect-all had: unreachable ports // do not add up while the caller holds the agent-wide connect lock long deadline = sys.nanoTime() + java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(endpointTimeoutMillis); for (Target t : targets) { - if (present.contains(t.port())) { + List existing = present.get(t.port()); + if (existing != null) { connected++; + List stale = withoutKeysOf(existing, t); + if (!stale.isEmpty()) { + long remaining = java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime()); + movePort(t, stale, stale.size() < existing.size(), remaining); + } continue; } long remaining = java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime()); @@ -354,6 +357,135 @@ boolean connectDirect(List endpoints, long endpointTimeoutMillis, return noEndpointAnswered("connecting the advertised data ports failed", failures); } + /** This host's Lightbits paths by port ({@link Target#port()}). */ + private java.util.Map> pathsByPort() { + java.util.Map> present = new java.util.HashMap<>(); + for (Path p : paths()) { + present.computeIfAbsent(p.subsysNqn + " " + addressPart(p.address, "traddr") + ":" + addressPart(p.address, "trsvcid"), + k -> new ArrayList<>()).add(p); + } + return present; + } + + /** + * Move the host's existing paths to the ports {@code targetsFor} returns (from the first endpoint + * whose discovery answers) onto new paths with the targets' keys, as a connect does, without + * making a path to a port the host has none to: a host connect uses it, and a host without + * volumes of the cluster stays unconnected. Returns the number of ports moved. + */ + int movePathsInPlace(List endpoints, long endpointTimeoutMillis, + java.util.function.Function> targetsFor) { + List failures = new ArrayList<>(); + for (String endpoint : endpoints) { + List targets; + try { + targets = targetsFor.apply(endpoint); + } catch (RuntimeException e) { + failures.add(endpoint + " (" + e.getMessage() + ")"); + continue; + } + if (targets.isEmpty()) { + failures.add(endpoint + " (its discovery log page lists no data port)"); + continue; + } + java.util.Map> present = pathsByPort(); + long deadline = sys.nanoTime() + java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(endpointTimeoutMillis); + int moved = 0; + for (Target t : targets) { + List existing = present.get(t.port()); + if (existing == null) { + continue; + } + List stale = withoutKeysOf(existing, t); + if (!stale.isEmpty()) { + movePort(t, stale, stale.size() < existing.size(), + java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime())); + moved++; + } + } + return moved; + } + LOG.warn("Lightbits: could not move this host's paths onto its current in-band authentication key(s): no discovery" + + " endpoint answered: {}", failures); + return 0; + } + + /** + * The paths of a port that do not hold the keys {@code t} connects with: a host key (and, for + * two-way, a controller key) other than the current one, or none. A path whose key attribute + * the kernel does not have (no in-band authentication support) cannot be judged and is kept. + */ + private List withoutKeysOf(List paths, Target t) { + List stale = new ArrayList<>(); + for (Path p : paths) { + if (lacks(p, "dhchap_secret", option(t.options, "dhchap_secret")) + || lacks(p, "dhchap_ctrl_secret", option(t.options, "dhchap_ctrl_secret"))) { + stale.add(p); + } + } + return stale; + } + + private boolean lacks(Path p, String attribute, String key) { + if (key == null) { + return false; + } + String file = "/sys/class/nvme/" + p.controller + "/" + attribute; + if (!sys.exists(file)) { + return false; + } + String held = sys.read(file); + return held == null || !held.trim().equals(key); + } + + /** The value of one option in a /dev/nvme-fabrics options string, or null. */ + static String option(String options, String name) { + for (String o : options.split(",")) { + if (o.startsWith(name + "=")) { + return o.substring(name.length() + 1); + } + } + return null; + } + + /** + * Move a port onto a path with the current keys without a pause in I/O: make a second + * controller to the same port with the keys ({@code duplicate_connect}), then disconnect the + * old one; the kernel's native multipath keeps the namespaces on the other paths meanwhile + * (lab: guest writes went on through the replacement of every path). When the new path cannot + * be made (for example the cluster enforces authentication and has not taken the new key yet), + * the old one is kept and the next connect tries again. {@code keyedPathExists}: the port has + * a path with the keys already (an earlier move whose disconnect failed), so only the old ones go. + */ + private void movePort(Target t, List stale, boolean keyedPathExists, long remainingMillis) { + if (!keyedPathExists) { + if (remainingMillis <= 0) { + LOG.warn("Lightbits: path(s) {} to {} do not hold this host's current in-band authentication key(s); not moved now" + + " (the connect's time ran out), the next connect tries again", stale, t); + return; + } + try { + sys.connectFabrics(t.options + ",duplicate_connect", remainingMillis); + } catch (RuntimeException e) { + LOG.warn("Lightbits: path(s) {} to {} do not hold this host's current in-band authentication key(s), and a new" + + " path with them could not be made ({}); the old path is kept and the next connect tries again", stale, t, + e.getMessage()); + return; + } + } + for (Path p : stale) { + Result r = sys.run(30_000, "nvme", "disconnect", "-d", p.controller); + if (r.ok() && !sys.exists("/sys/class/nvme/" + p.controller)) { + LOG.info("Lightbits: moved {} onto a new path with this host's current in-band authentication key(s);" + + " disconnected the old path {}", t, p.controller); + } else { + LOG.warn("Lightbits: made a path to {} with this host's current in-band authentication key(s), but the old path {}" + + " could not be disconnected (exit {}: {}); the next connect tries again, or disconnect it by hand" + + " (nvme disconnect -d {})", t, p.controller, r.exit, r.output, p.controller); + } + } + } + /** One field ({@code traddr}, {@code trsvcid}) of a controller's sysfs address, or "" if absent. */ static String addressPart(String address, String field) { if (address != null) { @@ -651,10 +783,9 @@ void requireTwoWayPaths(String kernelName, String currentCtrlKey) { if (!unsafe.isEmpty()) { throw new CloudRuntimeException("Lightbits: the pool uses two-way in-band authentication, but path(s) " + unsafe + " of subsystem " + subsystem.trim() + " on this host do not hold its current controller key, so the host" - + " would not check the cluster on them; the volume is not handed over. Move the host onto two-way paths" - + " in the host order of INSTALL.md (\"In-band authentication\"): migrate its VMs to hosts already moved" - + " (CloudStack stops a VM that maintenance cannot migrate), put it in maintenance, disconnect its Lightbits" - + " paths (nvme disconnect -n " + subsystem.trim() + "), cancel maintenance and reconnect the host." + + " would not check the cluster on them; the volume is not handed over. A connect of the pool moves such" + + " paths in place; reconnect the host (cmk reconnect host) and see the agent log for why a path was not" + + " moved. A path that cannot be moved can be disconnected by hand (nvme disconnect -d )." + " Running VMs are not affected."); } } diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java index 0f424d2..ee2323f 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java @@ -342,6 +342,40 @@ public static void rotateInbandKeys() { } /** Rotate this host's keys for one cluster (its subsystem NQN; null: the host-wide keys). */ + /** + * At a host connect: move this host's paths of the cluster ({@code scope}, its subsystem NQN; null: + * every Lightbits path, host-wide keys) that do not hold the current key, or for {@code twoWay} the + * current controller key, onto new paths with them (LightbitsNvmeHost#movePathsInPlace). Nothing + * is read from the cluster when every path holds them. No path to a new port is made. + */ + public static void movePathsInPlace(List endpoints, String scope, boolean twoWay) { + movePathsInPlace(new LightbitsNvmeHost(), new LightbitsHostKey().forScope(scope), endpoints, scope, twoWay); + } + + static void movePathsInPlace(LightbitsNvmeHost nvme, LightbitsHostKey keys, List endpoints, String scope, boolean twoWay) { + String s = scope == null || scope.isBlank() ? null : scope.trim(); + synchronized (CONNECT_LOCK) { + String key = keys.ensure(); + String ctrl = twoWay ? keys.ensureCtrlKey() : null; + int stale = nvme.pathsWithoutKey(key, s) + (twoWay ? nvme.pathsWithoutCtrlKey(ctrl, s) : 0); + if (stale == 0) { + return; + } + List normalized = new ArrayList<>(); + for (String e : endpoints) { + normalized.add(e.lastIndexOf(':') > 0 ? e : e + ":" + LightbitsNvmeHost.DEFAULT_DISCOVERY_PORT); + } + nvme.movePathsInPlace(normalized, LOOKUP_CONNECT_TIMEOUT_MILLIS, endpoint -> { + List ports = nvme.discover(endpoint, DISCOVER_TIMEOUT_MILLIS); + if (s != null) { + ports = ports.stream().filter(p -> s.equals(p.subsystemNqn == null ? null : p.subsystemNqn.trim())) + .collect(java.util.stream.Collectors.toList()); + } + return keys.targets(null, ports, twoWay); + }); + } + } + public static void rotateInbandKeys(String scope) { rotateInbandKeys(new LightbitsNvmeHost(), new LightbitsHostKey().forScope(scope), scope); } @@ -466,6 +500,25 @@ private void requireTwoWayPaths(String kernelName, KVMStoragePool pool) { } } + /** + * The two-way check of a lookup, which runs before any connect of a VM start (the agent looks + * the disks up first): when paths lack the current keys, a connect of the pool (rate-limited as + * for any lookup) moves them in place, and the check runs again. + */ + private void requireTwoWayPathsMovingThem(String kernelName, KVMStoragePool pool) { + try { + requireTwoWayPaths(kernelName, pool); + } catch (CloudRuntimeException e) { + try { + connectIfDue(pool); + } catch (CloudRuntimeException connect) { + e.addSuppressed(connect); + throw e; + } + requireTwoWayPaths(kernelName, pool); + } + } + /** * The two-way check of a lookup. A lookup also serves operations that hand nothing to a VM: * a detach looks the disk up before it removes it from the VM, and so do volume statistics. @@ -475,7 +528,7 @@ private void requireTwoWayPaths(String kernelName, KVMStoragePool pool) { */ private void requireTwoWayPathsUnlessInUse(String kernelName, String uuid, KVMStoragePool pool) { try { - requireTwoWayPaths(kernelName, pool); + requireTwoWayPathsMovingThem(kernelName, pool); } catch (CloudRuntimeException e) { if (!nvme.openByVm(kernelName)) { throw e; diff --git a/src/main/java/org/apache/cloudstack/storage/datastore/command/LightbitsGetHostNqnCommand.java b/src/main/java/org/apache/cloudstack/storage/datastore/command/LightbitsGetHostNqnCommand.java index d6fbb72..5d00884 100644 --- a/src/main/java/org/apache/cloudstack/storage/datastore/command/LightbitsGetHostNqnCommand.java +++ b/src/main/java/org/apache/cloudstack/storage/datastore/command/LightbitsGetHostNqnCommand.java @@ -100,6 +100,29 @@ public String getKeyScope() { return keyScope; } + /** + * Move this host's existing paths of the pool's cluster that do not hold its current keys onto + * new paths with them, before they are counted (see {@code LightbitsNvmeHost#movePathsInPlace}). + * The pool's discovery endpoints and whether the pool is two-way; null from an older + * management server, and during a key rotation: nothing is moved. + */ + private java.util.List moveEndpoints; + private boolean moveTwoWay; + + public LightbitsGetHostNqnCommand withMovePaths(java.util.List endpoints, boolean twoWay) { + this.moveEndpoints = endpoints; + this.moveTwoWay = twoWay; + return this; + } + + public java.util.List getMoveEndpoints() { + return moveEndpoints; + } + + public boolean isMoveTwoWay() { + return moveTwoWay; + } + public java.util.List getEndpoints() { return endpoints; } diff --git a/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java b/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java index 4b48db6..742fc69 100644 --- a/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java +++ b/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java @@ -260,7 +260,8 @@ private void ensureHostDetails(long hostId, long poolId, org.apache.cloudstack.s // two-way ones included Answer answer = agentMgr.easySend(hostId, new LightbitsGetHostNqnCommand(wantIps ? cfg.discoveryEndpoints() : null, wantAuth, wantAuth && (cfg.isInbandAuthTwoWay() || rotate)).withRotateKeys(rotate) - .withKeyScope(wantAuth ? scope : null)); + .withKeyScope(wantAuth ? scope : null) + .withMovePaths(wantAuth && !rotate ? cfg.discoveryEndpoints() : null, cfg.isInbandAuthTwoWay())); boolean rotated = false; if (rotate && answer instanceof LightbitsGetHostNqnAnswer && answer.getResult()) { rotated = recordRotation(hostId, poolId, cfg.getInbandKeyGeneration(), (LightbitsGetHostNqnAnswer) answer); @@ -650,8 +651,8 @@ private void reportInbandReadiness(long poolId) { } else { LOG.warn("Lightbits: the hosts of pool {} are NOT ready for in-band authentication; do not turn it on yet. Not" + " registered: {}. With paths that do not hold the host's current key, none or an old one (they fail" - + " at their next reconnect once it is on; put the host in maintenance, disconnect its Lightbits paths" - + " and cancel maintenance, see INSTALL.md): {}.{}", poolId, unregistered, keyless, + + " at their next reconnect once it is on; a host connect moves them in place, and the host's agent log" + + " says why a path was not moved, see INSTALL.md, \"Moving paths in place\"): {}.{}", poolId, unregistered, keyless, optionalNote); } } diff --git a/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java b/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java index 3a49ae8..e6bd886 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java @@ -217,6 +217,57 @@ void theKeyIsReportedOnlyWhenAskedForAndNeverLogged() throws IOException { assertTrue(!logged.contains("DHHC-1"), "the key is left out of the logged answer: " + logged); } + @Test + void pathsAreMovedBeforeTheyAreCountedButNotDuringARotation() throws IOException { + LibvirtLightbitsGetHostNqnCommandWrapper base = wrapper(null); + Files.createDirectories(base.hostNqnPath().getParent()); + Files.writeString(base.hostNqnPath(), NQN + "\n"); + List calls = new java.util.ArrayList<>(); + LibvirtLightbitsGetHostNqnCommandWrapper w = new LibvirtLightbitsGetHostNqnCommandWrapper() { + @Override + protected Path hostNqnPath() { + return base.hostNqnPath(); + } + + @Override + protected com.cloud.hypervisor.kvm.storage.LightbitsHostKey hostKey() { + return new com.cloud.hypervisor.kvm.storage.LightbitsHostKey() { + @Override + public String ensure() { + return "DHHC-1:00:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh+KfiaR:"; + } + }; + } + + @Override + protected void movePaths(List endpoints, String scope, boolean twoWay) { + calls.add("move " + endpoints + " " + scope + " " + twoWay); + } + + @Override + protected void rotateKeys(String scope) { + calls.add("rotate"); + } + + @Override + protected int pathsWithoutKey(String currentKey, String scope) { + calls.add("count"); + return 0; + } + }; + w.execute(new LightbitsGetHostNqnCommand(null, true).withKeyScope("nqn.2016-01.com.lightbitslabs:uuid:x") + .withMovePaths(List.of("10.0.0.1:8009"), false), null); + assertEquals(List.of("move [10.0.0.1:8009] nqn.2016-01.com.lightbitslabs:uuid:x false", "count"), calls); + + calls.clear(); + w.execute(new LightbitsGetHostNqnCommand(null, true).withRotateKeys(true).withMovePaths(List.of("10.0.0.1:8009"), false), null); + assertFalse(calls.stream().anyMatch(c -> c.startsWith("move")), calls.toString()); + + calls.clear(); + w.execute(new LightbitsGetHostNqnCommand(null, true), null); // an older management server + assertFalse(calls.stream().anyMatch(c -> c.startsWith("move")), calls.toString()); + } + @Test void aKeyThatCannotBePreparedIsReportedButTheNqnStillAnswers() throws IOException { LibvirtLightbitsGetHostNqnCommandWrapper w = authWrapper(() -> { diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java index f0cb7bd..c7f4837 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java @@ -22,6 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; @@ -87,6 +88,10 @@ public LightbitsNvmeHost.Result run(long timeoutMillis, String... argv) { if (cmd.startsWith("nvme connect-all")) { onConnect.run(); } + if (cmd.startsWith("nvme disconnect -d ") && disconnectRemoves && !results.containsKey(cmd)) { + String dir = "/sys/class/nvme/" + cmd.substring("nvme disconnect -d ".length()) + "/"; + files.keySet().removeIf(k -> k.startsWith(dir)); + } if (cmd.startsWith("nvme disconnect -n ") && disconnectRemoves) { // like the kernel: a subsystem goes away with its last controller String nqn = cmd.substring("nvme disconnect -n ".length()); @@ -563,6 +568,123 @@ void aTwoWayConnectMakesExactlyTheDiscoveredPortsWithoutConnectAll() { assertFalse(target("10.0.0.2").toString().contains("DHHC-1"), "a target prints without its keys"); } + private void keys(String ctrl, String hostKey, String ctrlKey) { + sys.files.put("/sys/class/nvme/" + ctrl + "/dhchap_secret", hostKey); + sys.files.put("/sys/class/nvme/" + ctrl + "/dhchap_ctrl_secret", ctrlKey); + } + + private List disconnects() { + return sys.commands.stream().filter(c -> c.startsWith("nvme disconnect")).collect(java.util.stream.Collectors.toList()); + } + + @Test + void aPathWithoutTheCurrentKeysIsMovedInPlaceNewPathFirst() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); // one-way path made before two-way + sys.controller("nvme2", "traddr=10.0.0.2,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme2", "DHHC-1:00:host:", "DHHC-1:00:old-ctrl:"); // a controller key replaced since + List order = new ArrayList<>(); + sys.onConnect = () -> order.add("connect"); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1"), target("10.0.0.2")))); + assertEquals(2, sys.fabrics.size()); + assertTrue(sys.fabrics.stream().allMatch(o -> o.endsWith(",duplicate_connect")), "a second controller next to the old one"); + assertTrue(sys.fabrics.get(0).contains("traddr=10.0.0.1,") && sys.fabrics.get(1).contains("traddr=10.0.0.2,")); + assertTrue(sys.fabrics.stream().allMatch(o -> o.contains("dhchap_ctrl_secret=DHHC-1:00:ctrl:"))); + assertEquals(List.of("nvme disconnect -d nvme1", "nvme disconnect -d nvme2"), disconnects()); + assertTrue(sys.commands.stream().noneMatch(c -> c.contains("DHHC-1")), "no key on any command line"); + } + + @Test + void aPathWithTheCurrentKeysIsLeftAlone() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "DHHC-1:00:host:", "DHHC-1:00:ctrl:"); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1")))); + assertTrue(sys.fabrics.isEmpty()); + assertTrue(disconnects().isEmpty()); + } + + @Test + void aOneWayConnectDoesNotMoveATwoWayPath() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "DHHC-1:00:host:", "DHHC-1:00:ctrl:"); + LightbitsNvmeHost.Target oneWay = new LightbitsNvmeHost.Target(NQN, "10.0.0.1", "4420", + "transport=tcp,traddr=10.0.0.1,trsvcid=4420,nqn=" + NQN + ",dhchap_secret=DHHC-1:00:host:"); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(oneWay))); + assertTrue(sys.fabrics.isEmpty(), "the host key matches; the controller key is not the one-way pool's business"); + assertTrue(disconnects().isEmpty()); + } + + @Test + void aOneWayConnectMovesAPathWithAnOldHostKey() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "DHHC-1:00:old-host:", "none"); + LightbitsNvmeHost.Target oneWay = new LightbitsNvmeHost.Target(NQN, "10.0.0.1", "4420", + "transport=tcp,traddr=10.0.0.1,trsvcid=4420,nqn=" + NQN + ",dhchap_secret=DHHC-1:00:host:"); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(oneWay))); + assertEquals(1, sys.fabrics.size()); + assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); + } + + @Test + void theOldPathIsKeptWhenTheNewOneCannotBeMade() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + sys.fabricsErrors.put("10.0.0.1", "Key was rejected by service"); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1"))), + "the port still has its path: the endpoint answered"); + assertEquals(1, sys.fabrics.size()); + assertTrue(disconnects().isEmpty(), "never drop the only path to a port before its replacement is there"); + } + + @Test + void anOldPathLeftNextToAKeyedOneIsDisconnectedWithoutAnotherController() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + sys.controller("nvme4", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme4", "DHHC-1:00:host:", "DHHC-1:00:ctrl:"); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1")))); + assertTrue(sys.fabrics.isEmpty()); + assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); + } + + @Test + void aFailedDisconnectOfTheOldPathDoesNotFailTheConnect() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + sys.results.put("nvme disconnect -d nvme1", new LightbitsNvmeHost.Result(1, "busy")); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1")))); + assertEquals(1, sys.fabrics.size()); + assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); + } + + @Test + void aHostConnectMovesExistingPathsButMakesNoNewOne() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + assertEquals(1, host.movePathsInPlace(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1"), target("10.0.0.2")))); + assertEquals(1, sys.fabrics.size(), "only the port the host had a path to"); + assertTrue(sys.fabrics.get(0).contains("traddr=10.0.0.1,") && sys.fabrics.get(0).endsWith(",duplicate_connect")); + assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); + } + + @Test + void aHostConnectWhoseDiscoveryFailsMovesNothing() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + assertEquals(0, host.movePathsInPlace(List.of("10.0.0.1:8009"), 1000, endpoint -> { + throw new CloudRuntimeException("'nvme discover' failed"); + })); + assertTrue(sys.fabrics.isEmpty()); + assertTrue(disconnects().isEmpty()); + } + + @Test + void optionReadsOneValue() { + assertEquals("b", LightbitsNvmeHost.option("a=1,x=b,c=3", "x")); + assertNull(LightbitsNvmeHost.option("a=1,c=3", "x")); + assertNull(LightbitsNvmeHost.option("ax=1", "x")); + } + @Test void aTwoWayConnectGoesOnWhenSomePortsFailAndTriesTheNextEndpointWhenAllDo() { sys.fabricsErrors.put("10.0.0.2", "Operation already in progress"); // made meanwhile: connected @@ -706,6 +828,7 @@ void anUnknownPathCountRefusesTheRotation(@org.junit.jupiter.api.io.TempDir java @Test void newPathsWithoutTheControllerKeyAreDroppedOldOnesKept() { + sys.disconnectRemoves = false; // the same path is dropped again below, this time failing String ctrl = "DHHC-1:00:ctrl:"; sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420", "live"); // older one-way path, may carry volumes java.util.Set before = host.pathNames(); diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java index 2b09d96..39be97e 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java @@ -410,11 +410,71 @@ void aTwoWayLookupOfAVolumeAVmAlreadyUsesIsNotRefusedAHandoffStillIs(@org.junit. sys.files.put("/proc/4711/fd/21", ""); sys.links.put("/proc/4711/fd/21", "/dev/nvme3n2"); assertNotNull(a.getPhysicalDisk(VOL, twoWay)); - // a handoff goes through the connect, which still refuses + // a handoff goes through the connect, which still refuses while the path cannot be moved + sys.fabricsErrors.put("10.0.1.1", "Key was rejected by service"); sys.results.put("nvme discover -t tcp -a 10.0.1.1 -s 8009 -o json", new LightbitsNvmeHost.Result(0, "{\"genctr\":1,\"records\":[{\"trtype\":\"tcp\",\"subtype\":\"nvme subsystem\",\"traddr\":\"10.0.1.1\"," + "\"trsvcid\":\"4420\",\"subnqn\":\"" + NQN + "\"}]}")); e = assertThrows(CloudRuntimeException.class, () -> a.connectPhysicalDisk(VOL, twoWay, null, false)); assertTrue(e.getMessage().contains("not handed over"), e.getMessage()); } + + @Test + void aTwoWayVmStartOnAHostNotMovedYetMovesItsPathsAndGoesOn(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tmp) throws Exception { + java.nio.file.Files.writeString(tmp.resolve("hostnqn"), "nqn.2014-08.org.nvmexpress:uuid:60c10b61-c740-478c-a800-402344d475c9"); + LightbitsStorageAdaptor a = new LightbitsStorageAdaptor(new LightbitsNvmeHost(sys), new LightbitsHostKey(tmp.resolve("lightbits"), tmp, + (Integer) java.nio.file.Files.getAttribute(tmp, "unix:uid"))); + KVMStoragePool twoWay = a.createStoragePool(POOL_B, "10.0.1.1", 443, "/proj", null, StoragePoolType.IscsiLUN, + Map.of(LightbitsStorageAdaptor.DETAIL_NVME_DISCOVERY, "10.0.1.1", LightbitsStorageAdaptor.DETAIL_INBAND_AUTH, "true", + LightbitsStorageAdaptor.DETAIL_INBAND_TWO_WAY, "true"), true); + sys.controller("nvme3", "traddr=10.0.1.1,trsvcid=4420", "live"); + sys.files.put("/sys/class/nvme/nvme3/dhchap_secret", "none"); // a one-way path made before two-way + sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", "none"); + deviceAppears(); + sys.results.put("nvme discover -t tcp -a 10.0.1.1 -s 8009 -o json", new LightbitsNvmeHost.Result(0, + "{\"genctr\":1,\"records\":[{\"trtype\":\"tcp\",\"subtype\":\"nvme subsystem\",\"traddr\":\"10.0.1.1\"," + + "\"trsvcid\":\"4420\",\"subnqn\":\"" + NQN + "\"}]}")); + // the kernel makes the second controller with the keys it was given + sys.onConnect = () -> { + String o = sys.fabrics.get(sys.fabrics.size() - 1); + sys.controller("nvme7", "traddr=10.0.1.1,trsvcid=4420", "live"); + sys.files.put("/sys/class/nvme/nvme7/dhchap_secret", LightbitsNvmeHost.option(o, "dhchap_secret")); + sys.files.put("/sys/class/nvme/nvme7/dhchap_ctrl_secret", LightbitsNvmeHost.option(o, "dhchap_ctrl_secret")); + }; + // the agent looks the disk up before it connects it (VM start): the lookup moves the paths + assertNotNull(a.getPhysicalDisk(VOL, twoWay)); + assertEquals(1, sys.fabrics.size()); + assertTrue(sys.fabrics.get(0).endsWith(",duplicate_connect"), "a second controller first"); + assertTrue(sys.commands.contains("nvme disconnect -d nvme3"), "then the old path goes"); + assertFalse(sys.files.containsKey("/sys/class/nvme/nvme3/subsysnqn")); + assertTrue(sys.commands.stream().noneMatch(c -> c.contains("DHHC-1")), "no key on any command line"); + // and the handoff passes the check + assertTrue(a.connectPhysicalDisk(VOL, twoWay, null, false)); + } + + @Test + void aHostConnectReadsNothingFromTheClusterWhenEveryPathHoldsTheKeys(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tmp) + throws Exception { + java.nio.file.Files.writeString(tmp.resolve("hostnqn"), "nqn.2014-08.org.nvmexpress:uuid:60c10b61-c740-478c-a800-402344d475c9"); + LightbitsHostKey keys = new LightbitsHostKey(tmp.resolve("lightbits"), tmp, (Integer) java.nio.file.Files.getAttribute(tmp, "unix:uid")); + LightbitsNvmeHost nvme = new LightbitsNvmeHost(sys); + sys.controller("nvme3", "traddr=10.0.1.1,trsvcid=4420", "live"); + sys.files.put("/sys/class/nvme/nvme3/dhchap_secret", keys.ensure()); + sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", keys.ensureCtrlKey()); + sys.commands.clear(); + LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, List.of("10.0.1.1"), null, true); + assertTrue(sys.commands.stream().noneMatch(c -> c.startsWith("nvme discover")), sys.commands.toString()); + assertTrue(sys.fabrics.isEmpty()); + + // a path without the controller key: discovery (default port added) and a move + sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", "none"); + sys.results.put("nvme discover -t tcp -a 10.0.1.1 -s 8009 -o json", new LightbitsNvmeHost.Result(0, + "{\"genctr\":1,\"records\":[{\"trtype\":\"tcp\",\"subtype\":\"nvme subsystem\",\"traddr\":\"10.0.1.1\"," + + "\"trsvcid\":\"4420\",\"subnqn\":\"" + NQN + "\"}]}")); + LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, List.of("10.0.1.1"), null, true); + assertEquals(1, sys.fabrics.size()); + assertTrue(sys.fabrics.get(0).endsWith(",duplicate_connect")); + assertTrue(sys.commands.contains("nvme disconnect -d nvme3")); + assertTrue(sys.commands.stream().noneMatch(c -> c.contains("DHHC-1")), "no key on any command line"); + } } diff --git a/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java b/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java index 394b94a..caed442 100644 --- a/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java +++ b/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java @@ -33,6 +33,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -414,6 +415,9 @@ void oneWayRegistersTheHostKeyAndRecordsItsFingerprint() { .withRequestBody(matchingJsonPath("$.hostSecret", equalTo(KEY))) .withRequestBody(matchingJsonPath("$.targetSecretType", equalTo("Disabled")))); assertFalse(nqnCommands().get(0).isTwoWay()); + assertNotNull(nqnCommands().get(0).getMoveEndpoints(), "the agent moves paths without the key at the host connect"); + assertFalse(nqnCommands().get(0).getMoveEndpoints().isEmpty()); + assertFalse(nqnCommands().get(0).isMoveTwoWay()); } @Test @@ -439,6 +443,7 @@ void twoWayRegistersTheControllerKeyAsTheTargetSecret() { option(LightbitsPoolConfig.KEY_INBAND_AUTH_TWO_WAY, "true"); listener.hostConnect(HOST, POOL); assertTrue(nqnCommands().get(0).isTwoWay()); + assertTrue(nqnCommands().get(0).isMoveTwoWay()); wm.verify(putRequestedFor(urlEqualTo(P + "/trustedHostSecrets/" + TH_NAME)) .withRequestBody(matchingJsonPath("$.targetSecretType", equalTo("Enabled"))) .withRequestBody(matchingJsonPath("$.targetSecret", equalTo(CTRL)))); @@ -506,6 +511,7 @@ void aRaisedGenerationRotatesAnIdleHostAndRecordsIt() throws Exception { listener.hostConnect(HOST, POOL); assertTrue(nqnCommands().get(0).isRotateKeys()); assertTrue(nqnCommands().get(0).isTwoWay(), "a rotation also asks for the controller key"); + assertNull(nqnCommands().get(0).getMoveEndpoints(), "a rotation moves no path: it drops them"); assertEquals("1", detail(LightbitsTrustedHosts.generationDetailKey(POOL))); sent.clear(); From f0d087ceafbc3fd01486a428b84e3038d545a28d Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 08:13:59 +0000 Subject: [PATCH 02/10] Host connect: ask the agent once more after registering new keys, so paths move without a second reconnect Co-Authored-By: Claude Opus 5.5 --- .../provider/LightbitsHostListener.java | 19 +++++++++++++ .../provider/LightbitsHostListenerTest.java | 28 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java b/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java index 742fc69..8fa0c44 100644 --- a/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java +++ b/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java @@ -298,6 +298,19 @@ private void ensureHostDetails(long hostId, long poolId, org.apache.cloudstack.s setHostDetail(hostId, LightbitsTrustedHosts.perPool(HOST_SCOPE_DETAIL, poolId), report.getKeyScope() == null ? HOST_WIDE : report.getKeyScope()); registerTrustedHost(hostId, poolId, hostNqn, report); + if (!rotate && stale(report)) { + // The agent moved its paths before this registration: with enforcement on, a path + // with a key the cluster did not have yet (a new controller key) could not be made. + // Now that the keys are registered, ask once more, so the move and the readiness + // count need no second reconnect. + Answer again = agentMgr.easySend(hostId, new LightbitsGetHostNqnCommand(null, true, cfg.isInbandAuthTwoWay()) + .withKeyScope(scope).withMovePaths(cfg.discoveryEndpoints(), cfg.isInbandAuthTwoWay())); + if (again instanceof LightbitsGetHostNqnAnswer && again.getResult() + && ((LightbitsGetHostNqnAnswer) again).getDhchapKey() != null + && java.util.Objects.equals(((LightbitsGetHostNqnAnswer) again).getKeyScope(), report.getKeyScope())) { + registerTrustedHost(hostId, poolId, hostNqn, (LightbitsGetHostNqnAnswer) again); + } + } // An agent that does not know scopes answers without one: its keys are host-wide and // shared by every in-band pool of the host, whatever cluster each is on. boolean hostWide = scope != null && report.getKeyScope() == null; @@ -435,6 +448,12 @@ private void storeAndRefresh(long hostId, long poolId, String nqn, java.util.Lis * paths without its current key, then log whether every host of the pool is ready for the cluster admin to * turn in-band authentication on. Failures are logged and retried at the next connect. */ + /** The agent reports paths without its current key, or without its current controller key. */ + private static boolean stale(LightbitsGetHostNqnAnswer report) { + return report.getDhchapKey() != null && ((report.getKeylessPaths() != null && report.getKeylessPaths() > 0) + || (report.getPathsWithoutCtrlKey() != null && report.getPathsWithoutCtrlKey() > 0)); + } + private void registerTrustedHost(long hostId, long poolId, String nqn, LightbitsGetHostNqnAnswer answer) { String key = answer.getDhchapKey(); if (key == null) { diff --git a/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java b/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java index caed442..408bcac 100644 --- a/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java +++ b/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java @@ -420,6 +420,34 @@ void oneWayRegistersTheHostKeyAndRecordsItsFingerprint() { assertFalse(nqnCommands().get(0).isMoveTwoWay()); } + @Test + void aHostWithPathsLeftWithoutTheNewKeysIsAskedOnceMoreAfterTheRegistration() { + option(LightbitsPoolConfig.KEY_INBAND_AUTH, "true"); + option(LightbitsPoolConfig.KEY_INBAND_AUTH_TWO_WAY, "true"); + int[] asked = {0}; + // first answer: 3 paths could not be moved yet (the cluster did not have the controller key) + agent = cmd -> { + if (!(cmd instanceof LightbitsGetHostNqnCommand)) { + return new Answer(cmd); + } + LightbitsGetHostNqnCommand c = (LightbitsGetHostNqnCommand) cmd; + LightbitsGetHostNqnAnswer a = new LightbitsGetHostNqnAnswer(c, NQN, null); + a.withInbandAuth(KEY, 0, null); + a.withCtrlKey(CTRL, asked[0]++ == 0 ? 3 : 0); + return a; + }; + listener.hostConnect(HOST, POOL); + assertEquals(2, nqnCommands().size(), "asked once more after the keys were registered"); + assertNotNull(nqnCommands().get(1).getMoveEndpoints()); + assertTrue(nqnCommands().get(1).isMoveTwoWay()); + assertFalse(nqnCommands().get(1).isRotateKeys()); + + // nothing left to move: one command only + sent.clear(); + listener.hostConnect(HOST, POOL); + assertEquals(1, nqnCommands().size()); + } + @Test void aHostWhoseKeysMayHaveBeenCopiedIsRecordedUntilItRotates() { option(LightbitsPoolConfig.KEY_INBAND_AUTH, "true"); From 5aa370403d2e4134562e2f12172f054d8d751370 Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 08:37:20 +0000 Subject: [PATCH 03/10] Host connect moves the host's own paths, without a discovery read The cluster's discovery service lists its subsystem only to a host with access to a volume, so a host without volumes there saw no port to move. The ports now come from the host's own paths. Co-Authored-By: Claude Opus 5.5 --- INSTALL.md | 5 +- ...virtLightbitsGetHostNqnCommandWrapper.java | 8 +-- .../kvm/storage/LightbitsNvmeHost.java | 51 ++++++------------- .../kvm/storage/LightbitsStorageAdaptor.java | 36 +++++++------ .../command/LightbitsGetHostNqnCommand.java | 16 +++--- .../provider/LightbitsHostListener.java | 11 ++-- ...LightbitsGetHostNqnCommandWrapperTest.java | 10 ++-- .../kvm/storage/LightbitsNvmeHostTest.java | 13 +---- .../storage/LightbitsStorageAdaptorTest.java | 27 ++++++---- .../provider/LightbitsHostListenerTest.java | 7 ++- 10 files changed, 84 insertions(+), 100 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index b6a06c6..cf2d306 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -429,8 +429,9 @@ the host side: #### Moving paths in place -At each connect of a pool with in-band authentication, the agent checks the host's paths to -the ports it connects. A path that does not hold the host's current key (and, for two-way, +At each connect of a pool with in-band authentication, and at each host connect, the agent +checks the host's paths to the pool's cluster (a host connect checks the paths the host already +has, and makes no new one). A path that does not hold the host's current key (and, for two-way, its current controller key) is replaced without a pause in I/O: the agent first makes a second path to the same port with the keys, then disconnects the old one; the kernel's NVMe multipath keeps the volumes on the other paths meanwhile. If the new path cannot be made (for diff --git a/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapper.java b/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapper.java index 3c88688..a1ab5da 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapper.java +++ b/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapper.java @@ -80,9 +80,9 @@ public Answer execute(LightbitsGetHostNqnCommand command, LibvirtComputingResour answer.withRotation(false, e.getMessage()); } } - if (!command.isRotateKeys() && command.getMoveEndpoints() != null && !command.getMoveEndpoints().isEmpty()) { + if (!command.isRotateKeys() && command.isMovePaths()) { try { - movePaths(command.getMoveEndpoints(), command.getKeyScope(), command.isMoveTwoWay()); + movePaths(command.getKeyScope(), command.isMoveTwoWay()); } catch (RuntimeException e) { // the count below reports the paths that are left; the next connect tries again LOG.warn("Lightbits: could not move this host's paths onto its current in-band authentication key(s): {}", @@ -194,8 +194,8 @@ protected int pathsWithoutCtrlKey(String currentCtrlKey, String scope) { } /** Move this host's paths of the cluster that lack its current keys (see LightbitsStorageAdaptor#movePathsInPlace). */ - protected void movePaths(java.util.List endpoints, String scope, boolean twoWay) { - com.cloud.hypervisor.kvm.storage.LightbitsStorageAdaptor.movePathsInPlace(endpoints, scope, twoWay); + protected void movePaths(String scope, boolean twoWay) { + com.cloud.hypervisor.kvm.storage.LightbitsStorageAdaptor.movePathsInPlace(scope, twoWay); } /** Rotate this host's keys for one cluster (null: the host-wide keys). */ diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java index 2ab46d2..c49f987 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java @@ -368,46 +368,27 @@ private java.util.Map> pathsByPort() { } /** - * Move the host's existing paths to the ports {@code targetsFor} returns (from the first endpoint - * whose discovery answers) onto new paths with the targets' keys, as a connect does, without - * making a path to a port the host has none to: a host connect uses it, and a host without - * volumes of the cluster stays unconnected. Returns the number of ports moved. + * Move the host's existing paths to the ports of {@code targets} onto new paths with the + * targets' keys, as a connect does, without making a path to a port the host has none to: a + * host connect uses it. All ports share one time budget. Returns the number of ports moved. */ - int movePathsInPlace(List endpoints, long endpointTimeoutMillis, - java.util.function.Function> targetsFor) { - List failures = new ArrayList<>(); - for (String endpoint : endpoints) { - List targets; - try { - targets = targetsFor.apply(endpoint); - } catch (RuntimeException e) { - failures.add(endpoint + " (" + e.getMessage() + ")"); + int movePathsInPlace(List targets, long timeoutMillis) { + java.util.Map> present = pathsByPort(); + long deadline = sys.nanoTime() + java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(timeoutMillis); + int moved = 0; + for (Target t : targets) { + List existing = present.get(t.port()); + if (existing == null) { continue; } - if (targets.isEmpty()) { - failures.add(endpoint + " (its discovery log page lists no data port)"); - continue; - } - java.util.Map> present = pathsByPort(); - long deadline = sys.nanoTime() + java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(endpointTimeoutMillis); - int moved = 0; - for (Target t : targets) { - List existing = present.get(t.port()); - if (existing == null) { - continue; - } - List stale = withoutKeysOf(existing, t); - if (!stale.isEmpty()) { - movePort(t, stale, stale.size() < existing.size(), - java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime())); - moved++; - } + List stale = withoutKeysOf(existing, t); + if (!stale.isEmpty()) { + movePort(t, stale, stale.size() < existing.size(), + java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime())); + moved++; } - return moved; } - LOG.warn("Lightbits: could not move this host's paths onto its current in-band authentication key(s): no discovery" - + " endpoint answered: {}", failures); - return 0; + return moved; } /** diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java index ee2323f..f5f1a32 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java @@ -345,14 +345,16 @@ public static void rotateInbandKeys() { /** * At a host connect: move this host's paths of the cluster ({@code scope}, its subsystem NQN; null: * every Lightbits path, host-wide keys) that do not hold the current key, or for {@code twoWay} the - * current controller key, onto new paths with them (LightbitsNvmeHost#movePathsInPlace). Nothing - * is read from the cluster when every path holds them. No path to a new port is made. + * current controller key, onto new paths with them (LightbitsNvmeHost#movePathsInPlace). The ports + * are those of the host's own paths, not a discovery read: the cluster's discovery service lists + * its subsystem only to a host that has access to a volume, and a host can hold paths without + * that. Nothing is done when every path holds the keys, and no path to a new port is made. */ - public static void movePathsInPlace(List endpoints, String scope, boolean twoWay) { - movePathsInPlace(new LightbitsNvmeHost(), new LightbitsHostKey().forScope(scope), endpoints, scope, twoWay); + public static void movePathsInPlace(String scope, boolean twoWay) { + movePathsInPlace(new LightbitsNvmeHost(), new LightbitsHostKey().forScope(scope), scope, twoWay); } - static void movePathsInPlace(LightbitsNvmeHost nvme, LightbitsHostKey keys, List endpoints, String scope, boolean twoWay) { + static void movePathsInPlace(LightbitsNvmeHost nvme, LightbitsHostKey keys, String scope, boolean twoWay) { String s = scope == null || scope.isBlank() ? null : scope.trim(); synchronized (CONNECT_LOCK) { String key = keys.ensure(); @@ -361,18 +363,20 @@ static void movePathsInPlace(LightbitsNvmeHost nvme, LightbitsHostKey keys, List if (stale == 0) { return; } - List normalized = new ArrayList<>(); - for (String e : endpoints) { - normalized.add(e.lastIndexOf(':') > 0 ? e : e + ":" + LightbitsNvmeHost.DEFAULT_DISCOVERY_PORT); - } - nvme.movePathsInPlace(normalized, LOOKUP_CONNECT_TIMEOUT_MILLIS, endpoint -> { - List ports = nvme.discover(endpoint, DISCOVER_TIMEOUT_MILLIS); - if (s != null) { - ports = ports.stream().filter(p -> s.equals(p.subsystemNqn == null ? null : p.subsystemNqn.trim())) - .collect(java.util.stream.Collectors.toList()); + List ports = new ArrayList<>(); + java.util.Set seen = new java.util.HashSet<>(); + for (LightbitsNvmeHost.Path p : nvme.paths()) { + String nqn = p.subsysNqn == null ? null : p.subsysNqn.trim(); + if (nqn == null || (s != null && !s.equals(nqn))) { + continue; + } + String address = LightbitsNvmeHost.addressPart(p.address, "traddr"); + String service = LightbitsNvmeHost.addressPart(p.address, "trsvcid"); + if (!address.isEmpty() && !service.isEmpty() && seen.add(nqn + " " + address + ":" + service)) { + ports.add(new LightbitsHostKey.Port(nqn, address, service)); } - return keys.targets(null, ports, twoWay); - }); + } + nvme.movePathsInPlace(keys.targets(null, ports, twoWay), LOOKUP_CONNECT_TIMEOUT_MILLIS); } } diff --git a/src/main/java/org/apache/cloudstack/storage/datastore/command/LightbitsGetHostNqnCommand.java b/src/main/java/org/apache/cloudstack/storage/datastore/command/LightbitsGetHostNqnCommand.java index 5d00884..dda39e1 100644 --- a/src/main/java/org/apache/cloudstack/storage/datastore/command/LightbitsGetHostNqnCommand.java +++ b/src/main/java/org/apache/cloudstack/storage/datastore/command/LightbitsGetHostNqnCommand.java @@ -102,21 +102,21 @@ public String getKeyScope() { /** * Move this host's existing paths of the pool's cluster that do not hold its current keys onto - * new paths with them, before they are counted (see {@code LightbitsNvmeHost#movePathsInPlace}). - * The pool's discovery endpoints and whether the pool is two-way; null from an older - * management server, and during a key rotation: nothing is moved. + * new paths with them, before they are counted (LightbitsStorageAdaptor#movePathsInPlace), and + * whether the pool is two-way. False from an older management server, and during a key + * rotation: nothing is moved. */ - private java.util.List moveEndpoints; + private boolean movePaths; private boolean moveTwoWay; - public LightbitsGetHostNqnCommand withMovePaths(java.util.List endpoints, boolean twoWay) { - this.moveEndpoints = endpoints; + public LightbitsGetHostNqnCommand withMovePaths(boolean twoWay) { + this.movePaths = true; this.moveTwoWay = twoWay; return this; } - public java.util.List getMoveEndpoints() { - return moveEndpoints; + public boolean isMovePaths() { + return movePaths; } public boolean isMoveTwoWay() { diff --git a/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java b/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java index 8fa0c44..0ea20cc 100644 --- a/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java +++ b/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java @@ -258,10 +258,13 @@ private void ensureHostDetails(long hostId, long poolId, org.apache.cloudstack.s ? otherPoolGenerations(hostId, poolId, null, true) : otherGenerations; // a rotation also asks for the controller key: the new keys go to every pool of the host, // two-way ones included - Answer answer = agentMgr.easySend(hostId, new LightbitsGetHostNqnCommand(wantIps ? cfg.discoveryEndpoints() : null, wantAuth, + LightbitsGetHostNqnCommand nqnCommand = new LightbitsGetHostNqnCommand(wantIps ? cfg.discoveryEndpoints() : null, wantAuth, wantAuth && (cfg.isInbandAuthTwoWay() || rotate)).withRotateKeys(rotate) - .withKeyScope(wantAuth ? scope : null) - .withMovePaths(wantAuth && !rotate ? cfg.discoveryEndpoints() : null, cfg.isInbandAuthTwoWay())); + .withKeyScope(wantAuth ? scope : null); + if (wantAuth && !rotate) { + nqnCommand.withMovePaths(cfg.isInbandAuthTwoWay()); + } + Answer answer = agentMgr.easySend(hostId, nqnCommand); boolean rotated = false; if (rotate && answer instanceof LightbitsGetHostNqnAnswer && answer.getResult()) { rotated = recordRotation(hostId, poolId, cfg.getInbandKeyGeneration(), (LightbitsGetHostNqnAnswer) answer); @@ -304,7 +307,7 @@ private void ensureHostDetails(long hostId, long poolId, org.apache.cloudstack.s // Now that the keys are registered, ask once more, so the move and the readiness // count need no second reconnect. Answer again = agentMgr.easySend(hostId, new LightbitsGetHostNqnCommand(null, true, cfg.isInbandAuthTwoWay()) - .withKeyScope(scope).withMovePaths(cfg.discoveryEndpoints(), cfg.isInbandAuthTwoWay())); + .withKeyScope(scope).withMovePaths(cfg.isInbandAuthTwoWay())); if (again instanceof LightbitsGetHostNqnAnswer && again.getResult() && ((LightbitsGetHostNqnAnswer) again).getDhchapKey() != null && java.util.Objects.equals(((LightbitsGetHostNqnAnswer) again).getKeyScope(), report.getKeyScope())) { diff --git a/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java b/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java index e6bd886..89e1b3e 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java @@ -240,8 +240,8 @@ public String ensure() { } @Override - protected void movePaths(List endpoints, String scope, boolean twoWay) { - calls.add("move " + endpoints + " " + scope + " " + twoWay); + protected void movePaths(String scope, boolean twoWay) { + calls.add("move " + scope + " " + twoWay); } @Override @@ -256,11 +256,11 @@ protected int pathsWithoutKey(String currentKey, String scope) { } }; w.execute(new LightbitsGetHostNqnCommand(null, true).withKeyScope("nqn.2016-01.com.lightbitslabs:uuid:x") - .withMovePaths(List.of("10.0.0.1:8009"), false), null); - assertEquals(List.of("move [10.0.0.1:8009] nqn.2016-01.com.lightbitslabs:uuid:x false", "count"), calls); + .withMovePaths(false), null); + assertEquals(List.of("move nqn.2016-01.com.lightbitslabs:uuid:x false", "count"), calls); calls.clear(); - w.execute(new LightbitsGetHostNqnCommand(null, true).withRotateKeys(true).withMovePaths(List.of("10.0.0.1:8009"), false), null); + w.execute(new LightbitsGetHostNqnCommand(null, true).withRotateKeys(true).withMovePaths(false), null); assertFalse(calls.stream().anyMatch(c -> c.startsWith("move")), calls.toString()); calls.clear(); diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java index c7f4837..d95f9fd 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java @@ -661,23 +661,12 @@ void aFailedDisconnectOfTheOldPathDoesNotFailTheConnect() { void aHostConnectMovesExistingPathsButMakesNoNewOne() { sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); keys("nvme1", "none", "none"); - assertEquals(1, host.movePathsInPlace(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1"), target("10.0.0.2")))); + assertEquals(1, host.movePathsInPlace(List.of(target("10.0.0.1"), target("10.0.0.2")), 1000)); assertEquals(1, sys.fabrics.size(), "only the port the host had a path to"); assertTrue(sys.fabrics.get(0).contains("traddr=10.0.0.1,") && sys.fabrics.get(0).endsWith(",duplicate_connect")); assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); } - @Test - void aHostConnectWhoseDiscoveryFailsMovesNothing() { - sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); - keys("nvme1", "none", "none"); - assertEquals(0, host.movePathsInPlace(List.of("10.0.0.1:8009"), 1000, endpoint -> { - throw new CloudRuntimeException("'nvme discover' failed"); - })); - assertTrue(sys.fabrics.isEmpty()); - assertTrue(disconnects().isEmpty()); - } - @Test void optionReadsOneValue() { assertEquals("b", LightbitsNvmeHost.option("a=1,x=b,c=3", "x")); diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java index 39be97e..68576d9 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java @@ -453,7 +453,7 @@ void aTwoWayVmStartOnAHostNotMovedYetMovesItsPathsAndGoesOn(@org.junit.jupiter.a } @Test - void aHostConnectReadsNothingFromTheClusterWhenEveryPathHoldsTheKeys(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tmp) + void aHostConnectMovesItsOwnPathsWithoutReadingTheCluster(@org.junit.jupiter.api.io.TempDir java.nio.file.Path tmp) throws Exception { java.nio.file.Files.writeString(tmp.resolve("hostnqn"), "nqn.2014-08.org.nvmexpress:uuid:60c10b61-c740-478c-a800-402344d475c9"); LightbitsHostKey keys = new LightbitsHostKey(tmp.resolve("lightbits"), tmp, (Integer) java.nio.file.Files.getAttribute(tmp, "unix:uid")); @@ -462,19 +462,26 @@ void aHostConnectReadsNothingFromTheClusterWhenEveryPathHoldsTheKeys(@org.junit. sys.files.put("/sys/class/nvme/nvme3/dhchap_secret", keys.ensure()); sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", keys.ensureCtrlKey()); sys.commands.clear(); - LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, List.of("10.0.1.1"), null, true); - assertTrue(sys.commands.stream().noneMatch(c -> c.startsWith("nvme discover")), sys.commands.toString()); - assertTrue(sys.fabrics.isEmpty()); + LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, null, true); + assertTrue(sys.fabrics.isEmpty(), "every path holds the keys: nothing to do"); - // a path without the controller key: discovery (default port added) and a move + // a path without the controller key: moved to the same port, and the cluster's discovery is + // not read (it lists the subsystem only to a host with access to a volume) sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", "none"); - sys.results.put("nvme discover -t tcp -a 10.0.1.1 -s 8009 -o json", new LightbitsNvmeHost.Result(0, - "{\"genctr\":1,\"records\":[{\"trtype\":\"tcp\",\"subtype\":\"nvme subsystem\",\"traddr\":\"10.0.1.1\"," - + "\"trsvcid\":\"4420\",\"subnqn\":\"" + NQN + "\"}]}")); - LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, List.of("10.0.1.1"), null, true); + LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, NQN, true); assertEquals(1, sys.fabrics.size()); - assertTrue(sys.fabrics.get(0).endsWith(",duplicate_connect")); + assertTrue(sys.fabrics.get(0).contains("traddr=10.0.1.1,trsvcid=4420,nqn=" + NQN + ",") && sys.fabrics.get(0).endsWith(",duplicate_connect")); assertTrue(sys.commands.contains("nvme disconnect -d nvme3")); + assertTrue(sys.commands.stream().noneMatch(c -> c.startsWith("nvme discover")), sys.commands.toString()); assertTrue(sys.commands.stream().noneMatch(c -> c.contains("DHHC-1")), "no key on any command line"); + + // another cluster's path is not this scope's business + sys.fabrics.clear(); + sys.controller("nvme5", "traddr=10.0.2.1,trsvcid=4420", "live"); + sys.files.put("/sys/class/nvme/nvme5/subsysnqn", "nqn.2016-01.com.lightbitslabs:uuid:00000000-0000-0000-0000-000000000009"); + sys.files.put("/sys/class/nvme/nvme5/dhchap_secret", "none"); + sys.files.put("/sys/class/nvme/nvme5/dhchap_ctrl_secret", "none"); + LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, NQN, true); + assertTrue(sys.fabrics.stream().noneMatch(o -> o.contains("traddr=10.0.2.1,")), sys.fabrics.toString()); } } diff --git a/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java b/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java index 408bcac..040c949 100644 --- a/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java +++ b/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java @@ -415,8 +415,7 @@ void oneWayRegistersTheHostKeyAndRecordsItsFingerprint() { .withRequestBody(matchingJsonPath("$.hostSecret", equalTo(KEY))) .withRequestBody(matchingJsonPath("$.targetSecretType", equalTo("Disabled")))); assertFalse(nqnCommands().get(0).isTwoWay()); - assertNotNull(nqnCommands().get(0).getMoveEndpoints(), "the agent moves paths without the key at the host connect"); - assertFalse(nqnCommands().get(0).getMoveEndpoints().isEmpty()); + assertTrue(nqnCommands().get(0).isMovePaths(), "the agent moves paths without the key at the host connect"); assertFalse(nqnCommands().get(0).isMoveTwoWay()); } @@ -438,7 +437,7 @@ void aHostWithPathsLeftWithoutTheNewKeysIsAskedOnceMoreAfterTheRegistration() { }; listener.hostConnect(HOST, POOL); assertEquals(2, nqnCommands().size(), "asked once more after the keys were registered"); - assertNotNull(nqnCommands().get(1).getMoveEndpoints()); + assertTrue(nqnCommands().get(1).isMovePaths()); assertTrue(nqnCommands().get(1).isMoveTwoWay()); assertFalse(nqnCommands().get(1).isRotateKeys()); @@ -539,7 +538,7 @@ void aRaisedGenerationRotatesAnIdleHostAndRecordsIt() throws Exception { listener.hostConnect(HOST, POOL); assertTrue(nqnCommands().get(0).isRotateKeys()); assertTrue(nqnCommands().get(0).isTwoWay(), "a rotation also asks for the controller key"); - assertNull(nqnCommands().get(0).getMoveEndpoints(), "a rotation moves no path: it drops them"); + assertFalse(nqnCommands().get(0).isMovePaths(), "a rotation moves no path: it drops them"); assertEquals("1", detail(LightbitsTrustedHosts.generationDetailKey(POOL))); sent.clear(); From 3edac2c9e9d1c313bedb3a147fd2a05823c52f0a Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 09:10:29 +0000 Subject: [PATCH 04/10] Test: the wrapper's move test uses the fake key store, never /etc/nvme Co-Authored-By: Claude Opus 5.5 --- .../LibvirtLightbitsGetHostNqnCommandWrapperTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java b/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java index 89e1b3e..8a28a03 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtLightbitsGetHostNqnCommandWrapperTest.java @@ -239,6 +239,11 @@ public String ensure() { }; } + @Override + protected com.cloud.hypervisor.kvm.storage.LightbitsHostKey keysFor(String scope) { + return hostKey(); // never the real key store under /etc/nvme + } + @Override protected void movePaths(String scope, boolean twoWay) { calls.add("move " + scope + " " + twoWay); From 99ecb7e8540c96d8253dc232b9664b669c9bc3b2 Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 09:10:57 +0000 Subject: [PATCH 05/10] Test: assert that each port's new path comes before the old one is disconnected Co-Authored-By: Claude Opus 5.5 --- .../cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java index d95f9fd..57a6313 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java @@ -583,9 +583,11 @@ void aPathWithoutTheCurrentKeysIsMovedInPlaceNewPathFirst() { keys("nvme1", "none", "none"); // one-way path made before two-way sys.controller("nvme2", "traddr=10.0.0.2,trsvcid=4420,src_addr=10.0.0.9", "live"); keys("nvme2", "DHHC-1:00:host:", "DHHC-1:00:old-ctrl:"); // a controller key replaced since - List order = new ArrayList<>(); - sys.onConnect = () -> order.add("connect"); + List disconnectsBeforeEachConnect = new ArrayList<>(); + sys.onConnect = () -> disconnectsBeforeEachConnect.add(disconnects().size()); assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1"), target("10.0.0.2")))); + assertEquals(List.of(0, 1), disconnectsBeforeEachConnect, + "each port's new path is made before its old one is disconnected"); assertEquals(2, sys.fabrics.size()); assertTrue(sys.fabrics.stream().allMatch(o -> o.endsWith(",duplicate_connect")), "a second controller next to the old one"); assertTrue(sys.fabrics.get(0).contains("traddr=10.0.0.1,") && sys.fabrics.get(1).contains("traddr=10.0.0.2,")); From fd9ea9acc99a6bece0485cf6d3ac4f1f65536fbc Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 10:34:40 +0000 Subject: [PATCH 06/10] In-place move: only with native multipath, only with a live keyed path, and at a host connect only for a known cluster Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++ INSTALL.md | 8 +++++ .../kvm/storage/LightbitsNvmeHost.java | 33 +++++++++++++++++-- .../kvm/storage/LightbitsStorageAdaptor.java | 8 ++++- .../provider/LightbitsHostListener.java | 5 +-- .../kvm/storage/LightbitsNvmeHostTest.java | 26 +++++++++++++++ .../storage/LightbitsStorageAdaptorTest.java | 10 ++++-- .../provider/LightbitsHostListenerTest.java | 12 ++++++- 8 files changed, 96 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f54dc93..54cbd21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), paths. A reconnect of each host after turning the option on is enough, and an attach, VM start or migration onto a host not yet reconnected moves its paths first. If the new path cannot be made, the old one is kept and the next connect tries again (the agent log says why). + The move needs native NVMe multipath (`nvme_core.multipath=Y`, the EL default). - A pool registration that fails at the first API call now says why: no API endpoint answered (check the addresses, the network and the TLS fingerprint; the token was not checked), the connection broke or timed out after the request was sent, the cluster refused the token, the @@ -24,6 +25,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), other hosts"). ### Known limitations +- Paths are moved in place only on hosts with native NVMe multipath; a host with + `nvme_core.multipath=N` is moved in maintenance, as before. - Attaches and live migrations take longer while a Lightbits node is down (in the lab, up to about 15 seconds more per attach); none fails. See [docs/known-limitations-and-issues.md](docs/known-limitations-and-issues.md). diff --git a/INSTALL.md b/INSTALL.md index cf2d306..79763cf 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -439,6 +439,14 @@ example, enforcement is on and the cluster does not have the new key yet), the o kept and the next connect tries again; the agent log says so. A path on a kernel without in-band authentication support cannot be checked and is left as it is. +The move needs the kernel's native NVMe multipath (`nvme_core.multipath=Y`, the default on +EL8 and later). Without it, a volume's device hangs below a single path, and disconnecting +that path would remove the device a VM uses, so nothing is moved: the agent log says so, and +such a host is moved in maintenance (disconnect its Lightbits paths while it runs no VMs, +then reconnect it). A host connect also moves nothing while the management server does not +know the pool's cluster (its subsystem NQN could not be read); the pool's next connect on the +host moves the paths instead. + #### What two-way checks The host checks the cluster during the authentication the cluster asks for when a path diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java index c49f987..6942440 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java @@ -320,7 +320,7 @@ boolean connectDirect(List endpoints, long endpointTimeoutMillis, List stale = withoutKeysOf(existing, t); if (!stale.isEmpty()) { long remaining = java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime()); - movePort(t, stale, stale.size() < existing.size(), remaining); + movePort(t, stale, liveKeyedPath(existing, stale), remaining); } continue; } @@ -383,7 +383,7 @@ int movePathsInPlace(List targets, long timeoutMillis) { } List stale = withoutKeysOf(existing, t); if (!stale.isEmpty()) { - movePort(t, stale, stale.size() < existing.size(), + movePort(t, stale, liveKeyedPath(existing, stale), java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime())); moved++; } @@ -407,6 +407,25 @@ private List withoutKeysOf(List paths, Target t) { return stale; } + /** The port already has a live path with the keys (an earlier move whose disconnect failed). */ + private static boolean liveKeyedPath(List existing, List stale) { + for (Path p : existing) { + if (!stale.contains(p) && p.live()) { + return true; + } + } + return false; + } + + /** + * The kernel's native NVMe multipath is on. Without it a namespace hangs below one controller, + * so disconnecting a controller removes the device a VM uses: paths are then never moved. + */ + private boolean nativeMultipath() { + String mp = sys.read("/sys/module/nvme_core/parameters/multipath"); + return mp != null && mp.trim().equalsIgnoreCase("Y"); + } + private boolean lacks(Path p, String attribute, String key) { if (key == null) { return false; @@ -433,12 +452,20 @@ static String option(String options, String name) { * Move a port onto a path with the current keys without a pause in I/O: make a second * controller to the same port with the keys ({@code duplicate_connect}), then disconnect the * old one; the kernel's native multipath keeps the namespaces on the other paths meanwhile - * (lab: guest writes went on through the replacement of every path). When the new path cannot + * (lab: guest writes went on through the replacement of every path); without native multipath + * nothing is moved. When the new path cannot * be made (for example the cluster enforces authentication and has not taken the new key yet), * the old one is kept and the next connect tries again. {@code keyedPathExists}: the port has * a path with the keys already (an earlier move whose disconnect failed), so only the old ones go. */ private void movePort(Target t, List stale, boolean keyedPathExists, long remainingMillis) { + if (!nativeMultipath()) { + LOG.warn("Lightbits: path(s) {} to {} do not hold this host's current in-band authentication key(s), and are not" + + " moved in place: native NVMe multipath is off on this host (nvme_core.multipath), so disconnecting a" + + " path would remove the device a VM uses. Move the host in maintenance: disconnect its Lightbits paths" + + " while it runs no VMs, then reconnect it", stale, t); + return; + } if (!keyedPathExists) { if (remainingMillis <= 0) { LOG.warn("Lightbits: path(s) {} to {} do not hold this host's current in-band authentication key(s); not moved now" diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java index f5f1a32..b2d98ba 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java @@ -344,7 +344,7 @@ public static void rotateInbandKeys() { /** Rotate this host's keys for one cluster (its subsystem NQN; null: the host-wide keys). */ /** * At a host connect: move this host's paths of the cluster ({@code scope}, its subsystem NQN; null: - * every Lightbits path, host-wide keys) that do not hold the current key, or for {@code twoWay} the + * nothing is moved, as the paths of other clusters cannot be told apart) that do not hold the current key, or for {@code twoWay} the * current controller key, onto new paths with them (LightbitsNvmeHost#movePathsInPlace). The ports * are those of the host's own paths, not a discovery read: the cluster's discovery service lists * its subsystem only to a host that has access to a volume, and a host can hold paths without @@ -356,6 +356,12 @@ public static void movePathsInPlace(String scope, boolean twoWay) { static void movePathsInPlace(LightbitsNvmeHost nvme, LightbitsHostKey keys, String scope, boolean twoWay) { String s = scope == null || scope.isBlank() ? null : scope.trim(); + if (s == null) { + // Without the cluster a host connect cannot tell this pool's paths from another cluster's, and + // would move those onto this key: a connect of the pool (its own discovery) moves them instead. + LOG.info("Lightbits: this host's paths are not moved at this host connect: the pool's cluster is not known"); + return; + } synchronized (CONNECT_LOCK) { String key = keys.ensure(); String ctrl = twoWay ? keys.ensureCtrlKey() : null; diff --git a/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java b/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java index 0ea20cc..da86b2e 100644 --- a/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java +++ b/src/main/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListener.java @@ -261,7 +261,8 @@ private void ensureHostDetails(long hostId, long poolId, org.apache.cloudstack.s LightbitsGetHostNqnCommand nqnCommand = new LightbitsGetHostNqnCommand(wantIps ? cfg.discoveryEndpoints() : null, wantAuth, wantAuth && (cfg.isInbandAuthTwoWay() || rotate)).withRotateKeys(rotate) .withKeyScope(wantAuth ? scope : null); - if (wantAuth && !rotate) { + if (wantAuth && !rotate && scope != null) { + // only with the cluster known: the agent moves that cluster's paths and no other's nqnCommand.withMovePaths(cfg.isInbandAuthTwoWay()); } Answer answer = agentMgr.easySend(hostId, nqnCommand); @@ -301,7 +302,7 @@ private void ensureHostDetails(long hostId, long poolId, org.apache.cloudstack.s setHostDetail(hostId, LightbitsTrustedHosts.perPool(HOST_SCOPE_DETAIL, poolId), report.getKeyScope() == null ? HOST_WIDE : report.getKeyScope()); registerTrustedHost(hostId, poolId, hostNqn, report); - if (!rotate && stale(report)) { + if (!rotate && scope != null && stale(report)) { // The agent moved its paths before this registration: with enforcement on, a path // with a key the cluster did not have yet (a new controller key) could not be made. // Now that the keys are registered, ask once more, so the move and the readiness diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java index 57a6313..1477861 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java @@ -569,6 +569,7 @@ void aTwoWayConnectMakesExactlyTheDiscoveredPortsWithoutConnectAll() { } private void keys(String ctrl, String hostKey, String ctrlKey) { + sys.files.put("/sys/module/nvme_core/parameters/multipath", "Y"); sys.files.put("/sys/class/nvme/" + ctrl + "/dhchap_secret", hostKey); sys.files.put("/sys/class/nvme/" + ctrl + "/dhchap_ctrl_secret", ctrlKey); } @@ -669,6 +670,31 @@ void aHostConnectMovesExistingPathsButMakesNoNewOne() { assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); } + @Test + void nothingIsMovedWithoutNativeMultipath() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + sys.files.put("/sys/module/nvme_core/parameters/multipath", "N"); // a namespace hangs below its controller + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1")))); + assertTrue(sys.fabrics.isEmpty()); + assertTrue(disconnects().isEmpty(), "disconnecting would remove the device a VM uses"); + sys.files.remove("/sys/module/nvme_core/parameters/multipath"); // unreadable: the same + assertEquals(1, host.movePathsInPlace(List.of(target("10.0.0.1")), 1000)); + assertTrue(sys.fabrics.isEmpty()); + assertTrue(disconnects().isEmpty()); + } + + @Test + void aKeyedPathThatIsNotLiveDoesNotReplaceTheOldOne() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + sys.controller("nvme4", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "connecting"); + keys("nvme4", "DHHC-1:00:host:", "DHHC-1:00:ctrl:"); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1")))); + assertEquals(1, sys.fabrics.size(), "a live path with the keys is made first"); + assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); + } + @Test void optionReadsOneValue() { assertEquals("b", LightbitsNvmeHost.option("a=1,x=b,c=3", "x")); diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java index 68576d9..6e241c9 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptorTest.java @@ -427,6 +427,7 @@ void aTwoWayVmStartOnAHostNotMovedYetMovesItsPathsAndGoesOn(@org.junit.jupiter.a KVMStoragePool twoWay = a.createStoragePool(POOL_B, "10.0.1.1", 443, "/proj", null, StoragePoolType.IscsiLUN, Map.of(LightbitsStorageAdaptor.DETAIL_NVME_DISCOVERY, "10.0.1.1", LightbitsStorageAdaptor.DETAIL_INBAND_AUTH, "true", LightbitsStorageAdaptor.DETAIL_INBAND_TWO_WAY, "true"), true); + sys.files.put("/sys/module/nvme_core/parameters/multipath", "Y"); sys.controller("nvme3", "traddr=10.0.1.1,trsvcid=4420", "live"); sys.files.put("/sys/class/nvme/nvme3/dhchap_secret", "none"); // a one-way path made before two-way sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", "none"); @@ -465,9 +466,14 @@ void aHostConnectMovesItsOwnPathsWithoutReadingTheCluster(@org.junit.jupiter.api LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, null, true); assertTrue(sys.fabrics.isEmpty(), "every path holds the keys: nothing to do"); - // a path without the controller key: moved to the same port, and the cluster's discovery is - // not read (it lists the subsystem only to a host with access to a volume) + // a path without the controller key: without the cluster known, nothing is moved (another + // cluster's paths could not be told apart) + sys.files.put("/sys/module/nvme_core/parameters/multipath", "Y"); sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", "none"); + LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, null, true); + assertTrue(sys.fabrics.isEmpty()); + // with it: moved to the same port, and the cluster's discovery is not read (it lists the + // subsystem only to a host with access to a volume) LightbitsStorageAdaptor.movePathsInPlace(nvme, keys, NQN, true); assertEquals(1, sys.fabrics.size()); assertTrue(sys.fabrics.get(0).contains("traddr=10.0.1.1,trsvcid=4420,nqn=" + NQN + ",") && sys.fabrics.get(0).endsWith(",duplicate_connect")); diff --git a/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java b/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java index 040c949..02121f1 100644 --- a/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java +++ b/src/test/java/org/apache/cloudstack/storage/datastore/provider/LightbitsHostListenerTest.java @@ -415,7 +415,15 @@ void oneWayRegistersTheHostKeyAndRecordsItsFingerprint() { .withRequestBody(matchingJsonPath("$.hostSecret", equalTo(KEY))) .withRequestBody(matchingJsonPath("$.targetSecretType", equalTo("Disabled")))); assertFalse(nqnCommands().get(0).isTwoWay()); - assertTrue(nqnCommands().get(0).isMovePaths(), "the agent moves paths without the key at the host connect"); + assertFalse(nqnCommands().get(0).isMovePaths(), "the pool's cluster is not known: no path is moved at a host connect"); + } + + @Test + void aHostConnectMovesPathsOnlyWithThePoolsClusterKnown() { + option(LightbitsPoolConfig.KEY_INBAND_AUTH, "true"); + poolDetails.put("lightbits.subsystemnqn", "nqn.2016-01.com.lightbitslabs:uuid:9c17511f-50e4-4620-9d0f-dc139863abcf"); + listener.hostConnect(HOST, POOL); + assertTrue(nqnCommands().get(0).isMovePaths(), "the agent moves that cluster's paths without the key"); assertFalse(nqnCommands().get(0).isMoveTwoWay()); } @@ -423,6 +431,7 @@ void oneWayRegistersTheHostKeyAndRecordsItsFingerprint() { void aHostWithPathsLeftWithoutTheNewKeysIsAskedOnceMoreAfterTheRegistration() { option(LightbitsPoolConfig.KEY_INBAND_AUTH, "true"); option(LightbitsPoolConfig.KEY_INBAND_AUTH_TWO_WAY, "true"); + poolDetails.put("lightbits.subsystemnqn", "nqn.2016-01.com.lightbitslabs:uuid:9c17511f-50e4-4620-9d0f-dc139863abcf"); int[] asked = {0}; // first answer: 3 paths could not be moved yet (the cluster did not have the controller key) agent = cmd -> { @@ -468,6 +477,7 @@ void aHostWhoseKeysMayHaveBeenCopiedIsRecordedUntilItRotates() { void twoWayRegistersTheControllerKeyAsTheTargetSecret() { option(LightbitsPoolConfig.KEY_INBAND_AUTH, "true"); option(LightbitsPoolConfig.KEY_INBAND_AUTH_TWO_WAY, "true"); + poolDetails.put("lightbits.subsystemnqn", "nqn.2016-01.com.lightbitslabs:uuid:9c17511f-50e4-4620-9d0f-dc139863abcf"); listener.hostConnect(HOST, POOL); assertTrue(nqnCommands().get(0).isTwoWay()); assertTrue(nqnCommands().get(0).isMoveTwoWay()); From 98774f372edd12e357b66ea7df6688958a5ff5b4 Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 10:39:21 +0000 Subject: [PATCH 07/10] Drop a null check the early return makes redundant Co-Authored-By: Claude Opus 5.5 --- .../cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java index b2d98ba..bb3f3bc 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsStorageAdaptor.java @@ -373,7 +373,7 @@ static void movePathsInPlace(LightbitsNvmeHost nvme, LightbitsHostKey keys, Stri java.util.Set seen = new java.util.HashSet<>(); for (LightbitsNvmeHost.Path p : nvme.paths()) { String nqn = p.subsysNqn == null ? null : p.subsysNqn.trim(); - if (nqn == null || (s != null && !s.equals(nqn))) { + if (nqn == null || !s.equals(nqn)) { continue; } String address = LightbitsNvmeHost.addressPart(p.address, "traddr"); From 1bbd067f55fb5596ba58505ba85801cdd7450d0f Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 12:29:45 +0000 Subject: [PATCH 08/10] Re-check a keyed path's state before dropping old paths; keep path moves within the connect's time Moving earlier ports can take a while, so the live state of a port's keyed path is read again from sysfs right before its old paths are disconnected; if it is no longer live, a new keyed path is made first. The disconnects now share the connect's time budget; old paths not reached in time are kept for the next connect. The test fake treats a controller directory as existing, so a failed disconnect is told apart from a removed controller. Co-Authored-By: Claude Opus 5.5 --- .../kvm/storage/LightbitsNvmeHost.java | 44 +++++++++++----- .../kvm/storage/LightbitsNvmeHostTest.java | 52 +++++++++++++++++-- 2 files changed, 81 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java index 6942440..922f86d 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java @@ -319,8 +319,7 @@ boolean connectDirect(List endpoints, long endpointTimeoutMillis, connected++; List stale = withoutKeysOf(existing, t); if (!stale.isEmpty()) { - long remaining = java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime()); - movePort(t, stale, liveKeyedPath(existing, stale), remaining); + movePort(t, existing, stale, deadline); } continue; } @@ -383,8 +382,7 @@ int movePathsInPlace(List targets, long timeoutMillis) { } List stale = withoutKeysOf(existing, t); if (!stale.isEmpty()) { - movePort(t, stale, liveKeyedPath(existing, stale), - java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime())); + movePort(t, existing, stale, deadline); moved++; } } @@ -407,16 +405,29 @@ private List withoutKeysOf(List paths, Target t) { return stale; } - /** The port already has a live path with the keys (an earlier move whose disconnect failed). */ - private static boolean liveKeyedPath(List existing, List stale) { + /** + * The port has a live path with the keys now (an earlier move whose disconnect failed). The + * state is read again from sysfs rather than taken from the snapshot the ports were listed + * from: moving earlier ports can take a while, and a path that failed meanwhile must not + * count, or the old paths would be dropped with nothing live left on the port. + */ + private boolean liveKeyedPath(List existing, List stale) { for (Path p : existing) { - if (!stale.contains(p) && p.live()) { + if (!stale.contains(p) && "live".equals(trimmed(sys.read("/sys/class/nvme/" + p.controller + "/state")))) { return true; } } return false; } + private static String trimmed(String s) { + return s == null ? null : s.trim(); + } + + private long millisLeft(long deadline) { + return java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime()); + } + /** * The kernel's native NVMe multipath is on. Without it a namespace hangs below one controller, * so disconnecting a controller removes the device a VM uses: paths are then never moved. @@ -455,10 +466,12 @@ static String option(String options, String name) { * (lab: guest writes went on through the replacement of every path); without native multipath * nothing is moved. When the new path cannot * be made (for example the cluster enforces authentication and has not taken the new key yet), - * the old one is kept and the next connect tries again. {@code keyedPathExists}: the port has - * a path with the keys already (an earlier move whose disconnect failed), so only the old ones go. + * the old one is kept and the next connect tries again. When the port has a live path with the + * keys already (an earlier move whose disconnect failed), only the old ones go. Everything, + * the disconnects included, stays within {@code deadline} (the connect's shared time budget): + * old paths not reached in time are kept for the next connect. */ - private void movePort(Target t, List stale, boolean keyedPathExists, long remainingMillis) { + private void movePort(Target t, List existing, List stale, long deadline) { if (!nativeMultipath()) { LOG.warn("Lightbits: path(s) {} to {} do not hold this host's current in-band authentication key(s), and are not" + " moved in place: native NVMe multipath is off on this host (nvme_core.multipath), so disconnecting a" @@ -466,7 +479,8 @@ private void movePort(Target t, List stale, boolean keyedPathExists, long + " while it runs no VMs, then reconnect it", stale, t); return; } - if (!keyedPathExists) { + if (!liveKeyedPath(existing, stale)) { + long remainingMillis = millisLeft(deadline); if (remainingMillis <= 0) { LOG.warn("Lightbits: path(s) {} to {} do not hold this host's current in-band authentication key(s); not moved now" + " (the connect's time ran out), the next connect tries again", stale, t); @@ -482,7 +496,13 @@ private void movePort(Target t, List stale, boolean keyedPathExists, long } } for (Path p : stale) { - Result r = sys.run(30_000, "nvme", "disconnect", "-d", p.controller); + long left = millisLeft(deadline); + if (left <= 0) { + LOG.warn("Lightbits: made a path to {} with this host's current in-band authentication key(s); the old path {}" + + " is kept for now (the connect's time ran out), the next connect disconnects it", t, p.controller); + continue; + } + Result r = sys.run(Math.min(30_000, left), "nvme", "disconnect", "-d", p.controller); if (r.ok() && !sys.exists("/sys/class/nvme/" + p.controller)) { LOG.info("Lightbits: moved {} onto a new path with this host's current in-band authentication key(s);" + " disconnected the old path {}", t, p.controller); diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java index 1477861..b1e8a3b 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java @@ -47,6 +47,7 @@ static class FakeSys implements LightbitsNvmeHost.Sys { final Map files = new HashMap<>(); final Map links = new HashMap<>(); final List commands = new ArrayList<>(); + final Map timeouts = new HashMap<>(); final Map results = new HashMap<>(); Runnable onRescan = () -> { }; Runnable onConnect = () -> { }; @@ -82,6 +83,7 @@ public void connectFabrics(String options, long timeoutMillis) { public LightbitsNvmeHost.Result run(long timeoutMillis, String... argv) { String cmd = String.join(" ", argv); commands.add(cmd); + timeouts.put(cmd, timeoutMillis); if (cmd.startsWith("nvme ns-rescan")) { onRescan.run(); } @@ -112,7 +114,10 @@ public LightbitsNvmeHost.Result run(long timeoutMillis, String... argv) { return new LightbitsNvmeHost.Result(0, ""); } - @Override public boolean exists(String path) { return links.containsKey(path) || files.containsKey(path); } + /** A file, a link, or a directory (any file below it), like a sysfs controller directory. */ + @Override public boolean exists(String path) { + return links.containsKey(path) || files.containsKey(path) || files.keySet().stream().anyMatch(k -> k.startsWith(path + "/")); + } @Override public String read(String path) { return unreadable.contains(path) ? null : files.get(path); } @Override public String canonical(String path) { return links.get(path); } @Override public void sleep(long millis) { slept++; } @@ -695,6 +700,41 @@ void aKeyedPathThatIsNotLiveDoesNotReplaceTheOldOne() { assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); } + @Test + void aKeyedPathThatFailedWhileAnEarlierPortMovedIsReplacedBeforeTheOldOneGoes() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + sys.controller("nvme2", "traddr=10.0.0.2,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme2", "none", "none"); + sys.controller("nvme5", "traddr=10.0.0.2,trsvcid=4420,src_addr=10.0.0.9", "live"); // live when the ports are listed + keys("nvme5", "DHHC-1:00:host:", "DHHC-1:00:ctrl:"); + sys.onConnect = () -> sys.files.put("/sys/class/nvme/nvme5/state", "connecting"); // fails while port 1 moves + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1"), target("10.0.0.2")))); + assertEquals(2, sys.fabrics.size(), "port 2 gets a new keyed path: its earlier one is no longer live"); + assertTrue(sys.fabrics.get(1).contains("traddr=10.0.0.2,") && sys.fabrics.get(1).endsWith(",duplicate_connect")); + assertEquals(List.of("nvme disconnect -d nvme1", "nvme disconnect -d nvme2"), disconnects()); + } + + @Test + void theDisconnectsStayWithinTheConnectsTime() { + sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme1", "none", "none"); + sys.fabricsDelayMillis = 400; + assertEquals(1, host.movePathsInPlace(List.of(target("10.0.0.1")), 1000)); + assertEquals(List.of("nvme disconnect -d nvme1"), disconnects(), "a fast replacement still drops its old path"); + assertEquals(600L, sys.timeouts.get("nvme disconnect -d nvme1"), "the disconnect gets only the time left"); + + sys.commands.clear(); + sys.fabrics.clear(); + sys.controller("nvme2", "traddr=10.0.0.2,trsvcid=4420,src_addr=10.0.0.9", "live"); + keys("nvme2", "none", "none"); + sys.fabricsDelayMillis = 1000; // the new path takes all the time + assertEquals(1, host.movePathsInPlace(List.of(target("10.0.0.2")), 1000)); + assertEquals(1, sys.fabrics.size()); + assertTrue(disconnects().isEmpty(), "the old path is kept for the next connect"); + assertTrue(sys.exists("/sys/class/nvme/nvme2")); + } + @Test void optionReadsOneValue() { assertEquals("b", LightbitsNvmeHost.option("a=1,x=b,c=3", "x")); @@ -845,7 +885,6 @@ void anUnknownPathCountRefusesTheRotation(@org.junit.jupiter.api.io.TempDir java @Test void newPathsWithoutTheControllerKeyAreDroppedOldOnesKept() { - sys.disconnectRemoves = false; // the same path is dropped again below, this time failing String ctrl = "DHHC-1:00:ctrl:"; sys.controller("nvme1", "traddr=10.0.0.1,trsvcid=4420", "live"); // older one-way path, may carry volumes java.util.Set before = host.pathNames(); @@ -856,7 +895,11 @@ void newPathsWithoutTheControllerKeyAreDroppedOldOnesKept() { assertEquals(List.of("nvme3"), host.dropNewPathsWithoutCtrlKey(before, ctrl)); assertTrue(sys.commands.contains("nvme disconnect -d nvme3"), sys.commands.toString()); assertTrue(sys.commands.stream().noneMatch(c -> c.equals("nvme disconnect -d nvme1")), "an older path is left alone"); + assertFalse(sys.exists("/sys/class/nvme/nvme3"), "the dropped path is gone"); + // the same kind of path made again, and this time its disconnect fails (the controller stays) + sys.controller("nvme3", "traddr=10.0.0.3,trsvcid=4420", "live"); + sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", "none"); sys.results.put("nvme disconnect -d nvme3", new LightbitsNvmeHost.Result(1, "failed")); CloudRuntimeException e = assertThrows(CloudRuntimeException.class, () -> host.dropNewPathsWithoutCtrlKey(before, ctrl)); assertTrue(e.getMessage().contains("could not be disconnected"), e.getMessage()); @@ -874,7 +917,10 @@ void newPathsWithoutTheControllerKeyAreDroppedOldOnesKept() { assertThrows(CloudRuntimeException.class, () -> host.dropNewPathsWithoutCtrlKey(next, ctrl)); sys.results.remove("nvme disconnect -d nvme3"); assertEquals(List.of("nvme3"), host.dropNewPathsWithoutCtrlKey(next, ctrl), "dropped once the disconnect works"); - // (the fake keeps nvme3 in sysfs) once dropped it is no longer rejected: an old path again, left alone + assertFalse(sys.exists("/sys/class/nvme/nvme3"), "the dropped path is gone"); + // once dropped it is no longer rejected: a controller of that name listed before the connect is an old path, left alone + sys.controller("nvme3", "traddr=10.0.0.3,trsvcid=4420", "live"); + sys.files.put("/sys/class/nvme/nvme3/dhchap_ctrl_secret", "none"); assertEquals(List.of(), host.dropNewPathsWithoutCtrlKey(next, ctrl)); } From 4cd76b60780a1178bc29e6052debcfcf4b1ee6de Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 13:39:55 +0000 Subject: [PATCH 09/10] Drop an old path only once its replacement carries its namespaces A new controller is made before the kernel has scanned its namespaces. The old path is now disconnected only once the port's live keyed paths carry every namespace it does, within the connect's time; otherwise it is kept for the next connect. INSTALL describes the wait. Co-Authored-By: Claude Opus 5.5 --- INSTALL.md | 6 ++- .../kvm/storage/LightbitsNvmeHost.java | 49 +++++++++++++++++++ .../kvm/storage/LightbitsNvmeHostTest.java | 38 +++++++++++++- 3 files changed, 90 insertions(+), 3 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index 79763cf..efb544b 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -433,8 +433,10 @@ At each connect of a pool with in-band authentication, and at each host connect, checks the host's paths to the pool's cluster (a host connect checks the paths the host already has, and makes no new one). A path that does not hold the host's current key (and, for two-way, its current controller key) is replaced without a pause in I/O: the agent first makes a second -path to the same port with the keys, then disconnects the old one; the kernel's NVMe -multipath keeps the volumes on the other paths meanwhile. If the new path cannot be made (for +path to the same port with the keys, waits until the new path carries every volume the old +one does, then disconnects the old one; the kernel's NVMe multipath keeps the volumes on the +other paths meanwhile. An old path the agent could not drop within the connect's time is +kept, and the next connect drops it. If the new path cannot be made (for example, enforcement is on and the cluster does not have the new key yet), the old path is kept and the next connect tries again; the agent log says so. A path on a kernel without in-band authentication support cannot be checked and is left as it is. diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java index 922f86d..4bc56d3 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java @@ -58,6 +58,8 @@ class LightbitsNvmeHost { private static final Pattern SUBSYS_NQN = Pattern.compile("nqn\\.2016-01\\.com\\.lightbitslabs:[A-Za-z0-9:._-]{1,200}"); private static final Pattern NAMESPACE_ENTRY = Pattern.compile("nvme[0-9]+(c[0-9]+)?n[0-9]+"); private static final Pattern CONTROLLER_ENTRY = Pattern.compile("nvme[0-9]+"); + /** A namespace path below a controller with native multipath: nvmecn. */ + private static final Pattern NAMESPACE_PATH = Pattern.compile("nvme[0-9]+c[0-9]+n([0-9]+)"); private static final String SUBSYSTEMS = "/sys/class/nvme-subsystem"; private static final AtomicInteger ROTATION = new AtomicInteger(); /** Two-way: paths rejected for lacking the controller key that could not be disconnected (agent-wide). */ @@ -496,6 +498,12 @@ private void movePort(Target t, List existing, List stale, long dead } } for (Path p : stale) { + if (!replacementHasNamespacesOf(t, stale, p, deadline)) { + LOG.warn("Lightbits: made a path to {} with this host's current in-band authentication key(s); the old path {}" + + " is kept for now (the new path has not attached all its namespaces in the connect's time), the next" + + " connect disconnects it", t, p.controller); + continue; + } long left = millisLeft(deadline); if (left <= 0) { LOG.warn("Lightbits: made a path to {} with this host's current in-band authentication key(s); the old path {}" @@ -514,6 +522,47 @@ private void movePort(Target t, List existing, List stale, long dead } } + /** + * Wait, within {@code deadline}, until the port's live paths with the keys carry every + * namespace the old path {@code old} carries. A new controller is made before the kernel has + * scanned its namespaces; disconnecting the old path first could leave a namespace with no path + * for a moment, and the kernel then removes the device a VM uses. + */ + private boolean replacementHasNamespacesOf(Target t, List stale, Path old, long deadline) { + java.util.Set needed = namespaceIds(old.controller); + java.util.Set staleNames = new java.util.HashSet<>(); + for (Path s : stale) { + staleNames.add(s.controller); + } + while (true) { + java.util.Set covered = new java.util.HashSet<>(); + for (Path p : pathsByPort().getOrDefault(t.port(), List.of())) { + if (!staleNames.contains(p.controller) && p.live()) { + covered.addAll(namespaceIds(p.controller)); + } + } + if (covered.containsAll(needed)) { + return true; + } + if (millisLeft(deadline) <= 0) { + return false; + } + sys.sleep(Math.min(200, Math.max(1, millisLeft(deadline)))); + } + } + + /** The namespace ids a controller has a path to (its nvmecn entries). */ + private java.util.Set namespaceIds(String controller) { + java.util.Set ids = new java.util.HashSet<>(); + for (String e : sys.list("/sys/class/nvme/" + controller)) { + java.util.regex.Matcher m = NAMESPACE_PATH.matcher(e); + if (m.matches()) { + ids.add(m.group(1)); + } + } + return ids; + } + /** One field ({@code traddr}, {@code trsvcid}) of a controller's sysfs address, or "" if absent. */ static String addressPart(String address, String field) { if (address != null) { diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java index b1e8a3b..1fb72dd 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java @@ -120,7 +120,12 @@ public LightbitsNvmeHost.Result run(long timeoutMillis, String... argv) { } @Override public String read(String path) { return unreadable.contains(path) ? null : files.get(path); } @Override public String canonical(String path) { return links.get(path); } - @Override public void sleep(long millis) { slept++; } + Runnable onSleep = () -> { }; + @Override public void sleep(long millis) { + slept++; + nanos += java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(millis); + onSleep.run(); + } @Override public List listOrNull(String dir) { @@ -735,6 +740,37 @@ void theDisconnectsStayWithinTheConnectsTime() { assertTrue(sys.exists("/sys/class/nvme/nvme2")); } + private void keyedReplacement(String ctrl, String address) { + sys.controller(ctrl, address, "live"); + sys.files.put("/sys/class/nvme/" + ctrl + "/dhchap_secret", "DHHC-1:00:host:"); + sys.files.put("/sys/class/nvme/" + ctrl + "/dhchap_ctrl_secret", "DHHC-1:00:ctrl:"); + } + + @Test + void theOldPathGoesOnlyOnceTheNewOneCarriesItsNamespaces() { + String addr = "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9"; + sys.controller("nvme1", addr, "live"); + keys("nvme1", "none", "none"); + sys.files.put("/sys/class/nvme/nvme1/nvme3c1n2/dev", "259:1"); // the volume a VM uses, only via this port + sys.onConnect = () -> keyedReplacement("nvme6", addr); // the controller is there, its scan is not + sys.onSleep = () -> sys.files.put("/sys/class/nvme/nvme6/nvme3c6n2/dev", "259:2"); + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1")))); + assertTrue(sys.slept > 0, "waited for the new path's namespace scan"); + assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); + } + + @Test + void theOldPathIsKeptWhenTheNewOneHasNotItsNamespacesInTime() { + String addr = "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9"; + sys.controller("nvme1", addr, "live"); + keys("nvme1", "none", "none"); + sys.files.put("/sys/class/nvme/nvme1/nvme3c1n2/dev", "259:1"); + sys.onConnect = () -> keyedReplacement("nvme6", addr); // its scan never finishes + assertEquals(1, host.movePathsInPlace(List.of(target("10.0.0.1")), 1000)); + assertTrue(disconnects().isEmpty(), "the namespace would lose its only path"); + assertTrue(sys.nanos <= java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(1200), "the wait stays within the connect's time"); + } + @Test void optionReadsOneValue() { assertEquals("b", LightbitsNvmeHost.option("a=1,x=b,c=3", "x")); From 279b6effa99c71394606173f630e18c2b5d04881 Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 14:50:31 +0000 Subject: [PATCH 10/10] Re-read the old path's namespaces on each poll; INSTALL: the next connect retries the move Co-Authored-By: Claude Opus 5.5 --- INSTALL.md | 2 +- .../kvm/storage/LightbitsNvmeHost.java | 9 ++++++--- .../kvm/storage/LightbitsNvmeHostTest.java | 20 +++++++++++++++++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index efb544b..573646f 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -436,7 +436,7 @@ its current controller key) is replaced without a pause in I/O: the agent first path to the same port with the keys, waits until the new path carries every volume the old one does, then disconnects the old one; the kernel's NVMe multipath keeps the volumes on the other paths meanwhile. An old path the agent could not drop within the connect's time is -kept, and the next connect drops it. If the new path cannot be made (for +kept, and the next connect retries the move (the agent log says so each time). If the new path cannot be made (for example, enforcement is on and the cluster does not have the new key yet), the old path is kept and the next connect tries again; the agent log says so. A path on a kernel without in-band authentication support cannot be checked and is left as it is. diff --git a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java index 4bc56d3..59a8fd4 100644 --- a/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java +++ b/src/main/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHost.java @@ -526,10 +526,13 @@ private void movePort(Target t, List existing, List stale, long dead * Wait, within {@code deadline}, until the port's live paths with the keys carry every * namespace the old path {@code old} carries. A new controller is made before the kernel has * scanned its namespaces; disconnecting the old path first could leave a namespace with no path - * for a moment, and the kernel then removes the device a VM uses. + * for a moment, and the kernel then removes the device a VM uses. Both sides are read again on + * each poll, so a namespace attached to the old path during the wait counts too. A namespace + * attached between the last check and the disconnect is not covered (the kernel scans new + * namespaces on its own); the window is a few milliseconds and is accepted, and the new path + * picks the namespace up at its own scan. */ private boolean replacementHasNamespacesOf(Target t, List stale, Path old, long deadline) { - java.util.Set needed = namespaceIds(old.controller); java.util.Set staleNames = new java.util.HashSet<>(); for (Path s : stale) { staleNames.add(s.controller); @@ -541,7 +544,7 @@ private boolean replacementHasNamespacesOf(Target t, List stale, Path old, covered.addAll(namespaceIds(p.controller)); } } - if (covered.containsAll(needed)) { + if (covered.containsAll(namespaceIds(old.controller))) { return true; } if (millisLeft(deadline) <= 0) { diff --git a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java index 1fb72dd..dc22110 100644 --- a/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java +++ b/src/test/java/com/cloud/hypervisor/kvm/storage/LightbitsNvmeHostTest.java @@ -759,6 +759,26 @@ void theOldPathGoesOnlyOnceTheNewOneCarriesItsNamespaces() { assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); } + @Test + void aNamespaceAttachedToTheOldPathDuringTheWaitIsWaitedForToo() { + String addr = "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9"; + sys.controller("nvme1", addr, "live"); + keys("nvme1", "none", "none"); + sys.files.put("/sys/class/nvme/nvme1/nvme3c1n2/dev", "259:1"); + sys.onConnect = () -> keyedReplacement("nvme6", addr); + sys.onSleep = () -> { + if (sys.slept == 1) { + sys.files.put("/sys/class/nvme/nvme6/nvme3c6n2/dev", "259:2"); // the first volume reaches the new path + sys.files.put("/sys/class/nvme/nvme1/nvme3c1n3/dev", "259:3"); // a volume attached meanwhile, old path only + } else { + sys.files.put("/sys/class/nvme/nvme6/nvme3c6n3/dev", "259:4"); + } + }; + assertTrue(host.connectDirect(List.of("10.0.0.1:8009"), 1000, endpoint -> List.of(target("10.0.0.1")))); + assertEquals(2, sys.slept, "waited for the volume attached during the wait as well"); + assertEquals(List.of("nvme disconnect -d nvme1"), disconnects()); + } + @Test void theOldPathIsKeptWhenTheNewOneHasNotItsNamespacesInTime() { String addr = "traddr=10.0.0.1,trsvcid=4420,src_addr=10.0.0.9";