From 718296555992a3bcd2e399f3a1373919d2f37fa1 Mon Sep 17 00:00:00 2001 From: Roiy Zysman Date: Sun, 29 Nov 2026 08:59:16 +0000 Subject: [PATCH] Tests: pool delete removes only this pool's cluster objects; storage-side clone from a template, volume or snapshot Co-Authored-By: Claude Opus 5.5 --- .../LightbitsPrimaryDataStoreLifeCycle.java | 10 +- .../driver/LightbitsDriverOperationsTest.java | 126 +++++++++++++- .../LightbitsLifeCycleDeleteTest.java | 159 ++++++++++++++++++ 3 files changed, 291 insertions(+), 4 deletions(-) create mode 100644 src/test/java/org/apache/cloudstack/storage/datastore/lifecycle/LightbitsLifeCycleDeleteTest.java diff --git a/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/LightbitsPrimaryDataStoreLifeCycle.java b/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/LightbitsPrimaryDataStoreLifeCycle.java index e2557b1..7b098ff 100644 --- a/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/LightbitsPrimaryDataStoreLifeCycle.java +++ b/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/LightbitsPrimaryDataStoreLifeCycle.java @@ -276,6 +276,10 @@ public interface ClientFactory { private ClientFactory clientFactory = LightbitsPoolConfig::newClient; + /** The stored configuration of a pool (tests: without the database and its encryption). */ + java.util.function.LongFunction poolConfig = + id -> org.apache.cloudstack.storage.datastore.util.LightbitsPoolSecret.load(storagePoolDetailsDao, id); + public void setClientFactory(ClientFactory factory) { this.clientFactory = factory; } @@ -443,16 +447,16 @@ static List releaseHosts(String poolName, List hostIds, java.util.fu * Best-effort by design: an unreachable cluster must not wedge pool removal. Failures are * logged with the objects left behind. */ - private void cleanupClusterObjects(DataStore store) { + void cleanupClusterObjects(DataStore store) { try { LightbitsPoolConfig cfg; try { - cfg = org.apache.cloudstack.storage.datastore.util.LightbitsPoolSecret.load(storagePoolDetailsDao, store.getId()); + cfg = poolConfig.apply(store.getId()); } catch (IllegalArgumentException e) { // A failed token replacement (missing file, a token passed through the API) clears the // pending replacement and keeps the stored token: report it and clean up with that one. LOG.warn("Lightbits pool {} delete: {}; cleaning up with the stored token", store.getId(), e.getMessage()); - cfg = org.apache.cloudstack.storage.datastore.util.LightbitsPoolSecret.load(storagePoolDetailsDao, store.getId()); + cfg = poolConfig.apply(store.getId()); } LightbitsApiClient client = clientFactory.create(cfg); diff --git a/src/test/java/org/apache/cloudstack/storage/datastore/driver/LightbitsDriverOperationsTest.java b/src/test/java/org/apache/cloudstack/storage/datastore/driver/LightbitsDriverOperationsTest.java index 2a67455..90a6ee1 100644 --- a/src/test/java/org/apache/cloudstack/storage/datastore/driver/LightbitsDriverOperationsTest.java +++ b/src/test/java/org/apache/cloudstack/storage/datastore/driver/LightbitsDriverOperationsTest.java @@ -157,7 +157,24 @@ public boolean deleteSnapshot(String uuid) { @Override public Snapshot createSnapshot(String name, String sourceVolumeUuid) { calls.add("snapshot " + name + " of " + sourceVolumeUuid); - return addSnapshot(name, sourceVolumeUuid, volumes.get(sourceVolumeUuid).getSizeBytes()); + Snapshot s = addSnapshot(name, sourceVolumeUuid, volumes.get(sourceVolumeUuid).getSizeBytes()); + s.setCreatedByThisCall(true); + return s; + } + + /** The error the next clone gets, or null. */ + RuntimeException cloneFailure; + + @Override + public Volume createVolumeFromSnapshot(String name, String snapshotUuid, long sizeBytes, int replicaCount, List aclNqns, + boolean compression, String qosPolicyName, VolumeExtras extras) { + calls.add("clone " + name + " from " + snapshotUuid + " size " + sizeBytes + " replicas " + replicaCount); + if (cloneFailure != null) { + throw cloneFailure; + } + Volume v = add(name, sizeBytes, List.of()); + v.setReplicaCount(replicaCount); + return v; } Snapshot addSnapshot(String name, String source, long size) { @@ -753,4 +770,111 @@ void theStatisticsPollRetriesARevocationEvenWhenTheClusterReportsNoCapacity() { "no statistics this cycle"); assertEquals(List.of("ALLOW_NONE"), v.getAcl().getValues(), "the removed host is taken out all the same"); } + + // ---- storage-side clone (volume from a template, a volume or a snapshot on this cluster) ---- + + private static final String TPL_UUID = "bbbbbbbb-1111-2222-3333-444444444444"; + + private DataStore primaryStore(long id) { + return fake(DataStore.class, n -> { + switch (n) { + case "getId": return a -> id; + case "getUuid": return a -> POOL_UUID; + case "getRole": return a -> com.cloud.storage.DataStoreRole.Primary; + default: return null; + } + }); + } + + private org.apache.cloudstack.engine.subsystem.api.storage.DataObject source(DataObjectType type, String uuid, long poolId) { + DataStore s = primaryStore(poolId); + return fake(org.apache.cloudstack.engine.subsystem.api.storage.DataObject.class, n -> { + switch (n) { + case "getType": return a -> type; + case "getUuid": return a -> uuid; + case "getDataStore": return a -> s; + default: return null; + } + }); + } + + private List copy( + org.apache.cloudstack.engine.subsystem.api.storage.DataObject src, VolumeInfo dest) { + List done = new ArrayList<>(); + driver.copyAsync(src, dest, capture(done)); + return done; + } + + @Test + void aVolumeFromATemplateIsANativeCloneAtTheLargerSizeWithTheTemplatesReplicas() { + Volume tpl = cluster.add(LightbitsUtil.volumeName("cs1", POOL, TPL_UUID), 2L << 30, List.of()); + tpl.setReplicaCount(2); + Volume placeholder = cluster.add(volName(), 1L << 30, List.of()); // createAsync may have made one + offering.put("lightbitsReplicas", "3"); + List done = + copy(source(DataObjectType.TEMPLATE, TPL_UUID, POOL), volume(1L << 30, null)); + assertEquals(1, done.size()); + assertTrue(done.get(0).isSuccess(), String.valueOf(done.get(0).getResult())); + assertTrue(cluster.calls.contains("delete " + placeholder.getUuid()), "the empty placeholder goes: " + cluster.calls); + assertTrue(cluster.calls.stream().anyMatch(c -> c.equals("snapshot " + volName() + "-src of " + tpl.getUuid())), cluster.calls.toString()); + String clone = cluster.calls.stream().filter(c -> c.startsWith("clone ")).findFirst().orElse(""); + assertTrue(clone.endsWith("size " + (2L << 30) + " replicas 2"), + "never smaller than the source, and a clone keeps its source's replica count: " + clone); + Volume created = cluster.getVolumeByName(volName()).orElseThrow(); + assertEquals(created.getUuid(), volumeRow.getPath(), "the backing path is saved on the volume row"); + } + + @Test + void aFailedCloneRemovesTheCloneSourceSnapshotItTook() { + Volume tpl = cluster.add(LightbitsUtil.volumeName("cs1", POOL, TPL_UUID), 2L << 30, List.of()); + tpl.setReplicaCount(3); + cluster.cloneFailure = new org.apache.cloudstack.storage.datastore.client.LightbitsApiException( + org.apache.cloudstack.storage.datastore.client.LightbitsApiException.Kind.QUOTA, 507, "no space"); + List done = + copy(source(DataObjectType.TEMPLATE, TPL_UUID, POOL), volume(1L << 30, null)); + assertFalse(done.get(0).isSuccess()); + assertTrue(String.valueOf(done.get(0).getResult()).contains("no space"), String.valueOf(done.get(0).getResult())); + assertTrue(cluster.snapshots.isEmpty(), "the clone-source snapshot is not left behind: " + cluster.calls); + } + + @Test + void aVolumeFromASnapshotClonesThatSnapshotAndNeverDeletesIt() { + Volume base = cluster.add(LightbitsUtil.volumeName("cs1", POOL, "cccccccc-1111-2222-3333-444444444444"), 4L << 30, List.of()); + String snapUuid = "dddddddd-1111-2222-3333-444444444444"; + org.apache.cloudstack.storage.datastore.client.model.Snapshot userSnap = + cluster.addSnapshot(LightbitsUtil.volumeName("cs1", POOL, snapUuid), base.getUuid(), 4L << 30); + cluster.cloneFailure = new RuntimeException("cluster busy"); + List done = + copy(source(DataObjectType.SNAPSHOT, snapUuid, POOL), volume(1L << 30, null)); + assertFalse(done.get(0).isSuccess()); + assertTrue(cluster.snapshots.containsKey(userSnap.getUuid()), "a user's snapshot is never removed: " + cluster.calls); + assertTrue(cluster.calls.stream().noneMatch(c -> c.startsWith("snapshot ")), "no new snapshot for a snapshot source"); + + cluster.cloneFailure = null; + done = copy(source(DataObjectType.SNAPSHOT, snapUuid, POOL), volume(1L << 30, null)); + assertTrue(done.get(0).isSuccess(), String.valueOf(done.get(0).getResult())); + assertTrue(cluster.calls.stream().anyMatch(c -> c.startsWith("clone " + volName() + " from " + userSnap.getUuid() + " size " + (4L << 30))), + cluster.calls.toString()); + } + + @Test + void aCloneFromAPoolInAnotherProjectIsRefusedWithAPointedMessage() throws Exception { + LightbitsPrimaryDataStoreDriver d = new LightbitsPrimaryDataStoreDriver() { + @Override + LightbitsPoolConfig configForPool(long poolId) { + return LightbitsPoolConfig.fromUrl("lightbits://10.0.0.1/" + (poolId == POOL ? "default" : "other") + + "?environment=cs1&replicas=3", "jwt"); + } + + @Override + LightbitsApiClient clientFor(LightbitsPoolConfig cfg) { + return cluster; + } + }; + List done = new ArrayList<>(); + d.copyAsync(source(DataObjectType.TEMPLATE, TPL_UUID, 8L), volume(1L << 30, null), capture(done)); + assertFalse(done.get(0).isSuccess()); + assertTrue(String.valueOf(done.get(0).getResult()).contains("different projects/clusters"), String.valueOf(done.get(0).getResult())); + assertTrue(cluster.calls.isEmpty(), "nothing is asked of the cluster: " + cluster.calls); + } } diff --git a/src/test/java/org/apache/cloudstack/storage/datastore/lifecycle/LightbitsLifeCycleDeleteTest.java b/src/test/java/org/apache/cloudstack/storage/datastore/lifecycle/LightbitsLifeCycleDeleteTest.java new file mode 100644 index 0000000..db7dd43 --- /dev/null +++ b/src/test/java/org/apache/cloudstack/storage/datastore/lifecycle/LightbitsLifeCycleDeleteTest.java @@ -0,0 +1,159 @@ +/* + * Copyright 2026 Lightbits Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.cloudstack.storage.datastore.lifecycle; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.storage.datastore.client.LightbitsApiClient; +import org.apache.cloudstack.storage.datastore.util.LightbitsPoolConfig; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.cloud.storage.VMTemplateStoragePoolVO; +import com.cloud.storage.dao.VMTemplatePoolDao; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; + +/** + * Deleting a pool removes what the plugin made on the cluster for THAT pool only: its cached + * template volumes and any volume or snapshot named exactly like one of its objects. A sibling + * pool in the same project, an environment whose name merely starts the same, and objects the + * plugin did not make are left alone; an unreachable cluster does not stop the delete. + */ +class LightbitsLifeCycleDeleteTest { + private static final long POOL = 7L; + private static final String P = "/api/v2/projects/default"; + private static final String U1 = "11111111-1111-1111-1111-111111111111"; + private static final String U2 = "22222222-2222-2222-2222-222222222222"; + private static final String U3 = "33333333-3333-3333-3333-333333333333"; + private static final String U4 = "44444444-4444-4444-4444-444444444444"; + private static final String U5 = "55555555-5555-5555-5555-555555555555"; + private static final String U6 = "66666666-6666-6666-6666-666666666666"; + private static final String CS = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"; + + private WireMockServer wm; + private LightbitsPrimaryDataStoreLifeCycle lc; + private final List templateRefs = new ArrayList<>(); + private final List removedRefs = new ArrayList<>(); + + @BeforeEach + void setUp() { + wm = new WireMockServer(WireMockConfiguration.options().dynamicPort()); + wm.start(); + lc = new LightbitsPrimaryDataStoreLifeCycle(); + lc.setClientFactory(cfg -> new LightbitsApiClient("http://localhost:" + wm.port(), cfg.getJwt(), cfg.getProject(), + java.net.http.HttpClient.newHttpClient(), 1)); + lc.poolConfig = id -> LightbitsPoolConfig.fromUrl("lightbits://h/default?environment=cs1", "jwt"); + lc.templatePoolDao = (VMTemplatePoolDao) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {VMTemplatePoolDao.class}, + (proxy, m, args) -> { + switch (m.getName()) { + case "listByPoolId": return args[0].equals(POOL) ? new ArrayList<>(templateRefs) : List.of(); + case "remove": removedRefs.add((Long) args[0]); return true; + default: throw new UnsupportedOperationException(m.getName()); + } + }); + wm.stubFor(delete(anyUrl()).willReturn(aResponse().withStatus(200).withBody("{}"))); + } + + @AfterEach + void tearDown() { + wm.stop(); + } + + private static DataStore store(long id) { + return (DataStore) Proxy.newProxyInstance(LightbitsLifeCycleDeleteTest.class.getClassLoader(), new Class[] {DataStore.class}, + (proxy, m, args) -> { + if ("getId".equals(m.getName())) { + return id; + } + throw new UnsupportedOperationException(m.getName()); + }); + } + + private static String obj(String uuid, String name) { + return "{\"UUID\":\"" + uuid + "\",\"name\":\"" + name + "\",\"state\":\"Available\",\"size\":\"1073741824\"," + + "\"replicaCount\":3,\"projectName\":\"default\",\"ETag\":\"1\",\"acl\":{\"values\":[\"ALLOW_NONE\"]}}"; + } + + private List deleted() { + return wm.findAll(deleteRequestedFor(anyUrl())).stream().map(r -> r.getUrl()).collect(Collectors.toList()); + } + + @Test + void onlyThisPoolsObjectsAndCachedTemplatesAreRemoved() { + VMTemplateStoragePoolVO ref = new VMTemplateStoragePoolVO(POOL, 201L, null); + ref.setInstallPath(U6); + templateRefs.add(ref); + templateRefs.add(new VMTemplateStoragePoolVO(POOL, 202L, null)); // never copied: no volume to remove + wm.stubFor(get(urlPathEqualTo(P + "/volumes")).willReturn(aResponse().withStatus(200).withBody("{\"volumes\":[" + + obj(U1, "cs-cs1-p7-" + CS) + "," // this pool's + + obj(U2, "cs-cs1-p8-" + CS) + "," // a sibling pool in the same project + + obj(U3, "cs-cs1-p7-p7-" + CS) + "," // environment "cs1-p7", pool 7 + + obj(U4, "cs-cs1-p7-not-a-uuid") + "," // not a name the plugin makes + + obj(U5, "customer-volume") + "]}"))); + wm.stubFor(get(urlPathEqualTo(P + "/snapshots")).willReturn(aResponse().withStatus(200).withBody("{\"snapshots\":[" + + obj(U2, "cs-cs1-p7-" + CS + "-src") + "," // this pool's clone-source snapshot, left behind + + obj(U3, "cs-cs1-p8-" + CS + "-src") + "," // the sibling pool's + + obj(U5, "cs-cs1-p7-" + CS.replace('a', 'f')) + "]}"))); + + lc.cleanupClusterObjects(store(POOL)); + + assertEquals(List.of(P + "/volumes/" + U6, P + "/snapshots/" + U2, P + "/snapshots/" + U5, P + "/volumes/" + U1), deleted(), + "the cached template volume, then this pool's snapshots and volume, nothing else"); + assertEquals(2, removedRefs.size(), "both template records of the pool are dropped"); + } + + @Test + void anUnreachableClusterDoesNotStopThePoolDelete() { + wm.stubFor(get(urlPathEqualTo(P + "/volumes")).willReturn(aResponse().withStatus(503).withBody("down"))); + wm.stubFor(get(urlPathEqualTo(P + "/snapshots")).willReturn(aResponse().withStatus(503).withBody("down"))); + lc.cleanupClusterObjects(store(POOL)); // logs what is left; does not throw + assertTrue(deleted().isEmpty()); + } + + @Test + void aTokenReplacementThatFailsCleansUpWithTheStoredToken() { + int[] loads = {0}; + lc.poolConfig = id -> { + if (loads[0]++ == 0) { + throw new IllegalArgumentException("the token file /etc/cloudstack/management/x.jwt cannot be read"); + } + return LightbitsPoolConfig.fromUrl("lightbits://h/default?environment=cs1", "jwt"); + }; + wm.stubFor(get(urlPathEqualTo(P + "/volumes")).willReturn(aResponse().withStatus(200).withBody("{\"volumes\":[" + + obj(U1, "cs-cs1-p7-" + CS) + "]}"))); + wm.stubFor(get(urlPathEqualTo(P + "/snapshots")).willReturn(aResponse().withStatus(200).withBody("{\"snapshots\":[]}"))); + lc.cleanupClusterObjects(store(POOL)); + assertEquals(2, loads[0]); + assertEquals(List.of(P + "/volumes/" + U1), deleted()); + wm.verify(deleteRequestedFor(urlEqualTo(P + "/volumes/" + U1))); + } +}