diff --git a/CHANGELOG.md b/CHANGELOG.md index ff39268..54cbd21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,18 @@ 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). + 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 cluster has no such project, or the cluster answered with an - error. It no longer says "with the supplied credentials" when the cluster could not be reached. + connection broke or timed out after the request was sent, the cluster refused the token, the + cluster has no such project, or the cluster answered with an error. It no longer says "with the supplied credentials" when the cluster could not be reached. - 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, @@ -17,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 d65bb3d..573646f 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,44 @@ 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, 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, 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 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. + +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 @@ -451,8 +464,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 +475,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 +492,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 03810ea..6b412a7 100644 --- a/docs/known-limitations-and-issues.md +++ b/docs/known-limitations-and-issues.md @@ -77,11 +77,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..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,6 +80,15 @@ public Answer execute(LightbitsGetHostNqnCommand command, LibvirtComputingResour answer.withRotation(false, e.getMessage()); } } + if (!command.isRotateKeys() && command.isMovePaths()) { + try { + 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): {}", + 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(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). */ 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..59a8fd4 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). */ @@ -307,18 +309,20 @@ 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()) { + movePort(t, existing, stale, deadline); + } continue; } long remaining = java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(deadline - sys.nanoTime()); @@ -354,6 +358,214 @@ 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 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 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; + } + List stale = withoutKeysOf(existing, t); + if (!stale.isEmpty()) { + movePort(t, existing, stale, deadline); + moved++; + } + } + return moved; + } + + /** + * 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; + } + + /** + * 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) && "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. + */ + 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; + } + 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); 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. 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 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" + + " 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 (!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); + 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) { + 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 {}" + + " 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); + } 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); + } + } + } + + /** + * 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. 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 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(namespaceIds(old.controller))) { + 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) { @@ -651,10 +863,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..bb3f3bc 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,50 @@ 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: + * 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 + * that. Nothing is done when every path holds the keys, and no path to a new port is made. + */ + public static void movePathsInPlace(String scope, boolean twoWay) { + movePathsInPlace(new LightbitsNvmeHost(), new LightbitsHostKey().forScope(scope), scope, 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; + int stale = nvme.pathsWithoutKey(key, s) + (twoWay ? nvme.pathsWithoutCtrlKey(ctrl, s) : 0); + if (stale == 0) { + return; + } + 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.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)); + } + } + nvme.movePathsInPlace(keys.targets(null, ports, twoWay), LOOKUP_CONNECT_TIMEOUT_MILLIS); + } + } + public static void rotateInbandKeys(String scope) { rotateInbandKeys(new LightbitsNvmeHost(), new LightbitsHostKey().forScope(scope), scope); } @@ -466,6 +510,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 +538,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..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 @@ -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 (LightbitsStorageAdaptor#movePathsInPlace), and + * whether the pool is two-way. False from an older management server, and during a key + * rotation: nothing is moved. + */ + private boolean movePaths; + private boolean moveTwoWay; + + public LightbitsGetHostNqnCommand withMovePaths(boolean twoWay) { + this.movePaths = true; + this.moveTwoWay = twoWay; + return this; + } + + public boolean isMovePaths() { + return movePaths; + } + + 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..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 @@ -258,9 +258,14 @@ 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)); + .withKeyScope(wantAuth ? scope : null); + 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); boolean rotated = false; if (rotate && answer instanceof LightbitsGetHostNqnAnswer && answer.getResult()) { rotated = recordRotation(hostId, poolId, cfg.getInbandKeyGeneration(), (LightbitsGetHostNqnAnswer) answer); @@ -297,6 +302,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 && 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 + // count need no second reconnect. + Answer again = agentMgr.easySend(hostId, new LightbitsGetHostNqnCommand(null, true, 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())) { + 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; @@ -434,6 +452,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) { @@ -650,8 +674,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..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 @@ -217,6 +217,62 @@ 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 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); + } + + @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(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(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..dc22110 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; @@ -46,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 = () -> { }; @@ -81,12 +83,17 @@ 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(); } 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()); @@ -107,10 +114,18 @@ 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++; } + 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) { @@ -563,6 +578,226 @@ 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/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); + } + + 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 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,")); + 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(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 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 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")); + } + + 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 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"; + 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")); + 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 @@ -716,7 +951,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()); @@ -734,7 +973,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)); } 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..6e241c9 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,84 @@ 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.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"); + 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 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")); + 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, null, true); + assertTrue(sys.fabrics.isEmpty(), "every path holds the keys: nothing to do"); + + // 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")); + 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 394b94a..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 @@ -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,45 @@ void oneWayRegistersTheHostKeyAndRecordsItsFingerprint() { .withRequestBody(matchingJsonPath("$.hostSecret", equalTo(KEY))) .withRequestBody(matchingJsonPath("$.targetSecretType", equalTo("Disabled")))); assertFalse(nqnCommands().get(0).isTwoWay()); + 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()); + } + + @Test + 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 -> { + 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"); + assertTrue(nqnCommands().get(1).isMovePaths()); + 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 @@ -437,8 +477,10 @@ 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()); wm.verify(putRequestedFor(urlEqualTo(P + "/trustedHostSecrets/" + TH_NAME)) .withRequestBody(matchingJsonPath("$.targetSecretType", equalTo("Enabled"))) .withRequestBody(matchingJsonPath("$.targetSecret", equalTo(CTRL)))); @@ -506,6 +548,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"); + assertFalse(nqnCommands().get(0).isMovePaths(), "a rotation moves no path: it drops them"); assertEquals("1", detail(LightbitsTrustedHosts.generationDetailKey(POOL))); sent.clear();