diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/asup/OntapAsupManagerTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/asup/OntapAsupManagerTest.java index 700ae8f83e2b..255cd327d47f 100644 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/asup/OntapAsupManagerTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/asup/OntapAsupManagerTest.java @@ -61,6 +61,7 @@ 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.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -75,8 +76,26 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.cloud.event.EventTypes; +import com.cloud.utils.Ternary; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.messagebus.MessageBus; +import org.apache.cloudstack.framework.messagebus.MessageSubscriber; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import java.lang.reflect.Field; +import java.util.Date; +import java.util.concurrent.ScheduledFuture; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyInt; @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class OntapAsupManagerTest { // ── DAOs ────────────────────────────────────────────────────────────────── @@ -87,6 +106,7 @@ class OntapAsupManagerTest { @Mock private VMSnapshotDao vmSnapshotDao; @Mock private ManagementService managementService; @Mock private ManagementServerHostDao managementServerHostDao; + @Mock private MessageBus messageBus; @InjectMocks private OntapAsupManager asupManager; @@ -121,6 +141,10 @@ void setUp() { .thenReturn(OntapStorageConstants.ASUP_PLATFORM_TYPE_PERFORMANCE); lenient().when(managementService.getVersion()).thenReturn("4.23.0.0-SNAPSHOT"); lenient().when(managementServerHostDao.listAll()).thenReturn(Collections.emptyList()); + lenient().when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(poolDetails); + lenient().when(mockStrategy.getClusterInfo()).thenReturn(mockCluster); + lenient().when(mockStrategy.getClusterVersion(mockCluster)).thenReturn("9.17.1"); + lenient().when(volumeDao.findNonDestroyedVolumesByPoolId(eq(1L), isNull())).thenReturn(Collections.emptyList()); } // ────────────────────────────────────────────────────────────────────────── @@ -603,6 +627,29 @@ void validateAsupInterval_rejectsOutOfRangeAndNonInteger() { assertThrows(InvalidParameterValueException.class, () -> OntapConfigurationManager.AsupIntervalHours.validateValue("")); } + @Test + void validateAsupInterval_errorMessagesNameTheKeyAndTheAllowedRange() { + InvalidParameterValueException outOfRange = assertThrows(InvalidParameterValueException.class, + () -> OntapConfigurationManager.AsupIntervalHours.validateValue("1")); + assertTrue(outOfRange.getMessage().contains(OntapStorageConstants.ASUP_INTERVAL_CONFIG_KEY), outOfRange.getMessage()); + assertTrue(outOfRange.getMessage().contains( + "between " + OntapStorageConstants.ASUP_MIN_INTERVAL_HOURS + " hours and " + + OntapStorageConstants.ASUP_MAX_INTERVAL_HOURS + " hours"), outOfRange.getMessage()); + + InvalidParameterValueException notInteger = assertThrows(InvalidParameterValueException.class, + () -> OntapConfigurationManager.AsupIntervalHours.validateValue("abc")); + assertTrue(notInteger.getMessage().contains("must be an integer"), notInteger.getMessage()); + } + + @Test + void configurationManagerPublishesItsComponentNameAndTheAsupIntervalKey() { + OntapConfigurationManager manager = new OntapConfigurationManager(); + + assertEquals("OntapConfigurationManager", manager.getConfigComponentName()); + assertEquals(1, manager.getConfigKeys().length); + assertSame(OntapConfigurationManager.AsupIntervalHours, manager.getConfigKeys()[0]); + } + @Test void getAsupIntervalHours_fallsBackOutsideRange() { assertEquals(OntapStorageConstants.ASUP_DEFAULT_INTERVAL_HOURS, @@ -744,4 +791,439 @@ private VMSnapshotVO makeVmSnapshot(VMSnapshot.State state, java.util.Date remov lenient().when(vmSnap.getRemoved()).thenReturn(removed); return vmSnap; } + + // ------------------------------------------------------------ helpers + + private List pushPool() { + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.resolveStrategyFromPoolDetails(any())).thenReturn(mockStrategy); + asupManager.pushAsupForStoragePool(pool, new HashMap<>()); + } + ArgumentCaptor captor = ArgumentCaptor.forClass(EmsApplicationLog.class); + verify(mockStrategy, times(2)).sendAsupMessage(captor.capture()); + List messages = captor.getAllValues(); + assertEquals(OntapStorageConstants.ASUP_EVENT_ID_HEARTBEAT, messages.get(0).getEventId()); + assertEquals(OntapStorageConstants.ASUP_EVENT_ID_STORAGE_POOL, messages.get(1).getEventId()); + return messages; + } + + private static VolumeVO volume(Volume.State state, Volume.Type type, Long size, Long instanceId) { + VolumeVO volume = mock(VolumeVO.class); + when(volume.getId()).thenReturn(System.nanoTime()); + when(volume.getState()).thenReturn(state); + when(volume.getVolumeType()).thenReturn(type); + when(volume.getSize()).thenReturn(size); + when(volume.getInstanceId()).thenReturn(instanceId); + return volume; + } + + private Object field(String name) throws Exception { + Field field = OntapAsupManager.class.getDeclaredField(name); + field.setAccessible(true); + return field.get(asupManager); + } + + // ------------------------------------------------------------ lifecycle / scheduling + + @Test + void configureSubscribesToConfigurationEdits() throws Exception { + assertTrue(asupManager.configure("OntapAsupManager", new HashMap<>())); + + verify(messageBus).subscribe(eq(EventTypes.EVENT_CONFIGURATION_VALUE_EDIT), any(MessageSubscriber.class)); + } + + @Test + void stopWithoutStartIsHarmless() { + assertTrue(asupManager.stop()); + } + + @Test + void startBooksOnePendingRunAndStopShutsTheSchedulerDown() throws Exception { + asupManager.lastPushTime = java.time.Instant.now(); // not overdue, so the run is booked for later + + assertTrue(asupManager.start()); + try { + ScheduledFuture pending = (ScheduledFuture) field("pendingRun"); + assertNotNull(pending); + assertFalse(pending.isDone()); + assertTrue(pending.getDelay(java.util.concurrent.TimeUnit.MINUTES) > 0); + } finally { + assertTrue(asupManager.stop()); + } + + assertTrue(((java.util.concurrent.ScheduledExecutorService) field("asupScheduler")).isShutdown()); + } + + private MessageSubscriber configureAndCaptureSubscriber() throws Exception { + asupManager.configure("OntapAsupManager", new HashMap<>()); + ArgumentCaptor captor = ArgumentCaptor.forClass(MessageSubscriber.class); + verify(messageBus).subscribe(eq(EventTypes.EVENT_CONFIGURATION_VALUE_EDIT), captor.capture()); + return captor.getValue(); + } + + @Test + void editingTheAsupIntervalRebooksThePendingRun() throws Exception { + MessageSubscriber subscriber = configureAndCaptureSubscriber(); + asupManager.lastPushTime = java.time.Instant.now(); + asupManager.start(); + try { + ScheduledFuture before = (ScheduledFuture) field("pendingRun"); + + subscriber.onPublishMessage("sender", EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, + new Ternary<>(OntapConfigurationManager.AsupIntervalHours.key(), ConfigKey.Scope.Global, null)); + + ScheduledFuture after = (ScheduledFuture) field("pendingRun"); + assertNotSame(before, after); + assertTrue(before.isCancelled()); + assertFalse(after.isCancelled()); + } finally { + asupManager.stop(); + } + } + + @Test + void unrelatedConfigurationEditsDoNotTouchTheSchedule() throws Exception { + MessageSubscriber subscriber = configureAndCaptureSubscriber(); + asupManager.lastPushTime = java.time.Instant.now(); + asupManager.start(); + try { + ScheduledFuture before = (ScheduledFuture) field("pendingRun"); + + subscriber.onPublishMessage("sender", EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, + new Ternary<>("some.other.key", ConfigKey.Scope.Global, null)); + subscriber.onPublishMessage("sender", EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, "not a ternary"); + subscriber.onPublishMessage("sender", EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, null); + + assertSame(before, field("pendingRun")); + assertFalse(before.isCancelled()); + } finally { + asupManager.stop(); + } + } + + @Test + void editingTheIntervalBeforeStartOrAfterStopBooksNothing() throws Exception { + MessageSubscriber subscriber = configureAndCaptureSubscriber(); + Ternary edit = + new Ternary<>(OntapConfigurationManager.AsupIntervalHours.key(), ConfigKey.Scope.Global, null); + + subscriber.onPublishMessage("sender", EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, edit); + assertNull(field("pendingRun")); + + asupManager.lastPushTime = java.time.Instant.now(); + asupManager.start(); + asupManager.stop(); + ScheduledFuture beforeEdit = (ScheduledFuture) field("pendingRun"); + subscriber.onPublishMessage("sender", EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, edit); + assertSame(beforeEdit, field("pendingRun")); + } + + // ------------------------------------------------------------ pushAsupTelemetry locking + + @Test + void pushTelemetryPushesEveryPoolWhileHoldingTheClusterLock() { + when(storagePoolDao.findPoolsByProvider(OntapStorageConstants.ONTAP_PLUGIN_NAME)).thenReturn(List.of(pool)); + GlobalLock lock = mock(GlobalLock.class); + when(lock.lock(anyInt())).thenReturn(true); + + try (MockedStatic locks = mockStatic(GlobalLock.class); + MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + locks.when(() -> GlobalLock.getInternLock(OntapStorageConstants.ASUP_GLOBAL_LOCK_NAME)).thenReturn(lock); + utils.when(() -> OntapStorageUtils.resolveStrategyFromPoolDetails(any())).thenReturn(mockStrategy); + + asupManager.pushAsupTelemetry(); + } + + verify(mockStrategy, times(2)).sendAsupMessage(any(EmsApplicationLog.class)); + verify(lock).unlock(); + verify(lock).releaseRef(); + } + + @Test + void pushTelemetrySkipsTheCycleWhenAnotherServerHoldsTheLock() { + when(storagePoolDao.findPoolsByProvider(OntapStorageConstants.ONTAP_PLUGIN_NAME)).thenReturn(List.of(pool)); + GlobalLock lock = mock(GlobalLock.class); + when(lock.lock(anyInt())).thenReturn(false); + + try (MockedStatic locks = mockStatic(GlobalLock.class)) { + locks.when(() -> GlobalLock.getInternLock(OntapStorageConstants.ASUP_GLOBAL_LOCK_NAME)).thenReturn(lock); + + asupManager.pushAsupTelemetry(); + } + + verify(mockStrategy, never()).sendAsupMessage(any(EmsApplicationLog.class)); + verify(lock, never()).unlock(); + verify(lock).releaseRef(); + } + + @Test + void pushTelemetryWithNullPoolListDoesNothing() { + when(storagePoolDao.findPoolsByProvider(OntapStorageConstants.ONTAP_PLUGIN_NAME)).thenReturn(null); + + asupManager.pushAsupTelemetry(); + + verify(mockStrategy, never()).sendAsupMessage(any(EmsApplicationLog.class)); + } + + @Test + void asupTaskKeepsRunningWhenThePushThrows() throws Exception { + asupManager.lastPushTime = java.time.Instant.now(); + assertTrue(asupManager.start()); + try { + ScheduledFuture bookedBeforeTheFailure = (ScheduledFuture) field("pendingRun"); + assertNotNull(bookedBeforeTheFailure); + asupManager.lastPushTime = java.time.Instant.EPOCH; + when(storagePoolDao.findPoolsByProvider(OntapStorageConstants.ONTAP_PLUGIN_NAME)) + .thenThrow(new IllegalStateException("db down")); + + asupManager.new OntapAsupTask().run(); + + assertFalse(asupManager.lastPushTime.equals(java.time.Instant.EPOCH)); + ScheduledFuture bookedAfterTheFailure = (ScheduledFuture) field("pendingRun"); + assertNotNull(bookedAfterTheFailure); + assertNotSame(bookedBeforeTheFailure, bookedAfterTheFailure); + assertTrue(bookedBeforeTheFailure.isCancelled()); + assertFalse(bookedAfterTheFailure.isDone()); + assertTrue(bookedAfterTheFailure.getDelay(java.util.concurrent.TimeUnit.MILLISECONDS) > 0); + } finally { + assertTrue(asupManager.stop()); + } + } + + // ------------------------------------------------------------ pushAsupForStoragePool edge cases + + @Test + void poolWithoutStorageIpIsNotCachedAndStillGetsHeartbeat() { + poolDetails.remove(OntapStorageConstants.STORAGE_IP); + Map cache = new HashMap<>(); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.resolveStrategyFromPoolDetails(any())).thenReturn(mockStrategy); + asupManager.pushAsupForStoragePool(pool, cache); + } + + assertTrue(cache.isEmpty()); + verify(mockStrategy, times(2)).sendAsupMessage(any(EmsApplicationLog.class)); + } + + @Test + void poolWithNullDetailsIsSkipped() { + when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(null); + + asupManager.pushAsupForStoragePool(pool, new HashMap<>()); + + verify(mockStrategy, never()).sendAsupMessage(any(EmsApplicationLog.class)); + } + + @Test + void heartbeatUsesUnknownWhenClusterAndVersionsAreMissing() { + when(mockStrategy.getClusterInfo()).thenReturn(null); + when(mockStrategy.getClusterVersion(null)).thenReturn(null); + when(managementService.getVersion()).thenReturn(null); + + List messages = pushPool(); + + String heartbeat = messages.get(0).getEventDescription(); + assertTrue(heartbeat.contains("\"ontapVersion\":\"unknown\""), heartbeat); + assertTrue(heartbeat.contains("\"ontapClusterModel\":\"unknown\""), heartbeat); + assertTrue(heartbeat.contains("\"ontapPlatformType\":\"unknown\""), heartbeat); + assertTrue(heartbeat.contains("\"clusterUuid\":\"unknown\""), heartbeat); + assertTrue(heartbeat.contains("\"cloudstackVersion\":\"unknown\""), heartbeat); + } + + @Test + void poolMessageUsesUnknownForMissingPoolFields() { + when(pool.getName()).thenReturn(null); + when(pool.getStatus()).thenReturn(null); + poolDetails.remove(OntapStorageConstants.PROTOCOL); + + List messages = pushPool(); + + String description = messages.get(1).getEventDescription(); + assertTrue(description.contains("\"poolName\":\"unknown\""), description); + assertTrue(description.contains("\"poolStatus\":\"unknown\""), description); + assertTrue(description.contains("\"protocol\":\"unknown\""), description); + } + + @Test + void usageCountsOnlyVolumesThatExistOnOntap() { + List volumes = Arrays.asList( + volume(Volume.State.Ready, Volume.Type.ROOT, 10L, 100L), + volume(Volume.State.Ready, Volume.Type.DATADISK, 20L, null), + volume(Volume.State.Attaching, Volume.Type.DATADISK, null, null), + volume(Volume.State.Ready, Volume.Type.ISO, 5L, null), + volume(Volume.State.Allocated, Volume.Type.ROOT, 1000L, 101L)); + when(volumeDao.findNonDestroyedVolumesByPoolId(eq(1L), isNull())).thenReturn(volumes); + + String description = pushPool().get(1).getEventDescription(); + + assertTrue(description.contains("\"rootDiskCount\":1"), description); + assertTrue(description.contains("\"dataDiskCount\":2"), description); + assertTrue(description.contains("\"totalLogicalSizeBytes\":35"), description); + } + + @Test + void poolMessageStillSentWhenVolumesCannotBeLoaded() { + when(volumeDao.findNonDestroyedVolumesByPoolId(eq(1L), isNull())).thenThrow(new IllegalStateException("db down")); + + String description = pushPool().get(1).getEventDescription(); + + assertFalse(description.contains("rootDiskCount"), description); + assertTrue(description.contains("multiPrimaryStoragePoolVm"), description); + } + + @Test + void nullVolumeListIsTreatedAsEmpty() { + when(volumeDao.findNonDestroyedVolumesByPoolId(eq(1L), isNull())).thenReturn(null); + + String description = pushPool().get(1).getEventDescription(); + + assertTrue(description.contains("\"rootDiskCount\":0"), description); + assertTrue(description.contains("\"volumeSnapshotCount\":0"), description); + assertTrue(description.contains("\"vmSnapshotCount\":0"), description); + } + + @Test + void usageIsOmittedWhenAVolumeCannotBeRead() { + VolumeVO broken = mock(VolumeVO.class); + when(broken.getState()).thenThrow(new IllegalStateException("corrupt row")); + when(volumeDao.findNonDestroyedVolumesByPoolId(eq(1L), isNull())).thenReturn(List.of(broken)); + + String description = pushPool().get(1).getEventDescription(); + + assertFalse(description.contains("rootDiskCount"), description); + } + + @Test + void multiPrimaryPoolFlagIsOmittedWhenQueryFails() { + when(volumeDao.hasMultiPrimaryStoragePoolVm(1L)).thenThrow(new IllegalStateException("db down")); + + String description = pushPool().get(1).getEventDescription(); + + assertFalse(description.contains("multiPrimaryStoragePoolVm"), description); + } + + @Test + void snapshotCountsAreZeroWhenDaosReturnNull() { + VolumeVO root = volume(Volume.State.Ready, Volume.Type.ROOT, 10L, 100L); + when(volumeDao.findNonDestroyedVolumesByPoolId(eq(1L), isNull())).thenReturn(List.of(root)); + when(snapshotDao.searchByVolumes(anyList())).thenReturn(null); + when(vmSnapshotDao.searchByVms(anyList())).thenReturn(null); + + String description = pushPool().get(1).getEventDescription(); + + assertTrue(description.contains("\"volumeSnapshotCount\":0"), description); + assertTrue(description.contains("\"vmSnapshotCount\":0"), description); + } + + @Test + void snapshotCountsAreOmittedWhenDaosFail() { + VolumeVO root = volume(Volume.State.Ready, Volume.Type.ROOT, 10L, 100L); + when(volumeDao.findNonDestroyedVolumesByPoolId(eq(1L), isNull())).thenReturn(List.of(root)); + when(snapshotDao.searchByVolumes(anyList())).thenThrow(new IllegalStateException("db down")); + when(vmSnapshotDao.searchByVms(anyList())).thenThrow(new IllegalStateException("db down")); + + String description = pushPool().get(1).getEventDescription(); + + assertFalse(description.contains("volumeSnapshotCount"), description); + assertFalse(description.contains("vmSnapshotCount"), description); + } + + @Test + void snapshotCountsExcludeDestroyedExpungingAndRemovedSnapshots() { + VolumeVO root = volume(Volume.State.Ready, Volume.Type.ROOT, 10L, 100L); + when(volumeDao.findNonDestroyedVolumesByPoolId(eq(1L), isNull())).thenReturn(List.of(root)); + SnapshotVO live = mock(SnapshotVO.class); + when(live.getState()).thenReturn(com.cloud.storage.Snapshot.State.BackedUp); + SnapshotVO destroyed = mock(SnapshotVO.class); + when(destroyed.getState()).thenReturn(com.cloud.storage.Snapshot.State.Destroyed); + when(snapshotDao.searchByVolumes(anyList())).thenReturn(List.of(live, destroyed)); + VMSnapshotVO active = mock(VMSnapshotVO.class); + when(active.getState()).thenReturn(VMSnapshot.State.Ready); + VMSnapshotVO expunging = mock(VMSnapshotVO.class); + when(expunging.getState()).thenReturn(VMSnapshot.State.Expunging); + VMSnapshotVO removed = mock(VMSnapshotVO.class); + when(removed.getState()).thenReturn(VMSnapshot.State.Ready); + when(removed.getRemoved()).thenReturn(new Date()); + when(vmSnapshotDao.searchByVms(anyList())).thenReturn(List.of(active, expunging, removed)); + + String description = pushPool().get(1).getEventDescription(); + + assertTrue(description.contains("\"volumeSnapshotCount\":1"), description); + assertTrue(description.contains("\"vmSnapshotCount\":1"), description); + } + + @Test + void descriptionFallsBackToMapStringWhenJsonSerialisationFails() throws Exception { + ObjectMapper broken = mock(ObjectMapper.class); + when(broken.writeValueAsString(any())).thenThrow(new JsonProcessingException("cannot serialise") { }); + Field mapper = OntapAsupManager.class.getDeclaredField("objectMapper"); + mapper.setAccessible(true); + mapper.set(asupManager, broken); + + List messages = pushPool(); + + assertEquals(2, messages.size()); + verify(broken, times(2)).writeValueAsString(any()); + assertTrue(messages.get(0).getEventDescription().startsWith("{"), messages.get(0).getEventDescription()); + assertTrue(messages.get(1).getEventDescription().startsWith("{message="), messages.get(1).getEventDescription()); + } + + // ------------------------------------------------------------ helper edge cases + + @Test + void cloudStackVersionIsUnknownWithoutManagementService() throws Exception { + Field service = OntapAsupManager.class.getDeclaredField("managementService"); + service.setAccessible(true); + service.set(asupManager, null); + + assertEquals(OntapStorageConstants.ASUP_UNKNOWN, asupManager.getCloudStackVersion()); + } + + @Test + void managementServerCountHandlesNullListAndDaoFailure() { + when(managementServerHostDao.listAll()).thenReturn(null); + assertEquals(0, asupManager.getManagementServerCount()); + + when(managementServerHostDao.listAll()).thenReturn(List.of(mock(ManagementServerHostVO.class))); + assertEquals(1, asupManager.getManagementServerCount()); + + when(managementServerHostDao.listAll()).thenThrow(new IllegalStateException("db down")); + assertEquals(0, asupManager.getManagementServerCount()); + } + + @Test + void computerNameFallsBackToUnknownWhenHostnameIsBlank() { + try (MockedStatic net = mockStatic(NetUtils.class)) { + net.when(NetUtils::getCanonicalHostName).thenReturn(" "); + assertEquals(OntapStorageConstants.ASUP_UNKNOWN, asupManager.getComputerName()); + + net.when(NetUtils::getCanonicalHostName).thenReturn("mgmt-1"); + assertEquals("mgmt-1", asupManager.getComputerName()); + } + } + + @Test + void operatingSystemDescriptionHandlesMissingProperties() { + String name = System.getProperty("os.name"); + String version = System.getProperty("os.version"); + String arch = System.getProperty("os.arch"); + try { + System.setProperty("os.name", "TestOS"); + System.setProperty("os.version", "1.2"); + System.setProperty("os.arch", "x86"); + assertEquals("TestOS 1.2 (x86)", asupManager.getOperatingSystem()); + + System.setProperty("os.version", " "); + System.setProperty("os.arch", ""); + assertEquals("TestOS", asupManager.getOperatingSystem()); + + System.setProperty("os.name", " "); + assertEquals(OntapStorageConstants.ASUP_UNKNOWN, asupManager.getOperatingSystem()); + } finally { + System.setProperty("os.name", name); + System.setProperty("os.version", version); + System.setProperty("os.arch", arch); + } + } } diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/driver/OntapPrimaryDatastoreDriverTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/driver/OntapPrimaryDatastoreDriverTest.java index 5c07a66088a0..fd297cb71fad 100644 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/driver/OntapPrimaryDatastoreDriverTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/driver/OntapPrimaryDatastoreDriverTest.java @@ -111,6 +111,30 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import org.junit.jupiter.api.Nested; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verifyNoInteractions; +import java.util.concurrent.atomic.AtomicReference; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import com.cloud.agent.api.to.DataObjectType; +import com.cloud.agent.api.to.DiskTO; +import static org.mockito.Mockito.spy; +import java.util.function.Consumer; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import java.util.function.Supplier; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.Mockito.atLeast; +import java.util.Collections; +import org.apache.cloudstack.storage.feign.client.SnapshotFeignClient; +import org.apache.cloudstack.storage.feign.model.FlexVolSnapshot; +import org.apache.cloudstack.storage.feign.model.Job; +import org.apache.cloudstack.storage.feign.model.response.JobResponse; +import org.apache.cloudstack.storage.feign.model.response.OntapResponse; +import org.apache.cloudstack.storage.to.SnapshotObjectTO; +import feign.FeignException; @ExtendWith(MockitoExtension.class) class OntapPrimaryDatastoreDriverTest { @@ -4276,4 +4300,3266 @@ void testGrantAccess_TemporarySnapshotCopy_SyncsIscsiPathOnInMemoryVolume() { assertEquals(iscsiPath, inMemoryVolume.get_iScsiName()); } } + + /** + * Host access (grant/revoke), QoS policy application and volume-delete failure handling of + * {@link OntapPrimaryDatastoreDriver}. + */ + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + @Nested + class OntapPrimaryDatastoreDriverAccessAndQosTest { + + private static final long POOL_ID = 5L; + private static final long VOLUME_ID = 10L; + private static final long TEMPLATE_ID = 31L; + private static final String SVM = "svm1"; + private static final String LUN_NAME = "/vol/flexvol/lun1"; + private static final String LUN_UUID = "lun-uuid"; + private static final String IGROUP_UUID = "igroup-uuid"; + private static final String TARGET_IQN = "iqn.1992-08.com.netapp:sn.1"; + private static final String WWID = "600a098078304d2d383f2f6b45734a54"; + private static final String SERIAL = "x0M-8?/kEsJT"; + + @Mock + private StoragePoolDetailsDao storagePoolDetailsDao; + @Mock + private PrimaryDataStoreDao storagePoolDao; + @Mock + private VolumeDao volumeDao; + @Mock + private VolumeDetailsDao volumeDetailsDao; + @Mock + private StorageManager storageManager; + + @Mock + private DataStore dataStore; + @Mock + private StoragePoolVO storagePool; + @Mock + private VolumeVO volumeVO; + @Mock + private VolumeInfo volumeInfo; + @Mock + private TemplateInfo templateInfo; + @Mock + private HostVO host; + @Mock + private UnifiedSANStrategy sanStrategy; + @Mock + private StorageStrategy nasStrategy; + @Mock + private AsyncCompletionCallback commandCallback; + + @InjectMocks + private OntapPrimaryDatastoreDriver driver; + + private Map poolDetails; + + @BeforeEach + void setUp() throws Exception { + poolDetails = new HashMap<>(); + poolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.ISCSI.name()); + poolDetails.put(OntapStorageConstants.SVM_NAME, SVM); + poolDetails.put(OntapStorageConstants.VOLUME_UUID, "flexvol-uuid"); + poolDetails.put(OntapStorageConstants.IS_AFF, "true"); + + when(dataStore.getId()).thenReturn(POOL_ID); + when(storagePoolDao.findById(POOL_ID)).thenReturn(storagePool); + when(storagePool.getId()).thenReturn(POOL_ID); + when(storagePool.getName()).thenReturn("flexvol"); + when(storagePool.getPath()).thenReturn(TARGET_IQN); + when(storagePool.getScope()).thenReturn(ScopeType.CLUSTER); + when(storagePool.getClusterId()).thenReturn(1L); + when(storagePool.getHypervisor()).thenReturn(Hypervisor.HypervisorType.KVM); + when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(poolDetails); + + when(volumeInfo.getId()).thenReturn(VOLUME_ID); + when(volumeInfo.getType()).thenReturn(DataObjectType.VOLUME); + when(volumeInfo.getName()).thenReturn("data-volume"); + when(volumeInfo.getSize()).thenReturn(1073741824L); + when(volumeInfo.getPoolId()).thenReturn(POOL_ID); + when(volumeInfo.getVolumeType()).thenReturn(Volume.Type.DATADISK); + when(volumeDao.findById(VOLUME_ID)).thenReturn(volumeVO); + when(volumeVO.getId()).thenReturn(VOLUME_ID); + when(volumeVO.getName()).thenReturn("data-volume"); + + when(host.getUuid()).thenReturn("host-uuid"); + when(host.getName()).thenReturn("kvm-1"); + when(host.getStorageUrl()).thenReturn("iqn.host"); + when(host.getClusterId()).thenReturn(1L); + + when(templateInfo.getType()).thenReturn(DataObjectType.TEMPLATE); + when(templateInfo.getId()).thenReturn(TEMPLATE_ID); + when(templateInfo.getUuid()).thenReturn("template-uuid"); + + when(storageManager.connectHostToSharedPool(any(), anyLong())).thenReturn(true); + } + + // ---------------------------------------------------------------- helpers + + private T withStrategy(StorageStrategy strategy, java.util.function.Supplier action) { + try (MockedStatic utils = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails)).thenReturn(strategy); + return action.get(); + } + } + + private void withStrategy(StorageStrategy strategy, Runnable action) { + withStrategy(strategy, () -> { + action.run(); + return null; + }); + } + + private void givenIscsiVolume() { + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME, LUN_NAME, false)); + when(volumeDetailsDao.findDetail(VOLUME_ID, DiskTO.SCSI_NAA_DEVICE_ID)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, DiskTO.SCSI_NAA_DEVICE_ID, WWID, false)); + AccessGroup existing = new AccessGroup(); + Igroup igroup = new Igroup(); + igroup.setName("cs_host-uuid_svm1"); + existing.setIgroup(igroup); + when(sanStrategy.getAccessGroup(anyMap())).thenReturn(existing); + when(sanStrategy.ensureLunMapped(eq(SVM), eq(LUN_NAME), anyString())).thenReturn("3"); + } + + private void givenNfsPool() { + poolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name()); + } + + private CloudStackVolume nfsDeleteRequest() { + return argThat(request -> request != null + && request.getVolumeInfo() == volumeInfo + && String.valueOf(POOL_ID).equals(request.getDatastoreId())); + } + + private CloudStackVolume nfsQosUpdate(String policyName, String policyUuid) { + return argThat(request -> request != null + && request.getVolumeInfo() == volumeInfo + && String.valueOf(POOL_ID).equals(request.getDatastoreId()) + && "flexvol-uuid".equals(request.getFlexVolumeUuid()) + && request.getFile() != null + && request.getFile().getQosPolicy() != null + && (policyName == null || policyName.equals(request.getFile().getQosPolicy().getName())) + && (policyUuid == null || policyUuid.equals(request.getFile().getQosPolicy().getUuid()))); + } + + // ------------------------------------------------- trivial driver contract + + @Test + void trivialCapabilities_reportExpectedStaticValues() throws Exception { + assertFalse(driver.canProvideStorageStats()); + assertFalse(driver.canProvideVolumeStats()); + assertNull(driver.getStorageStats(storagePool)); + assertNull(driver.getVolumeStats(storagePool, "vol")); + assertTrue(driver.canHostAccessStoragePool(host, storagePool)); + assertTrue(driver.isVmInfoNeeded()); + assertTrue(driver.isVmTagsNeeded("any")); + assertTrue(driver.isStorageSupportHA(Storage.StoragePoolType.NetworkFilesystem)); + assertTrue(driver.volumesRequireGrantAccessWhenUsed()); + assertNull(driver.getChapInfo(volumeInfo)); + assertNull(driver.getTO(volumeInfo)); + assertNull(driver.getStoreTO(dataStore)); + } + + @Test + void noOpCallbacks_doNotInteractWithDependencies() throws Exception { + driver.provideVmInfo(1L, 2L); + driver.provideVmTags(1L, 2L, "tag"); + driver.detachVolumeFromAllStorageNodes(volumeVO); + driver.handleQualityOfServiceForVolumeMigration(volumeInfo, null); + + verifyNoInteractions(volumeDao); + } + + // ------------------------------------------------- grantAccess: negative + + @Test + void grantAccess_throws_whenDataStoreIsNull() throws Exception { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.grantAccess(volumeInfo, host, null)); + + assertTrue(ex.getMessage().contains("dataStore should not be null"), ex.getMessage()); + } + + @Test + void grantAccess_throws_whenDataObjectIsNull() throws Exception { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.grantAccess(null, host, dataStore)); + + assertTrue(ex.getMessage().contains("dataObject should not be null"), ex.getMessage()); + } + + @Test + void grantAccess_throws_whenHostIsNull() throws Exception { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.grantAccess(volumeInfo, null, dataStore)); + + assertTrue(ex.getMessage().contains("host should not be null"), ex.getMessage()); + } + + @Test + void grantAccess_throws_whenStoragePoolNotFound() throws Exception { + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.grantAccess(volumeInfo, host, dataStore)); + + assertTrue(ex.getMessage().contains("Storage Pool not found"), ex.getMessage()); + } + + @Test + void grantAccess_throws_whenPoolScopeIsHost() throws Exception { + when(storagePool.getScope()).thenReturn(ScopeType.HOST); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.grantAccess(volumeInfo, host, dataStore)); + + assertTrue(ex.getMessage().contains("Only Cluster and Zone scoped"), ex.getMessage()); + } + + @Test + void grantAccess_throws_whenVolumeNotFound() throws Exception { + when(volumeDao.findById(VOLUME_ID)).thenReturn(null); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.grantAccess(volumeInfo, host, dataStore)); + + assertTrue(ex.getMessage().contains("CloudStack Volume not found"), ex.getMessage()); + } + + @Test + void grantAccess_throws_whenDataObjectTypeIsUnsupported() throws Exception { + DataObject snapshot = mock(DataObject.class); + when(snapshot.getType()).thenReturn(DataObjectType.SNAPSHOT); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.grantAccess(snapshot, host, dataStore)); + + assertTrue(ex.getMessage().contains("Invalid DataObjectType"), ex.getMessage()); + } + + // ------------------------------------------------- grantAccess: iSCSI + + @Test + void grantAccess_mapsLunAndUpdatesVolumePath_forIscsiVolume() throws Exception { + givenIscsiVolume(); + + boolean granted = withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore)); + + assertTrue(granted); + String expectedPath = "/" + TARGET_IQN + "/" + WWID; + verify(volumeVO).setPath(expectedPath); + verify(volumeVO).set_iScsiName(expectedPath); + verify(volumeVO).setPoolType(Storage.StoragePoolType.NetworkFilesystem); + verify(volumeVO).setPoolId(POOL_ID); + verify(volumeDao).update(VOLUME_ID, volumeVO); + verify(sanStrategy, never()).createAccessGroup(any(AccessGroup.class)); + verify(storageManager, never()).connectHostToSharedPool(any(), anyLong()); + } + + @Test + void grantAccess_createsIgroup_whenHostIgroupIsMissing() throws Exception { + givenIscsiVolume(); + when(sanStrategy.getAccessGroup(anyMap())).thenReturn(null); + AccessGroup created = new AccessGroup(); + Igroup igroup = new Igroup(); + igroup.setName("cs_host-uuid_svm1"); + created.setIgroup(igroup); + when(sanStrategy.createAccessGroup(any(AccessGroup.class))).thenReturn(created); + + assertTrue(withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AccessGroup.class); + verify(sanStrategy).createAccessGroup(captor.capture()); + assertEquals(POOL_ID, captor.getValue().getStoragePoolId()); + assertEquals(1, captor.getValue().getHostsToConnect().size()); + } + + @Test + void grantAccess_resolvesAndCachesWwid_whenNotCachedYet() throws Exception { + givenIscsiVolume(); + when(volumeDetailsDao.findDetail(VOLUME_ID, DiskTO.SCSI_NAA_DEVICE_ID)).thenReturn(null); + when(sanStrategy.getLunSerialNumber(SVM, LUN_NAME)).thenReturn(SERIAL); + + assertTrue(withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + verify(volumeDetailsDao).addDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_SERIAL_NUMBER, SERIAL, false); + verify(volumeDetailsDao).addDetail(VOLUME_ID, DiskTO.SCSI_NAA_DEVICE_ID, WWID, false); + } + + @Test + void grantAccess_throws_whenOntapReportsNoSerialNumber() throws Exception { + givenIscsiVolume(); + when(volumeDetailsDao.findDetail(VOLUME_ID, DiskTO.SCSI_NAA_DEVICE_ID)).thenReturn(null); + when(sanStrategy.getLunSerialNumber(SVM, LUN_NAME)).thenReturn(""); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + assertTrue(ex.getMessage().contains( + "ONTAP did not report a serial number for LUN " + LUN_NAME + " on SVM " + SVM), ex.getMessage()); + verify(sanStrategy).getLunSerialNumber(SVM, LUN_NAME); + verify(volumeDao, never()).update(anyLong(), any(VolumeVO.class)); + } + + @Test + void grantAccess_connectsHostToPool_whenIscsiVolumeIsMigrating() throws Exception { + givenIscsiVolume(); + when(volumeVO.getState()).thenReturn(Volume.State.Migrating); + + assertTrue(withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + verify(storageManager).connectHostToSharedPool(host, POOL_ID); + } + + @Test + void grantAccess_connectsHostToPool_whenIscsiVolumeIsTaggedMigrationDestination() throws Exception { + givenIscsiVolume(); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.MIGRATION_DESTINATION)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.MIGRATION_DESTINATION, "true", false)); + + assertTrue(withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + verify(storageManager).connectHostToSharedPool(host, POOL_ID); + } + + @Test + void grantAccess_throws_whenHostCannotConnectToIscsiPool() throws Exception { + givenIscsiVolume(); + when(volumeVO.getState()).thenReturn(Volume.State.Migrating); + when(storageManager.connectHostToSharedPool(eq(host), eq(POOL_ID))).thenReturn(false); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + assertEquals("Failed with error: Failed to connect host [kvm-1] to iSCSI storage pool [flexvol]", ex.getMessage()); + verify(storageManager).connectHostToSharedPool(host, POOL_ID); + } + + @Test + void grantAccess_copiesPathToCallerVolume_whenDataObjectCarriesVolumeVO() throws Exception { + givenIscsiVolume(); + VolumeVO callerVolume = mock(VolumeVO.class); + when(volumeInfo.getVolume()).thenReturn(callerVolume); + AtomicReference path = new AtomicReference<>("/server/side/path"); + AtomicReference iscsiName = new AtomicReference<>(); + when(volumeVO.getPath()).thenAnswer(invocation -> path.get()); + when(volumeVO.get_iScsiName()).thenAnswer(invocation -> iscsiName.get()); + doAnswer(invocation -> { + path.set(invocation.getArgument(0)); + return null; + }).when(volumeVO).setPath(anyString()); + doAnswer(invocation -> { + iscsiName.set(invocation.getArgument(0)); + return null; + }).when(volumeVO).set_iScsiName(anyString()); + + assertTrue(withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + String expectedPath = "/" + TARGET_IQN + "/" + WWID; + verify(callerVolume).setPath(expectedPath); + verify(callerVolume).set_iScsiName(expectedPath); + } + + // --------------------------------------------------- grantAccess: NFS + + @Test + void grantAccess_skipsExportPolicyUpdate_whenNfsVolumeIsNotMigrating() throws Exception { + givenNfsPool(); + + assertTrue(withStrategy(nasStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + verify(nasStrategy, never()).updateAccessGroup(any(AccessGroup.class)); + verify(storageManager, never()).connectHostToSharedPool(any(), anyLong()); + } + + @Test + void grantAccess_addsHostToExportPolicyAndConnects_whenNfsVolumeIsMigrating() throws Exception { + givenNfsPool(); + when(volumeVO.getState()).thenReturn(Volume.State.Migrating); + + assertTrue(withStrategy(nasStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AccessGroup.class); + verify(nasStrategy).updateAccessGroup(captor.capture()); + assertEquals(AccessGroup.HostRuleAction.ADD, captor.getValue().getHostRuleAction()); + assertEquals(POOL_ID, captor.getValue().getStoragePoolId()); + verify(storageManager).connectHostToSharedPool(host, POOL_ID); + } + + @Test + void grantAccess_throws_whenHostCannotConnectToNfsPool() throws Exception { + givenNfsPool(); + when(volumeVO.getState()).thenReturn(Volume.State.Migrating); + when(storageManager.connectHostToSharedPool(eq(host), eq(POOL_ID))).thenReturn(false); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> withStrategy(nasStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + assertEquals("Failed with error: Failed to connect host [kvm-1] to NFS storage pool [flexvol]", ex.getMessage()); + verify(storageManager).connectHostToSharedPool(host, POOL_ID); + } + + // ------------------------------------------------- revokeAccess: negative + + @Test + void revokeAccess_throws_whenDataStoreIsNull() throws Exception { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.revokeAccess(volumeInfo, host, null)); + + assertTrue(ex.getMessage().contains("dataStore should not be null"), ex.getMessage()); + } + + @Test + void revokeAccess_throws_whenDataObjectIsNull() throws Exception { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.revokeAccess(null, host, dataStore)); + + assertTrue(ex.getMessage().contains("dataObject should not be null"), ex.getMessage()); + } + + @Test + void revokeAccess_throws_whenHostIsNull() throws Exception { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.revokeAccess(volumeInfo, null, dataStore)); + + assertTrue(ex.getMessage().contains("host should not be null"), ex.getMessage()); + } + + @Test + void revokeAccess_throws_whenStoragePoolNotFound() throws Exception { + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + assertTrue(ex.getMessage().contains("Storage Pool not found"), ex.getMessage()); + } + + @Test + void revokeAccess_throws_whenPoolScopeIsHost() throws Exception { + when(storagePool.getScope()).thenReturn(ScopeType.HOST); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + assertTrue(ex.getMessage().contains("Only Cluster and Zone scoped"), ex.getMessage()); + } + + @Test + void revokeAccess_throws_whenVolumeNotFound() throws Exception { + when(volumeDao.findById(VOLUME_ID)).thenReturn(null); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + assertTrue(ex.getMessage().contains("CloudStack Volume not found"), ex.getMessage()); + } + + @Test + void revokeAccess_throws_whenDataObjectTypeIsUnsupported() throws Exception { + DataObject snapshot = mock(DataObject.class); + when(snapshot.getType()).thenReturn(DataObjectType.SNAPSHOT); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> driver.revokeAccess(snapshot, host, dataStore)); + + assertTrue(ex.getMessage().contains("Invalid DataObjectType"), ex.getMessage()); + } + + // ------------------------------------------------ revokeAccess: iSCSI + + private void givenLunAndIgroupOnOntap() { + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME, LUN_NAME, false)); + Lun lun = new Lun(); + lun.setName(LUN_NAME); + lun.setUuid(LUN_UUID); + CloudStackVolume csVolume = new CloudStackVolume(); + csVolume.setLun(lun); + when(sanStrategy.getCloudStackVolume(anyMap())).thenReturn(csVolume); + AccessGroup accessGroup = new AccessGroup(); + // Igroup.uuid is only populated by JSON deserialization, so a mock supplies it here. + Igroup igroup = mock(Igroup.class); + when(igroup.getName()).thenReturn("cs_host-uuid_svm1"); + when(igroup.getUuid()).thenReturn(IGROUP_UUID); + accessGroup.setIgroup(igroup); + when(sanStrategy.getAccessGroup(anyMap())).thenReturn(accessGroup); + when(sanStrategy.validateInitiatorInAccessGroup(eq("iqn.host"), eq(SVM), any(Igroup.class))).thenReturn(true); + } + + @Test + void revokeAccess_unmapsLun_whenLunIgroupAndInitiatorExist() throws Exception { + givenLunAndIgroupOnOntap(); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(sanStrategy).disableLogicalAccess(captor.capture()); + assertEquals(LUN_UUID, captor.getValue().get(OntapStorageConstants.LUN_DOT_UUID)); + assertEquals(IGROUP_UUID, captor.getValue().get(OntapStorageConstants.IGROUP_DOT_UUID)); + } + + @Test + void revokeAccess_skips_whenLunNameDetailMissing() throws Exception { + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME)).thenReturn(null); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(sanStrategy, never()).disableLogicalAccess(anyMap()); + } + + @Test + void revokeAccess_skips_whenLunNameDetailHasNullValue() throws Exception { + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME, null, false)); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(sanStrategy, never()).disableLogicalAccess(anyMap()); + } + + @Test + void revokeAccess_skips_whenLunNoLongerExistsOnOntap() throws Exception { + givenLunAndIgroupOnOntap(); + when(sanStrategy.getCloudStackVolume(anyMap())).thenReturn(null); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(sanStrategy, never()).disableLogicalAccess(anyMap()); + } + + @Test + void revokeAccess_skips_whenLunHasNoName() throws Exception { + givenLunAndIgroupOnOntap(); + CloudStackVolume unnamed = new CloudStackVolume(); + unnamed.setLun(new Lun()); + when(sanStrategy.getCloudStackVolume(anyMap())).thenReturn(unnamed); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(sanStrategy, never()).disableLogicalAccess(anyMap()); + } + + @Test + void revokeAccess_skips_whenLunHasNoUuid() throws Exception { + givenLunAndIgroupOnOntap(); + Lun named = new Lun(); + named.setName(LUN_NAME); + CloudStackVolume noUuid = new CloudStackVolume(); + noUuid.setLun(named); + when(sanStrategy.getCloudStackVolume(anyMap())).thenReturn(noUuid); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(sanStrategy, never()).disableLogicalAccess(anyMap()); + } + + @Test + void revokeAccess_skips_whenIgroupNoLongerExistsOnOntap() throws Exception { + givenLunAndIgroupOnOntap(); + when(sanStrategy.getAccessGroup(anyMap())).thenReturn(null); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(sanStrategy, never()).disableLogicalAccess(anyMap()); + } + + @Test + void revokeAccess_skips_whenIgroupHasNoUuid() throws Exception { + givenLunAndIgroupOnOntap(); + AccessGroup noUuid = new AccessGroup(); + noUuid.setIgroup(new Igroup()); + when(sanStrategy.getAccessGroup(anyMap())).thenReturn(noUuid); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(sanStrategy, never()).disableLogicalAccess(anyMap()); + } + + @Test + void revokeAccess_skips_whenHostInitiatorIsNotInIgroup() throws Exception { + givenLunAndIgroupOnOntap(); + when(sanStrategy.validateInitiatorInAccessGroup(anyString(), anyString(), any(Igroup.class))).thenReturn(false); + + withStrategy(sanStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(sanStrategy, never()).disableLogicalAccess(anyMap()); + } + + // -------------------------------------------------- revokeAccess: NFS + + @Test + void revokeAccess_removesHostFromExportPolicy_whenHostIsInDifferentCluster() throws Exception { + givenNfsPool(); + when(host.getClusterId()).thenReturn(2L); + + withStrategy(nasStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AccessGroup.class); + verify(nasStrategy).updateAccessGroup(captor.capture()); + assertEquals(AccessGroup.HostRuleAction.REMOVE, captor.getValue().getHostRuleAction()); + } + + @Test + void revokeAccess_keepsExportPolicy_whenHostIsInPoolCluster() throws Exception { + givenNfsPool(); + + withStrategy(nasStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(nasStrategy, never()).updateAccessGroup(any(AccessGroup.class)); + } + + @Test + void revokeAccess_keepsExportPolicy_whenHostHasNoCluster() throws Exception { + givenNfsPool(); + when(host.getClusterId()).thenReturn(null); + + withStrategy(nasStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(nasStrategy, never()).updateAccessGroup(any(AccessGroup.class)); + } + + @Test + void revokeAccess_keepsExportPolicy_whenPoolHasNoCluster() throws Exception { + givenNfsPool(); + when(host.getClusterId()).thenReturn(2L); + when(storagePool.getClusterId()).thenReturn(null); + + withStrategy(nasStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(nasStrategy, never()).updateAccessGroup(any(AccessGroup.class)); + } + + @Test + void revokeAccess_keepsExportPolicy_whenPoolIsZoneScoped() throws Exception { + givenNfsPool(); + when(storagePool.getScope()).thenReturn(ScopeType.ZONE); + when(host.getClusterId()).thenReturn(2L); + + withStrategy(nasStrategy, () -> driver.revokeAccess(volumeInfo, host, dataStore)); + + verify(nasStrategy, never()).updateAccessGroup(any(AccessGroup.class)); + } + + // ------------------------------------------------ revokeAccess: template + + @Test + void revokeAccess_isNoOp_forNfsTemplate() throws Exception { + givenNfsPool(); + + withStrategy(nasStrategy, () -> driver.revokeAccess(templateInfo, host, dataStore)); + + verifyNoInteractions(nasStrategy); + } + + @Test + void revokeAccess_unmapsTemplateCacheLun_forIscsiTemplate() throws Exception { + givenLunAndIgroupOnOntap(); + + withStrategy(sanStrategy, () -> driver.revokeAccess(templateInfo, host, dataStore)); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(sanStrategy).disableLogicalAccess(captor.capture()); + assertEquals(LUN_UUID, captor.getValue().get(OntapStorageConstants.LUN_DOT_UUID)); + } + + // ------------------------------------------- applyQosPolicyToVolume + + private VolumeQosPolicy qosPolicy() { + VolumeQosPolicy policy = new VolumeQosPolicy(); + policy.setName("cs_100_to_500_iops_svm1"); + policy.setUuid("qos-uuid"); + return policy; + } + + @Test + void applyQosPolicy_doesNothing_whenVolumeIsNull() throws Exception { + driver.applyQosPolicyToVolume(null); + + verifyNoInteractions(storagePoolDao); + } + + @Test + void applyQosPolicy_doesNothing_whenPoolNotFound() throws Exception { + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + + driver.applyQosPolicyToVolume(volumeInfo); + + verifyNoInteractions(storagePoolDetailsDao); + } + + @Test + void applyQosPolicy_doesNothing_whenVolumeTypeIsNotRootOrData() throws Exception { + when(volumeInfo.getVolumeType()).thenReturn(Volume.Type.ISO); + + driver.applyQosPolicyToVolume(volumeInfo); + + verifyNoInteractions(storagePoolDetailsDao); + } + + @Test + void applyQosPolicy_attachesPolicyToLunAndPersistsDetail_forIscsiVolume() throws Exception { + when(volumeInfo.getMinIops()).thenReturn(100L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + when(sanStrategy.createVolumeQosPolicy("cs_100_to_500_iops_svm1", 100L, 500L)).thenReturn(qosPolicy()); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID, LUN_UUID, false)); + + withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo)); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(sanStrategy).updateCloudStackVolume(request.capture()); + assertEquals(LUN_UUID, request.getValue().getLun().getUuid()); + assertSame(volumeInfo, request.getValue().getVolumeInfo()); + assertEquals("qos-uuid", request.getValue().getLun().getQosPolicy().getUuid()); + verify(volumeDetailsDao).removeDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID); + verify(volumeDetailsDao).addDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID, "qos-uuid", false); + } + + @Test + void applyQosPolicy_attachesPolicyToFile_forNfsVolume() throws Exception { + givenNfsPool(); + when(volumeInfo.getMinIops()).thenReturn(0L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + when(nasStrategy.createVolumeQosPolicy("cs_0_to_500_iops_svm1", 0L, 500L)).thenReturn(qosPolicy()); + + withStrategy(nasStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo)); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).updateCloudStackVolume(request.capture()); + assertEquals("qos-uuid", request.getValue().getFile().getQosPolicy().getUuid()); + assertEquals("flexvol-uuid", request.getValue().getFlexVolumeUuid()); + } + + @Test + void applyQosPolicy_usesStoredVolumeIops_whenInfoReportsNone() throws Exception { + when(volumeInfo.getMinIops()).thenReturn(null); + when(volumeInfo.getMaxIops()).thenReturn(null); + VolumeVO stored = mock(VolumeVO.class); + when(stored.getMinIops()).thenReturn(100L); + when(stored.getMaxIops()).thenReturn(500L); + when(volumeDao.findById(VOLUME_ID, true)).thenReturn(stored); + when(sanStrategy.createVolumeQosPolicy("cs_100_to_500_iops_svm1", 100L, 500L)).thenReturn(qosPolicy()); + + withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo)); + + verify(sanStrategy).updateCloudStackVolume(any(CloudStackVolume.class)); + } + + @Test + void applyQosPolicy_leavesQosUntouched_whenNoIopsAnywhere() throws Exception { + when(volumeInfo.getMinIops()).thenReturn(null); + when(volumeInfo.getMaxIops()).thenReturn(null); + when(volumeDao.findById(VOLUME_ID, true)).thenReturn(null); + + withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo)); + + verify(sanStrategy, never()).createVolumeQosPolicy(anyString(), anyLong(), anyLong()); + verify(sanStrategy, never()).updateCloudStackVolume(any(CloudStackVolume.class)); + } + + @Test + void applyQosPolicy_leavesQosUntouched_whenStoredVolumeAlsoHasNoIops() throws Exception { + when(volumeInfo.getMinIops()).thenReturn(0L); + when(volumeInfo.getMaxIops()).thenReturn(0L); + VolumeVO stored = mock(VolumeVO.class); + when(volumeDao.findById(VOLUME_ID, true)).thenReturn(stored); + + withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo)); + + verify(sanStrategy, never()).updateCloudStackVolume(any(CloudStackVolume.class)); + } + + @Test + void applyQosPolicy_throws_whenMinIopsExceedsMaxIops() throws Exception { + when(volumeInfo.getMinIops()).thenReturn(900L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo))); + + assertTrue(ex.getMessage().contains("Minimum IOPS cannot be greater than maximum IOPS"), ex.getMessage()); + verify(sanStrategy, never()).updateCloudStackVolume(any(CloudStackVolume.class)); + } + + @Test + void applyQosPolicy_throws_whenMinIopsRequestedOnFasSystem() throws Exception { + poolDetails.put(OntapStorageConstants.IS_AFF, "false"); + when(volumeInfo.getMinIops()).thenReturn(100L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo))); + + assertEquals(OntapStorageConstants.MIN_IOPS_NOT_SUPPORTED_ON_FAS, ex.getMessage()); + } + + @Test + void applyQosPolicy_detectsAndStoresAffFlag_whenPoolDetailMissing() throws Exception { + poolDetails.remove(OntapStorageConstants.IS_AFF); + when(volumeInfo.getMinIops()).thenReturn(100L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + when(sanStrategy.isAff()).thenReturn(true); + when(sanStrategy.createVolumeQosPolicy(anyString(), anyLong(), anyLong())).thenReturn(qosPolicy()); + + withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo)); + + verify(storagePoolDetailsDao).addDetail(POOL_ID, OntapStorageConstants.IS_AFF, "true", false); + verify(sanStrategy).updateCloudStackVolume(any(CloudStackVolume.class)); + } + + @Test + void applyQosPolicy_rejectsMinIops_whenDetectedSystemIsFas() throws Exception { + poolDetails.remove(OntapStorageConstants.IS_AFF); + when(volumeInfo.getMinIops()).thenReturn(100L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + when(sanStrategy.isAff()).thenReturn(false); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo))); + + assertEquals(OntapStorageConstants.MIN_IOPS_NOT_SUPPORTED_ON_FAS, ex.getMessage()); + verify(sanStrategy).isAff(); + verify(storagePoolDetailsDao).addDetail(POOL_ID, OntapStorageConstants.IS_AFF, "false", false); + verify(sanStrategy, never()).createVolumeQosPolicy(any(), any(), any()); + verify(sanStrategy, never()).updateCloudStackVolume(any()); + } + + @Test + void applyQosPolicy_proceeds_whenAffDetectionFails() throws Exception { + poolDetails.remove(OntapStorageConstants.IS_AFF); + when(volumeInfo.getMinIops()).thenReturn(100L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + when(sanStrategy.isAff()).thenThrow(new RuntimeException("cluster unreachable")); + when(sanStrategy.createVolumeQosPolicy(anyString(), anyLong(), anyLong())).thenReturn(qosPolicy()); + + withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo)); + + verify(sanStrategy).updateCloudStackVolume(any(CloudStackVolume.class)); + verify(storagePoolDetailsDao, never()).addDetail(anyLong(), eq(OntapStorageConstants.IS_AFF), anyString(), anyBoolean()); + } + + @Test + void applyQosPolicy_sanitizesSvmNameDotsInPolicyName() throws Exception { + poolDetails.put(OntapStorageConstants.SVM_NAME, "svm.with.dots"); + when(volumeInfo.getMinIops()).thenReturn(100L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + when(sanStrategy.createVolumeQosPolicy("cs_100_to_500_iops_svm_with_dots", 100L, 500L)).thenReturn(qosPolicy()); + + withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo)); + + verify(sanStrategy).createVolumeQosPolicy("cs_100_to_500_iops_svm_with_dots", 100L, 500L); + } + + @Test + void applyQosPolicy_rejectsVolumeName_thatIsNotValidForOntap() throws Exception { + when(volumeInfo.getName()).thenReturn("1-starts-with-digit"); + when(volumeInfo.getMinIops()).thenReturn(100L); + when(volumeInfo.getMaxIops()).thenReturn(500L); + when(sanStrategy.createVolumeQosPolicy(anyString(), anyLong(), anyLong())).thenReturn(qosPolicy()); + + InvalidParameterValueException ex = assertThrows(InvalidParameterValueException.class, + () -> withStrategy(sanStrategy, () -> driver.applyQosPolicyToVolume(volumeInfo))); + + assertTrue(ex.getMessage().contains("Invalid dataObject name [1_starts_with_digit]"), ex.getMessage()); + verify(sanStrategy, never()).updateCloudStackVolume(any()); + } + + // ----------------------------------- deleteAsync: volume failure handling + + private CommandResult deleteVolume(StorageStrategy strategy) { + withStrategy(strategy, () -> driver.deleteAsync(dataStore, volumeInfo, commandCallback)); + ArgumentCaptor captor = ArgumentCaptor.forClass(CommandResult.class); + verify(commandCallback).complete(captor.capture()); + return captor.getValue(); + } + + @Test + void deleteAsync_reportsFailure_whenPoolNotFoundForVolume() throws Exception { + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + + CommandResult result = deleteVolume(sanStrategy); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("Storage Pool not found"), result.getResult()); + } + + @Test + void deleteAsync_reportsFailure_forUnsupportedDataObjectType() throws Exception { + DataObject archive = mock(DataObject.class); + when(archive.getType()).thenReturn(DataObjectType.ARCHIVE); + + withStrategy(sanStrategy, () -> driver.deleteAsync(dataStore, archive, commandCallback)); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CommandResult.class); + verify(commandCallback).complete(captor.capture()); + assertFalse(captor.getValue().isSuccess()); + assertTrue(captor.getValue().getResult().contains("Unsupported data object type")); + } + + @Test + void deleteAsync_continuesDelete_whenClearingNfsQosPolicyFails() throws Exception { + givenNfsPool(); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID, "qos-uuid", false)); + doThrow(new RuntimeException("qos update rejected")).when(nasStrategy).updateCloudStackVolume(nfsQosUpdate("none", null)); + + CommandResult result = deleteVolume(nasStrategy); + + assertTrue(result.isSuccess()); + verify(nasStrategy).updateCloudStackVolume(nfsQosUpdate("none", null)); + verify(nasStrategy).deleteCloudStackVolume(nfsDeleteRequest()); + verify(nasStrategy).deleteVolumeQosPolicy("qos-uuid"); + } + + @Test + void deleteAsync_restoresNfsQosPolicy_whenDeleteFailsAfterPolicyWasCleared() throws Exception { + givenNfsPool(); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID, "qos-uuid", false)); + doThrow(new CloudRuntimeException("file busy")).when(nasStrategy).deleteCloudStackVolume(nfsDeleteRequest()); + + CommandResult result = deleteVolume(nasStrategy); + + assertFalse(result.isSuccess()); + assertEquals("file busy", result.getResult()); + ArgumentCaptor updates = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy, times(2)).updateCloudStackVolume(updates.capture()); + assertEquals("none", updates.getAllValues().get(0).getFile().getQosPolicy().getName()); + assertEquals(volumeInfo, updates.getAllValues().get(0).getVolumeInfo()); + assertEquals("qos-uuid", updates.getAllValues().get(1).getFile().getQosPolicy().getUuid()); + assertEquals(volumeInfo, updates.getAllValues().get(1).getVolumeInfo()); + verify(nasStrategy).deleteCloudStackVolume(nfsDeleteRequest()); + verify(nasStrategy, never()).deleteVolumeQosPolicy(anyString()); + } + + @Test + void deleteAsync_stillReportsDeleteFailure_whenRestoringNfsQosPolicyAlsoFails() throws Exception { + givenNfsPool(); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID, "qos-uuid", false)); + doThrow(new CloudRuntimeException("file busy")).when(nasStrategy).deleteCloudStackVolume(nfsDeleteRequest()); + doReturn(null).doThrow(new RuntimeException("restore failed")) + .when(nasStrategy).updateCloudStackVolume(any(CloudStackVolume.class)); + + CommandResult result = deleteVolume(nasStrategy); + + assertFalse(result.isSuccess()); + assertEquals("file busy", result.getResult()); + ArgumentCaptor updates = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy, times(2)).updateCloudStackVolume(updates.capture()); + assertEquals("none", updates.getAllValues().get(0).getFile().getQosPolicy().getName()); + assertEquals("qos-uuid", updates.getAllValues().get(1).getFile().getQosPolicy().getUuid()); + verify(nasStrategy).deleteCloudStackVolume(nfsDeleteRequest()); + } + + @Test + void deleteAsync_ignoresFailure_whenDeletingUnusedQosPolicyFails() throws Exception { + givenNfsPool(); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID, "qos-uuid", false)); + doThrow(new RuntimeException("policy in use")).when(nasStrategy).deleteVolumeQosPolicy("qos-uuid"); + + CommandResult result = deleteVolume(nasStrategy); + + assertTrue(result.isSuccess()); + verify(nasStrategy).updateCloudStackVolume(nfsQosUpdate("none", null)); + verify(nasStrategy).deleteCloudStackVolume(nfsDeleteRequest()); + verify(nasStrategy).deleteVolumeQosPolicy("qos-uuid"); + } + + @Test + void deleteAsync_skipsQosHandling_whenNfsVolumeHasNoQosPolicy() throws Exception { + givenNfsPool(); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID)).thenReturn(null); + + CommandResult result = deleteVolume(nasStrategy); + + assertTrue(result.isSuccess()); + verify(nasStrategy).deleteCloudStackVolume(nfsDeleteRequest()); + verify(nasStrategy, never()).updateCloudStackVolume(any(CloudStackVolume.class)); + verify(nasStrategy, never()).deleteVolumeQosPolicy(anyString()); + } + + // ------------------------------------------- temporary snapshot copy path sync + + /** + * {@code getPath} and {@code get_iScsiName} return whatever this test last stored, so a later + * read sees the path grantAccess computed rather than a value stubbed in advance. + */ + private void rememberPathWrites(VolumeVO volume) { + AtomicReference path = new AtomicReference<>(); + AtomicReference iscsiName = new AtomicReference<>(); + doAnswer(invocation -> { + path.set(invocation.getArgument(0)); + return null; + }).when(volume).setPath(anyString()); + doAnswer(invocation -> { + iscsiName.set(invocation.getArgument(0)); + return null; + }).when(volume).set_iScsiName(anyString()); + when(volume.getPath()).thenAnswer(invocation -> path.get()); + when(volume.get_iScsiName()).thenAnswer(invocation -> iscsiName.get()); + } + + /** Path the KVM agent is given: {@code //}. */ + private String computedIscsiPath() { + return "/" + TARGET_IQN + "/" + WWID; + } + + @Test + void grantAccess_syncsLunPathToCallerVolume_forTemporarySnapshotCopy() throws Exception { + givenIscsiVolume(); + rememberPathWrites(volumeVO); + VolumeVO callerVolume = mock(VolumeVO.class); + when(volumeInfo.getVolume()).thenReturn(callerVolume); + when(volumeVO.getState()).thenReturn(Volume.State.Allocated); + when(volumeVO.getDiskOfferingId()).thenReturn(null); + String iscsiPath = computedIscsiPath(); + + assertTrue(withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + assertEquals(iscsiPath, volumeVO.getPath()); + assertEquals(iscsiPath, volumeVO.get_iScsiName()); + verify(volumeVO).setPath(iscsiPath); + verify(volumeVO).set_iScsiName(iscsiPath); + // The mapping writes the path on the volume row. grantAccess copies it onto the caller's + // volume, and a temporary snapshot copy copies that same computed path a second time. + verify(callerVolume, times(2)).setPath(iscsiPath); + verify(callerVolume, times(2)).set_iScsiName(iscsiPath); + } + + @Test + void grantAccess_doesNotResyncPath_forRegularVolume() throws Exception { + givenIscsiVolume(); + rememberPathWrites(volumeVO); + VolumeVO callerVolume = mock(VolumeVO.class); + when(volumeInfo.getVolume()).thenReturn(callerVolume); + when(volumeVO.getState()).thenReturn(Volume.State.Allocated); + when(volumeVO.getDiskOfferingId()).thenReturn(15L); + String iscsiPath = computedIscsiPath(); + + assertTrue(withStrategy(sanStrategy, () -> driver.grantAccess(volumeInfo, host, dataStore))); + + assertEquals(iscsiPath, volumeVO.getPath()); + assertEquals(iscsiPath, volumeVO.get_iScsiName()); + verify(callerVolume, times(1)).setPath(iscsiPath); + verify(callerVolume, times(1)).set_iScsiName(iscsiPath); + } + } + + /** + * Offline iSCSI volume copy between ONTAP pools and snapshot-to-temporary-volume detection in + * {@link OntapPrimaryDatastoreDriver}: which object pairs the driver accepts, and how a copy + * persists its result or cleans up after a failure. + */ + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + @Nested + class OntapPrimaryDatastoreDriverCopyTest { + + private static final long SRC_POOL_ID = 1L; + private static final long DEST_POOL_ID = 2L; + private static final long SRC_VOLUME_ID = 10L; + private static final long DEST_VOLUME_ID = 20L; + + @Mock private StoragePoolDetailsDao storagePoolDetailsDao; + @Mock private PrimaryDataStoreDao storagePoolDao; + @Mock private VolumeDao volumeDao; + @Mock private VolumeDetailsDao volumeDetailsDao; + @Mock private StorageStrategy strategy; + @Mock private AsyncCompletionCallback callback; + + @InjectMocks + private OntapPrimaryDatastoreDriver driver; + + private OntapPrimaryDatastoreDriver spied; + private VolumeInfo src; + private VolumeInfo dest; + private StoragePoolVO srcPool; + private StoragePoolVO destPool; + private VolumeVO destVolumeVO; + private Map srcDetails; + private Map destDetails; + + @BeforeEach + void setUp() { + srcDetails = iscsiDetails("10.0.0.1", "svm-uuid-1", "svm1"); + destDetails = iscsiDetails("10.0.0.1", "svm-uuid-1", "svm1"); + + srcPool = pool(SRC_POOL_ID); + destPool = pool(DEST_POOL_ID); + when(storagePoolDao.findById(SRC_POOL_ID)).thenReturn(srcPool); + when(storagePoolDao.findById(DEST_POOL_ID)).thenReturn(destPool); + when(storagePoolDetailsDao.listDetailsKeyPairs(SRC_POOL_ID)).thenReturn(srcDetails); + when(storagePoolDetailsDao.listDetailsKeyPairs(DEST_POOL_ID)).thenReturn(destDetails); + + src = volume(SRC_VOLUME_ID, SRC_POOL_ID); + when(src.getState()).thenReturn(Volume.State.Migrating); + when(src.getHypervisorType()).thenReturn(HypervisorType.KVM); + dest = volume(DEST_VOLUME_ID, DEST_POOL_ID); + + destVolumeVO = mock(VolumeVO.class); + when(destVolumeVO.getId()).thenReturn(DEST_VOLUME_ID); + when(destVolumeVO.getPath()).thenReturn("old-path"); + when(volumeDao.findById(DEST_VOLUME_ID)).thenReturn(destVolumeVO); + + spied = spy(driver); + } + + // ---------------------------------------------------------------- fixtures + + private Map iscsiDetails(String ip, String svmUuid, String svmName) { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.PROTOCOL, "ISCSI"); + details.put(OntapStorageConstants.STORAGE_IP, ip); + if (svmUuid != null) { + details.put(OntapStorageConstants.SVM_UUID, svmUuid); + } + if (svmName != null) { + details.put(OntapStorageConstants.SVM_NAME, svmName); + } + return details; + } + + private StoragePoolVO pool(long id) { + StoragePoolVO pool = mock(StoragePoolVO.class); + when(pool.getId()).thenReturn(id); + when(pool.getName()).thenReturn("pool-" + id); + when(pool.getStorageProviderName()).thenReturn("NetApp ONTAP"); + when(pool.getPoolType()).thenReturn(Storage.StoragePoolType.OntapiSCSI); + when(pool.getHypervisor()).thenReturn(HypervisorType.KVM); + return pool; + } + + private VolumeInfo volume(long id, long poolId) { + VolumeInfo volume = mock(VolumeInfo.class); + DataStore store = mock(DataStore.class); + when(store.getId()).thenReturn(poolId); + when(store.getRole()).thenReturn(DataStoreRole.Primary); + when(volume.getId()).thenReturn(id); + when(volume.getPoolId()).thenReturn(poolId); + when(volume.getDataStore()).thenReturn(store); + when(volume.getType()).thenReturn(DataObjectType.VOLUME); + when(volume.getTO()).thenReturn(new VolumeObjectTO()); + return volume; + } + + private Lun lun(String name, String uuid) { + Lun lun = new Lun(); + lun.setName(name); + lun.setUuid(uuid); + return lun; + } + + private CloudStackVolume copiedLun() { + CloudStackVolume copied = new CloudStackVolume(); + copied.setLun(lun("/vol/dest/copied", "copied-uuid")); + return copied; + } + + private void whenCopied(CloudStackVolume copied) { + when(strategy.copyCloudStackVolume(eq(src), eq(dest), eq(destPool), eq(destDetails), anyInt())).thenReturn(copied); + } + + private void copy(DataObject source, DataObject destination, AsyncCompletionCallback cb) { + try (MockedStatic utils = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(strategy); + spied.copyAsync(source, destination, null, cb); + } + } + + private CopyCommandResult copyAndCaptureResult() { + doNothing().when(spied).applyQosPolicyToVolume(any(VolumeInfo.class)); + copy(src, dest, callback); + ArgumentCaptor captor = ArgumentCaptor.forClass(CopyCommandResult.class); + verify(callback).complete(captor.capture()); + return captor.getValue(); + } + + // ---------------------------------------------------------------- canCopy: compatible iSCSI pools + + @Test + void canCopyAcceptsMigratingKvmVolumeBetweenCompatibleIscsiPools() { + assertTrue(driver.canCopy(src, dest)); + } + + @Test + void canCopyRejectsMissingObjectsOrDataStores() { + assertFalse(driver.canCopy(null, dest)); + assertFalse(driver.canCopy(src, null)); + + VolumeInfo noStore = mock(VolumeInfo.class); + when(noStore.getDataStore()).thenReturn(null); + assertFalse(driver.canCopy(noStore, dest)); + assertFalse(driver.canCopy(src, noStore)); + } + + @Test + void canCopyRejectsObjectsThatAreNotVolumes() { + DataObject template = mock(DataObject.class); + DataStore store = mock(DataStore.class); + when(template.getDataStore()).thenReturn(store); + when(template.getType()).thenReturn(DataObjectType.TEMPLATE); + + assertFalse(driver.canCopy(template, dest)); + assertFalse(driver.canCopy(src, template)); + } + + @Test + void canCopyRejectsVolumeThatIsNotMigratingOrNotKvm() { + when(src.getState()).thenReturn(Volume.State.Ready); + assertFalse(driver.canCopy(src, dest)); + + when(src.getState()).thenReturn(Volume.State.Migrating); + when(src.getHypervisorType()).thenReturn(HypervisorType.VMware); + assertFalse(driver.canCopy(src, dest)); + } + + @Test + void canCopyRejectsUnknownSamePoolNonOntapOrNonIscsiPools() { + when(storagePoolDao.findById(SRC_POOL_ID)).thenReturn(null); + assertFalse(driver.canCopy(src, dest)); + when(storagePoolDao.findById(SRC_POOL_ID)).thenReturn(srcPool); + + when(storagePoolDao.findById(DEST_POOL_ID)).thenReturn(null); + assertFalse(driver.canCopy(src, dest)); + when(storagePoolDao.findById(DEST_POOL_ID)).thenReturn(destPool); + + when(dest.getPoolId()).thenReturn(SRC_POOL_ID); + assertFalse(driver.canCopy(src, dest)); + when(dest.getPoolId()).thenReturn(DEST_POOL_ID); + + when(srcPool.getStorageProviderName()).thenReturn("DefaultPrimary"); + assertFalse(driver.canCopy(src, dest)); + when(srcPool.getStorageProviderName()).thenReturn("NetApp ONTAP"); + + when(destPool.getStorageProviderName()).thenReturn("DefaultPrimary"); + assertFalse(driver.canCopy(src, dest)); + when(destPool.getStorageProviderName()).thenReturn("NetApp ONTAP"); + + when(srcPool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + assertFalse(driver.canCopy(src, dest)); + when(srcPool.getPoolType()).thenReturn(Storage.StoragePoolType.OntapiSCSI); + + when(destPool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + assertFalse(driver.canCopy(src, dest)); + } + + private boolean canCopyWithDetails(Consumer> srcChange, Consumer> destChange) { + srcChange.accept(srcDetails); + destChange.accept(destDetails); + return driver.canCopy(src, dest); + } + + @Test + void canCopyRequiresSameClusterAndSameSvmIdentity() { + // identical SVM UUID wins even when names differ + assertTrue(canCopyWithDetails(d -> d.put(OntapStorageConstants.SVM_NAME, "a"), d -> d.put(OntapStorageConstants.SVM_NAME, "b"))); + // different storage IP + assertFalse(canCopyWithDetails(d -> { }, d -> d.put(OntapStorageConstants.STORAGE_IP, "10.0.0.2"))); + assertFalse(canCopyWithDetails(d -> d.remove(OntapStorageConstants.STORAGE_IP), d -> { })); + // UUID present on only one side, or different on both + assertFalse(canCopyWithDetails(d -> { }, d -> d.remove(OntapStorageConstants.SVM_UUID))); + assertFalse(canCopyWithDetails(d -> d.remove(OntapStorageConstants.SVM_UUID), d -> d.put(OntapStorageConstants.SVM_UUID, "uuid-2"))); + assertFalse(canCopyWithDetails(d -> d.put(OntapStorageConstants.SVM_UUID, "uuid-3"), d -> { })); + } + + @Test + void canCopyFallsBackToSvmNamesWhenNoUuidsAreKnown() { + srcDetails.remove(OntapStorageConstants.SVM_UUID); + destDetails.remove(OntapStorageConstants.SVM_UUID); + assertTrue(driver.canCopy(src, dest)); + + destDetails.put(OntapStorageConstants.SVM_NAME, "other-svm"); + assertFalse(driver.canCopy(src, dest)); + + destDetails.put(OntapStorageConstants.SVM_NAME, "svm1"); + srcDetails.remove(OntapStorageConstants.SVM_NAME); + assertFalse(driver.canCopy(src, dest)); + + srcDetails.put(OntapStorageConstants.SVM_NAME, " "); + destDetails.put(OntapStorageConstants.SVM_NAME, " "); + assertFalse(driver.canCopy(src, dest)); + } + + @Test + void canCopyRequiresIscsiProtocolOnBothPoolsAndReadableDetails() { + srcDetails.put(OntapStorageConstants.PROTOCOL, "NFS3"); + assertFalse(driver.canCopy(src, dest)); + srcDetails.put(OntapStorageConstants.PROTOCOL, "iscsi"); + assertTrue(driver.canCopy(src, dest)); + + destDetails.put(OntapStorageConstants.PROTOCOL, "NFS3"); + assertFalse(driver.canCopy(src, dest)); + destDetails.put(OntapStorageConstants.PROTOCOL, "ISCSI"); + + when(storagePoolDetailsDao.listDetailsKeyPairs(SRC_POOL_ID)).thenReturn(null); + assertFalse(driver.canCopy(src, dest)); + when(storagePoolDetailsDao.listDetailsKeyPairs(SRC_POOL_ID)).thenReturn(srcDetails); + + when(storagePoolDetailsDao.listDetailsKeyPairs(DEST_POOL_ID)).thenReturn(null); + assertFalse(driver.canCopy(src, dest)); + } + + // ---------------------------------------------------------------- canCopy: snapshot to temporary volume + + private DataObject snapshot(long storePoolId, DataStoreRole role) { + DataObject snapshot = mock(DataObject.class); + DataStore store = mock(DataStore.class); + when(store.getId()).thenReturn(storePoolId); + when(store.getRole()).thenReturn(role); + when(snapshot.getDataStore()).thenReturn(store); + when(snapshot.getType()).thenReturn(DataObjectType.SNAPSHOT); + when(snapshot.getId()).thenReturn(77L); + return snapshot; + } + + private VolumeVO temporaryVolumeRow(Volume.State state, Long diskOfferingId) { + VolumeVO row = mock(VolumeVO.class); + when(row.getState()).thenReturn(state); + when(row.getDiskOfferingId()).thenReturn(diskOfferingId); + return row; + } + + private void stubTemporaryVolumeRow(Volume.State state, Long diskOfferingId) { + VolumeVO row = temporaryVolumeRow(state, diskOfferingId); + when(volumeDao.findById(DEST_VOLUME_ID)).thenReturn(row); + } + + @Test + void canCopyAcceptsSnapshotCopiedToTemporaryVolumeOnTheSameStore() { + DataObject snapshot = snapshot(DEST_POOL_ID, DataStoreRole.Primary); + + stubTemporaryVolumeRow(Volume.State.Allocated, null); + assertTrue(driver.canCopy(snapshot, dest)); + + stubTemporaryVolumeRow(Volume.State.Allocated, 0L); + assertTrue(driver.canCopy(snapshot, dest)); + } + + @Test + void canCopyRejectsSnapshotCopiesThatDoNotTargetATemporaryVolume() { + DataObject snapshot = snapshot(DEST_POOL_ID, DataStoreRole.Primary); + + when(volumeDao.findById(DEST_VOLUME_ID)).thenReturn(null); + assertFalse(driver.canCopy(snapshot, dest)); + + stubTemporaryVolumeRow(Volume.State.Ready, null); + assertFalse(driver.canCopy(snapshot, dest)); + + stubTemporaryVolumeRow(Volume.State.Allocated, 15L); + assertFalse(driver.canCopy(snapshot, dest)); + + stubTemporaryVolumeRow(Volume.State.Allocated, null); + assertFalse(driver.canCopy(snapshot(DEST_POOL_ID, DataStoreRole.Image), dest)); + assertFalse(driver.canCopy(snapshot(SRC_POOL_ID, DataStoreRole.Primary), dest)); + + DataObject notSnapshot = snapshot(DEST_POOL_ID, DataStoreRole.Primary); + when(notSnapshot.getType()).thenReturn(DataObjectType.TEMPLATE); + assertFalse(driver.canCopy(notSnapshot, dest)); + + DataObject destNotVolume = mock(DataObject.class); + when(destNotVolume.getDataStore()).thenReturn(mock(DataStore.class)); + when(destNotVolume.getType()).thenReturn(DataObjectType.SNAPSHOT); + assertFalse(driver.canCopy(snapshot, destNotVolume)); + } + + @Test + void snapshotCopyFailureIsThrownWhenNoCallbackAndReportedWhenCallbackGiven() { + DataObject snapshot = snapshot(DEST_POOL_ID, DataStoreRole.Primary); + stubTemporaryVolumeRow(Volume.State.Allocated, null); + when(storagePoolDao.findById(DEST_POOL_ID)).thenReturn(null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> spied.copyAsync(snapshot, dest, null, null)); + assertTrue(thrown.getMessage().contains("Failed to copy"), thrown.getMessage()); + + spied.copyAsync(snapshot, dest, null, callback); + ArgumentCaptor captor = ArgumentCaptor.forClass(CopyCommandResult.class); + verify(callback).complete(captor.capture()); + assertFalse(captor.getValue().isSuccess()); + assertTrue(captor.getValue().getResult().contains("Storage Pool not found"), captor.getValue().getResult()); + } + + // ---------------------------------------------------------------- copyAsync + + @Test + void copyAsyncRejectsPairsTheDriverDoesNotHandle() { + when(src.getState()).thenReturn(Volume.State.Ready); + + UnsupportedOperationException thrown = assertThrows(UnsupportedOperationException.class, + () -> spied.copyAsync(src, dest, null, callback)); + assertTrue(thrown.getMessage().contains("VOLUME [10]"), thrown.getMessage()); + + UnsupportedOperationException nullDest = assertThrows(UnsupportedOperationException.class, + () -> spied.copyAsync(src, null, null, callback)); + assertTrue(nullDest.getMessage().contains("null"), nullDest.getMessage()); + verify(callback, never()).complete(any()); + } + + @Test + void copyAsyncPersistsCopiedLunAndReportsSuccess() { + whenCopied(copiedLun()); + + CopyCommandResult result = copyAndCaptureResult(); + + assertTrue(result.isSuccess()); + VolumeObjectTO copiedTO = (VolumeObjectTO) ((CopyCmdAnswer) result.getAnswer()).getNewData(); + assertEquals("/vol/dest/copied", copiedTO.getPath()); + assertEquals(Storage.ImageFormat.RAW, copiedTO.getFormat()); + verify(destVolumeVO).setPoolId(DEST_POOL_ID); + verify(destVolumeVO).setPoolType(Storage.StoragePoolType.OntapiSCSI); + verify(destVolumeVO).setFormat(Storage.ImageFormat.RAW); + verify(destVolumeVO).setFolder("copied-uuid"); + verify(destVolumeVO).set_iScsiName(null); + verify(destVolumeVO).setPath("/vol/dest/copied"); + verify(volumeDetailsDao).addDetail(DEST_VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID, "copied-uuid", false); + verify(volumeDetailsDao).addDetail(DEST_VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME, "/vol/dest/copied", false); + verify(volumeDao).update(DEST_VOLUME_ID, destVolumeVO); + verify(spied).applyQosPolicyToVolume(dest); + } + + @Test + void copyAsyncWorksWithoutCallback() { + whenCopied(copiedLun()); + doNothing().when(spied).applyQosPolicyToVolume(any(VolumeInfo.class)); + + copy(src, dest, null); + + verify(volumeDao).update(DEST_VOLUME_ID, destVolumeVO); + } + + @Test + void copyAsyncUsesFilePathWhenCopyResultIsAFile() { + CloudStackVolume copied = new CloudStackVolume(); + FileInfo file = new FileInfo(); + file.setPath("dir/file.qcow2"); + copied.setFile(file); + whenCopied(copied); + + copyAndCaptureResult(); + + verify(destVolumeVO).setPath("dir/file.qcow2"); + verify(volumeDetailsDao, never()).addDetail(anyLong(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean()); + } + + @Test + void copyAsyncKeepsExistingPathWhenCopyResultCarriesNoLunOrFilePath() { + CloudStackVolume copied = new CloudStackVolume(); + copied.setFile(new FileInfo()); + whenCopied(copied); + + copyAndCaptureResult(); + + verify(destVolumeVO).setPath("old-path"); + } + + @Test + void copyAsyncReportsFailureWithoutCleanupWhenStorageCopyFails() { + when(strategy.copyCloudStackVolume(eq(src), eq(dest), eq(destPool), eq(destDetails), anyInt())) + .thenThrow(new CloudRuntimeException("copy refused")); + + CopyCommandResult result = copyAndCaptureResult(); + + assertFalse(result.isSuccess()); + assertEquals("copy refused", result.getResult()); + verify(strategy).copyCloudStackVolume(eq(src), eq(dest), eq(destPool), eq(destDetails), anyInt()); + verify(strategy, never()).deleteCloudStackVolume(any(CloudStackVolume.class)); + verify(volumeDao, never()).update(anyLong(), any(VolumeVO.class)); + } + + @Test + void copyAsyncRemovesCopiedLunWhenDestinationVolumeRecordIsMissing() { + CloudStackVolume copied = copiedLun(); + whenCopied(copied); + when(volumeDao.findById(DEST_VOLUME_ID)).thenReturn(null); + + CopyCommandResult result = copyAndCaptureResult(); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("was not found"), result.getResult()); + verify(strategy).deleteCloudStackVolume(copied); + } + + @Test + void copyAsyncStillReportsOriginalFailureWhenCleanupAlsoFails() { + CloudStackVolume copied = copiedLun(); + whenCopied(copied); + when(volumeDao.findById(DEST_VOLUME_ID)).thenReturn(null); + doThrow(new CloudRuntimeException("cleanup failed")).when(strategy).deleteCloudStackVolume(copied); + + CopyCommandResult result = copyAndCaptureResult(); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("was not found"), result.getResult()); + verify(strategy).deleteCloudStackVolume(copied); + } + + @Test + void copyAsyncFailsForUnsupportedHypervisorOfDestinationPool() { + CloudStackVolume copied = copiedLun(); + whenCopied(copied); + when(destPool.getHypervisor()).thenReturn(HypervisorType.VMware); + + CopyCommandResult result = copyAndCaptureResult(); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("Unsupported hypervisor"), result.getResult()); + verify(strategy).deleteCloudStackVolume(copied); + } + + // ---------------------------------------------------------------- QoS carried over from the source volume + + private void srcHasIops(Long min, Long max) { + when(src.getMinIops()).thenReturn(min); + when(src.getMaxIops()).thenReturn(max); + } + + @Test + void copyAsyncCopiesSourceIopsToDestinationRowWhenDestinationHasNone() { + whenCopied(copiedLun()); + srcHasIops(100L, 200L); + + copyAndCaptureResult(); + + verify(destVolumeVO).setMinIops(100L); + verify(destVolumeVO).setMaxIops(200L); + verify(volumeDao, org.mockito.Mockito.atLeastOnce()).update(DEST_VOLUME_ID, destVolumeVO); + } + + @Test + void copyAsyncKeepsDestinationIopsWhenAlreadySet() { + whenCopied(copiedLun()); + srcHasIops(100L, 200L); + when(dest.getMaxIops()).thenReturn(500L); + + copyAndCaptureResult(); + + verify(destVolumeVO, never()).setMinIops(any()); + verify(destVolumeVO, never()).setMaxIops(any()); + } + + @Test + void copyAsyncKeepsDestinationRowIopsWhenRowAlreadyHasThem() { + whenCopied(copiedLun()); + srcHasIops(100L, 200L); + when(destVolumeVO.getMinIops()).thenReturn(50L); + + copyAndCaptureResult(); + + verify(destVolumeVO, never()).setMinIops(any()); + } + + @Test + void copyAsyncLeavesDestinationWithoutIopsWhenSourceHasNone() { + whenCopied(copiedLun()); + srcHasIops(null, 0L); + + copyAndCaptureResult(); + + verify(destVolumeVO, never()).setMinIops(any()); + verify(destVolumeVO, never()).setMaxIops(any()); + } + + // ---------------------------------------------------------------- applyQosPolicyToVolume early exits + + private void applyQos(VolumeInfo volume) { + try (MockedStatic utils = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(strategy); + driver.applyQosPolicyToVolume(volume); + } + } + + @Test + void applyQosPolicyDoesNothingForNullVolumeMissingPoolOrNonDiskVolume() { + applyQos(null); + + when(storagePoolDao.findById(DEST_POOL_ID)).thenReturn(null); + applyQos(dest); + when(storagePoolDao.findById(DEST_POOL_ID)).thenReturn(destPool); + + when(dest.getVolumeType()).thenReturn(Volume.Type.ISO); + applyQos(dest); + + verify(strategy, never()).updateCloudStackVolume(any()); + } + + @Test + void applyQosPolicyKeepsCurrentQosWhenNeitherVolumeNorStoredRowHasIops() { + when(dest.getVolumeType()).thenReturn(Volume.Type.ROOT); + VolumeVO stored = mock(VolumeVO.class); + when(volumeDao.findById(DEST_VOLUME_ID, true)).thenReturn(stored); + + applyQos(dest); + + verify(strategy, never()).updateCloudStackVolume(any()); + verify(volumeDetailsDao, never()).addDetail(anyLong(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean()); + + when(volumeDao.findById(DEST_VOLUME_ID, true)).thenReturn(null); + applyQos(dest); + verify(strategy, never()).updateCloudStackVolume(any()); + } + + @Test + void snapshotCopyFailsBeforeCallingOntapWhenPoolProtocolIsUnsupported() { + DataObject snapshot = snapshot(DEST_POOL_ID, DataStoreRole.Primary); + stubTemporaryVolumeRow(Volume.State.Allocated, null); + destDetails.put(OntapStorageConstants.PROTOCOL, "FC"); + + spied.copyAsync(snapshot, dest, null, callback); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CopyCommandResult.class); + verify(callback).complete(captor.capture()); + assertFalse(captor.getValue().isSuccess()); + assertTrue(captor.getValue().getResult().contains("Unsupported protocol [FC]"), captor.getValue().getResult()); + verify(strategy, never()).cloneCloudStackVolume(any()); + } + } + + /** + * Checks the exact content of what {@link OntapPrimaryDatastoreDriver} sends to the ONTAP storage + * strategy (LUN and file requests, clone sources, QoS references), what it records on the volume + * and template rows, and the success flag and message it reports on delete. + */ + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + @Nested + class OntapPrimaryDatastoreDriverRequestContentTest { + + private static final long POOL_ID = 5L; + private static final long VOLUME_ID = 10L; + private static final long TEMPLATE_ID = 31L; + private static final long SNAPSHOT_ID = 77L; + private static final long ONE_GB = 1073741824L; + + @Mock private StoragePoolDetailsDao storagePoolDetailsDao; + @Mock private PrimaryDataStoreDao storagePoolDao; + @Mock private VolumeDao volumeDao; + @Mock private VolumeDetailsDao volumeDetailsDao; + @Mock private SnapshotDetailsDao snapshotDetailsDao; + @Mock private SnapshotDao snapshotDao; + @Mock private VMTemplatePoolDao vmTemplatePoolDao; + @Mock private StorageManager storageManager; + @Mock private DataStore dataStore; + @Mock private StoragePoolVO storagePool; + @Mock private VolumeVO volumeVO; + @Mock private VolumeInfo volumeInfo; + @Mock private TemplateInfo templateInfo; + @Mock private VMTemplateStoragePoolVO templatePoolRef; + @Mock private UnifiedSANStrategy sanStrategy; + @Mock private StorageStrategy nasStrategy; + @Mock private AsyncCompletionCallback createCallback; + @Mock private AsyncCompletionCallback commandCallback; + + @InjectMocks + private OntapPrimaryDatastoreDriver driver; + + private Map poolDetails; + + @BeforeEach + void setUp() { + poolDetails = new HashMap<>(); + poolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.ISCSI.name()); + poolDetails.put(OntapStorageConstants.SVM_NAME, "svm1"); + poolDetails.put(OntapStorageConstants.VOLUME_UUID, "flexvol-uuid"); + poolDetails.put(OntapStorageConstants.VOLUME_NAME, "flexvol"); + poolDetails.put(OntapStorageConstants.IS_AFF, "true"); + + when(dataStore.getId()).thenReturn(POOL_ID); + when(dataStore.getName()).thenReturn("flexvol"); + when(storagePoolDao.findById(POOL_ID)).thenReturn(storagePool); + when(storagePool.getId()).thenReturn(POOL_ID); + when(storagePool.getName()).thenReturn("flexvol"); + when(storagePool.getHypervisor()).thenReturn(Hypervisor.HypervisorType.KVM); + when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.OntapiSCSI); + when(storagePool.getCapacityIops()).thenReturn(null); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(poolDetails); + + when(volumeInfo.getId()).thenReturn(VOLUME_ID); + when(volumeInfo.getType()).thenReturn(DataObjectType.VOLUME); + when(volumeInfo.getName()).thenReturn("data-volume"); + when(volumeInfo.getUuid()).thenReturn("vol-uuid"); + when(volumeInfo.getSize()).thenReturn(ONE_GB); + when(volumeInfo.getVolumeType()).thenReturn(Volume.Type.DATADISK); + when(volumeInfo.getMinIops()).thenReturn(null); + when(volumeInfo.getMaxIops()).thenReturn(null); + when(volumeInfo.getDataStore()).thenReturn(dataStore); + when(volumeDao.findById(VOLUME_ID)).thenReturn(volumeVO); + when(volumeVO.getId()).thenReturn(VOLUME_ID); + when(volumeDao.update(anyLong(), any(VolumeVO.class))).thenReturn(true); + + when(templateInfo.getType()).thenReturn(DataObjectType.TEMPLATE); + when(templateInfo.getId()).thenReturn(TEMPLATE_ID); + when(templateInfo.getUuid()).thenReturn("template-uuid"); + when(templateInfo.getSize()).thenReturn(4096L); + when(vmTemplatePoolDao.findByPoolTemplate(POOL_ID, TEMPLATE_ID, null)).thenReturn(templatePoolRef); + when(templatePoolRef.getId()).thenReturn(900L); + } + + // ---------------------------------------------------------------- helpers + + private T withStrategy(StorageStrategy strategy, Supplier action) { + try (MockedStatic utils = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails)).thenReturn(strategy); + return action.get(); + } + } + + private void givenNfs() { + poolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name()); + when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + } + + private CreateCmdResult create(StorageStrategy strategy, DataObject object) { + withStrategy(strategy, () -> { + driver.createAsync(dataStore, object, createCallback); + return null; + }); + ArgumentCaptor captor = ArgumentCaptor.forClass(CreateCmdResult.class); + verify(createCallback).complete(captor.capture()); + return captor.getValue(); + } + + private CommandResult delete(StorageStrategy strategy, DataStore store, DataObject object) { + withStrategy(strategy, () -> { + driver.deleteAsync(store, object, commandCallback); + return null; + }); + ArgumentCaptor captor = ArgumentCaptor.forClass(CommandResult.class); + verify(commandCallback).complete(captor.capture()); + return captor.getValue(); + } + + private CloudStackVolume createdLun(String name, String uuid) { + Lun lun = new Lun(); + lun.setName(name); + lun.setUuid(uuid); + CloudStackVolume created = new CloudStackVolume(); + created.setLun(lun); + return created; + } + + private VolumeQosPolicy policy(String name, String uuid) { + VolumeQosPolicy policy = new VolumeQosPolicy(); + policy.setName(name); + policy.setUuid(uuid); + return policy; + } + + private void volumeDetail(String key, String value) { + when(volumeDetailsDao.findDetail(VOLUME_ID, key)).thenReturn(new VolumeDetailVO(VOLUME_ID, key, value, false)); + } + + private void snapshotDetail(String key, String value) { + when(snapshotDetailsDao.findDetail(SNAPSHOT_ID, key)).thenReturn(new SnapshotDetailsVO(SNAPSHOT_ID, key, value, false)); + } + + private void givenCloneOfSnapshot(String protocol, String sourcePath, long snapshotSize) { + volumeDetail(OntapStorageConstants.CLONE_OF_SNAPSHOT, String.valueOf(SNAPSHOT_ID)); + snapshotDetail(OntapStorageConstants.ONTAP_SNAP_NAME, "snap1"); + snapshotDetail(OntapStorageConstants.VOLUME_PATH, sourcePath); + snapshotDetail(OntapStorageConstants.PRIMARY_POOL_ID, String.valueOf(POOL_ID)); + snapshotDetail(OntapStorageConstants.PROTOCOL, protocol); + SnapshotVO snapshotVO = mock(SnapshotVO.class); + when(snapshotVO.getSize()).thenReturn(snapshotSize); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(snapshotVO); + } + + private void givenCloneOfTemplate(String localLunUuid, String installPath, long cachedSize) { + volumeDetail(OntapStorageConstants.CLONE_OF_TEMPLATE, String.valueOf(TEMPLATE_ID)); + when(templatePoolRef.getLocalDownloadPath()).thenReturn(localLunUuid); + when(templatePoolRef.getInstallPath()).thenReturn(installPath); + when(templatePoolRef.getTemplateSize()).thenReturn(cachedSize); + } + + private void givenIops(Long min, Long max) { + when(volumeInfo.getMinIops()).thenReturn(min); + when(volumeInfo.getMaxIops()).thenReturn(max); + } + + // ---------------------------------------------------------------- blank volume create + + @Test + void createIscsiVolumeSendsLunRequestAndRecordsLunIdentity() { + when(sanStrategy.createCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "lun-uuid")); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(sanStrategy).createCloudStackVolume(request.capture()); + Lun lun = request.getValue().getLun(); + assertEquals("svm1", lun.getSvm().getName()); + assertEquals("/vol/flexvol/data_volume", lun.getName()); + assertEquals(Long.valueOf(ONE_GB), lun.getSpace().getSize()); + assertEquals(Lun.OsTypeEnum.LINUX, lun.getOsType()); + assertNull(lun.getQosPolicy()); + assertSame(volumeInfo, request.getValue().getVolumeInfo()); + + assertTrue(result.isSuccess()); + assertEquals("/vol/flexvol/data_volume", result.getPath()); + verify(volumeVO).setPoolType(Storage.StoragePoolType.OntapiSCSI); + verify(volumeVO).setPoolId(POOL_ID); + verify(volumeVO).setFormat(Storage.ImageFormat.RAW); + verify(volumeVO).setFolder("lun-uuid"); + verify(volumeDetailsDao).addDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID, "lun-uuid", false); + verify(volumeDetailsDao).addDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME, "/vol/flexvol/data_volume", false); + verify(volumeDao).update(VOLUME_ID, volumeVO); + } + + @Test + void createNfsVolumeSendsFlexVolReferenceAndReportsVolumeUuidAsPath() { + givenNfs(); + when(nasStrategy.createCloudStackVolume(any())).thenReturn(new CloudStackVolume()); + + CreateCmdResult result = create(nasStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).createCloudStackVolume(request.capture()); + assertEquals("5", request.getValue().getDatastoreId()); + assertEquals("flexvol-uuid", request.getValue().getFlexVolumeUuid()); + assertSame(volumeInfo, request.getValue().getVolumeInfo()); + assertNull(request.getValue().getFile()); + + assertTrue(result.isSuccess()); + assertEquals("vol-uuid", result.getPath()); + verify(volumeVO).setPoolType(Storage.StoragePoolType.NetworkFilesystem); + verify(volumeVO).setPoolId(POOL_ID); + verify(volumeVO).setFormat(Storage.ImageFormat.QCOW2); + verify(volumeDao).update(VOLUME_ID, volumeVO); + } + + @Test + void createVolumeWithIopsAttachesPolicyReferenceToLunAndRemembersItsUuid() { + givenIops(100L, 200L); + when(sanStrategy.createVolumeQosPolicy("cs_100_to_200_iops_svm1", 100L, 200L)).thenReturn(policy("cs_100_to_200_iops_svm1", "qos-1")); + when(sanStrategy.createCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "lun-uuid")); + + create(sanStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(sanStrategy).createCloudStackVolume(request.capture()); + assertEquals("cs_100_to_200_iops_svm1", request.getValue().getLun().getQosPolicy().getName()); + assertEquals("qos-1", request.getValue().getLun().getQosPolicy().getUuid()); + verify(volumeDetailsDao).addDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID, "qos-1", false); + } + + @Test + void createNfsVolumeWithIopsAttachesPolicyReferenceToFile() { + givenNfs(); + givenIops(0L, 300L); + when(nasStrategy.createVolumeQosPolicy("cs_0_to_300_iops_svm1", 0L, 300L)).thenReturn(policy("cs_0_to_300_iops_svm1", "qos-2")); + when(nasStrategy.createCloudStackVolume(any())).thenReturn(new CloudStackVolume()); + + create(nasStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).createCloudStackVolume(request.capture()); + assertEquals("qos-2", request.getValue().getFile().getQosPolicy().getUuid()); + assertEquals("cs_0_to_300_iops_svm1", request.getValue().getFile().getQosPolicy().getName()); + } + + @Test + void createVolumeDeletesTheNewQosPolicyWhenOntapRejectsTheLun() { + givenIops(100L, 200L); + when(sanStrategy.createVolumeQosPolicy(any(), any(), any())).thenReturn(policy("p", "qos-1")); + when(sanStrategy.createCloudStackVolume(any())).thenThrow(new CloudRuntimeException("lun refused")); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + assertFalse(result.isSuccess()); + assertEquals("lun refused", result.getResult()); + verify(sanStrategy).createVolumeQosPolicy("cs_100_to_200_iops_svm1", 100L, 200L); + verify(sanStrategy).deleteVolumeQosPolicy("qos-1"); + } + + @Test + void createVolumeDoesNotCreateQosPolicyForVolumesThatAreNotRootOrData() { + givenIops(100L, 200L); + when(volumeInfo.getVolumeType()).thenReturn(Volume.Type.ISO); + when(sanStrategy.createCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "lun-uuid")); + + create(sanStrategy, volumeInfo); + + verify(sanStrategy, never()).createVolumeQosPolicy(any(), any(), any()); + } + + @Test + void createVolumeAcceptsIopsThatExactlyFillThePoolAndIgnoresItsOwnReservation() { + when(storagePool.getCapacityIops()).thenReturn(1000L); + VolumeVO other = mock(VolumeVO.class); + when(other.getId()).thenReturn(99L); + when(other.getMinIops()).thenReturn(500L); + VolumeVO self = mock(VolumeVO.class); + when(self.getId()).thenReturn(VOLUME_ID); + when(self.getMinIops()).thenReturn(400L); + when(volumeDao.findNonDestroyedVolumesByPoolId(POOL_ID, null)).thenReturn(java.util.Arrays.asList(other, self)); + when(sanStrategy.createVolumeQosPolicy("cs_500_to_600_iops_svm1", 500L, 600L)).thenReturn(policy("p", "qos-1")); + when(sanStrategy.createCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "lun-uuid")); + + givenIops(500L, 600L); + assertTrue(create(sanStrategy, volumeInfo).isSuccess()); + verify(sanStrategy).createVolumeQosPolicy("cs_500_to_600_iops_svm1", 500L, 600L); + verify(sanStrategy).createCloudStackVolume(any()); + } + + @Test + void createVolumeRejectsIopsThatExceedPoolCapacityByOne() { + when(storagePool.getCapacityIops()).thenReturn(1000L); + VolumeVO other = mock(VolumeVO.class); + when(other.getId()).thenReturn(99L); + when(other.getMinIops()).thenReturn(500L); + when(volumeDao.findNonDestroyedVolumesByPoolId(POOL_ID, null)).thenReturn(java.util.Arrays.asList(other)); + givenIops(501L, 600L); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("Insufficient IOPS capacity"), result.getResult()); + verify(sanStrategy, never()).createCloudStackVolume(any()); + } + + @Test + void createVolumeWithoutMinimumIopsIgnoresPoolIopsUsage() { + when(storagePool.getCapacityIops()).thenReturn(1000L); + VolumeVO other = mock(VolumeVO.class); + when(other.getId()).thenReturn(99L); + when(other.getMinIops()).thenReturn(5000L); + when(volumeDao.findNonDestroyedVolumesByPoolId(POOL_ID, null)).thenReturn(java.util.Arrays.asList(other)); + givenIops(0L, 0L); + when(sanStrategy.createCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "lun-uuid")); + + assertTrue(create(sanStrategy, volumeInfo).isSuccess()); + } + + @Test + void createVolumeAllowsEqualMinAndMaxIops() { + givenIops(200L, 200L); + when(sanStrategy.createVolumeQosPolicy("cs_200_to_200_iops_svm1", 200L, 200L)).thenReturn(policy("p", "qos-1")); + when(sanStrategy.createCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "lun-uuid")); + assertTrue(create(sanStrategy, volumeInfo).isSuccess()); + verify(sanStrategy).createVolumeQosPolicy("cs_200_to_200_iops_svm1", 200L, 200L); + verify(sanStrategy).createCloudStackVolume(any()); + } + + @Test + void createVolumeRejectsMinIopsGreaterThanMaxIops() { + givenIops(201L, 200L); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("Minimum IOPS cannot be greater than maximum IOPS"), result.getResult()); + } + + // ---------------------------------------------------------------- template cache on primary + + @Test + void createIscsiTemplateCacheRecordsLunUuidAndSizeAndReturnsLunName() { + when(sanStrategy.createTemplateCache(any(), any(), anyMap(), anyLong())) + .thenReturn(createdLun("/vol/flexvol/cs_tmpl_31", "tmpl-lun-uuid")); + + CreateCmdResult result = create(sanStrategy, templateInfo); + + assertTrue(result.isSuccess()); + assertEquals("/vol/flexvol/cs_tmpl_31", result.getPath()); + verify(templatePoolRef).setLocalDownloadPath("tmpl-lun-uuid"); + verify(templatePoolRef).setTemplateSize(4096L); + verify(vmTemplatePoolDao).update(900L, templatePoolRef); + } + + @Test + void createNfsTemplateCacheReturnsTemplateUuidAndLeavesSpoolRefUntouched() { + givenNfs(); + when(nasStrategy.createTemplateCache(any(), any(), anyMap(), anyLong())).thenReturn(new CloudStackVolume()); + + CreateCmdResult result = create(nasStrategy, templateInfo); + + assertTrue(result.isSuccess()); + assertEquals("template-uuid", result.getPath()); + verify(vmTemplatePoolDao, never()).update(anyLong(), any(VMTemplateStoragePoolVO.class)); + } + + @Test + void createTemplateCacheReturnsTemplateUuidWhenStrategyReturnsNothing() { + when(sanStrategy.createTemplateCache(any(), any(), anyMap(), anyLong())).thenReturn(null); + + CreateCmdResult result = create(sanStrategy, templateInfo); + + assertTrue(result.isSuccess()); + assertEquals("template-uuid", result.getPath()); + verify(sanStrategy).createTemplateCache(eq(storagePool), eq(templateInfo), eq(poolDetails), eq(4096L)); + verify(vmTemplatePoolDao, never()).update(anyLong(), any(VMTemplateStoragePoolVO.class)); + } + + // ---------------------------------------------------------------- required template size + + private void givenSpoolRef(ObjectInDataStoreStateMachine.State state, String lunUuid, String installPath) { + when(templatePoolRef.getState()).thenReturn(state); + when(templatePoolRef.getLocalDownloadPath()).thenReturn(lunUuid); + when(templatePoolRef.getInstallPath()).thenReturn(installPath); + } + + @Test + void iscsiTemplateNeedsNoSpaceOnlyWhenReadyWithALunUuid() { + givenSpoolRef(ObjectInDataStoreStateMachine.State.Ready, "lun-uuid", null); + assertEquals(0L, driver.getBytesRequiredForTemplate(templateInfo, storagePool)); + + givenSpoolRef(ObjectInDataStoreStateMachine.State.Ready, " ", "install/path"); + assertEquals(4096L, driver.getBytesRequiredForTemplate(templateInfo, storagePool)); + + givenSpoolRef(ObjectInDataStoreStateMachine.State.Allocated, "lun-uuid", null); + assertEquals(4096L, driver.getBytesRequiredForTemplate(templateInfo, storagePool)); + + when(vmTemplatePoolDao.findByPoolTemplate(POOL_ID, TEMPLATE_ID, null)).thenReturn(null); + assertEquals(4096L, driver.getBytesRequiredForTemplate(templateInfo, storagePool)); + } + + @Test + void nfsTemplateNeedsNoSpaceOnlyWhenReadyWithAnInstallPath() { + givenNfs(); + givenSpoolRef(ObjectInDataStoreStateMachine.State.Ready, null, "install/path"); + assertEquals(0L, driver.getBytesRequiredForTemplate(templateInfo, storagePool)); + + givenSpoolRef(ObjectInDataStoreStateMachine.State.Ready, "lun-uuid", ""); + assertEquals(4096L, driver.getBytesRequiredForTemplate(templateInfo, storagePool)); + } + + // ---------------------------------------------------------------- clone from template + + @Test + void cloneIscsiFromTemplateSendsCloneSourceAndKeepsRequestSizeless() { + givenCloneOfTemplate("tmpl-lun-uuid", null, ONE_GB); + when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "clone-uuid")); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(sanStrategy).cloneCloudStackVolume(request.capture()); + Lun lun = request.getValue().getLun(); + assertEquals("/vol/flexvol/cs_tmpl_31", lun.getClone().getSource().getName()); + assertEquals("tmpl-lun-uuid", lun.getClone().getSource().getUuid()); + assertEquals("svm1", lun.getSvm().getName()); + assertEquals("/vol/flexvol/data_volume", lun.getName()); + assertNull(lun.getSpace()); + assertSame(volumeInfo, request.getValue().getVolumeInfo()); + assertTrue(result.isSuccess()); + assertEquals("/vol/flexvol/data_volume", result.getPath()); + verify(sanStrategy, never()).resizeCloudStackVolume(any(), anyLong()); + } + + @Test + void cloneFromTemplateGrowsTheCloneOnlyWhenVolumeIsLargerThanTheCachedTemplate() { + CloudStackVolume cloned = createdLun("/vol/flexvol/data_volume", "clone-uuid"); + givenCloneOfTemplate("tmpl-lun-uuid", null, ONE_GB - 1); + when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(cloned); + + assertTrue(create(sanStrategy, volumeInfo).isSuccess()); + + verify(sanStrategy).resizeCloudStackVolume(cloned, ONE_GB); + } + + @Test + void cloneFromTemplateAttachesQosToTheCloneRequestAndRemembersPolicy() { + givenIops(100L, 200L); + givenCloneOfTemplate("tmpl-lun-uuid", null, ONE_GB); + when(sanStrategy.createVolumeQosPolicy(any(), any(), any())).thenReturn(policy("pol", "qos-9")); + when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "clone-uuid")); + + create(sanStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(sanStrategy).cloneCloudStackVolume(request.capture()); + assertEquals("pol", request.getValue().getLun().getQosPolicy().getName()); + assertEquals("qos-9", request.getValue().getLun().getQosPolicy().getUuid()); + verify(volumeDetailsDao).addDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID, "qos-9", false); + } + + @Test + void cloneFromTemplateDeletesNewQosPolicyWhenOntapReturnsNothing() { + givenIops(100L, 200L); + givenCloneOfTemplate("tmpl-lun-uuid", null, ONE_GB); + when(sanStrategy.createVolumeQosPolicy(any(), any(), any())).thenReturn(policy("pol", "qos-9")); + when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(null); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("ONTAP returned nothing when cloning template"), result.getResult()); + verify(sanStrategy).createVolumeQosPolicy("cs_100_to_200_iops_svm1", 100L, 200L); + verify(sanStrategy).deleteVolumeQosPolicy("qos-9"); + } + + @Test + void cloneFromTemplateChecksPoolIopsCapacity() { + when(storagePool.getCapacityIops()).thenReturn(100L); + givenIops(200L, 300L); + givenCloneOfTemplate("tmpl-lun-uuid", null, ONE_GB); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("Insufficient IOPS capacity"), result.getResult()); + verify(sanStrategy, never()).cloneCloudStackVolume(any()); + } + + @Test + void cloneNfsFromTemplateSendsSourceFileAndDestinationNamedAfterVolume() { + givenNfs(); + givenCloneOfTemplate(null, "tmpl/cached.qcow2", ONE_GB); + when(nasStrategy.cloneCloudStackVolume(any())).thenReturn(new CloudStackVolume()); + + CreateCmdResult result = create(nasStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).cloneCloudStackVolume(request.capture()); + assertEquals("5", request.getValue().getDatastoreId()); + assertEquals("tmpl/cached.qcow2", request.getValue().getFile().getPath()); + assertEquals("vol-uuid", request.getValue().getDestinationPath()); + assertSame(volumeInfo, request.getValue().getVolumeInfo()); + assertEquals("vol-uuid", result.getPath()); + } + + @Test + void cloneNfsFromTemplateAppliesQosAfterTheFileExists() { + givenNfs(); + givenIops(0L, 300L); + givenCloneOfTemplate(null, "tmpl/cached.qcow2", ONE_GB); + when(nasStrategy.createVolumeQosPolicy(any(), any(), any())).thenReturn(policy("pol", "qos-5")); + when(nasStrategy.cloneCloudStackVolume(any())).thenReturn(new CloudStackVolume()); + + create(nasStrategy, volumeInfo); + + ArgumentCaptor update = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).updateCloudStackVolume(update.capture()); + assertEquals("qos-5", update.getValue().getFile().getQosPolicy().getUuid()); + assertEquals("flexvol-uuid", update.getValue().getFlexVolumeUuid()); + } + + // ---------------------------------------------------------------- clone from snapshot + + @Test + void cloneIscsiFromSnapshotSendsSnapshotResidentSourcePath() { + givenCloneOfSnapshot("ISCSI", "/vol/flexvol/lun1", ONE_GB); + when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "clone-uuid")); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(sanStrategy).cloneCloudStackVolume(request.capture()); + Lun lun = request.getValue().getLun(); + assertEquals("/vol/flexvol/.snapshot/snap1/lun1", lun.getClone().getSource().getName()); + assertNull(lun.getClone().getSource().getUuid()); + assertEquals("svm1", lun.getSvm().getName()); + assertEquals("/vol/flexvol/data_volume", lun.getName()); + assertSame(volumeInfo, request.getValue().getVolumeInfo()); + assertTrue(result.isSuccess()); + verify(sanStrategy, never()).resizeCloudStackVolume(any(), anyLong()); + } + + @Test + void cloneFromSnapshotUsesPoolNameWhenFlexVolNameIsNotRecorded() { + poolDetails.remove(OntapStorageConstants.VOLUME_NAME); + givenCloneOfSnapshot("ISCSI", "/vol/flexvol/lun1", ONE_GB); + when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "clone-uuid")); + + create(sanStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(sanStrategy).cloneCloudStackVolume(request.capture()); + assertEquals("/vol/flexvol/.snapshot/snap1/lun1", request.getValue().getLun().getClone().getSource().getName()); + } + + @Test + void cloneFromSnapshotGrowsOnlyWhenSnapshotIsKnownAndSmallerThanVolume() { + CloudStackVolume cloned = createdLun("/vol/flexvol/data_volume", "clone-uuid"); + when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(cloned); + + givenCloneOfSnapshot("ISCSI", "/vol/flexvol/lun1", ONE_GB - 1); + assertTrue(create(sanStrategy, volumeInfo).isSuccess()); + verify(sanStrategy).resizeCloudStackVolume(cloned, ONE_GB); + } + + @Test + void cloneFromSnapshotDoesNotGrowWhenSnapshotSizeIsUnknown() { + givenCloneOfSnapshot("ISCSI", "/vol/flexvol/lun1", 0L); + when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(createdLun("/vol/flexvol/data_volume", "clone-uuid")); + + assertTrue(create(sanStrategy, volumeInfo).isSuccess()); + + verify(sanStrategy, never()).resizeCloudStackVolume(any(), anyLong()); + } + + @Test + void cloneNfsFromSnapshotSendsSnapshotRelativeFilePath() { + givenNfs(); + poolDetails.put(OntapStorageConstants.VOLUME_NAME, "flexvol"); + givenCloneOfSnapshot("NFS3", "src-file-uuid", ONE_GB); + when(nasStrategy.cloneCloudStackVolume(any())).thenReturn(new CloudStackVolume()); + + CreateCmdResult result = create(nasStrategy, volumeInfo); + + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).cloneCloudStackVolume(request.capture()); + assertEquals("5", request.getValue().getDatastoreId()); + assertEquals("./.snapshot/snap1/src-file-uuid", request.getValue().getFile().getPath()); + assertEquals("vol-uuid", request.getValue().getDestinationPath()); + assertSame(volumeInfo, request.getValue().getVolumeInfo()); + assertEquals("vol-uuid", result.getPath()); + } + + @Test + void cloneFromSnapshotChecksPoolIopsCapacityBeforeCallingOntap() { + when(storagePool.getCapacityIops()).thenReturn(100L); + givenIops(200L, 300L); + givenCloneOfSnapshot("ISCSI", "/vol/flexvol/lun1", ONE_GB); + + CreateCmdResult result = create(sanStrategy, volumeInfo); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("Insufficient IOPS capacity"), result.getResult()); + verify(sanStrategy, never()).cloneCloudStackVolume(any()); + } + + // ---------------------------------------------------------------- delete + + @Test + void deleteIscsiVolumeSendsLunIdentityAndReportsSuccess() { + volumeDetail(OntapStorageConstants.LUN_DOT_NAME, "/vol/flexvol/data_volume"); + volumeDetail(OntapStorageConstants.LUN_DOT_UUID, "lun-uuid"); + + CommandResult result = delete(sanStrategy, dataStore, volumeInfo); + + assertTrue(result.isSuccess()); + assertNull(result.getResult()); + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(sanStrategy).deleteCloudStackVolume(request.capture()); + assertEquals("/vol/flexvol/data_volume", request.getValue().getLun().getName()); + assertEquals("lun-uuid", request.getValue().getLun().getUuid()); + verify(sanStrategy, never()).updateCloudStackVolume(any()); + } + + @Test + void deleteNfsVolumeClearsQosThenDeletesFileAndRemovesThePolicy() { + givenNfs(); + volumeDetail(OntapStorageConstants.QOS_POLICY_UUID, "old-policy"); + + CommandResult result = delete(nasStrategy, dataStore, volumeInfo); + + assertTrue(result.isSuccess()); + ArgumentCaptor clear = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).updateCloudStackVolume(clear.capture()); + assertEquals(OntapStorageConstants.QOS_POLICY_NONE, clear.getValue().getFile().getQosPolicy().getName()); + ArgumentCaptor delete = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).deleteCloudStackVolume(delete.capture()); + assertEquals("5", delete.getValue().getDatastoreId()); + assertSame(volumeInfo, delete.getValue().getVolumeInfo()); + verify(nasStrategy).deleteVolumeQosPolicy("old-policy"); + } + + @Test + void deleteNfsVolumeRestoresPreviousPolicyWhenDeleteFailsAfterItWasCleared() { + givenNfs(); + volumeDetail(OntapStorageConstants.QOS_POLICY_UUID, "old-policy"); + doThrow(new CloudRuntimeException("delete failed")).when(nasStrategy).deleteCloudStackVolume(any(CloudStackVolume.class)); + + CommandResult result = delete(nasStrategy, dataStore, volumeInfo); + + assertFalse(result.isSuccess()); + assertEquals("delete failed", result.getResult()); + ArgumentCaptor updates = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy, times(2)).updateCloudStackVolume(updates.capture()); + assertEquals("old-policy", updates.getAllValues().get(1).getFile().getQosPolicy().getUuid()); + verify(nasStrategy, never()).deleteVolumeQosPolicy(any()); + } + + @Test + void deleteNfsVolumeDoesNotRestorePolicyWhenItCouldNotBeCleared() { + givenNfs(); + volumeDetail(OntapStorageConstants.QOS_POLICY_UUID, "old-policy"); + doThrow(new CloudRuntimeException("clear failed")).when(nasStrategy).updateCloudStackVolume(any(CloudStackVolume.class)); + doThrow(new CloudRuntimeException("delete failed")).when(nasStrategy).deleteCloudStackVolume(any(CloudStackVolume.class)); + + CommandResult result = delete(nasStrategy, dataStore, volumeInfo); + + assertFalse(result.isSuccess()); + assertEquals("delete failed", result.getResult()); + verify(nasStrategy, times(1)).updateCloudStackVolume(any(CloudStackVolume.class)); + } + + @Test + void deleteReportsFailureWhenStoreOrDataIsMissingOrTypeIsUnsupported() { + CommandResult noStore = delete(sanStrategy, null, volumeInfo); + assertFalse(noStore.isSuccess()); + assertEquals("store or data is null", noStore.getResult()); + + DataObject iso = mock(DataObject.class); + when(iso.getType()).thenReturn(DataObjectType.ARCHIVE); + driver.deleteAsync(dataStore, iso, commandCallback); + ArgumentCaptor captor = ArgumentCaptor.forClass(CommandResult.class); + verify(commandCallback, times(2)).complete(captor.capture()); + CommandResult unsupported = captor.getAllValues().get(1); + assertFalse(unsupported.isSuccess()); + assertTrue(unsupported.getResult().contains("Unsupported data object type"), unsupported.getResult()); + } + + private SnapshotInfo givenSnapshot() { + SnapshotInfo snapshot = mock(SnapshotInfo.class); + when(snapshot.getId()).thenReturn(SNAPSHOT_ID); + when(snapshot.getType()).thenReturn(DataObjectType.SNAPSHOT); + snapshotDetail(OntapStorageConstants.BASE_ONTAP_FV_ID, "fv-uuid"); + snapshotDetail(OntapStorageConstants.ONTAP_SNAP_ID, "snap-uuid"); + snapshotDetail(OntapStorageConstants.ONTAP_SNAP_NAME, "snap1"); + snapshotDetail(OntapStorageConstants.PRIMARY_POOL_ID, String.valueOf(POOL_ID)); + return snapshot; + } + + @Test + void deleteSnapshotReportsFailureWithOntapMessageAndSuccessOtherwise() { + SnapshotInfo snapshot = givenSnapshot(); + doThrow(new CloudRuntimeException("ontap boom")).when(sanStrategy) + .deleteFlexVolSnapshotForCloudStackVolume("fv-uuid", "snap-uuid", "snap1"); + + CommandResult failed = delete(sanStrategy, dataStore, snapshot); + + assertFalse(failed.isSuccess()); + assertEquals("ontap boom", failed.getResult()); + } + + @Test + void deleteSnapshotReportsSuccessAfterOntapDelete() { + SnapshotInfo snapshot = givenSnapshot(); + + CommandResult result = delete(sanStrategy, dataStore, snapshot); + + assertTrue(result.isSuccess()); + assertNull(result.getResult()); + verify(sanStrategy).deleteFlexVolSnapshotForCloudStackVolume("fv-uuid", "snap-uuid", "snap1"); + } + + // ---------------------------------------------------------------- resize with QoS + + private void givenResize(long newSize, Long minIops, Long maxIops) { + when(volumeInfo.getpayload()).thenReturn(new ResizeVolumePayload(newSize, minIops, maxIops, null, false, null, null, true)); + when(volumeVO.getSize()).thenReturn(ONE_GB); + } + + private CreateCmdResult resize() { + withStrategy(nasStrategy, () -> { + driver.resize(volumeInfo, createCallback); + return null; + }); + ArgumentCaptor captor = ArgumentCaptor.forClass(CreateCmdResult.class); + verify(createCallback).complete(captor.capture()); + return captor.getValue(); + } + + @Test + void resizeDeletesTheNewQosPolicyWhenOntapRejectsTheResize() { + givenNfs(); + givenResize(2 * ONE_GB, 0L, 400L); + volumeDetail(OntapStorageConstants.QOS_POLICY_UUID, "old-policy"); + when(nasStrategy.createVolumeQosPolicy(any(), any(), any())).thenReturn(policy("new", "new-policy")); + doThrow(new CloudRuntimeException("resize refused")).when(nasStrategy).resizeCloudStackVolume(any(), anyLong()); + + CreateCmdResult result = resize(); + + assertFalse(result.isSuccess()); + assertEquals("resize refused", result.getResult()); + verify(nasStrategy).createVolumeQosPolicy("cs_0_to_400_iops_svm1", 0L, 400L); + verify(nasStrategy).resizeCloudStackVolume(argThat(request -> request.getFile() != null + && request.getFile().getQosPolicy() != null + && "new-policy".equals(request.getFile().getQosPolicy().getUuid())), eq(2 * ONE_GB)); + verify(nasStrategy).deleteVolumeQosPolicy("new-policy"); + verify(nasStrategy, never()).deleteVolumeQosPolicy("old-policy"); + } + + @Test + void resizeKeepsTheExistingPolicyWhenItIsStillTheSame() { + givenNfs(); + givenResize(2 * ONE_GB, 0L, 400L); + volumeDetail(OntapStorageConstants.QOS_POLICY_UUID, "same-policy"); + when(nasStrategy.createVolumeQosPolicy(any(), any(), any())).thenReturn(policy("same", "same-policy")); + doThrow(new CloudRuntimeException("resize refused")).when(nasStrategy).resizeCloudStackVolume(any(), anyLong()); + + resize(); + + verify(nasStrategy, never()).deleteVolumeQosPolicy(any()); + } + + @Test + void resizeSwitchesToNewPolicyAndRemovesTheOldOne() { + givenNfs(); + givenResize(2 * ONE_GB, 0L, 400L); + volumeDetail(OntapStorageConstants.QOS_POLICY_UUID, "old-policy"); + when(nasStrategy.createVolumeQosPolicy(any(), any(), any())).thenReturn(policy("new", "new-policy")); + + CreateCmdResult result = resize(); + + assertTrue(result.isSuccess()); + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).resizeCloudStackVolume(request.capture(), org.mockito.ArgumentMatchers.eq(2 * ONE_GB)); + assertEquals("new-policy", request.getValue().getFile().getQosPolicy().getUuid()); + verify(volumeDetailsDao).addDetail(VOLUME_ID, OntapStorageConstants.QOS_POLICY_UUID, "new-policy", false); + verify(nasStrategy).deleteVolumeQosPolicy("old-policy"); + } + + @Test + void resizeClearsPolicyWhenNewIopsAreRemoved() { + givenNfs(); + givenResize(2 * ONE_GB, 0L, 0L); + volumeDetail(OntapStorageConstants.QOS_POLICY_UUID, "old-policy"); + + CreateCmdResult result = resize(); + + assertTrue(result.isSuccess()); + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).resizeCloudStackVolume(request.capture(), org.mockito.ArgumentMatchers.eq(2 * ONE_GB)); + assertEquals(OntapStorageConstants.QOS_POLICY_NONE, request.getValue().getFile().getQosPolicy().getName()); + verify(nasStrategy).deleteVolumeQosPolicy("old-policy"); + } + + @Test + void resizeWithoutQosChangeSendsOnlyTheVolumeReference() { + givenNfs(); + givenResize(2 * ONE_GB, 0L, 0L); + + CreateCmdResult result = resize(); + + assertTrue(result.isSuccess()); + ArgumentCaptor request = ArgumentCaptor.forClass(CloudStackVolume.class); + verify(nasStrategy).resizeCloudStackVolume(request.capture(), org.mockito.ArgumentMatchers.eq(2 * ONE_GB)); + assertSame(volumeInfo, request.getValue().getVolumeInfo()); + assertNull(request.getValue().getFile()); + verify(nasStrategy, never()).deleteVolumeQosPolicy(any()); + } + } + + /** + * Snapshot workflows of {@link OntapPrimaryDatastoreDriver}: take, revert and delete of a + * CloudStack volume snapshot backed by an ONTAP FlexVol snapshot. + */ + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + @Nested + class OntapPrimaryDatastoreDriverSnapshotTest { + + private static final long SNAPSHOT_ID = 77L; + private static final long VOLUME_ID = 10L; + private static final long POOL_ID = 5L; + private static final String FLEXVOL_UUID = "flexvol-uuid"; + private static final String FLEXVOL_NAME = "flexvol-name"; + private static final String ONTAP_SNAP_UUID = "ontap-snap-uuid"; + private static final String LUN_NAME = "/vol/flexvol-name/lun1"; + private static final String LUN_UUID = "lun-uuid"; + private static final String NFS_FILE_PATH = "vol-file-uuid"; + private static final String EXPECTED_SNAPSHOT_NAME = "daily_cs77"; + + @Mock + private StoragePoolDetailsDao storagePoolDetailsDao; + @Mock + private PrimaryDataStoreDao storagePoolDao; + @Mock + private VolumeDao volumeDao; + @Mock + private VolumeDetailsDao volumeDetailsDao; + @Mock + private SnapshotDetailsDao snapshotDetailsDao; + @Mock + private SnapshotDao snapshotDao; + + @Mock + private SnapshotInfo snapshotInfo; + @Mock + private SnapshotInfo primarySnapshotInfo; + @Mock + private VolumeInfo baseVolumeInfo; + @Mock + private VolumeVO volumeVO; + @Mock + private StoragePoolVO storagePool; + @Mock + private DataStore dataStore; + @Mock + private StorageStrategy strategy; + @Mock + private SnapshotFeignClient snapshotClient; + + @Mock + private AsyncCompletionCallback createCallback; + @Mock + private AsyncCompletionCallback commandCallback; + + @InjectMocks + private OntapPrimaryDatastoreDriver driver; + + private Map poolDetails; + private SnapshotObjectTO snapshotTo; + private Map> snapshotDetailStore; + + @BeforeEach + void setUp() { + poolDetails = new HashMap<>(); + poolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.ISCSI.name()); + poolDetails.put(OntapStorageConstants.VOLUME_UUID, FLEXVOL_UUID); + poolDetails.put(OntapStorageConstants.VOLUME_NAME, FLEXVOL_NAME); + poolDetails.put(OntapStorageConstants.SVM_NAME, "svm1"); + + snapshotTo = new SnapshotObjectTO(); + when(snapshotInfo.getId()).thenReturn(SNAPSHOT_ID); + when(snapshotInfo.getName()).thenReturn("daily"); + when(snapshotInfo.getBaseVolume()).thenReturn(baseVolumeInfo); + when(snapshotInfo.getTO()).thenReturn(snapshotTo); + when(snapshotInfo.getType()).thenReturn(DataObjectType.SNAPSHOT); + when(baseVolumeInfo.getId()).thenReturn(VOLUME_ID); + when(baseVolumeInfo.getName()).thenReturn("vol-name"); + + when(volumeDao.findById(VOLUME_ID)).thenReturn(volumeVO); + when(volumeVO.getId()).thenReturn(VOLUME_ID); + when(volumeVO.getPoolId()).thenReturn(POOL_ID); + when(volumeVO.getPath()).thenReturn(NFS_FILE_PATH); + when(storagePoolDao.findById(POOL_ID)).thenReturn(storagePool); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(poolDetails); + when(dataStore.getId()).thenReturn(POOL_ID); + + when(strategy.getSnapshotFeignClient()).thenReturn(snapshotClient); + when(strategy.getAuthHeader()).thenReturn("Basic abc"); + + snapshotDetailStore = new HashMap<>(); + when(snapshotDetailsDao.findDetail(anyLong(), anyString())).thenAnswer(inv -> { + String value = snapshotDetailStore.getOrDefault(inv.getArgument(0, Long.class), Collections.emptyMap()) + .get(inv.getArgument(1, String.class)); + return value == null ? null : new SnapshotDetailsVO(inv.getArgument(0), inv.getArgument(1), value, false); + }); + } + + // ---------------------------------------------------------------- helpers + + private void givenIscsiVolumeDetails() { + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID, LUN_UUID, false)); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME, LUN_NAME, false)); + } + + private void givenSnapshotCreationSucceeds() { + Job job = new Job(); + job.setUuid("job-uuid"); + JobResponse response = new JobResponse(); + response.setJob(job); + when(snapshotClient.createSnapshot(eq("Basic abc"), eq(FLEXVOL_UUID), any(FlexVolSnapshot.class))).thenReturn(response); + when(strategy.jobPollForSuccess(eq("job-uuid"), anyInt(), anyInt())).thenReturn(true); + + FlexVolSnapshot created = new FlexVolSnapshot(); + created.setUuid(ONTAP_SNAP_UUID); + OntapResponse lookup = new OntapResponse<>(); + lookup.setRecords(List.of(created)); + when(snapshotClient.getSnapshots(eq("Basic abc"), eq(FLEXVOL_UUID), anyMap())).thenReturn(lookup); + } + + private CreateCmdResult takeSnapshot() { + try (MockedStatic utils = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails)).thenReturn(strategy); + driver.takeSnapshot(snapshotInfo, createCallback); + } + ArgumentCaptor captor = ArgumentCaptor.forClass(CreateCmdResult.class); + verify(createCallback).complete(captor.capture()); + return captor.getValue(); + } + + private Map persistedSnapshotDetails() { + ArgumentCaptor captor = ArgumentCaptor.forClass(SnapshotDetailsVO.class); + verify(snapshotDetailsDao, atLeast(0)).persist(captor.capture()); + Map persisted = new HashMap<>(); + for (SnapshotDetailsVO detail : captor.getAllValues()) { + persisted.put(detail.getName(), detail.getValue()); + } + return persisted; + } + + private void assertTakeSnapshotFailed(CreateCmdResult result, String expectedMessagePart) { + assertNotNull(result.getResult(), "takeSnapshot should report a failure"); + assertTrue(result.getResult().contains(expectedMessagePart), + "Expected '" + expectedMessagePart + "' in: " + result.getResult()); + assertFalse(result.getAnswer().getResult()); + verify(snapshotDetailsDao, never()).persist(any(SnapshotDetailsVO.class)); + } + + private FlexVolSnapshot dailySnapshotRequest() { + return argThat(request -> request != null && EXPECTED_SNAPSHOT_NAME.equals(request.getName())); + } + + private void assertDailySnapshotWasRequested() { + ArgumentCaptor request = ArgumentCaptor.forClass(FlexVolSnapshot.class); + verify(snapshotClient).createSnapshot(eq("Basic abc"), eq(FLEXVOL_UUID), request.capture()); + assertEquals(EXPECTED_SNAPSHOT_NAME, request.getValue().getName()); + } + + @SuppressWarnings("unchecked") + private Map dailySnapshotQuery() { + return argThat(query -> query != null + && EXPECTED_SNAPSHOT_NAME.equals(query.get("name")) + && "uuid,name".equals(query.get("fields"))); + } + + @SuppressWarnings("unchecked") + private void assertDailySnapshotWasLookedUp() { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(snapshotClient).getSnapshots(eq("Basic abc"), eq(FLEXVOL_UUID), query.capture()); + assertEquals(EXPECTED_SNAPSHOT_NAME, query.getValue().get("name")); + assertEquals("uuid,name", query.getValue().get("fields")); + } + + // ------------------------------------------------- takeSnapshot: positive + + @Test + void takeSnapshot_createsFlexVolSnapshotAndPersistsDetails_forIscsi() { + givenIscsiVolumeDetails(); + givenSnapshotCreationSucceeds(); + when(volumeVO.getMinIops()).thenReturn(100L); + when(volumeVO.getMaxIops()).thenReturn(500L); + + CreateCmdResult result = takeSnapshot(); + + assertNull(result.getResult()); + assertTrue(result.getAnswer().getResult()); + assertEquals(OntapStorageConstants.ONTAP_SNAP_ID + "=" + ONTAP_SNAP_UUID, snapshotTo.getPath()); + + ArgumentCaptor request = ArgumentCaptor.forClass(FlexVolSnapshot.class); + verify(snapshotClient).createSnapshot(eq("Basic abc"), eq(FLEXVOL_UUID), request.capture()); + assertEquals(EXPECTED_SNAPSHOT_NAME, request.getValue().getName()); + + Map details = persistedSnapshotDetails(); + assertEquals(String.valueOf(VOLUME_ID), details.get(OntapStorageConstants.SRC_CS_VOLUME_ID)); + assertEquals(FLEXVOL_UUID, details.get(OntapStorageConstants.BASE_ONTAP_FV_ID)); + assertEquals(ONTAP_SNAP_UUID, details.get(OntapStorageConstants.ONTAP_SNAP_ID)); + assertEquals(EXPECTED_SNAPSHOT_NAME, details.get(OntapStorageConstants.ONTAP_SNAP_NAME)); + assertEquals(LUN_NAME, details.get(OntapStorageConstants.VOLUME_PATH)); + assertEquals(String.valueOf(POOL_ID), details.get(OntapStorageConstants.PRIMARY_POOL_ID)); + assertEquals(ProtocolType.ISCSI.name(), details.get(OntapStorageConstants.PROTOCOL)); + assertEquals(LUN_UUID, details.get(OntapStorageConstants.LUN_DOT_UUID)); + assertEquals("100", details.get(OntapStorageConstants.MIN_IOPS)); + assertEquals("500", details.get(OntapStorageConstants.MAX_IOPS)); + } + + @Test + void takeSnapshot_usesFilePathAndOmitsLunAndIops_forNfs() { + poolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name()); + givenSnapshotCreationSucceeds(); + when(volumeVO.getMinIops()).thenReturn(null); + when(volumeVO.getMaxIops()).thenReturn(0L); + + CreateCmdResult result = takeSnapshot(); + + assertNull(result.getResult()); + Map details = persistedSnapshotDetails(); + assertEquals(NFS_FILE_PATH, details.get(OntapStorageConstants.VOLUME_PATH)); + assertFalse(details.containsKey(OntapStorageConstants.LUN_DOT_UUID)); + assertFalse(details.containsKey(OntapStorageConstants.MIN_IOPS)); + assertFalse(details.containsKey(OntapStorageConstants.MAX_IOPS)); + } + + // ------------------------------------------------- takeSnapshot: negative + + @Test + void takeSnapshot_fails_whenVolumeNotFound() { + when(volumeDao.findById(VOLUME_ID)).thenReturn(null); + + assertTakeSnapshotFailed(takeSnapshot(), "CloudStack Volume not found"); + } + + @Test + void takeSnapshot_fails_whenStoragePoolNotFound() { + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + + assertTakeSnapshotFailed(takeSnapshot(), "Storage Pool not found"); + } + + @Test + void takeSnapshot_fails_whenFlexVolUuidMissing() { + poolDetails.remove(OntapStorageConstants.VOLUME_UUID); + + assertTakeSnapshotFailed(takeSnapshot(), "FlexVolume UUID not found"); + } + + @Test + void takeSnapshot_fails_whenFlexVolUuidEmpty() { + poolDetails.put(OntapStorageConstants.VOLUME_UUID, ""); + + assertTakeSnapshotFailed(takeSnapshot(), "FlexVolume UUID not found"); + } + + @Test + void takeSnapshot_fails_whenIscsiLunNameDetailMissing() { + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME)).thenReturn(null); + + assertTakeSnapshotFailed(takeSnapshot(), "Unsupported protocol"); + } + + @Test + void takeSnapshot_fails_whenIscsiLunNameValueNull() { + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME, null, false)); + + assertTakeSnapshotFailed(takeSnapshot(), "No LUN name found"); + } + + @Test + void takeSnapshot_fails_whenIscsiLunUuidDetailMissing() { + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_NAME, LUN_NAME, false)); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID)).thenReturn(null); + + assertTakeSnapshotFailed(takeSnapshot(), "LUN UUID not found"); + } + + @Test + void takeSnapshot_fails_whenIscsiLunUuidValueNull() { + givenIscsiVolumeDetails(); + when(volumeDetailsDao.findDetail(VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID)) + .thenReturn(new VolumeDetailVO(VOLUME_ID, OntapStorageConstants.LUN_DOT_UUID, null, false)); + + assertTakeSnapshotFailed(takeSnapshot(), "LUN UUID not found"); + } + + @Test + void takeSnapshot_fails_whenProtocolUnsupported() { + poolDetails.put(OntapStorageConstants.PROTOCOL, "FC"); + + assertTakeSnapshotFailed(takeSnapshot(), "Unsupported protocol"); + } + + @Test + void takeSnapshot_fails_whenOntapReturnsNoJobResponse() { + givenIscsiVolumeDetails(); + when(snapshotClient.createSnapshot(eq("Basic abc"), eq(FLEXVOL_UUID), dailySnapshotRequest())).thenReturn(null); + + assertTakeSnapshotFailed(takeSnapshot(), + "Failed to initiate FlexVolume snapshot on FlexVol UUID [" + FLEXVOL_UUID + "]"); + assertDailySnapshotWasRequested(); + verify(strategy, never()).jobPollForSuccess(anyString(), anyInt(), anyInt()); + } + + @Test + void takeSnapshot_fails_whenJobResponseHasNoJob() { + givenIscsiVolumeDetails(); + when(snapshotClient.createSnapshot(eq("Basic abc"), eq(FLEXVOL_UUID), dailySnapshotRequest())) + .thenReturn(new JobResponse()); + + assertTakeSnapshotFailed(takeSnapshot(), + "Failed to initiate FlexVolume snapshot on FlexVol UUID [" + FLEXVOL_UUID + "]"); + assertDailySnapshotWasRequested(); + verify(strategy, never()).jobPollForSuccess(anyString(), anyInt(), anyInt()); + } + + @Test + void takeSnapshot_fails_whenSnapshotJobDoesNotSucceed() { + givenIscsiVolumeDetails(); + givenSnapshotCreationSucceeds(); + when(strategy.jobPollForSuccess(eq("job-uuid"), eq(30), eq(2000))).thenReturn(false); + + assertTakeSnapshotFailed(takeSnapshot(), + "FlexVolume snapshot job failed on FlexVol UUID [" + FLEXVOL_UUID + "]"); + assertDailySnapshotWasRequested(); + verify(strategy).jobPollForSuccess("job-uuid", 30, 2000); + verify(snapshotClient, never()).getSnapshots(anyString(), anyString(), anyMap()); + } + + @Test + void takeSnapshot_fails_whenSnapshotLookupReturnsNoResponse() { + givenIscsiVolumeDetails(); + givenSnapshotCreationSucceeds(); + when(snapshotClient.getSnapshots(eq("Basic abc"), eq(FLEXVOL_UUID), dailySnapshotQuery())).thenReturn(null); + + assertTakeSnapshotFailed(takeSnapshot(), + "Failed to resolve snapshot UUID for snapshot name [" + EXPECTED_SNAPSHOT_NAME + "]"); + assertDailySnapshotWasRequested(); + assertDailySnapshotWasLookedUp(); + } + + @Test + void takeSnapshot_fails_whenSnapshotLookupReturnsNoRecords() { + givenIscsiVolumeDetails(); + givenSnapshotCreationSucceeds(); + OntapResponse empty = new OntapResponse<>(); + empty.setRecords(Collections.emptyList()); + when(snapshotClient.getSnapshots(eq("Basic abc"), eq(FLEXVOL_UUID), dailySnapshotQuery())).thenReturn(empty); + + assertTakeSnapshotFailed(takeSnapshot(), + "Failed to resolve snapshot UUID for snapshot name [" + EXPECTED_SNAPSHOT_NAME + "]"); + assertDailySnapshotWasRequested(); + assertDailySnapshotWasLookedUp(); + } + + @Test + void takeSnapshot_fails_whenSnapshotLookupReturnsNullRecords() { + givenIscsiVolumeDetails(); + givenSnapshotCreationSucceeds(); + when(snapshotClient.getSnapshots(eq("Basic abc"), eq(FLEXVOL_UUID), dailySnapshotQuery())) + .thenReturn(new OntapResponse<>()); + + assertTakeSnapshotFailed(takeSnapshot(), + "Failed to resolve snapshot UUID for snapshot name [" + EXPECTED_SNAPSHOT_NAME + "]"); + assertDailySnapshotWasRequested(); + assertDailySnapshotWasLookedUp(); + } + + @Test + void takeSnapshot_fails_whenSnapshotUuidIsEmpty() { + givenIscsiVolumeDetails(); + givenSnapshotCreationSucceeds(); + FlexVolSnapshot blank = new FlexVolSnapshot(); + blank.setUuid(""); + OntapResponse lookup = new OntapResponse<>(); + lookup.setRecords(List.of(blank)); + when(snapshotClient.getSnapshots(eq("Basic abc"), eq(FLEXVOL_UUID), dailySnapshotQuery())).thenReturn(lookup); + + assertTakeSnapshotFailed(takeSnapshot(), + "Failed to resolve snapshot UUID for snapshot name [" + EXPECTED_SNAPSHOT_NAME + "]"); + assertDailySnapshotWasRequested(); + assertDailySnapshotWasLookedUp(); + } + + @Test + void takeSnapshot_reportsFailure_whenOntapCallThrows() { + givenIscsiVolumeDetails(); + when(snapshotClient.createSnapshot(eq("Basic abc"), eq(FLEXVOL_UUID), dailySnapshotRequest())) + .thenThrow(new RuntimeException("ONTAP unreachable")); + + assertTakeSnapshotFailed(takeSnapshot(), "ONTAP unreachable"); + assertDailySnapshotWasRequested(); + verify(strategy, never()).jobPollForSuccess(anyString(), anyInt(), anyInt()); + } + + // ------------------------------------------------------ revertSnapshot + + private void givenSnapshotDetail(long snapshotId, String key, String value) { + snapshotDetailStore.computeIfAbsent(snapshotId, id -> new HashMap<>()).put(key, value); + } + + private void givenRevertableSnapshot(long snapshotId, String protocol) { + givenSnapshotDetail(snapshotId, OntapStorageConstants.BASE_ONTAP_FV_ID, FLEXVOL_UUID); + givenSnapshotDetail(snapshotId, OntapStorageConstants.ONTAP_SNAP_ID, ONTAP_SNAP_UUID); + givenSnapshotDetail(snapshotId, OntapStorageConstants.ONTAP_SNAP_NAME, EXPECTED_SNAPSHOT_NAME); + givenSnapshotDetail(snapshotId, OntapStorageConstants.VOLUME_PATH, LUN_NAME); + givenSnapshotDetail(snapshotId, OntapStorageConstants.PRIMARY_POOL_ID, String.valueOf(POOL_ID)); + givenSnapshotDetail(snapshotId, OntapStorageConstants.PROTOCOL, protocol); + givenSnapshotDetail(snapshotId, OntapStorageConstants.LUN_DOT_UUID, LUN_UUID); + } + + private CommandResult revertSnapshot(SnapshotInfo onImageStore, SnapshotInfo onPrimaryStore) { + try (MockedStatic utils = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails)).thenReturn(strategy); + driver.revertSnapshot(onImageStore, onPrimaryStore, commandCallback); + } + ArgumentCaptor captor = ArgumentCaptor.forClass(CommandResult.class); + verify(commandCallback).complete(captor.capture()); + return captor.getValue(); + } + + @Test + void revertSnapshot_restoresLunWithLunUuid_forIscsi() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + JobResponse job = new JobResponse(); + when(strategy.revertSnapshotForCloudStackVolume(EXPECTED_SNAPSHOT_NAME, FLEXVOL_UUID, ONTAP_SNAP_UUID, + LUN_NAME, LUN_UUID, FLEXVOL_NAME)).thenReturn(job); + + CommandResult result = revertSnapshot(snapshotInfo, null); + + assertNull(result.getResult()); + verify(strategy).executeCliSfsrRestore(eq(job), contains("revert snapshot [" + EXPECTED_SNAPSHOT_NAME + "]")); + } + + @Test + void revertSnapshot_omitsLunUuid_forNfs() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.NFS3.name()); + poolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name()); + JobResponse job = new JobResponse(); + when(strategy.revertSnapshotForCloudStackVolume(EXPECTED_SNAPSHOT_NAME, FLEXVOL_UUID, ONTAP_SNAP_UUID, + LUN_NAME, null, FLEXVOL_NAME)).thenReturn(job); + + CommandResult result = revertSnapshot(snapshotInfo, null); + + assertNull(result.getResult()); + verify(strategy).executeCliSfsrRestore(eq(job), anyString()); + } + + @Test + void revertSnapshot_prefersPrimaryStoreSnapshotDetails() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + givenSnapshotDetail(SNAPSHOT_ID, OntapStorageConstants.ONTAP_SNAP_NAME, "secondary-snap"); + givenSnapshotDetail(SNAPSHOT_ID, OntapStorageConstants.VOLUME_PATH, "/vol/flexvol-name/secondary"); + + long primarySnapshotId = 88L; + when(primarySnapshotInfo.getId()).thenReturn(primarySnapshotId); + givenRevertableSnapshot(primarySnapshotId, ProtocolType.ISCSI.name()); + givenSnapshotDetail(primarySnapshotId, OntapStorageConstants.BASE_ONTAP_FV_ID, "primary-flexvol"); + givenSnapshotDetail(primarySnapshotId, OntapStorageConstants.ONTAP_SNAP_ID, "primary-ontap-snap"); + givenSnapshotDetail(primarySnapshotId, OntapStorageConstants.ONTAP_SNAP_NAME, "primary-snap"); + givenSnapshotDetail(primarySnapshotId, OntapStorageConstants.VOLUME_PATH, "/vol/flexvol-name/primary"); + givenSnapshotDetail(primarySnapshotId, OntapStorageConstants.LUN_DOT_UUID, "primary-lun-uuid"); + JobResponse job = new JobResponse(); + when(strategy.revertSnapshotForCloudStackVolume("primary-snap", "primary-flexvol", "primary-ontap-snap", + "/vol/flexvol-name/primary", "primary-lun-uuid", FLEXVOL_NAME)).thenReturn(job); + + CommandResult result = revertSnapshot(snapshotInfo, primarySnapshotInfo); + + assertNull(result.getResult()); + verify(strategy).revertSnapshotForCloudStackVolume("primary-snap", "primary-flexvol", "primary-ontap-snap", + "/vol/flexvol-name/primary", "primary-lun-uuid", FLEXVOL_NAME); + verify(strategy).executeCliSfsrRestore(eq(job), contains("revert snapshot [primary-snap]")); + } + + @Test + void revertSnapshot_fails_whenFlexVolUuidDetailMissing() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.BASE_ONTAP_FV_ID); + + assertMissingDetailFailure(revertSnapshot(snapshotInfo, null)); + } + + @Test + void revertSnapshot_fails_whenSnapshotNameDetailMissing() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.ONTAP_SNAP_NAME); + + assertMissingDetailFailure(revertSnapshot(snapshotInfo, null)); + } + + @Test + void revertSnapshot_fails_whenVolumePathDetailMissing() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.VOLUME_PATH); + + assertMissingDetailFailure(revertSnapshot(snapshotInfo, null)); + } + + @Test + void revertSnapshot_fails_whenPoolIdDetailMissing() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.PRIMARY_POOL_ID); + + assertMissingDetailFailure(revertSnapshot(snapshotInfo, null)); + } + + private void assertMissingDetailFailure(CommandResult result) { + assertNotNull(result.getResult()); + assertTrue(result.getResult().contains("Missing required snapshot details"), result.getResult()); + verify(strategy, never()).executeCliSfsrRestore(any(), anyString()); + } + + @Test + void revertSnapshot_fails_whenFlexVolNameMissingFromPoolDetails() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + poolDetails.remove(OntapStorageConstants.VOLUME_NAME); + + CommandResult result = revertSnapshot(snapshotInfo, null); + + assertTrue(result.getResult().contains("FlexVolume name not found"), result.getResult()); + verify(strategy, never()).executeCliSfsrRestore(any(), anyString()); + } + + @Test + void revertSnapshot_fails_whenFlexVolNameIsEmpty() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + poolDetails.put(OntapStorageConstants.VOLUME_NAME, ""); + + CommandResult result = revertSnapshot(snapshotInfo, null); + + assertTrue(result.getResult().contains("FlexVolume name not found"), result.getResult()); + verify(strategy, never()).executeCliSfsrRestore(any(), anyString()); + } + + @Test + void revertSnapshot_fails_whenPoolIdIsNotNumeric() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + givenSnapshotDetail(SNAPSHOT_ID, OntapStorageConstants.PRIMARY_POOL_ID, "not-a-number"); + + CommandResult result = revertSnapshot(snapshotInfo, null); + + assertTrue(result.getResult().contains("NumberFormatException"), result.getResult()); + assertTrue(result.getResult().contains("not-a-number"), result.getResult()); + verify(strategy, never()).revertSnapshotForCloudStackVolume( + anyString(), anyString(), anyString(), anyString(), any(), anyString()); + verify(strategy, never()).executeCliSfsrRestore(any(), anyString()); + } + + @Test + void revertSnapshot_fails_whenOntapRestoreCallThrows() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + when(strategy.revertSnapshotForCloudStackVolume(EXPECTED_SNAPSHOT_NAME, FLEXVOL_UUID, ONTAP_SNAP_UUID, + LUN_NAME, LUN_UUID, FLEXVOL_NAME)) + .thenThrow(new CloudRuntimeException("restore rejected")); + + CommandResult result = revertSnapshot(snapshotInfo, null); + + assertTrue(result.getResult().contains("restore rejected"), result.getResult()); + verify(strategy).revertSnapshotForCloudStackVolume(EXPECTED_SNAPSHOT_NAME, FLEXVOL_UUID, ONTAP_SNAP_UUID, + LUN_NAME, LUN_UUID, FLEXVOL_NAME); + verify(strategy, never()).executeCliSfsrRestore(any(), anyString()); + } + + @Test + void revertSnapshot_fails_whenCliRestoreFails() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + JobResponse job = new JobResponse(); + when(strategy.revertSnapshotForCloudStackVolume(EXPECTED_SNAPSHOT_NAME, FLEXVOL_UUID, ONTAP_SNAP_UUID, + LUN_NAME, LUN_UUID, FLEXVOL_NAME)).thenReturn(job); + doThrow(new CloudRuntimeException("sfsr failed")).when(strategy) + .executeCliSfsrRestore(eq(job), contains("revert snapshot [" + EXPECTED_SNAPSHOT_NAME + "]")); + + CommandResult result = revertSnapshot(snapshotInfo, null); + + assertTrue(result.getResult().contains("sfsr failed"), result.getResult()); + verify(strategy).revertSnapshotForCloudStackVolume(EXPECTED_SNAPSHOT_NAME, FLEXVOL_UUID, ONTAP_SNAP_UUID, + LUN_NAME, LUN_UUID, FLEXVOL_NAME); + verify(strategy).executeCliSfsrRestore(eq(job), contains("revert snapshot [" + EXPECTED_SNAPSHOT_NAME + "]")); + } + + // ------------------------------------- deleteAsync: volume snapshot branch + + private CommandResult deleteSnapshot() { + try (MockedStatic utils = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails)).thenReturn(strategy); + driver.deleteAsync(dataStore, snapshotInfo, commandCallback); + } + ArgumentCaptor captor = ArgumentCaptor.forClass(CommandResult.class); + verify(commandCallback).complete(captor.capture()); + return captor.getValue(); + } + + @Test + void deleteAsync_deletesFlexVolSnapshot_whenSnapshotDetailsPresent() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + assertNull(result.getResult()); + verify(strategy).deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + } + + @Test + void deleteAsync_isNoOpSuccess_whenFlexVolUuidDetailMissing() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.BASE_ONTAP_FV_ID); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + verify(strategy, never()).deleteFlexVolSnapshotForCloudStackVolume(anyString(), anyString(), anyString()); + } + + @Test + void deleteAsync_isNoOpSuccess_whenOntapSnapshotUuidDetailMissing() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.ONTAP_SNAP_ID); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + verify(strategy, never()).deleteFlexVolSnapshotForCloudStackVolume(anyString(), anyString(), anyString()); + } + + @Test + void deleteAsync_resolvesPoolFromVolume_whenPoolIdDetailMissing() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.PRIMARY_POOL_ID); + SnapshotVO snapshotVO = mock(SnapshotVO.class); + when(snapshotVO.getVolumeId()).thenReturn(VOLUME_ID); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(snapshotVO); + when(volumeDao.findByIdIncludingRemoved(VOLUME_ID)).thenReturn(volumeVO); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + verify(strategy).deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + } + + @Test + void deleteAsync_fallsBackToLastPoolId_whenVolumeHasNoCurrentPool() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.PRIMARY_POOL_ID); + SnapshotVO snapshotVO = mock(SnapshotVO.class); + when(snapshotVO.getVolumeId()).thenReturn(VOLUME_ID); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(snapshotVO); + when(volumeDao.findByIdIncludingRemoved(VOLUME_ID)).thenReturn(volumeVO); + when(volumeVO.getPoolId()).thenReturn(null); + long lastPoolId = 99L; + when(volumeVO.getLastPoolId()).thenReturn(lastPoolId); + when(storagePoolDetailsDao.listDetailsKeyPairs(lastPoolId)).thenReturn(poolDetails); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + assertNull(result.getResult()); + verify(storagePoolDetailsDao).listDetailsKeyPairs(lastPoolId); + verify(strategy).deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + } + + /** + * The "Snapshot not found" message raised while resolving the pool matches the generic + * "not found" check, so the delete is reported as an idempotent success and no ONTAP call is made. + */ + @Test + void deleteAsync_reportsSuccessWithoutOntapCall_whenPoolIdDetailMissingAndSnapshotNotFound() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.PRIMARY_POOL_ID); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(null); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + assertNull(result.getResult()); + verify(snapshotDao).findById(SNAPSHOT_ID); + verify(strategy, never()).deleteFlexVolSnapshotForCloudStackVolume(anyString(), anyString(), anyString()); + } + + /** + * The "CloudStack Volume not found" message matches the same generic "not found" check. + */ + @Test + void deleteAsync_reportsSuccessWithoutOntapCall_whenPoolIdDetailMissingAndVolumeNotFound() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.PRIMARY_POOL_ID); + SnapshotVO snapshotVO = mock(SnapshotVO.class); + when(snapshotVO.getVolumeId()).thenReturn(VOLUME_ID); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(snapshotVO); + when(volumeDao.findByIdIncludingRemoved(VOLUME_ID)).thenReturn(null); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + assertNull(result.getResult()); + verify(snapshotDao).findById(SNAPSHOT_ID); + verify(volumeDao).findByIdIncludingRemoved(VOLUME_ID); + verify(strategy, never()).deleteFlexVolSnapshotForCloudStackVolume(anyString(), anyString(), anyString()); + } + + @Test + void deleteAsync_fails_whenNoPoolCanBeResolvedForSnapshot() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.PRIMARY_POOL_ID); + SnapshotVO snapshotVO = mock(SnapshotVO.class); + when(snapshotVO.getVolumeId()).thenReturn(VOLUME_ID); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(snapshotVO); + when(volumeDao.findByIdIncludingRemoved(VOLUME_ID)).thenReturn(volumeVO); + when(volumeVO.getPoolId()).thenReturn(null); + when(volumeVO.getLastPoolId()).thenReturn(null); + + CommandResult result = deleteSnapshot(); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("Cannot resolve storage pool"), result.getResult()); + } + + @Test + void deleteAsync_fails_whenResolvedPoolIdIsNotPositive() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.PRIMARY_POOL_ID); + SnapshotVO snapshotVO = mock(SnapshotVO.class); + when(snapshotVO.getVolumeId()).thenReturn(VOLUME_ID); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(snapshotVO); + when(volumeDao.findByIdIncludingRemoved(VOLUME_ID)).thenReturn(volumeVO); + when(volumeVO.getPoolId()).thenReturn(0L); + + CommandResult result = deleteSnapshot(); + + assertFalse(result.isSuccess()); + assertTrue(result.getResult().contains("Cannot resolve storage pool"), result.getResult()); + } + + @Test + void deleteAsync_treatsHttp404AsAlreadyDeleted() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + FeignException notFound = mock(FeignException.class); + when(notFound.status()).thenReturn(404); + doThrow(notFound).when(strategy).deleteFlexVolSnapshotForCloudStackVolume(anyString(), anyString(), anyString()); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + assertNull(result.getResult()); + verify(strategy).deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + } + + @Test + void deleteAsync_treatsNotFoundMessageAsAlreadyDeleted() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + doThrow(new CloudRuntimeException("Snapshot entry doesn't exist")).when(strategy) + .deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + + CommandResult result = deleteSnapshot(); + + assertTrue(result.isSuccess()); + assertNull(result.getResult()); + verify(strategy).deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + } + + @Test + void deleteAsync_reportsFailure_whenOntapDeleteFailsForOtherReasons() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + doThrow(new CloudRuntimeException("volume busy")).when(strategy) + .deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + + CommandResult result = deleteSnapshot(); + + assertFalse(result.isSuccess()); + assertEquals("volume busy", result.getResult()); + verify(strategy).deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + } + + @Test + void deleteAsync_reportsFailure_whenStoreIsNull() { + driver.deleteAsync(null, snapshotInfo, commandCallback); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CommandResult.class); + verify(commandCallback).complete(captor.capture()); + assertFalse(captor.getValue().isSuccess()); + assertEquals("store or data is null", captor.getValue().getResult()); + } + + @Test + void deleteAsync_reportsFailure_whenDataIsNull() { + driver.deleteAsync(dataStore, null, commandCallback); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CommandResult.class); + verify(commandCallback).complete(captor.capture()); + assertFalse(captor.getValue().isSuccess()); + assertEquals("store or data is null", captor.getValue().getResult()); + verify(strategy, never()).deleteFlexVolSnapshotForCloudStackVolume(any(), any(), any()); + } + + @Test + void deleteAsync_toleratesNullCallback() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails)).thenReturn(strategy); + + driver.deleteAsync(dataStore, snapshotInfo, null); + } + + verify(strategy).deleteFlexVolSnapshotForCloudStackVolume(FLEXVOL_UUID, ONTAP_SNAP_UUID, EXPECTED_SNAPSHOT_NAME); + } + + @Test + void revertSnapshot_passesNullLunUuid_whenIscsiLunUuidDetailAbsent() { + givenRevertableSnapshot(SNAPSHOT_ID, ProtocolType.ISCSI.name()); + snapshotDetailStore.get(SNAPSHOT_ID).remove(OntapStorageConstants.LUN_DOT_UUID); + JobResponse job = new JobResponse(); + when(strategy.revertSnapshotForCloudStackVolume(EXPECTED_SNAPSHOT_NAME, FLEXVOL_UUID, ONTAP_SNAP_UUID, + LUN_NAME, null, FLEXVOL_NAME)).thenReturn(job); + + CommandResult result = revertSnapshot(snapshotInfo, null); + + assertNull(result.getResult()); + verify(strategy).revertSnapshotForCloudStackVolume(EXPECTED_SNAPSHOT_NAME, FLEXVOL_UUID, ONTAP_SNAP_UUID, + LUN_NAME, null, FLEXVOL_NAME); + verify(strategy).executeCliSfsrRestore(eq(job), contains("revert snapshot [" + EXPECTED_SNAPSHOT_NAME + "]")); + } + } } diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/lifecycle/OntapPrimaryDatastoreLifecycleTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/lifecycle/OntapPrimaryDatastoreLifecycleTest.java index de3e6bd9e234..82f7cab2fd64 100644 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/lifecycle/OntapPrimaryDatastoreLifecycleTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/lifecycle/OntapPrimaryDatastoreLifecycleTest.java @@ -79,6 +79,17 @@ import org.apache.cloudstack.storage.volume.datastore.PrimaryDataStoreHelper; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.junit.jupiter.api.Nested; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verifyNoInteractions; +import java.util.Collections; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDetailsDao; +import com.cloud.storage.StoragePoolAutomation; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import java.util.Arrays; @ExtendWith(MockitoExtension.class) @@ -1402,4 +1413,852 @@ public void testUpdateStoragePool_updateStorageVolumeThrows_propagatesCloudRunti } } + + /** + * Covers the maintenance, deletion, capacity-validation and passthrough operations of + * {@link OntapPrimaryDatastoreLifecycle} that {@link OntapPrimaryDatastoreLifecycleTest} does not reach. + */ + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + @Nested + class OntapPrimaryDatastoreLifecycleOperationsTest { + + private static final long POOL_ID = 77L; + + @InjectMocks + private OntapPrimaryDatastoreLifecycle lifecycle; + + @Mock private StorageManager _storageMgr; + @Mock private PrimaryDataStoreHelper _dataStoreHelper; + @Mock private PrimaryDataStoreDetailsDao _datastoreDetailsDao; + @Mock private StoragePoolAutomation _storagePoolAutomation; + @Mock private PrimaryDataStoreDao storagePoolDao; + @Mock private AlertManager _alertMgr; + @Mock private CapacityManager _capacityMgr; + @Mock private StorageStrategy storageStrategy; + @Mock private StoragePool storagePool; + + private DataStore store; + + @BeforeEach + void setUp() { + store = mock(DataStore.class, withSettings().extraInterfaces(PrimaryDataStoreInfo.class)); + when(store.getId()).thenReturn(POOL_ID); + when(storagePool.getId()).thenReturn(POOL_ID); + when(storagePool.getName()).thenReturn("ontap-pool"); + when(_storageMgr.getStoragePool(POOL_ID)).thenReturn(storagePool); + } + + private Map fullDetails() { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.VOLUME_UUID, "vol-uuid"); + details.put(OntapStorageConstants.VOLUME_NAME, "vol-name"); + return details; + } + + // ------------------------------------------------------------------ maintenance + + @Test + void maintain_marksPoolInMaintenance_onlyWhenAutomationSucceeds() { + when(_storagePoolAutomation.maintain(store)).thenReturn(true); + when(_dataStoreHelper.maintain(store)).thenReturn(true); + + assertTrue(lifecycle.maintain(store)); + verify(_dataStoreHelper).maintain(store); + } + + @Test + void maintain_returnsHelperResult_whenAutomationSucceedsButHelperFails() { + when(_storagePoolAutomation.maintain(store)).thenReturn(true); + when(_dataStoreHelper.maintain(store)).thenReturn(false); + + assertFalse(lifecycle.maintain(store)); + } + + @Test + void maintain_doesNotTouchPoolState_whenAutomationFails() { + when(_storagePoolAutomation.maintain(store)).thenReturn(false); + + assertFalse(lifecycle.maintain(store)); + verify(_dataStoreHelper, never()).maintain(store); + } + + @Test + void cancelMaintain_runsAutomationOnlyAfterHelperSucceeds() { + when(_dataStoreHelper.cancelMaintain(store)).thenReturn(true); + when(_storagePoolAutomation.cancelMaintain(store)).thenReturn(true); + + assertTrue(lifecycle.cancelMaintain(store)); + verify(_storagePoolAutomation).cancelMaintain(store); + } + + @Test + void cancelMaintain_returnsAutomationResult_whenAutomationFails() { + when(_dataStoreHelper.cancelMaintain(store)).thenReturn(true); + when(_storagePoolAutomation.cancelMaintain(store)).thenReturn(false); + + assertFalse(lifecycle.cancelMaintain(store)); + } + + @Test + void cancelMaintain_skipsAutomation_whenHelperFails() { + when(_dataStoreHelper.cancelMaintain(store)).thenReturn(false); + + assertFalse(lifecycle.cancelMaintain(store)); + verifyNoInteractions(_storagePoolAutomation); + } + + // ------------------------------------------------------------------ simple delegations + + @Test + void enableAndDisable_delegateToDataStoreHelper() { + lifecycle.enableStoragePool(store); + lifecycle.disableStoragePool(store); + + verify(_dataStoreHelper).enable(store); + verify(_dataStoreHelper).disable(store); + } + + @Test + void migrateToObjectStore_isNotSupported() { + assertFalse(lifecycle.migrateToObjectStore(store)); + } + + @Test + void scopeChanges_areNoOps() { + ClusterScope clusterScope = mock(ClusterScope.class); + + lifecycle.changeStoragePoolScopeToZone(store, clusterScope, Hypervisor.HypervisorType.KVM); + lifecycle.changeStoragePoolScopeToCluster(store, clusterScope, Hypervisor.HypervisorType.KVM); + + verifyNoInteractions(_dataStoreHelper, _storagePoolAutomation, _datastoreDetailsDao); + } + + // ------------------------------------------------------------------ deleteDataStore + + @Test + void deleteDataStore_succeedsWithoutTouchingOntap_whenPoolAlreadyGone() { + when(_storageMgr.getStoragePool(POOL_ID)).thenReturn(null); + + assertTrue(lifecycle.deleteDataStore(store)); + + verify(_dataStoreHelper, never()).deletePrimaryDataStore(any()); + verifyNoInteractions(_datastoreDetailsDao); + } + + @Test + void deleteDataStore_onlyRemovesCloudStackEntity_whenPoolHasNoDetails() { + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(Collections.emptyMap()); + when(_dataStoreHelper.deletePrimaryDataStore(store)).thenReturn(true); + + assertTrue(lifecycle.deleteDataStore(store)); + verify(_dataStoreHelper).deletePrimaryDataStore(store); + + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(null); + assertTrue(lifecycle.deleteDataStore(store)); + } + + @Test + void deleteDataStore_removesOntapVolumeAndAccessGroupBeforeCloudStackEntity() { + Map details = fullDetails(); + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(details); + when(_dataStoreHelper.deletePrimaryDataStore(store)).thenReturn(true); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(storageStrategy); + + assertTrue(lifecycle.deleteDataStore(store)); + } + + ArgumentCaptor volume = ArgumentCaptor.forClass(Volume.class); + verify(storageStrategy).deleteStorageVolume(volume.capture()); + assertEquals("vol-uuid", volume.getValue().getUuid()); + assertEquals("vol-name", volume.getValue().getName()); + ArgumentCaptor group = ArgumentCaptor.forClass(AccessGroup.class); + verify(storageStrategy).deleteAccessGroup(group.capture()); + assertEquals(POOL_ID, group.getValue().getStoragePoolId()); + verify((PrimaryDataStoreInfo) store).setDetails(details); + verify(_dataStoreHelper).deletePrimaryDataStore(store); + } + + @Test + void deleteDataStore_skipsVolumeDeletion_butStillCleansUp_whenVolumeIdentityMissing() { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.VOLUME_NAME, "vol-name"); + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(details); + when(_dataStoreHelper.deletePrimaryDataStore(store)).thenReturn(true); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(storageStrategy); + + assertTrue(lifecycle.deleteDataStore(store)); + } + + verify(storageStrategy, never()).deleteStorageVolume(any(Volume.class)); + verify(storageStrategy).deleteAccessGroup(any(AccessGroup.class)); + verify(_dataStoreHelper).deletePrimaryDataStore(store); + } + + @Test + void deleteDataStore_continuesWithAccessGroupAndEntity_whenOntapVolumeDeletionFails() { + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(fullDetails()); + when(_dataStoreHelper.deletePrimaryDataStore(store)).thenReturn(true); + doThrow(new CloudRuntimeException("volume busy")).when(storageStrategy).deleteStorageVolume(any(Volume.class)); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(storageStrategy); + + assertTrue(lifecycle.deleteDataStore(store)); + } + + verify(storageStrategy).deleteAccessGroup(any(AccessGroup.class)); + verify(_dataStoreHelper).deletePrimaryDataStore(store); + } + + @Test + void deleteDataStore_stillRemovesCloudStackEntity_whenAccessGroupCleanupFails() { + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(fullDetails()); + when(_dataStoreHelper.deletePrimaryDataStore(store)).thenReturn(true); + doThrow(new CloudRuntimeException("igroup in use")).when(storageStrategy).deleteAccessGroup(any(AccessGroup.class)); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(storageStrategy); + + assertTrue(lifecycle.deleteDataStore(store)); + } + + verify(_dataStoreHelper).deletePrimaryDataStore(store); + } + + @Test + void deleteDataStore_stillRemovesCloudStackEntity_whenOntapIsUnreachable() { + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(fullDetails()); + when(_dataStoreHelper.deletePrimaryDataStore(store)).thenReturn(true); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())) + .thenThrow(new CloudRuntimeException("cannot connect")); + + assertTrue(lifecycle.deleteDataStore(store)); + } + + verifyNoInteractions(storageStrategy); + verify(_dataStoreHelper).deletePrimaryDataStore(store); + } + + @Test + void deleteDataStore_reportsFailure_whenCloudStackEntityCannotBeDeleted() { + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(Collections.emptyMap()); + when(_dataStoreHelper.deletePrimaryDataStore(store)).thenReturn(false); + + assertFalse(lifecycle.deleteDataStore(store)); + } + + // ------------------------------------------------------------------ updateStoragePool: IOPS validation + + private Map iopsUpdate(String iops) { + Map details = new HashMap<>(); + details.put(PrimaryDataStoreLifeCycle.CAPACITY_IOPS, iops); + return details; + } + + @Test + void updateStoragePool_rejectsNonNumericIops() { + InvalidParameterValueException ex = assertThrows(InvalidParameterValueException.class, + () -> lifecycle.updateStoragePool(storagePool, iopsUpdate("lots"))); + + assertTrue(ex.getMessage().contains("Invalid storage pool IOPS capacity"), ex.getMessage()); + } + + @Test + void updateStoragePool_rejectsZeroOrNegativeIops() { + assertEquals("Storage pool IOPS capacity must be greater than 0", + assertThrows(InvalidParameterValueException.class, + () -> lifecycle.updateStoragePool(storagePool, iopsUpdate("0"))).getMessage()); + assertEquals("Storage pool IOPS capacity must be greater than 0", + assertThrows(InvalidParameterValueException.class, + () -> lifecycle.updateStoragePool(storagePool, iopsUpdate("-10"))).getMessage()); + verifyNoInteractions(storagePoolDao); + } + + @Test + void updateStoragePool_rejectsIopsForUnknownPool() { + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + + InvalidParameterValueException ex = assertThrows(InvalidParameterValueException.class, + () -> lifecycle.updateStoragePool(storagePool, iopsUpdate("1000"))); + + assertTrue(ex.getMessage().contains("Storage pool not found"), ex.getMessage()); + } + + @Test + void updateStoragePool_rejectsIopsBelowAllocatedIops() { + StoragePoolVO poolVO = mock(StoragePoolVO.class); + when(storagePoolDao.findById(POOL_ID)).thenReturn(poolVO); + when(_capacityMgr.getUsedIops(poolVO)).thenReturn(5000L); + + InvalidParameterValueException ex = assertThrows(InvalidParameterValueException.class, + () -> lifecycle.updateStoragePool(storagePool, iopsUpdate("4999"))); + + assertTrue(ex.getMessage().contains("5000 IOPS are already allocated"), ex.getMessage()); + } + + @Test + void updateStoragePool_acceptsIopsEqualToAllocated_andSkipsResizeWithoutCapacityChange() { + StoragePoolVO poolVO = mock(StoragePoolVO.class); + when(storagePoolDao.findById(POOL_ID)).thenReturn(poolVO); + when(_capacityMgr.getUsedIops(poolVO)).thenReturn(5000L); + + lifecycle.updateStoragePool(storagePool, iopsUpdate("5000")); + + verify(_capacityMgr).getUsedIops(poolVO); + verify(storagePool, never()).getCapacityBytes(); + } + + @Test + void updateStoragePool_doesNothing_whenNoRelevantDetailsChange() { + lifecycle.updateStoragePool(storagePool, new HashMap<>()); + + verifyNoInteractions(storagePoolDao, _capacityMgr); + verify(storagePool, never()).getCapacityBytes(); + } + + @Test + void updateStoragePool_failsToResize_whenFlexVolUuidMissing() { + Map details = new HashMap<>(); + details.put(PrimaryDataStoreLifeCycle.CAPACITY_BYTES, "1073741824"); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(storageStrategy); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> lifecycle.updateStoragePool(storagePool, details)); + + assertTrue(ex.getMessage().contains("Volume UUID or name not found"), ex.getMessage()); + } + verify(storageStrategy, never()).updateStorageVolume(any(Volume.class)); + } + + @Test + void updateStoragePool_resizesFlexVol_toRequestedCapacity() { + Map details = fullDetails(); + details.put(PrimaryDataStoreLifeCycle.CAPACITY_BYTES, "2147483648"); + when(storagePool.getCapacityBytes()).thenReturn(1073741824L); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(storageStrategy); + + lifecycle.updateStoragePool(storagePool, details); + } + + ArgumentCaptor volume = ArgumentCaptor.forClass(Volume.class); + verify(storageStrategy).updateStorageVolume(volume.capture()); + assertEquals("vol-uuid", volume.getValue().getUuid()); + assertEquals("vol-name", volume.getValue().getName()); + assertEquals(2147483648L, volume.getValue().getSize()); + } + + @Test + void updateStoragePool_wrapsResizeFailure() { + Map details = fullDetails(); + details.put(PrimaryDataStoreLifeCycle.CAPACITY_BYTES, "2147483648"); + doThrow(new CloudRuntimeException("resize rejected")).when(storageStrategy).updateStorageVolume(any(Volume.class)); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(storageStrategy); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> lifecycle.updateStoragePool(storagePool, details)); + + assertTrue(ex.getMessage().contains("ontap-pool"), ex.getMessage()); + assertTrue(ex.getMessage().contains("resize rejected"), ex.getMessage()); + } + } + + @Test + void updateStoragePool_rejectsNonNumericCapacity() { + Map details = fullDetails(); + details.put(PrimaryDataStoreLifeCycle.CAPACITY_BYTES, "big"); + when(storagePool.getCapacityBytes()).thenReturn(1L); + + assertThrows(NumberFormatException.class, () -> lifecycle.updateStoragePool(storagePool, details)); + } + } + + /** + * Input validation, zone-wide creation, protocol-specific host selection and delete edge cases of + * {@link OntapPrimaryDatastoreLifecycle}, complementing {@link OntapPrimaryDatastoreLifecycleTest}. + */ + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + @Nested + class OntapPrimaryDatastoreLifecycleScopeTest { + + private static final long POOL_ID = 1L; + + @InjectMocks + private OntapPrimaryDatastoreLifecycle lifecycle; + + @Mock private ClusterDao _clusterDao; + @Mock private StorageStrategy storageStrategy; + @Mock private PrimaryDataStoreHelper _dataStoreHelper; + @Mock private ResourceManager _resourceMgr; + @Mock private StorageManager _storageMgr; + @Mock private StoragePoolDetailsDao storagePoolDetailsDao; + @Mock private PrimaryDataStoreDetailsDao _datastoreDetailsDao; + @Mock private PrimaryDataStoreDao storagePoolDao; + @Mock private AlertManager _alertMgr; + @Mock private ClusterScope clusterScope; + @Mock private ZoneScope zoneScope; + @Mock private StoragePool storagePool; + + private DataStore dataStore; + private Map poolDetails; + + @BeforeEach + void setUp() { + dataStore = mock(DataStore.class, withSettings().extraInterfaces(PrimaryDataStoreInfo.class)); + when(dataStore.getId()).thenReturn(POOL_ID); + when(((PrimaryDataStoreInfo) dataStore).getClusterId()).thenReturn(1L); + + ClusterVO clusterVO = new ClusterVO(1L, 1L, "clusterName"); + clusterVO.setHypervisorType("KVM"); + when(_clusterDao.findById(1L)).thenReturn(clusterVO); + + when(storageStrategy.connect()).thenReturn(true); + Aggregate aggregate = new Aggregate(); + aggregate.setName("aggr1"); + aggregate.setUuid("aggr-uuid-1"); + when(storageStrategy.chooseAggregate(any(), any())).thenReturn(aggregate); + when(storageStrategy.getNetworkInterface(any())).thenReturn(Map.of(OntapStorageConstants.DATA_LIF, "10.1.1.1")); + Volume volume = new Volume(); + volume.setUuid("vol-uuid"); + volume.setName("vol-name"); + when(storageStrategy.createStorageVolume(any(), any(), any())).thenReturn(volume); + + StoragePoolVO poolVO = new StoragePoolVO(); + poolVO.setId(POOL_ID); + when(storagePoolDao.findById(POOL_ID)).thenReturn(poolVO); + when(zoneScope.getScopeId()).thenReturn(1L); + + poolDetails = new HashMap<>(); + poolDetails.put(OntapStorageConstants.USERNAME, "admin"); + poolDetails.put(OntapStorageConstants.PASSWORD, "password"); + poolDetails.put(OntapStorageConstants.SVM_NAME, "svm1"); + poolDetails.put(OntapStorageConstants.PROTOCOL, "NFS3"); + poolDetails.put(OntapStorageConstants.STORAGE_IP, "10.0.0.1"); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(poolDetails); + } + + // ---------------------------------------------------------------- initialize + + private Map dsInfos() { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.USERNAME, "user"); + details.put(OntapStorageConstants.PASSWORD, "pass"); + details.put(OntapStorageConstants.STORAGE_IP, "10.10.10.10"); + details.put(OntapStorageConstants.SVM_NAME, "vs0"); + details.put(OntapStorageConstants.PROTOCOL, "NFS3"); + + Map infos = new HashMap<>(); + infos.put("zoneId", 1L); + infos.put("podId", 1L); + infos.put("clusterId", 1L); + infos.put("name", "pool1"); + infos.put("providerName", "NetApp ONTAP"); + infos.put("capacityBytes", 1073741824L); + infos.put("managed", true); + infos.put("tags", "tag"); + infos.put("isTagARule", false); + infos.put("details", details); + return infos; + } + + @SuppressWarnings("unchecked") + private Map detailsOf(Map infos) { + return (Map) infos.get("details"); + } + + private void initialize(Map infos) { + try (MockedStatic factory = mockStatic(StorageProviderFactory.class)) { + factory.when(() -> StorageProviderFactory.getStrategy(any())).thenReturn(storageStrategy); + lifecycle.initialize(infos); + } + } + + private PrimaryDataStoreParameters initializeAndCaptureParameters(Map infos) { + initialize(infos); + ArgumentCaptor captor = ArgumentCaptor.forClass(PrimaryDataStoreParameters.class); + verify(_dataStoreHelper).createPrimaryDataStore(captor.capture()); + return captor.getValue(); + } + + @Test + void initializeFailsWhenOntapConnectionIsRejected() { + when(storageStrategy.connect()).thenReturn(false); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> initialize(dsInfos())); + + assertTrue(thrown.getMessage().contains("details validation failed"), thrown.getMessage()); + verify(_dataStoreHelper, never()).createPrimaryDataStore(any()); + } + + @Test + void initializeWrapsAggregateSelectionFailure() { + when(storageStrategy.chooseAggregate(any(), any())).thenThrow(new RuntimeException("no aggregate has space")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> initialize(dsInfos())); + + assertTrue(thrown.getMessage().contains("Failed to choose ONTAP aggregate for pool: pool1"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("no aggregate has space"), thrown.getMessage()); + } + + @Test + void initializeRecordsResolvedSvmUuidOnlyWhenKnown() { + when(storageStrategy.getResolvedSvmUuid()).thenReturn("svm-uuid-1"); + PrimaryDataStoreParameters withUuid = initializeAndCaptureParameters(dsInfos()); + assertEquals("svm-uuid-1", withUuid.getDetails().get(OntapStorageConstants.SVM_UUID)); + } + + @Test + void initializeSkipsSvmUuidWhenResolvedValueIsNullOrEmpty() { + when(storageStrategy.getResolvedSvmUuid()).thenReturn(null); + assertNull(initializeAndCaptureParameters(dsInfos()).getDetails().get(OntapStorageConstants.SVM_UUID)); + } + + @Test + void initializeSkipsSvmUuidWhenResolvedValueIsEmpty() { + when(storageStrategy.getResolvedSvmUuid()).thenReturn(""); + assertNull(initializeAndCaptureParameters(dsInfos()).getDetails().get(OntapStorageConstants.SVM_UUID)); + } + + @Test + void initializeCreatesZoneWideStorageWhenNoPodOrCluster() { + Map infos = dsInfos(); + infos.put("podId", null); + infos.put("clusterId", null); + + PrimaryDataStoreParameters parameters = initializeAndCaptureParameters(infos); + + assertNull(parameters.getClusterId()); + assertNull(parameters.getPodId()); + assertEquals(Long.valueOf(1L), parameters.getZoneId()); + assertNull(parameters.getHypervisorType()); + } + + @Test + void initializeFailsWhenClusterDoesNotExist() { + Map infos = dsInfos(); + infos.put("clusterId", 99L); + + NullPointerException thrown = assertThrows(NullPointerException.class, () -> initialize(infos)); + + assertTrue(thrown.getMessage().contains("Unable to locate the specified cluster"), thrown.getMessage()); + } + + @Test + void initializeRejectsMissingCapacity() { + Map infos = dsInfos(); + infos.remove("capacityBytes"); + + InvalidParameterValueException thrown = assertThrows(InvalidParameterValueException.class, () -> initialize(infos)); + + assertTrue(thrown.getMessage().contains("capacity is required"), thrown.getMessage()); + } + + @Test + void initializeRejectsPodWithoutClusterAndClusterWithoutPod() { + Map podOnly = dsInfos(); + podOnly.put("clusterId", null); + assertThrows(CloudRuntimeException.class, () -> initialize(podOnly)); + + Map clusterOnly = dsInfos(); + clusterOnly.put("podId", null); + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> initialize(clusterOnly)); + assertTrue(thrown.getMessage().contains("Cluster Id or Pod Id is null"), thrown.getMessage()); + } + + @Test + void initializeRejectsBlankDetailValue() { + Map infos = dsInfos(); + detailsOf(infos).put(OntapStorageConstants.USERNAME, " "); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> initialize(infos)); + + assertTrue(thrown.getMessage().contains("empty detail: " + OntapStorageConstants.USERNAME), thrown.getMessage()); + } + + @Test + void initializeRejectsZoneIdMissingWhenPodAndClusterAreAlsoMissing() { + Map infos = dsInfos(); + infos.put("podId", null); + infos.put("clusterId", null); + infos.put("zoneId", null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> initialize(infos)); + + assertTrue(thrown.getMessage().contains("all null"), thrown.getMessage()); + } + + // ---------------------------------------------------------------- argument checks on attach + + @Test + void attachClusterRejectsMissingArgumentsAndUnknownPool() { + assertThrows(InvalidParameterValueException.class, () -> lifecycle.attachCluster(null, clusterScope)); + assertThrows(InvalidParameterValueException.class, () -> lifecycle.attachCluster(dataStore, null)); + + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> lifecycle.attachCluster(dataStore, clusterScope)); + assertTrue(thrown.getMessage().contains("Storage Pool not found"), thrown.getMessage()); + } + + @Test + void attachZoneRejectsMissingArgumentsAndUnknownPool() { + assertThrows(InvalidParameterValueException.class, + () -> lifecycle.attachZone(null, zoneScope, Hypervisor.HypervisorType.KVM)); + assertThrows(InvalidParameterValueException.class, + () -> lifecycle.attachZone(dataStore, null, Hypervisor.HypervisorType.KVM)); + + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> lifecycle.attachZone(dataStore, zoneScope, Hypervisor.HypervisorType.KVM)); + assertTrue(thrown.getMessage().contains("Storage Pool not found"), thrown.getMessage()); + } + + @Test + void attachHostIsNotSupported() { + assertFalse(lifecycle.attachHost(dataStore, null, null)); + } + + // ---------------------------------------------------------------- host selection per protocol + + private HostVO host(String storageUrl, String storageIp, String privateIp) { + HostVO host = mock(HostVO.class); + when(host.getStorageUrl()).thenReturn(storageUrl); + when(host.getStorageIpAddress()).thenReturn(storageIp); + when(host.getPrivateIpAddress()).thenReturn(privateIp); + return host; + } + + private boolean attachClusterWith(List hosts) throws Exception { + when(_resourceMgr.getEligibleUpAndEnabledHostsInClusterForStorageConnection(any())).thenReturn(hosts); + when(_storageMgr.connectHostToSharedPool(any(), anyLong())).thenReturn(true); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(storageStrategy); + return lifecycle.attachCluster(dataStore, clusterScope); + } + } + + private AccessGroup captureAccessGroup() { + ArgumentCaptor captor = ArgumentCaptor.forClass(AccessGroup.class); + verify(storageStrategy).createAccessGroup(captor.capture()); + return captor.getValue(); + } + + @Test + void attachClusterWithIscsiSkipsExportPolicyAndStillConnectsEveryHost() throws Exception { + poolDetails.put(OntapStorageConstants.PROTOCOL, "ISCSI"); + List hosts = Arrays.asList( + host("iqn.1994-05.com.redhat:a", null, "10.0.0.5"), + host(null, null, "10.0.0.6"), + host(" ", null, "10.0.0.7"), + host("nfs://not-an-iqn", null, "10.0.0.8"), + null); + + assertTrue(attachClusterWith(hosts)); + + verify(storageStrategy, never()).createAccessGroup(any()); + verify(_storageMgr, times(5)).connectHostToSharedPool(any(), anyLong()); + verify(_dataStoreHelper).attachCluster(dataStore); + } + + @Test + void attachClusterWithNfsUsesStorageIpThenPrivateIpAndSkipsHostsWithoutAddress() throws Exception { + List hosts = Arrays.asList( + host(null, " 192.168.0.5 ", "10.0.0.5"), + host(null, null, "10.0.0.6"), + host(null, "", null), + host(null, " ", " "), + null); + + assertTrue(attachClusterWith(hosts)); + + AccessGroup group = captureAccessGroup(); + assertEquals(5, group.getHostsToConnect().size()); + assertSame(clusterScope, group.getScope()); + assertEquals(POOL_ID, group.getStoragePoolId()); + } + + @Test + void attachClusterWithNfsSkipsExportPolicyWhenNoHostHasAnAddress() throws Exception { + List hosts = new ArrayList<>(); + hosts.add(host(null, null, null)); + + assertTrue(attachClusterWith(hosts)); + + verify(storageStrategy, never()).createAccessGroup(any()); + } + + @Test + void attachClusterFailsWhenExportPolicyCannotBeCreated() throws Exception { + when(storageStrategy.createAccessGroup(any())).thenThrow(new RuntimeException("export policy rejected")); + List hosts = new ArrayList<>(); + hosts.add(host(null, "10.0.0.5", null)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> attachClusterWith(hosts)); + + assertTrue(thrown.getMessage().contains("Failed to create NFS access group"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("export policy rejected"), thrown.getMessage()); + verify(_dataStoreHelper, never()).attachCluster(any()); + } + + @Test + void attachZoneWithIscsiConnectsHostsAndReportsConnectFailure() throws Exception { + poolDetails.put(OntapStorageConstants.PROTOCOL, "ISCSI"); + List hosts = new ArrayList<>(); + hosts.add(host("iqn.1994-05.com.redhat:a", null, "10.0.0.5")); + when(_resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(any(), anyLong(), any())).thenReturn(hosts); + when(_storageMgr.connectHostToSharedPool(any(), anyLong())).thenReturn(true); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(storageStrategy); + assertTrue(lifecycle.attachZone(dataStore, zoneScope, Hypervisor.HypervisorType.KVM)); + verify(storageStrategy, never()).createAccessGroup(any()); + + when(_storageMgr.connectHostToSharedPool(any(), anyLong())).thenThrow(new RuntimeException("connect failed")); + assertFalse(lifecycle.attachZone(dataStore, zoneScope, Hypervisor.HypervisorType.KVM)); + } + } + + // ---------------------------------------------------------------- deleteDataStore volume identity + + @Test + void deleteDataStoreSkipsOntapVolumeDeleteWhenIdentityIsIncomplete() { + when(_storageMgr.getStoragePool(POOL_ID)).thenReturn(storagePool); + when(storagePool.getName()).thenReturn("ontap-pool"); + + String[][] identities = {{null, "name"}, {"", "name"}, {"uuid", null}, {"uuid", ""}}; + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(storageStrategy); + for (String[] identity : identities) { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.PROTOCOL, "NFS3"); + if (identity[0] != null) { + details.put(OntapStorageConstants.VOLUME_UUID, identity[0]); + } + if (identity[1] != null) { + details.put(OntapStorageConstants.VOLUME_NAME, identity[1]); + } + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(details); + when(_dataStoreHelper.deletePrimaryDataStore(dataStore)).thenReturn(true); + + assertTrue(lifecycle.deleteDataStore(dataStore)); + } + } + + verify(storageStrategy, never()).deleteStorageVolume(any()); + verify(storageStrategy, times(identities.length)).deleteAccessGroup(any()); + } + + // ------------------------------------------------- initialize: pool parameters and boundaries + + @Test + void initializeBuildsNfsPoolParametersFromTheRequestAndReturnsTheCreatedStore() { + DataStore created = mock(DataStore.class); + when(_dataStoreHelper.createPrimaryDataStore(any())).thenReturn(created); + Map infos = dsInfos(); + infos.put("isTagARule", true); + infos.put("capacityIops", 3000L); + DataStore returned; + try (MockedStatic factory = mockStatic(StorageProviderFactory.class)) { + factory.when(() -> StorageProviderFactory.getStrategy(any())).thenReturn(storageStrategy); + returned = lifecycle.initialize(infos); + } + ArgumentCaptor captor = ArgumentCaptor.forClass(PrimaryDataStoreParameters.class); + verify(_dataStoreHelper).createPrimaryDataStore(captor.capture()); + PrimaryDataStoreParameters p = captor.getValue(); + + assertSame(created, returned); + assertEquals(Hypervisor.HypervisorType.KVM, p.getHypervisorType()); + assertEquals("10.1.1.1", p.getHost()); + assertEquals(OntapStorageConstants.NFS3_PORT, p.getPort()); + assertEquals("/pool1", p.getPath()); + assertEquals(com.cloud.storage.Storage.StoragePoolType.NetworkFilesystem, p.getType()); + assertEquals("tag", p.getTags()); + assertEquals(Boolean.TRUE, p.isTagARule()); + assertNotNull(p.getUuid()); + assertEquals(java.util.UUID.fromString(p.getUuid()).toString(), p.getUuid()); + assertEquals(Long.valueOf(1L), p.getZoneId()); + assertEquals(Long.valueOf(1L), p.getPodId()); + assertEquals(Long.valueOf(1L), p.getClusterId()); + assertEquals("pool1", p.getName()); + assertEquals("NetApp ONTAP", p.getProviderName()); + assertTrue(p.isManaged()); + assertEquals(1073741824L, p.getCapacityBytes()); + assertEquals(Long.valueOf(3000L), p.getCapacityIops()); + assertEquals(0L, p.getUsedBytes()); + assertEquals("1073741824", p.getDetails().get(OntapStorageConstants.SIZE)); + assertEquals("vol-uuid", p.getDetails().get(OntapStorageConstants.VOLUME_UUID)); + assertEquals("vol-name", p.getDetails().get(OntapStorageConstants.VOLUME_NAME)); + } + + @Test + void initializeBuildsIscsiPoolParametersWithTheOntapTargetPath() { + when(storageStrategy.getStoragePath()).thenReturn("iqn.1992-08.com.netapp:sn.abc"); + Map infos = dsInfos(); + detailsOf(infos).put(OntapStorageConstants.PROTOCOL, "ISCSI"); + + PrimaryDataStoreParameters p = initializeAndCaptureParameters(infos); + + assertEquals(com.cloud.storage.Storage.StoragePoolType.OntapiSCSI, p.getType()); + assertEquals("iqn.1992-08.com.netapp:sn.abc", p.getPath()); + assertEquals(OntapStorageConstants.ISCSI_PORT, p.getPort()); + assertEquals("10.1.1.1", p.getHost()); + } + + @Test + void initializeAcceptsExactlyTheMinimumCapacityAndRejectsOneByteLess() { + long min = 20971520L; + Map atMin = dsInfos(); + atMin.put("capacityBytes", min); + assertEquals(min, initializeAndCaptureParameters(atMin).getCapacityBytes()); + + Map below = dsInfos(); + below.put("capacityBytes", min - 1); + InvalidParameterValueException thrown = assertThrows(InvalidParameterValueException.class, () -> initialize(below)); + assertTrue(thrown.getMessage().contains("below the ONTAP minimum"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains(String.valueOf(min - 1)), thrown.getMessage()); + } + + @Test + void initializeRejectsZeroCapacityWithTheRequiredMessage() { + Map zero = dsInfos(); + zero.put("capacityBytes", 0L); + + InvalidParameterValueException thrown = assertThrows(InvalidParameterValueException.class, () -> initialize(zero)); + + assertTrue(thrown.getMessage().contains("capacity is required"), thrown.getMessage()); + } + + @Test + void initializeAcceptsOneIopsAndRejectsZero() { + Map one = dsInfos(); + one.put("capacityIops", 1L); + assertEquals(Long.valueOf(1L), initializeAndCaptureParameters(one).getCapacityIops()); + + Map zero = dsInfos(); + zero.put("capacityIops", 0L); + assertThrows(InvalidParameterValueException.class, () -> initialize(zero)); + } + + @Test + void deleteDataStoreReportsFailureWhenOntapCleanupSucceedsButCloudStackDeleteFails() { + when(_storageMgr.getStoragePool(POOL_ID)).thenReturn(storagePool); + when(storagePool.getName()).thenReturn("ontap-pool"); + Map details = new HashMap<>(); + details.put(OntapStorageConstants.PROTOCOL, "NFS3"); + details.put(OntapStorageConstants.VOLUME_UUID, "vol-uuid"); + details.put(OntapStorageConstants.VOLUME_NAME, "vol-name"); + when(_datastoreDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(details); + when(_dataStoreHelper.deletePrimaryDataStore(dataStore)).thenReturn(false); + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(storageStrategy); + + assertFalse(lifecycle.deleteDataStore(dataStore)); + } + verify(storageStrategy).deleteStorageVolume(any()); + } + } } diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/listener/OntapHostListenerTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/listener/OntapHostListenerTest.java new file mode 100644 index 000000000000..dea8418818de --- /dev/null +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/listener/OntapHostListenerTest.java @@ -0,0 +1,648 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.listener; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.cloudstack.storage.service.StorageStrategy; +import org.apache.cloudstack.storage.service.model.AccessGroup; +import org.apache.cloudstack.storage.utils.OntapStorageConstants; +import org.apache.cloudstack.storage.utils.OntapStorageUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.ModifyStoragePoolAnswer; +import com.cloud.agent.api.ModifyStoragePoolCommand; +import com.cloud.agent.api.StoragePoolInfo; +import com.cloud.alert.AlertManager; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.storage.StoragePoolHostVO; +import com.cloud.storage.dao.StoragePoolHostDao; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class OntapHostListenerTest { + + private static final long HOST_ID = 11L; + private static final long POOL_ID = 22L; + private static final String LOCAL_PATH = "/mnt/ontap-pool"; + private static final long GB = 1024L * 1024L * 1024L; + + @Mock + private AgentManager agentMgr; + @Mock + private AlertManager alertMgr; + @Mock + private PrimaryDataStoreDao storagePoolDao; + @Mock + private HostDao hostDao; + @Mock + private StoragePoolHostDao storagePoolHostDao; + @Mock + private StoragePoolDetailsDao storagePoolDetailsDao; + + @Mock + private HostVO host; + @Mock + private StoragePoolVO pool; + @Mock + private StorageStrategy strategy; + + @InjectMocks + private OntapHostListener listener; + + // ------------------------------------------------------------ helpers + + private void givenKvmHost() { + when(hostDao.findById(HOST_ID)).thenReturn(host); + when(host.getHypervisorType()).thenReturn(HypervisorType.KVM); + when(host.getName()).thenReturn("kvm-host-1"); + when(host.getId()).thenReturn(HOST_ID); + when(host.getStorageIpAddress()).thenReturn("10.0.0.5"); + when(host.getPrivateIpAddress()).thenReturn("192.168.0.5"); + } + + private void givenPool() { + when(storagePoolDao.findById(POOL_ID)).thenReturn(pool); + when(pool.getId()).thenReturn(POOL_ID); + when(pool.getName()).thenReturn("ontap-pool"); + when(pool.getPoolType()).thenReturn(StoragePoolType.NetworkFilesystem); + } + + private Map details(String protocol) { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.SVM_NAME, "svm1"); + if (protocol != null) { + details.put(OntapStorageConstants.PROTOCOL, protocol); + } + return details; + } + + private void givenDetails(String protocol) { + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(details(protocol)); + } + + private ModifyStoragePoolAnswer givenSuccessfulAnswer(long capacityBytes, long availableBytes) { + ModifyStoragePoolAnswer answer = mock(ModifyStoragePoolAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getPoolInfo()).thenReturn(new StoragePoolInfo("uuid", "host", "/path", LOCAL_PATH, + StoragePoolType.NetworkFilesystem, capacityBytes, availableBytes)); + when(agentMgr.easySend(eq(HOST_ID), any(ModifyStoragePoolCommand.class))).thenReturn(answer); + return answer; + } + + private void givenReadyToConnect(String protocol) { + givenKvmHost(); + givenPool(); + givenDetails(protocol); + } + + // ------------------------------------------------- hostConnect: negative + + @Test + public void hostConnect_returnsFalse_whenHostNotFound() { + when(hostDao.findById(HOST_ID)).thenReturn(null); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(storagePoolDao, never()).findById(anyLong()); + verifyNoInteractions(agentMgr); + } + + @Test + public void hostConnect_returnsFalse_whenHostIsNotKvm() { + when(hostDao.findById(HOST_ID)).thenReturn(host); + when(host.getHypervisorType()).thenReturn(HypervisorType.VMware); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(storagePoolDao, never()).findById(anyLong()); + verifyNoInteractions(agentMgr); + } + + @Test + public void hostConnect_returnsFalse_whenPoolNotFound() { + givenKvmHost(); + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verifyNoInteractions(agentMgr); + verifyNoInteractions(storagePoolDetailsDao); + } + + @Test + public void hostConnect_returnsFalse_whenPoolDetailsAreNull() { + givenKvmHost(); + givenPool(); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(null); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verifyNoInteractions(agentMgr); + } + + @Test + public void hostConnect_returnsFalse_whenPoolDetailsAreEmpty() { + givenKvmHost(); + givenPool(); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(Collections.emptyMap()); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verifyNoInteractions(agentMgr); + } + + @Test + public void hostConnect_returnsFalse_whenProtocolDetailMissing() { + givenReadyToConnect(null); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verifyNoInteractions(agentMgr); + } + + @Test + public void hostConnect_returnsFalse_whenAgentReturnsNoAnswer() { + givenReadyToConnect("ISCSI"); + when(agentMgr.easySend(eq(HOST_ID), any(ModifyStoragePoolCommand.class))).thenReturn(null); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(storagePoolHostDao, never()).persist(any(StoragePoolHostVO.class)); + } + + @Test + public void hostConnect_returnsFalseAndRaisesAlert_whenAgentAnswerFails() { + givenReadyToConnect("ISCSI"); + Answer failed = mock(Answer.class); + when(failed.getResult()).thenReturn(false); + when(failed.getDetails()).thenReturn("mount failed"); + when(agentMgr.easySend(eq(HOST_ID), any(ModifyStoragePoolCommand.class))).thenReturn(failed); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(alertMgr).sendAlert(eq(AlertManager.AlertType.ALERT_TYPE_HOST), anyLong(), any(), anyString(), anyString()); + verify(storagePoolHostDao, never()).persist(any(StoragePoolHostVO.class)); + } + + @Test + public void hostConnect_returnsFalse_whenAnswerIsNotModifyStoragePoolAnswer() { + givenReadyToConnect("ISCSI"); + Answer unexpected = mock(Answer.class); + when(unexpected.getResult()).thenReturn(true); + when(agentMgr.easySend(eq(HOST_ID), any(ModifyStoragePoolCommand.class))).thenReturn(unexpected); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(storagePoolHostDao, never()).persist(any(StoragePoolHostVO.class)); + } + + @Test + public void hostConnect_returnsFalse_whenPoolInfoIsNull() { + givenReadyToConnect("ISCSI"); + ModifyStoragePoolAnswer answer = mock(ModifyStoragePoolAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getPoolInfo()).thenReturn(null); + when(agentMgr.easySend(eq(HOST_ID), any(ModifyStoragePoolCommand.class))).thenReturn(answer); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(storagePoolHostDao, never()).persist(any(StoragePoolHostVO.class)); + } + + @Test + public void hostConnect_returnsFalse_whenDaoThrows() { + givenReadyToConnect("ISCSI"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + when(storagePoolHostDao.findByPoolHost(POOL_ID, HOST_ID)).thenThrow(new RuntimeException("db down")); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + } + + // ------------------------------------------------- hostConnect: positive + + @Test + public void hostConnect_createsHostReferenceAndUpdatesCapacity_whenNoReferenceExists() { + givenReadyToConnect("ISCSI"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + when(storagePoolHostDao.findByPoolHost(POOL_ID, HOST_ID)).thenReturn(null); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + + ArgumentCaptor created = ArgumentCaptor.forClass(StoragePoolHostVO.class); + verify(storagePoolHostDao).persist(created.capture()); + assertEquals(POOL_ID, created.getValue().getPoolId()); + assertEquals(HOST_ID, created.getValue().getHostId()); + assertEquals(LOCAL_PATH, created.getValue().getLocalPath()); + verify(storagePoolHostDao, never()).update(anyLong(), any(StoragePoolHostVO.class)); + verify(pool).setCapacityBytes(100 * GB); + verify(pool).setUsedBytes(60 * GB); + verify(storagePoolDao).update(POOL_ID, pool); + } + + @Test + public void hostConnect_updatesExistingHostReference_whenReferenceExists() { + givenReadyToConnect("ISCSI"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + StoragePoolHostVO existing = mock(StoragePoolHostVO.class); + when(existing.getId()).thenReturn(5L); + when(storagePoolHostDao.findByPoolHost(POOL_ID, HOST_ID)).thenReturn(existing); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(existing).setLocalPath(LOCAL_PATH); + verify(storagePoolHostDao).update(5L, existing); + verify(storagePoolHostDao, never()).persist(any(StoragePoolHostVO.class)); + } + + @Test + public void hostConnect_sendsAddCommandWithPoolDetails() { + givenReadyToConnect("ISCSI"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + + ArgumentCaptor cmd = ArgumentCaptor.forClass(ModifyStoragePoolCommand.class); + verify(agentMgr).easySend(eq(HOST_ID), cmd.capture()); + assertTrue(cmd.getValue().getAdd()); + assertEquals("ISCSI", cmd.getValue().getDetails().get(OntapStorageConstants.PROTOCOL)); + } + + @Test + public void hostConnect_doesNotUpdateCapacity_whenReportedCapacityIsZero() { + givenReadyToConnect("ISCSI"); + givenSuccessfulAnswer(0L, 0L); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(storagePoolHostDao).persist(any(StoragePoolHostVO.class)); + verify(storagePoolDao, never()).update(anyLong(), any(StoragePoolVO.class)); + } + + @Test + public void hostConnect_clampsUsedBytesToZero_whenAvailableExceedsCapacity() { + givenReadyToConnect("ISCSI"); + givenSuccessfulAnswer(10 * GB, 20 * GB); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(pool).setUsedBytes(0L); + } + + @Test + public void hostConnect_skipsCapacityUpdate_whenPoolDisappearsAfterAnswer() { + givenKvmHost(); + givenDetails("ISCSI"); + when(pool.getName()).thenReturn("ontap-pool"); + when(pool.getPoolType()).thenReturn(StoragePoolType.NetworkFilesystem); + when(storagePoolDao.findById(POOL_ID)).thenReturn(pool, (StoragePoolVO) null); + givenSuccessfulAnswer(100 * GB, 40 * GB); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + + verify(storagePoolDao, never()).update(anyLong(), any(StoragePoolVO.class)); + } + + // ------------------------------------------- hostConnect: NFS3 export policy + + @Test + public void hostConnect_updatesExportPolicy_whenProtocolIsNfs3() { + givenReadyToConnect("NFS3"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(strategy); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + } + + ArgumentCaptor group = ArgumentCaptor.forClass(AccessGroup.class); + verify(strategy).updateAccessGroup(group.capture()); + assertEquals(POOL_ID, group.getValue().getStoragePoolId()); + assertEquals(List.of(host), group.getValue().getHostsToConnect()); + assertEquals(AccessGroup.HostRuleAction.ADD, group.getValue().getHostRuleAction()); + } + + @Test + public void hostConnect_matchesNfs3ProtocolCaseInsensitively() { + givenReadyToConnect("nfs3"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(strategy); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + } + + verify(strategy).updateAccessGroup(any(AccessGroup.class)); + } + + @Test + public void hostConnect_doesNotTouchExportPolicy_whenProtocolIsIscsi() { + givenReadyToConnect("ISCSI"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + + utils.verifyNoInteractions(); + } + verifyNoInteractions(strategy); + } + + @Test + public void hostConnect_returnsFalse_whenNfs3HostHasNoUsableIpAddress() { + givenReadyToConnect("NFS3"); + when(host.getStorageIpAddress()).thenReturn(" "); + when(host.getPrivateIpAddress()).thenReturn(" "); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + utils.verifyNoInteractions(); + } + verifyNoInteractions(agentMgr); + } + + @Test + public void hostConnect_returnsFalse_whenNfs3HostIpAddressesAreNull() { + givenReadyToConnect("NFS3"); + when(host.getStorageIpAddress()).thenReturn(null); + when(host.getPrivateIpAddress()).thenReturn(null); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + + verifyNoInteractions(agentMgr); + } + + @Test + public void hostConnect_continues_whenNfs3HostOnlyHasPrivateIp() { + givenReadyToConnect("NFS3"); + when(host.getStorageIpAddress()).thenReturn(null); + when(host.getPrivateIpAddress()).thenReturn("192.168.0.5"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(strategy); + + assertTrue(listener.hostConnect(HOST_ID, POOL_ID)); + } + + ArgumentCaptor group = ArgumentCaptor.forClass(AccessGroup.class); + verify(strategy).updateAccessGroup(group.capture()); + assertEquals(POOL_ID, group.getValue().getStoragePoolId()); + assertEquals(List.of(host), group.getValue().getHostsToConnect()); + assertEquals(AccessGroup.HostRuleAction.ADD, group.getValue().getHostRuleAction()); + assertEquals("192.168.0.5", host.getPrivateIpAddress()); + } + + @Test + public void hostConnect_returnsFalse_whenExportPolicyUpdateFails() { + givenReadyToConnect("NFS3"); + givenSuccessfulAnswer(100 * GB, 40 * GB); + when(strategy.updateAccessGroup(any(AccessGroup.class))).thenThrow(new RuntimeException("ONTAP unreachable")); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(strategy); + + assertFalse(listener.hostConnect(HOST_ID, POOL_ID)); + } + + ArgumentCaptor group = ArgumentCaptor.forClass(AccessGroup.class); + verify(strategy).updateAccessGroup(group.capture()); + assertEquals(POOL_ID, group.getValue().getStoragePoolId()); + assertEquals(List.of(host), group.getValue().getHostsToConnect()); + assertEquals(AccessGroup.HostRuleAction.ADD, group.getValue().getHostRuleAction()); + verifyNoInteractions(agentMgr); + } + + @Test + public void isNfs3EnabledOnHost_returnsFalse_whenHostIsNull() throws Exception { + Method method = OntapHostListener.class.getDeclaredMethod("isNfs3EnabledOnHost", com.cloud.host.Host.class); + method.setAccessible(true); + + assertFalse((Boolean) method.invoke(listener, (Object) null)); + } + + // ----------------------------------------------------- trivial callbacks + + @Test + public void hostDisconnected_returnsFalse() { + assertFalse(listener.hostDisconnected(HOST_ID, POOL_ID)); + } + + @Test + public void hostRemoved_returnsFalse() { + assertFalse(listener.hostRemoved(HOST_ID, 1L)); + } + + @Test + public void hostEnabled_returnsFalse() { + assertFalse(listener.hostEnabled(HOST_ID)); + } + + @Test + public void hostAdded_returnsFalse() { + assertFalse(listener.hostAdded(HOST_ID)); + } + + // ----------------------------------------------- hostAboutToBeRemoved + + private StoragePoolHostVO poolRef(long poolId) { + StoragePoolHostVO ref = mock(StoragePoolHostVO.class); + when(ref.getPoolId()).thenReturn(poolId); + return ref; + } + + private void givenHostWithPoolRefs(StoragePoolHostVO... refs) { + givenKvmHost(); + when(storagePoolHostDao.listByHostId(HOST_ID)).thenReturn(List.of(refs)); + } + + @Test + public void hostAboutToBeRemoved_returnsTrue_whenHostNotFound() { + when(hostDao.findById(HOST_ID)).thenReturn(null); + + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + + verify(storagePoolHostDao, never()).listByHostId(anyLong()); + } + + @Test + public void hostAboutToBeRemoved_returnsTrue_whenPoolReferencesAreNull() { + givenKvmHost(); + when(storagePoolHostDao.listByHostId(HOST_ID)).thenReturn(null); + + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + + verifyNoInteractions(storagePoolDao); + } + + @Test + public void hostAboutToBeRemoved_returnsTrue_whenNoPoolReferences() { + givenKvmHost(); + when(storagePoolHostDao.listByHostId(HOST_ID)).thenReturn(Collections.emptyList()); + + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + + verifyNoInteractions(storagePoolDao); + } + + @Test + public void hostAboutToBeRemoved_skipsReference_whenPoolNoLongerExists() { + givenHostWithPoolRefs(poolRef(POOL_ID)); + when(storagePoolDao.findById(POOL_ID)).thenReturn(null); + + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + + verifyNoInteractions(storagePoolDetailsDao); + } + + @Test + public void hostAboutToBeRemoved_removesHostFromExportPolicy_whenPoolIsNfs3() { + givenHostWithPoolRefs(poolRef(POOL_ID)); + givenPool(); + givenDetails("NFS3"); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(strategy); + + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + } + + ArgumentCaptor group = ArgumentCaptor.forClass(AccessGroup.class); + verify(strategy).updateAccessGroup(group.capture()); + assertEquals(POOL_ID, group.getValue().getStoragePoolId()); + assertSame(host, group.getValue().getHostsToConnect().get(0)); + assertEquals(AccessGroup.HostRuleAction.REMOVE, group.getValue().getHostRuleAction()); + } + + @Test + public void hostAboutToBeRemoved_skipsPool_whenPoolIsIscsi() { + givenHostWithPoolRefs(poolRef(POOL_ID)); + givenPool(); + givenDetails("ISCSI"); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + + utils.verifyNoInteractions(); + } + verifyNoInteractions(strategy); + } + + @Test + public void hostAboutToBeRemoved_skipsPool_whenPoolDetailsAreNull() { + givenHostWithPoolRefs(poolRef(POOL_ID)); + givenPool(); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(null); + + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + + verifyNoInteractions(strategy); + } + + @Test + public void hostAboutToBeRemoved_skipsPool_whenPoolDetailsAreEmpty() { + givenHostWithPoolRefs(poolRef(POOL_ID)); + givenPool(); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(Collections.emptyMap()); + + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + + verifyNoInteractions(strategy); + } + + @Test + public void hostAboutToBeRemoved_skipsPool_whenHostIsNotNfsEnabled() { + givenHostWithPoolRefs(poolRef(POOL_ID)); + givenPool(); + givenDetails("NFS3"); + when(host.getStorageIpAddress()).thenReturn(null); + when(host.getPrivateIpAddress()).thenReturn(""); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + + utils.verifyNoInteractions(); + } + verifyNoInteractions(strategy); + } + + @Test + public void hostAboutToBeRemoved_returnsTrueAndContinues_whenOnePoolFails() { + long secondPoolId = POOL_ID + 1; + StoragePoolVO secondPool = mock(StoragePoolVO.class); + when(secondPool.getId()).thenReturn(secondPoolId); + when(secondPool.getName()).thenReturn("ontap-pool-2"); + givenHostWithPoolRefs(poolRef(POOL_ID), poolRef(secondPoolId)); + givenPool(); + when(storagePoolDao.findById(secondPoolId)).thenReturn(secondPool); + givenDetails("NFS3"); + when(storagePoolDetailsDao.listDetailsKeyPairs(secondPoolId)).thenReturn(details("NFS3")); + StorageStrategy failing = mock(StorageStrategy.class); + when(failing.updateAccessGroup(any(AccessGroup.class))).thenThrow(new RuntimeException("boom")); + + try (MockedStatic utils = mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(anyMap())).thenReturn(failing, strategy); + + assertTrue(listener.hostAboutToBeRemoved(HOST_ID)); + } + + verify(failing).updateAccessGroup(any(AccessGroup.class)); + verify(strategy, times(1)).updateAccessGroup(any(AccessGroup.class)); + } +} diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/motion/OntapDataMotionStrategyTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/motion/OntapDataMotionStrategyTest.java index 3eedc4975fe9..863fcd1a13ca 100644 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/motion/OntapDataMotionStrategyTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/motion/OntapDataMotionStrategyTest.java @@ -20,12 +20,15 @@ import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; @@ -93,6 +96,8 @@ 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.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -529,6 +534,749 @@ public void offlineMigrationUsesSourceClusterHost() throws Exception { Mockito.verify(dataStoreManager, Mockito.never()).getPrimaryDataStore(2L); } + // ══════════════════════════════════════════════════════════════════════════ + // canHandle(DataObject, DataObject) – rejection paths + // ══════════════════════════════════════════════════════════════════════════ + + private VolumeInfo volumeOnStore(long storeId, DataStoreRole role, Volume.State state, HypervisorType hypervisor) { + VolumeInfo volume = Mockito.mock(VolumeInfo.class); + PrimaryDataStore store = Mockito.mock(PrimaryDataStore.class); + Mockito.doReturn(store).when(volume).getDataStore(); + Mockito.doReturn(role).when(store).getRole(); + Mockito.doReturn(storeId).when(store).getId(); + Mockito.doReturn(state).when(volume).getState(); + Mockito.doReturn(hypervisor).when(volume).getHypervisorType(); + return volume; + } + + private void poolOnStore(long storeId, String provider) { + StoragePoolVO pool = Mockito.mock(StoragePoolVO.class); + Mockito.doReturn(provider).when(pool).getStorageProviderName(); + Mockito.doReturn(pool).when(primaryDataStoreDao).findById(storeId); + } + + @Test + public void canHandleRejectsObjectsThatAreNotVolumes() { + org.apache.cloudstack.engine.subsystem.api.storage.DataObject snapshot = + Mockito.mock(org.apache.cloudstack.engine.subsystem.api.storage.DataObject.class); + VolumeInfo volume = Mockito.mock(VolumeInfo.class); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshot, volume)); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(volume, snapshot)); + } + + @Test + public void canHandleAcceptsMigrationWhenOnlyDestinationIsOntap() { + VolumeInfo src = volumeOnStore(1L, DataStoreRole.Primary, Volume.State.Migrating, HypervisorType.KVM); + VolumeInfo dest = volumeOnStore(2L, DataStoreRole.Primary, Volume.State.Allocated, HypervisorType.KVM); + poolOnStore(1L, DataStoreProvider.DEFAULT_PRIMARY); + poolOnStore(2L, DataStoreProvider.ONTAP_PLUGIN_NAME); + + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(src, dest)); + } + + @Test + public void canHandleRejectsMigrationBetweenNonOntapPools() { + VolumeInfo src = volumeOnStore(1L, DataStoreRole.Primary, Volume.State.Migrating, HypervisorType.KVM); + VolumeInfo dest = volumeOnStore(2L, DataStoreRole.Primary, Volume.State.Allocated, HypervisorType.KVM); + poolOnStore(1L, DataStoreProvider.DEFAULT_PRIMARY); + poolOnStore(2L, DataStoreProvider.DEFAULT_PRIMARY); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(src, dest)); + } + + @Test + public void canHandleRejectsMigrationWhenPoolsAreUnknown() { + VolumeInfo src = volumeOnStore(1L, DataStoreRole.Primary, Volume.State.Migrating, HypervisorType.KVM); + VolumeInfo dest = volumeOnStore(2L, DataStoreRole.Primary, Volume.State.Allocated, HypervisorType.KVM); + Mockito.doReturn(null).when(primaryDataStoreDao).findById(1L); + Mockito.doReturn(null).when(primaryDataStoreDao).findById(2L); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(src, dest)); + } + + @Test + public void canHandleRejectsNonPrimaryRolesAndNonKvmHypervisors() { + poolOnStore(1L, DataStoreProvider.ONTAP_PLUGIN_NAME); + poolOnStore(2L, DataStoreProvider.ONTAP_PLUGIN_NAME); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle( + volumeOnStore(1L, DataStoreRole.Image, Volume.State.Migrating, HypervisorType.KVM), + volumeOnStore(2L, DataStoreRole.Primary, Volume.State.Allocated, HypervisorType.KVM))); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle( + volumeOnStore(1L, DataStoreRole.Primary, Volume.State.Migrating, HypervisorType.KVM), + volumeOnStore(2L, DataStoreRole.Image, Volume.State.Allocated, HypervisorType.KVM))); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle( + volumeOnStore(1L, DataStoreRole.Primary, Volume.State.Migrating, HypervisorType.VMware), + volumeOnStore(2L, DataStoreRole.Primary, Volume.State.Allocated, HypervisorType.VMware))); + } + + @Test + public void canHandleLiveMigrationAcceptsWhenOnlyDestinationPoolIsOntap() { + VolumeInfo srcVolume = Mockito.mock(VolumeInfo.class); + Mockito.doReturn(1L).when(srcVolume).getPoolId(); + DataStore destStore = Mockito.mock(DataStore.class); + Mockito.doReturn(2L).when(destStore).getId(); + poolOnStore(1L, DataStoreProvider.DEFAULT_PRIMARY); + poolOnStore(2L, DataStoreProvider.ONTAP_PLUGIN_NAME); + Host srcHost = Mockito.mock(Host.class); + Mockito.doReturn(HypervisorType.KVM).when(srcHost).getHypervisorType(); + + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(Map.of(srcVolume, destStore), srcHost, Mockito.mock(Host.class))); + } + + @Test + public void canHandleLiveMigrationRejectsWhenNoPoolIsOntap() { + VolumeInfo srcVolume = Mockito.mock(VolumeInfo.class); + Mockito.doReturn(1L).when(srcVolume).getPoolId(); + DataStore destStore = Mockito.mock(DataStore.class); + Mockito.doReturn(2L).when(destStore).getId(); + poolOnStore(1L, DataStoreProvider.DEFAULT_PRIMARY); + Mockito.doReturn(null).when(primaryDataStoreDao).findById(2L); + Host srcHost = Mockito.mock(Host.class); + Mockito.doReturn(HypervisorType.KVM).when(srcHost).getHypervisorType(); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(Map.of(srcVolume, destStore), srcHost, Mockito.mock(Host.class))); + } + + // ══════════════════════════════════════════════════════════════════════════ + // Offline (single volume) migration – host selection and failure handling + // ══════════════════════════════════════════════════════════════════════════ + + @Test + public void offlineMigrationOfVolumeAttachedToRunningVmIsRejected() { + VirtualMachine vm = Mockito.mock(VirtualMachine.class); + Mockito.doReturn(VirtualMachine.State.Running).when(vm).getState(); + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", vm); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback)); + + assertTrue(thrown.getMessage().contains("can only be migrated offline"), thrown.getMessage()); + Mockito.verify(context.destVolume.getDataStore().getDriver(), Mockito.never()) + .createAsync(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(context.callback).complete(Mockito.argThat(CopyCommandResult::isFailed)); + } + + @Test + public void offlineMigrationOfVolumeAttachedToMigratingVmIsAccepted() throws Exception { + VirtualMachine vm = Mockito.mock(VirtualMachine.class); + Mockito.doReturn(VirtualMachine.State.Migrating).when(vm).getState(); + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", vm); + VolumeObjectTO copied = new VolumeObjectTO(); + copied.setPath("copied"); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(copied)); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + Mockito.verify(context.destVolumeVO).setPath("copied"); + } + + @Test + public void offlineMigrationUsesIscsiNameAsDestinationPathWhenPresent() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Mockito.doReturn("iqn.dest").when(context.destVolumeVO).get_iScsiName(); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + Mockito.verify(context.destVolumeVO).setPath("iqn.dest"); + Mockito.verify(volumeDao, Mockito.atLeastOnce()).update(Mockito.anyLong(), Mockito.eq(context.destVolumeVO)); + } + + @Test + public void offlineMigrationDefaultsDestinationFormatToQcow2WhenMissing() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Mockito.doReturn(null).when(context.destVolumeVO).getFormat(); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + Mockito.verify(context.destVolumeVO).setFormat(Storage.ImageFormat.QCOW2); + } + + @Test + public void offlineMigrationSucceedsEvenWhenCleanupStepsFail() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + Mockito.doThrow(new CloudRuntimeException("revoke failed")).when(volumeService) + .revokeAccess(Mockito.any(VolumeInfo.class), Mockito.any(Host.class), Mockito.any()); + Mockito.doThrow(new CloudRuntimeException("detail cleanup failed")).when(volumeDetailsDao) + .removeDetail(Mockito.anyLong(), Mockito.eq(OntapStorageConstants.MIGRATION_DESTINATION)); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + Mockito.verify(context.callback).complete(Mockito.argThat(result -> result != null && !result.isFailed())); + } + + @Test + public void offlineMigrationUsesDestinationHostScopeWhenSourceIsNotHostScoped() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Scope srcScope = context.srcVolume.getDataStore().getScope(); + Mockito.doReturn(ScopeType.CLUSTER).when(srcScope).getScopeType(); + Scope destScope = Mockito.mock(Scope.class); + Mockito.doReturn(ScopeType.HOST).when(destScope).getScopeType(); + Mockito.doReturn(3L).when(destScope).getScopeId(); + DataStore destStore = context.destVolume.getDataStore(); + Mockito.doReturn(destScope).when(destStore).getScope(); + Mockito.when(agentManager.send(Mockito.eq(3L), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + Mockito.verify(hostDao, Mockito.atLeastOnce()).findById(3L); + Mockito.verify(context.callback).complete(Mockito.argThat(result -> result != null && !result.isFailed())); + } + + private OfflineMigrationTestContext configureZoneScopedOfflineMigration() { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Scope srcScope = context.srcVolume.getDataStore().getScope(); + Mockito.doReturn(ScopeType.ZONE).when(srcScope).getScopeType(); + Scope destScope = Mockito.mock(Scope.class); + Mockito.doReturn(ScopeType.ZONE).when(destScope).getScopeType(); + DataStore destStore = context.destVolume.getDataStore(); + Mockito.doReturn(destScope).when(destStore).getScope(); + // a Long-returning mock method answers 0, so the cluster must be nulled explicitly + StoragePoolVO srcPool = primaryDataStoreDao.findById(1L); + Mockito.doReturn(null).when(srcPool).getClusterId(); + return context; + } + + @Test + public void offlineMigrationFromPoolWithoutClusterUsesEnabledHostInDestinationZone() throws Exception { + OfflineMigrationTestContext context = configureZoneScopedOfflineMigration(); + HostVO disabled = Mockito.mock(HostVO.class); + Mockito.doReturn(ResourceState.Disabled).when(disabled).getResourceState(); + HostVO enabled = Mockito.mock(HostVO.class); + Mockito.doReturn(9L).when(enabled).getId(); + Mockito.doReturn(ResourceState.Enabled).when(enabled).getResourceState(); + Mockito.doReturn(new java.util.ArrayList<>(List.of(disabled, enabled))).when(resourceManager) + .getEligibleUpAndEnabledHostsInZoneForStorageConnection(Mockito.any(), Mockito.anyLong(), Mockito.eq(HypervisorType.KVM)); + Mockito.when(agentManager.send(Mockito.eq(9L), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + Mockito.verify(agentManager).send(Mockito.eq(9L), Mockito.any(CopyCommand.class)); + } + + @Test + public void offlineMigrationFailsWhenNoEnabledHostCanBeFound() { + OfflineMigrationTestContext context = configureZoneScopedOfflineMigration(); + HostVO disabled = Mockito.mock(HostVO.class); + Mockito.doReturn(ResourceState.Disabled).when(disabled).getResourceState(); + Mockito.doReturn(new java.util.ArrayList<>(List.of(disabled))).when(resourceManager) + .getEligibleUpAndEnabledHostsInZoneForStorageConnection(Mockito.any(), Mockito.anyLong(), Mockito.eq(HypervisorType.KVM)); + + CloudRuntimeException disabledOnly = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback)); + assertEquals("Unable to locate a host to migrate the volume on", disabledOnly.getMessage()); + + Mockito.doReturn(null).when(resourceManager) + .getEligibleUpAndEnabledHostsInZoneForStorageConnection(Mockito.any(), Mockito.anyLong(), Mockito.eq(HypervisorType.KVM)); + CloudRuntimeException noHosts = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback)); + assertEquals("Unable to locate a host to migrate the volume on", noHosts.getMessage()); + Mockito.verify(resourceManager, Mockito.times(2)).getEligibleUpAndEnabledHostsInZoneForStorageConnection( + Mockito.eq(context.destVolume.getDataStore()), Mockito.anyLong(), Mockito.eq(HypervisorType.KVM)); + } + + @Test + public void offlineMigrationReportsDefaultMessageWhenAgentGivesNoAnswer() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))).thenReturn(null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback)); + + assertEquals("Unable to copy the volume between storage pools", thrown.getMessage()); + } + + @Test + public void offlineMigrationReportsDefaultMessageWhenFailedAnswerHasNoDetails() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(false, "NFS3", "svm1", null); + Answer failed = Mockito.mock(Answer.class); + Mockito.when(failed.getResult()).thenReturn(false); + Mockito.when(failed.getDetails()).thenReturn(""); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(MigrateVolumeCommand.class))).thenReturn(failed); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback)); + + assertEquals("Unable to migrate the volume between storage pools", thrown.getMessage()); + } + + @Test + public void offlineMigrationWrapsUnexpectedAgentErrors() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + long hostId = context.host.getId(); + com.cloud.exception.AgentUnavailableException unavailable = + new com.cloud.exception.AgentUnavailableException("agent gone", hostId); + Mockito.when(agentManager.send(Mockito.eq(hostId), Mockito.any(CopyCommand.class))).thenThrow(unavailable); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback)); + + assertTrue(thrown.getMessage().contains("Unexpected error during volume migration"), thrown.getMessage()); + assertTrue(thrown.getCause() instanceof com.cloud.exception.AgentUnavailableException); + } + + // ══════════════════════════════════════════════════════════════════════════ + // Offline migration – decision between CopyCommand and MigrateVolumeCommand + // ══════════════════════════════════════════════════════════════════════════ + + /** Runs an offline NFS migration between two ONTAP pools and reports whether a CopyCommand was used. */ + private boolean offlineMigrationUsesCopyCommand(Map srcDetails, Map destDetails, + StoragePoolType destPoolType) throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "NFS3", "svm1", null, + StoragePoolType.NetworkFilesystem, destPoolType); + Mockito.doReturn(srcDetails).when(primaryDataStoreDao).getDetails(1L); + Mockito.doReturn(destDetails).when(primaryDataStoreDao).getDetails(2L); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(MigrateVolumeCommand.class))) + .thenReturn(new MigrateVolumeAnswer(null, true, null, "migrated")); + Mockito.clearInvocations(agentManager); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + return Mockito.mockingDetails(agentManager).getInvocations().stream() + .anyMatch(invocation -> invocation.getMethod().getName().equals("send") + && invocation.getArguments()[1] instanceof CopyCommand); + } + + private static Map ontapDetails(String ip, String svmName, String svmUuid, String protocol) { + Map details = new java.util.HashMap<>(); + if (ip != null) { + details.put("storageIP", ip); + } + if (svmName != null) { + details.put("svmName", svmName); + } + if (svmUuid != null) { + details.put("svmUUID", svmUuid); + } + if (protocol != null) { + details.put("protocol", protocol); + } + return details; + } + + @Test + public void copyCommandIsUsedOnlyWhenBothPoolsShareClusterSvmProtocolAndType() throws Exception { + Map base = ontapDetails("10.0.0.1", "svm1", null, "NFS3"); + + assertTrue(offlineMigrationUsesCopyCommand(base, ontapDetails("10.0.0.1", "svm1", null, "NFS3"), StoragePoolType.NetworkFilesystem)); + // protocol comparison ignores case + assertTrue(offlineMigrationUsesCopyCommand(base, ontapDetails("10.0.0.1", "svm1", null, "nfs3"), StoragePoolType.NetworkFilesystem)); + // matching SVM UUIDs win even when the SVM names differ + assertTrue(offlineMigrationUsesCopyCommand(ontapDetails("10.0.0.1", "a", "uuid-1", "NFS3"), + ontapDetails("10.0.0.1", "b", "uuid-1", "NFS3"), StoragePoolType.NetworkFilesystem)); + } + + @Test + public void migrateVolumeCommandIsUsedWhenPoolsDifferByClusterSvmOrType() throws Exception { + Map base = ontapDetails("10.0.0.1", "svm1", null, "NFS3"); + + assertFalse(offlineMigrationUsesCopyCommand(base, ontapDetails("10.0.0.2", "svm1", null, "NFS3"), StoragePoolType.NetworkFilesystem)); + assertFalse(offlineMigrationUsesCopyCommand(base, ontapDetails("10.0.0.1", "svm2", null, "NFS3"), StoragePoolType.NetworkFilesystem)); + // UUID on one side only cannot be compared to a name + assertFalse(offlineMigrationUsesCopyCommand(ontapDetails("10.0.0.1", "svm1", "uuid-1", "NFS3"), + ontapDetails("10.0.0.1", "svm1", null, "NFS3"), StoragePoolType.NetworkFilesystem)); + assertFalse(offlineMigrationUsesCopyCommand(ontapDetails("10.0.0.1", "svm1", null, "NFS3"), + ontapDetails("10.0.0.1", "svm1", "uuid-1", "NFS3"), StoragePoolType.NetworkFilesystem)); + // different UUIDs + assertFalse(offlineMigrationUsesCopyCommand(ontapDetails("10.0.0.1", "svm1", "uuid-1", "NFS3"), + ontapDetails("10.0.0.1", "svm1", "uuid-2", "NFS3"), StoragePoolType.NetworkFilesystem)); + // no SVM identity at all + assertFalse(offlineMigrationUsesCopyCommand(ontapDetails("10.0.0.1", null, null, "NFS3"), + ontapDetails("10.0.0.1", null, null, "NFS3"), StoragePoolType.NetworkFilesystem)); + // missing storage IP + assertFalse(offlineMigrationUsesCopyCommand(ontapDetails(null, "svm1", null, "NFS3"), + ontapDetails(null, "svm1", null, "NFS3"), StoragePoolType.NetworkFilesystem)); + // missing protocol on the source + assertFalse(offlineMigrationUsesCopyCommand(ontapDetails("10.0.0.1", "svm1", null, null), + ontapDetails("10.0.0.1", "svm1", null, "NFS3"), StoragePoolType.NetworkFilesystem)); + // different pool types, same protocol string + assertFalse(offlineMigrationUsesCopyCommand(base, ontapDetails("10.0.0.1", "svm1", null, "NFS3"), StoragePoolType.OntapiSCSI)); + } + + @Test + public void migrateVolumeCommandIsUsedWhenPoolDetailsAreUnavailable() throws Exception { + Map base = ontapDetails("10.0.0.1", "svm1", null, "NFS3"); + + assertFalse(offlineMigrationUsesCopyCommand(null, base, StoragePoolType.NetworkFilesystem)); + assertFalse(offlineMigrationUsesCopyCommand(base, null, StoragePoolType.NetworkFilesystem)); + } + + // ══════════════════════════════════════════════════════════════════════════ + // Live migration – validation failures + // ══════════════════════════════════════════════════════════════════════════ + + @Test + public void liveMigrationFromNonKvmSourceHostIsRejected() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(HypervisorType.VMware).when(context.srcHost).getHypervisorType(); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback)); + + assertTrue(thrown.getMessage().contains("Only KVM is supported"), thrown.getMessage()); + Mockito.verify(volumeDao, Mockito.never()).persist(Mockito.any(VolumeVO.class)); + Mockito.verify(context.callback).complete(Mockito.argThat(CopyCommandResult::isFailed)); + } + + @Test + public void liveMigrationFailsWhenSourceOrDestinationPoolIsUnknown() { + LiveMigrationTestContext missingSource = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(null).when(primaryDataStoreDao).findById(1L); + CloudRuntimeException noSource = assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + missingSource.volumeMap, missingSource.vmTO, missingSource.srcHost, missingSource.destHost, missingSource.callback)); + assertTrue(noSource.getMessage().contains("is not associated with a storage pool"), noSource.getMessage()); + + LiveMigrationTestContext missingDest = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(null).when(primaryDataStoreDao).findById(2L); + CloudRuntimeException noDest = assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + missingDest.volumeMap, missingDest.vmTO, missingDest.srcHost, missingDest.destHost, missingDest.callback)); + assertTrue(noDest.getMessage().contains("was not located"), noDest.getMessage()); + } + + @Test + public void liveMigrationFromManagedPoolToNonOntapPoolIsRejected() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + StoragePoolVO destPool = primaryDataStoreDao.findById(2L); + Mockito.doReturn(DataStoreProvider.DEFAULT_PRIMARY).when(destPool).getStorageProviderName(); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback)); + + assertTrue(thrown.getMessage().contains("from managed storage is not currently supported"), thrown.getMessage()); + } + + @Test + public void liveMigrationBetweenOntapPoolsWithUnreadableDetailsIsRejectedWithMatchingRulesMessage() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(null).when(primaryDataStoreDao).getDetails(1L); + Mockito.doReturn(null).when(primaryDataStoreDao).getDetails(2L); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback)); + + assertTrue(thrown.getMessage().contains("ONTAP migration requires matching storageIP, SVM, protocol, and pool type"), + thrown.getMessage()); + } + + @Test + public void liveMigrationRejectsDestinationPoolsThatMixManagedAndUnmanaged() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + StoragePoolVO firstSrcPool = primaryDataStoreDao.findById(1L); + Mockito.doReturn(false).when(firstSrcPool).isManaged(); + + VolumeInfo secondVolume = Mockito.mock(VolumeInfo.class); + Mockito.doReturn(11L).when(secondVolume).getId(); + Mockito.doReturn(3L).when(secondVolume).getPoolId(); + PrimaryDataStore secondDest = Mockito.mock(PrimaryDataStore.class); + Mockito.doReturn(4L).when(secondDest).getId(); + StoragePoolVO secondSrcPool = Mockito.mock(StoragePoolVO.class); + Mockito.doReturn(3L).when(secondSrcPool).getId(); + Mockito.doReturn(false).when(secondSrcPool).isManaged(); + StoragePoolVO secondDestPool = Mockito.mock(StoragePoolVO.class); + Mockito.doReturn(4L).when(secondDestPool).getId(); + Mockito.doReturn(false).when(secondDestPool).isManaged(); + Mockito.doReturn(secondSrcPool).when(primaryDataStoreDao).findById(3L); + Mockito.doReturn(secondDestPool).when(primaryDataStoreDao).findById(4L); + Map volumes = new java.util.HashMap<>(context.volumeMap); + volumes.put(secondVolume, secondDest); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(volumes, context.vmTO, context.srcHost, context.destHost, context.callback)); + + assertTrue(thrown.getMessage().contains("all managed or all not managed"), thrown.getMessage()); + } + + // ══════════════════════════════════════════════════════════════════════════ + // Live migration – flow variations + // ══════════════════════════════════════════════════════════════════════════ + + @Test + public void liveMigrationSkipsVolumesAlreadyOnTheDestinationPool() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + DataStore onlyDest = context.volumeMap.values().iterator().next(); + Mockito.doReturn(1L).when(onlyDest).getId(); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + Mockito.verify(volumeDao, Mockito.never()).persist(Mockito.any(VolumeVO.class)); + MigrateCommand migrateCommand = captureMigrateCommand(); + assertTrue(migrateCommand.getMigrateStorage().isEmpty()); + Mockito.verify(context.callback).complete(Mockito.argThat(result -> result != null && !result.isFailed())); + } + + @Test + public void liveMigrationWithoutDisksOnVmLeavesDiskListUntouched() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(null).when(context.vmTO).getDisks(); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + assertTrue(context.vmDisk.getData() != context.destVolumeTO); + Mockito.verify(context.callback).complete(Mockito.argThat(result -> result != null && !result.isFailed())); + } + + @Test + public void liveMigrationFromUnmanagedSourceToOntapIscsiUsesSourcePathDirectly() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("ISCSI", StoragePoolType.OntapiSCSI); + StoragePoolVO srcPool = primaryDataStoreDao.findById(1L); + Mockito.doReturn(false).when(srcPool).isManaged(); + Mockito.doReturn(StoragePoolType.Filesystem).when(srcPool).getPoolType(); + Mockito.doReturn(DataStoreProvider.DEFAULT_PRIMARY).when(srcPool).getStorageProviderName(); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + MigrateCommand migrateCommand = captureMigrateCommand(); + MigrateDiskInfo diskInfo = migrateCommand.getMigrateDiskInfoList().get(0); + assertEquals("src-path", diskInfo.getSerialNumber()); + assertTrue(diskInfo.isSourceDiskOnStorageFileSystem()); + assertEquals(1, migrateCommand.getMigrateStorage().size()); + Mockito.verify(volumeService, Mockito.never()).grantAccess(Mockito.eq(context.srcVolume), Mockito.any(), Mockito.any()); + Mockito.verify(context.callback).complete(Mockito.argThat(result -> result != null && !result.isFailed())); + } + + @Test + public void liveMigrationWithoutCpuSharesInPrepareAnswerLeavesDefault() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(new PrepareForMigrationAnswer(new PrepareForMigrationCommand(context.vmTO))).when(agentManager) + .send(Mockito.eq(DEST_HOST_ID), Mockito.any(PrepareForMigrationCommand.class)); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + assertEquals(0, captureMigrateCommand().getNewVmCpuShares()); + } + + @Test + public void liveMigrationOfWindowsGuestIsFlaggedOnTheMigrateCommand() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + GuestOSCategoryVO windows = Mockito.mock(GuestOSCategoryVO.class); + Mockito.doReturn("windows").when(windows).getName(); + Mockito.doReturn(windows).when(guestOsCategoryDao).findById(8L); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + assertTrue(captureMigrateCommand().isWindows()); + } + + @Test + public void liveMigrationFailsWhenDestinationHostCannotPrepare() throws Exception { + LiveMigrationTestContext rejected = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Answer notPrepared = Mockito.mock(Answer.class); + Mockito.doReturn(false).when(notPrepared).getResult(); + Mockito.doReturn("no capacity").when(notPrepared).getDetails(); + Mockito.doReturn(notPrepared).when(agentManager).send(Mockito.eq(DEST_HOST_ID), Mockito.any(PrepareForMigrationCommand.class)); + CloudRuntimeException rejectedEx = assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + rejected.volumeMap, rejected.vmTO, rejected.srcHost, rejected.destHost, rejected.callback)); + assertTrue(rejectedEx.getMessage().contains("no capacity"), rejectedEx.getMessage()); + Mockito.verify(volumeService).expungeVolumeAsync(rejected.destVolume); + + LiveMigrationTestContext noAnswer = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(null).when(agentManager).send(Mockito.eq(DEST_HOST_ID), Mockito.any(PrepareForMigrationCommand.class)); + CloudRuntimeException noAnswerEx = assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + noAnswer.volumeMap, noAnswer.vmTO, noAnswer.srcHost, noAnswer.destHost, noAnswer.callback)); + assertTrue(noAnswerEx.getMessage().contains("null answer returned"), noAnswerEx.getMessage()); + + LiveMigrationTestContext timedOut = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doThrow(new OperationTimedoutException(null, DEST_HOST_ID, 0, 0, false)).when(agentManager) + .send(Mockito.eq(DEST_HOST_ID), Mockito.any(PrepareForMigrationCommand.class)); + CloudRuntimeException timedOutEx = assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + timedOut.volumeMap, timedOut.vmTO, timedOut.srcHost, timedOut.destHost, timedOut.callback)); + assertTrue(timedOutEx.getMessage().contains("Operation timed out"), timedOutEx.getMessage()); + } + + @Test + public void liveMigrationFailsWhenMigrateCommandGetsNoAnswerAndRollsBackPreparation() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(null).when(agentManager).send(Mockito.eq(SRC_HOST_ID), Mockito.any(MigrateCommand.class)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback)); + + assertTrue(thrown.getMessage().contains("Unable to get an answer to the migrate command"), thrown.getMessage()); + ArgumentCaptor prepare = ArgumentCaptor.forClass(PrepareForMigrationCommand.class); + Mockito.verify(agentManager, Mockito.times(2)).send(Mockito.eq(DEST_HOST_ID), prepare.capture()); + assertFalse(prepare.getAllValues().get(0).isRollback()); + assertTrue(prepare.getAllValues().get(1).isRollback()); + Mockito.verify(volumeService).expungeVolumeAsync(context.destVolume); + } + + @Test + public void liveMigrationFailsWhenMigrateAnswerReportsFailure() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(new MigrateAnswer(null, false, "libvirt exploded", null)).when(agentManager) + .send(Mockito.eq(SRC_HOST_ID), Mockito.any(MigrateCommand.class)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback)); + + assertTrue(thrown.getMessage().contains("libvirt exploded"), thrown.getMessage()); + Mockito.verify(volumeService).expungeVolumeAsync(context.destVolume); + Mockito.verify(volumeService, Mockito.never()).copyPoliciesBetweenVolumesAndDestroySourceVolumeAfterMigration( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + } + + @Test + public void liveMigrationStillCleansUpWhenRollbackOfPreparationFails() throws Exception { + LiveMigrationTestContext failedAnswer = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + PrepareForMigrationAnswer prepared = new PrepareForMigrationAnswer(new PrepareForMigrationCommand(failedAnswer.vmTO)); + Answer rollbackRefused = Mockito.mock(Answer.class); + Mockito.doReturn(false).when(rollbackRefused).getResult(); + Mockito.doReturn(prepared).doReturn(rollbackRefused).when(agentManager) + .send(Mockito.eq(DEST_HOST_ID), Mockito.any(PrepareForMigrationCommand.class)); + Mockito.doReturn(new MigrateAnswer(null, false, "boom", null)).when(agentManager) + .send(Mockito.eq(SRC_HOST_ID), Mockito.any(MigrateCommand.class)); + assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + failedAnswer.volumeMap, failedAnswer.vmTO, failedAnswer.srcHost, failedAnswer.destHost, failedAnswer.callback)); + Mockito.verify(volumeService).expungeVolumeAsync(failedAnswer.destVolume); + + LiveMigrationTestContext throwing = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + PrepareForMigrationAnswer prepared2 = new PrepareForMigrationAnswer(new PrepareForMigrationCommand(throwing.vmTO)); + Mockito.doReturn(prepared2).doThrow(new IllegalStateException("rollback unreachable")).when(agentManager) + .send(Mockito.eq(DEST_HOST_ID), Mockito.any(PrepareForMigrationCommand.class)); + Mockito.doReturn(new MigrateAnswer(null, false, "boom", null)).when(agentManager) + .send(Mockito.eq(SRC_HOST_ID), Mockito.any(MigrateCommand.class)); + assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + throwing.volumeMap, throwing.vmTO, throwing.srcHost, throwing.destHost, throwing.callback)); + Mockito.verify(volumeService).expungeVolumeAsync(throwing.destVolume); + } + + @Test + public void liveMigrationFailureCleanupToleratesRevokeFailure() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doThrow(new CloudRuntimeException("grant failed")).when(volumeService) + .grantAccess(Mockito.eq(context.destVolume), Mockito.eq(context.destHost), Mockito.any()); + Mockito.doThrow(new CloudRuntimeException("revoke failed")).when(volumeService) + .revokeAccess(Mockito.eq(context.destVolume), Mockito.eq(context.destHost), Mockito.any()); + + assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback)); + + Mockito.verify(volumeService).expungeVolumeAsync(context.destVolume); + } + + @Test + public void liveMigrationTimeoutIsFatalWhenVmIsNotRunningOnDestination() throws Exception { + LiveMigrationTestContext notOn = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + VMInstanceVO vmRowA = vmDao.findById(5L); + Mockito.doReturn("i-5-VM").when(vmRowA).getInstanceName(); + Mockito.doThrow(new OperationTimedoutException(null, SRC_HOST_ID, 0, 0, false)).when(agentManager) + .send(Mockito.eq(SRC_HOST_ID), Mockito.any(MigrateCommand.class)); + Mockito.doReturn(new CheckVirtualMachineAnswer(new CheckVirtualMachineCommand("i-5-VM"), VirtualMachine.PowerState.PowerOff, null)) + .when(agentManager).send(Mockito.eq(DEST_HOST_ID), Mockito.any(CheckVirtualMachineCommand.class)); + assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + notOn.volumeMap, notOn.vmTO, notOn.srcHost, notOn.destHost, notOn.callback)); + Mockito.verify(volumeService).expungeVolumeAsync(notOn.destVolume); + + LiveMigrationTestContext unknown = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + VMInstanceVO vmRowB = vmDao.findById(5L); + Mockito.doReturn("i-5-VM").when(vmRowB).getInstanceName(); + Mockito.doThrow(new OperationTimedoutException(null, SRC_HOST_ID, 0, 0, false)).when(agentManager) + .send(Mockito.eq(SRC_HOST_ID), Mockito.any(MigrateCommand.class)); + Mockito.doThrow(new IllegalStateException("cannot reach destination")).when(agentManager) + .send(Mockito.eq(DEST_HOST_ID), Mockito.any(CheckVirtualMachineCommand.class)); + assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + unknown.volumeMap, unknown.vmTO, unknown.srcHost, unknown.destHost, unknown.callback)); + Mockito.verify(volumeService).expungeVolumeAsync(unknown.destVolume); + + LiveMigrationTestContext notAnAnswer = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + VMInstanceVO vmRowC = vmDao.findById(5L); + Mockito.doReturn("i-5-VM").when(vmRowC).getInstanceName(); + Mockito.doThrow(new OperationTimedoutException(null, SRC_HOST_ID, 0, 0, false)).when(agentManager) + .send(Mockito.eq(SRC_HOST_ID), Mockito.any(MigrateCommand.class)); + Mockito.doReturn(new Answer(null, true, "ok")).when(agentManager) + .send(Mockito.eq(DEST_HOST_ID), Mockito.any(CheckVirtualMachineCommand.class)); + assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + notAnAnswer.volumeMap, notAnAnswer.vmTO, notAnAnswer.srcHost, notAnAnswer.destHost, notAnAnswer.callback)); + } + + @Test + public void liveMigrationFailsWhenTargetsCannotBeConnectedOnDestinationHost() { + LiveMigrationTestContext noAnswer = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(null).when(agentManager).easySend(Mockito.eq(DEST_HOST_ID), Mockito.any(ModifyTargetsCommand.class)); + CloudRuntimeException noAnswerEx = assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + noAnswer.volumeMap, noAnswer.vmTO, noAnswer.srcHost, noAnswer.destHost, noAnswer.callback)); + assertTrue(noAnswerEx.getMessage().contains("Unable to get an answer to the modify targets command"), noAnswerEx.getMessage()); + Mockito.verify(volumeService).expungeVolumeAsync(noAnswer.destVolume); + + LiveMigrationTestContext refused = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Answer refusal = Mockito.mock(Answer.class); + Mockito.doReturn(false).when(refusal).getResult(); + Mockito.doReturn("target busy").when(refusal).getDetails(); + Mockito.doReturn(refusal).when(agentManager).easySend(Mockito.eq(DEST_HOST_ID), Mockito.any(ModifyTargetsCommand.class)); + CloudRuntimeException refusedEx = assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + refused.volumeMap, refused.vmTO, refused.srcHost, refused.destHost, refused.callback)); + assertTrue(refusedEx.getMessage().contains("Unable to modify targets on host"), refusedEx.getMessage()); + assertTrue(refusedEx.getMessage().contains("target busy"), refusedEx.getMessage()); + + LiveMigrationTestContext wrongType = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doReturn(new Answer(null, true, "ok")).when(agentManager) + .easySend(Mockito.eq(DEST_HOST_ID), Mockito.any(ModifyTargetsCommand.class)); + CloudRuntimeException wrongTypeEx = assertThrows(CloudRuntimeException.class, () -> strategy.copyAsync( + wrongType.volumeMap, wrongType.vmTO, wrongType.srcHost, wrongType.destHost, wrongType.callback)); + assertTrue(wrongTypeEx.getMessage().contains("Unexpected answer type"), wrongTypeEx.getMessage()); + } + + // ══════════════════════════════════════════════════════════════════════════ + // ONTAP QoS re-apply after content rewrite + // ══════════════════════════════════════════════════════════════════════════ + + private OntapPrimaryDatastoreDriver configureOntapNfsDriver(LiveMigrationTestContext context) { + OntapPrimaryDatastoreDriver ontapDriver = Mockito.mock(OntapPrimaryDatastoreDriver.class); + DataStore destStore = context.destVolume.getDataStore(); + Mockito.doReturn(ontapDriver).when(destStore).getDriver(); + return ontapDriver; + } + + @Test + public void liveMigrationReappliesQosOnceWhenFirstAttemptSucceeds() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + OntapPrimaryDatastoreDriver ontapDriver = configureOntapNfsDriver(context); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + Mockito.verify(ontapDriver, Mockito.times(1)).applyQosPolicyToVolume(context.destVolume); + } + + @Test + public void liveMigrationRetriesQosReapplyAfterTransientFailure() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + OntapPrimaryDatastoreDriver ontapDriver = configureOntapNfsDriver(context); + Mockito.doThrow(new CloudRuntimeException("transient")).doNothing().when(ontapDriver) + .applyQosPolicyToVolume(context.destVolume); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + Mockito.verify(ontapDriver, Mockito.times(2)).applyQosPolicyToVolume(context.destVolume); + Mockito.verify(context.callback).complete(Mockito.argThat(result -> result != null && !result.isFailed())); + } + + @Test + public void liveMigrationStopsQosRetriesWhenInterrupted() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + OntapPrimaryDatastoreDriver ontapDriver = configureOntapNfsDriver(context); + Mockito.doThrow(new CloudRuntimeException("transient")).when(ontapDriver).applyQosPolicyToVolume(context.destVolume); + Thread.currentThread().interrupt(); + try { + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + Mockito.verify(ontapDriver, Mockito.times(1)).applyQosPolicyToVolume(context.destVolume); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } + private MigrateCommand captureMigrateCommand() throws Exception { ArgumentCaptor captor = ArgumentCaptor.forClass(MigrateCommand.class); Mockito.verify(agentManager).send(Mockito.eq(SRC_HOST_ID), captor.capture()); @@ -754,4 +1502,337 @@ private static class LiveMigrationTestContext { this.callback = callback; } } + + // =================================================================================== + // Assertions on the exact content of what the strategy sends, persists and cleans up. + // =================================================================================== + + private StoragePoolVO poolRow(long id) { + return primaryDataStoreDao.findById(id); + } + + private List modifyTargetsSentTo(long hostId, boolean add) { + ArgumentCaptor captor = ArgumentCaptor.forClass(ModifyTargetsCommand.class); + Mockito.verify(agentManager, Mockito.atLeast(0)).easySend(Mockito.eq(hostId), captor.capture()); + return captor.getAllValues().stream().filter(command -> command.getAdd() == add).collect(Collectors.toList()); + } + + private static Set iqnsOf(List commands) { + return commands.stream().flatMap(command -> command.getTargets().stream()) + .map(target -> target.get(ModifyTargetsCommand.IQN)).collect(Collectors.toSet()); + } + + private static void setField(Object target, String name, Object value) { + try { + java.lang.reflect.Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + @Test + public void liveMigrationMarksVmStateAndDrivesDestinationVolumeThroughMigrationEvents() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + Mockito.verify(context.vmTO).setState(VirtualMachine.State.Running); + InOrder order = Mockito.inOrder(context.destVolume); + order.verify(context.destVolume).processEvent(ObjectInDataStoreStateMachine.Event.MigrationCopyRequested); + order.verify(context.destVolume).processEvent(ObjectInDataStoreStateMachine.Event.MigrationCopySucceeded); + order.verify(context.destVolume).processEvent(ObjectInDataStoreStateMachine.Event.MigrationRequested); + DataStore destStore = context.destVolume.getDataStore(); + Mockito.verify(destStore.getDriver()).createAsync(Mockito.eq(destStore), Mockito.eq(context.destVolume), Mockito.isNull()); + Mockito.verify(context.destVolume, Mockito.never()).processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + Mockito.verify(volumeService, Mockito.never()).expungeVolumeAsync(Mockito.any()); + } + + @Test + public void liveMigrationPersistsDestinationRowWithOnlyDestinationPoolIdentity() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + VolumeVO sourceRow = volumeDao.findById(10L); + setField(sourceRow, "id", 10L); + sourceRow.setInstanceId(77L); + sourceRow.setChainInfo("chain-info"); + sourceRow.set_iScsiName("src-iqn"); + sourceRow.setPodId(4L); + sourceRow.setPoolId(1L); + sourceRow.setPoolType(StoragePoolType.Filesystem); + StoragePoolVO destPoolRow = poolRow(2L); + Mockito.doReturn(9L).when(destPoolRow).getPodId(); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + VolumeVO persisted = captureDuplicatedVolume(); + assertNull(persisted.getInstanceId()); + assertNull(persisted.getChainInfo()); + assertNull(persisted.getPath()); + assertNull(persisted.get_iScsiName()); + assertNull(persisted.getFolder()); + assertEquals(9L, persisted.getPodId()); + assertEquals(2L, persisted.getPoolId()); + assertEquals(StoragePoolType.NetworkFilesystem, persisted.getPoolType()); + assertEquals(1L, persisted.getLastPoolId()); + assertEquals(10L, persisted.getLastId()); + } + + @Test + public void liveMigrationRecordsPoolTypesOnDiskInfoAndFlagsTheCommandAsManaged() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + MigrateCommand command = captureMigrateCommand(); + MigrateDiskInfo diskInfo = command.getMigrateStorage().get("src-path"); + assertEquals(StoragePoolType.NetworkFilesystem, diskInfo.getSourcePoolType()); + assertEquals(StoragePoolType.NetworkFilesystem, diskInfo.getDestPoolType()); + assertEquals(86400, command.getWait()); + assertTrue(command.isMigrateStorageManaged()); + assertEquals("vm-name", command.getVmName()); + } + + @Test + public void liveMigrationToIscsiRecordsPoolTypesAndDisconnectsBothLunsFromSourceHostAfterSuccess() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("ISCSI", StoragePoolType.OntapiSCSI); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + MigrateDiskInfo diskInfo = captureMigrateCommand().getMigrateDiskInfoList().get(0); + assertEquals(StoragePoolType.OntapiSCSI, diskInfo.getSourcePoolType()); + assertEquals(StoragePoolType.OntapiSCSI, diskInfo.getDestPoolType()); + assertEquals(Set.of("/iqn/src/0", "/iqn/dest/1"), iqnsOf(modifyTargetsSentTo(SRC_HOST_ID, false))); + Mockito.verify(context.destVolumeVO).setLastId(10L); + Mockito.verify(context.destVolumeVO).setFormat(Storage.ImageFormat.RAW); + Mockito.verify(volumeDao, Mockito.atLeastOnce()).update(20L, context.destVolumeVO); + } + + @Test + public void liveMigrationToNfsNeverDisconnectsAnythingFromTheSourceHost() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + assertTrue(modifyTargetsSentTo(SRC_HOST_ID, false).isEmpty()); + Mockito.verify(context.destVolumeVO).setLastId(10L); + } + + @Test + public void connectCommandForNfsDestinationCarriesPoolIdentityAndVolumeUuid() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + StoragePoolVO destPoolRow = poolRow(2L); + Mockito.doReturn("10.1.1.2").when(destPoolRow).getHostAddress(); + Mockito.doReturn(2049).when(destPoolRow).getPort(); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + List connects = modifyTargetsSentTo(DEST_HOST_ID, true); + assertEquals(1, connects.size()); + ModifyTargetsCommand connect = connects.get(0); + assertTrue(connect.getApplyToAllHostsInCluster()); + assertEquals(ModifyTargetsCommand.TargetTypeToRemove.DYNAMIC, connect.getTargetTypeToRemove()); + assertEquals(1, connect.getTargets().size()); + Map target = connect.getTargets().get(0); + assertEquals("dest-uuid", target.get(ModifyTargetsCommand.IQN)); + assertEquals("NetworkFilesystem", target.get(ModifyTargetsCommand.STORAGE_TYPE)); + assertEquals("pool-uuid-2", target.get(ModifyTargetsCommand.STORAGE_UUID)); + assertEquals("10.1.1.2", target.get(ModifyTargetsCommand.STORAGE_HOST)); + assertEquals("2049", target.get(ModifyTargetsCommand.STORAGE_PORT)); + } + + @Test + public void connectCommandForIscsiDestinationUsesTheLunIqn() { + LiveMigrationTestContext context = configureLiveMigration("ISCSI", StoragePoolType.OntapiSCSI); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + List connects = modifyTargetsSentTo(DEST_HOST_ID, true); + assertEquals(Set.of("/iqn/dest/1"), iqnsOf(connects)); + assertEquals("OntapiSCSI", connects.get(0).getTargets().get(0).get(ModifyTargetsCommand.STORAGE_TYPE)); + } + + @Test + public void liveMigrationOnlyRewritesTheDiskMatchingTheMigratedVolume() { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + VolumeObjectTO otherVolumeTO = new VolumeObjectTO(); + otherVolumeTO.setId(99L); + DiskTO otherDisk = new DiskTO(); + otherDisk.setData(otherVolumeTO); + DiskTO diskWithoutData = new DiskTO(); + Mockito.doReturn(new DiskTO[] {otherDisk, diskWithoutData, context.vmDisk}).when(context.vmTO).getDisks(); + + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback); + + assertSame(otherVolumeTO, otherDisk.getData()); + assertNull(diskWithoutData.getData()); + assertSame(context.destVolumeTO, context.vmDisk.getData()); + } + + @Test + public void failedLiveMigrationRollsBackPreparationDisconnectsRevokesAndExpungesDestination() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("ISCSI", StoragePoolType.OntapiSCSI); + Mockito.doReturn(new MigrateAnswer(null, false, "libvirt refused", null)).when(agentManager) + .send(Mockito.eq(SRC_HOST_ID), Mockito.any(MigrateCommand.class)); + + assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback)); + + ArgumentCaptor prepare = ArgumentCaptor.forClass(PrepareForMigrationCommand.class); + Mockito.verify(agentManager, Mockito.times(2)).send(Mockito.eq(DEST_HOST_ID), prepare.capture()); + assertFalse(prepare.getAllValues().get(0).isRollback()); + assertTrue(prepare.getAllValues().get(1).isRollback()); + assertEquals(Set.of("/iqn/dest/1"), iqnsOf(modifyTargetsSentTo(DEST_HOST_ID, false))); + DataStore destStore = context.destVolume.getDataStore(); + InOrder order = Mockito.inOrder(volumeService, context.destVolume); + order.verify(volumeService).revokeAccess(context.destVolume, context.destHost, destStore); + order.verify(context.destVolume).processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + order.verify(context.destVolume).processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested); + order.verify(volumeService).expungeVolumeAsync(context.destVolume); + Mockito.verify(volumeService, Mockito.never()).copyPoliciesBetweenVolumesAndDestroySourceVolumeAfterMigration( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + ArgumentCaptor result = ArgumentCaptor.forClass(CopyCommandResult.class); + Mockito.verify(context.callback).complete(result.capture()); + assertTrue(result.getValue().isFailed()); + assertTrue(result.getValue().getResult().contains("libvirt refused"), result.getValue().getResult()); + } + + @Test + public void failureBeforeDestinationIsPreparedDoesNotSendARollbackToTheHost() throws Exception { + LiveMigrationTestContext context = configureLiveMigration("NFS3", StoragePoolType.NetworkFilesystem); + Mockito.doThrow(new CloudRuntimeException("grant failed")).when(volumeService) + .grantAccess(Mockito.eq(context.destVolume), Mockito.eq(context.destHost), Mockito.any()); + + assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.volumeMap, context.vmTO, context.srcHost, context.destHost, context.callback)); + + Mockito.verify(agentManager, Mockito.never()).send(Mockito.anyLong(), Mockito.any(PrepareForMigrationCommand.class)); + Mockito.verify(context.destVolume).processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + Mockito.verify(context.destVolume).processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested); + Mockito.verify(volumeService).expungeVolumeAsync(context.destVolume); + } + + // ------------------------------------------------------------------ offline migration + + @Test + public void offlineMigrationCreatesDestinationOnItsOwnStoreAndRevokesBothSides() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + DataStore destStore = context.destVolume.getDataStore(); + Mockito.verify(destStore.getDriver()).createAsync(Mockito.eq(destStore), Mockito.eq(context.destVolume), Mockito.isNull()); + Mockito.verify(volumeService).revokeAccess(context.srcVolume, context.host, context.srcVolume.getDataStore()); + // once after the copy command and once more when the whole migration finishes + Mockito.verify(volumeService, Mockito.times(2)).revokeAccess(context.destVolume, context.host, destStore); + Mockito.verify(volumeService, Mockito.times(2)).grantAccess(Mockito.eq(context.destVolume), Mockito.eq(context.host), Mockito.any()); + Mockito.verify(volumeService).grantAccess(Mockito.eq(context.srcVolume), Mockito.eq(context.host), Mockito.any()); + } + + @Test + public void offlineCopyCommandCarriesManagedVolumeDetailsForBothSides() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + StoragePoolVO srcPool = poolRow(1L); + StoragePoolVO destPool = poolRow(2L); + Mockito.doReturn("10.0.0.1").when(srcPool).getHostAddress(); + Mockito.doReturn(2049).when(srcPool).getPort(); + Mockito.doReturn("10.0.0.2").when(destPool).getHostAddress(); + Mockito.doReturn(3260).when(destPool).getPort(); + VolumeVO srcRow = volumeDao.findById(10L); + VolumeVO destRow = volumeDao.findById(20L); + Mockito.doReturn("src-iqn").when(srcRow).get_iScsiName(); + Mockito.doReturn(1000L).when(srcRow).getSize(); + Mockito.doReturn(2000L).when(destRow).getSize(); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CopyCommand.class); + Mockito.verify(agentManager).send(Mockito.eq(context.host.getId()), captor.capture()); + Map src = captor.getValue().getOptions(); + Map dest = captor.getValue().getOptions2(); + assertNotNull(src); + assertNotNull(dest); + assertEquals("10.0.0.1", src.get(DiskTO.STORAGE_HOST)); + assertEquals("2049", src.get(DiskTO.STORAGE_PORT)); + assertEquals("src-iqn", src.get(DiskTO.IQN)); + assertEquals("NetworkFilesystem", src.get(DiskTO.PROTOCOL_TYPE)); + assertEquals("1000", src.get(DiskTO.VOLUME_SIZE)); + assertEquals("10.0.0.2", dest.get(DiskTO.STORAGE_HOST)); + assertEquals("3260", dest.get(DiskTO.STORAGE_PORT)); + assertEquals("2000", dest.get(DiskTO.VOLUME_SIZE)); + assertEquals(10800, captor.getValue().getWait()); + } + + @Test + public void offlineMigrateVolumeCommandHasNoSourceDetailsWhenSourceIsNotManaged() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(false, "NFS3", "svm1", null); + StoragePoolVO destPoolRow = poolRow(2L); + Mockito.doReturn("10.0.0.2").when(destPoolRow).getHostAddress(); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(MigrateVolumeCommand.class))) + .thenReturn(new MigrateVolumeAnswer(null, true, null, "migrated")); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MigrateVolumeCommand.class); + Mockito.verify(agentManager).send(Mockito.eq(context.host.getId()), captor.capture()); + assertNull(captor.getValue().getSrcDetails()); + assertNotNull(captor.getValue().getDestDetails()); + assertEquals("10.0.0.2", captor.getValue().getDestDetails().get(DiskTO.STORAGE_HOST)); + assertEquals(10800, captor.getValue().getWaitInMillSeconds() / 1000); + } + + @Test + public void offlineMigrationReappliesQosOnDestinationNfsVolume() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + OntapPrimaryDatastoreDriver ontapDriver = Mockito.mock(OntapPrimaryDatastoreDriver.class); + DataStore destStoreRow = context.destVolume.getDataStore(); + Mockito.doReturn(ontapDriver).when(destStoreRow).getDriver(); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + Mockito.verify(ontapDriver).applyQosPolicyToVolume(context.destVolume); + } + + @Test + public void offlineMigrationSuccessReportsDestinationDataThroughTheCallback() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer(new VolumeObjectTO())); + + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CopyCommandResult.class); + Mockito.verify(context.callback).complete(captor.capture()); + CopyCommandResult result = captor.getValue(); + assertFalse(result.isFailed()); + assertNull(result.getResult()); + assertTrue(result.getAnswer().getResult()); + assertSame(context.destVolume.getTO(), ((CopyCmdAnswer)result.getAnswer()).getNewData()); + } + + @Test + public void offlineMigrationFailureReportsTheErrorThroughTheCallbackAndRethrows() throws Exception { + OfflineMigrationTestContext context = configureOfflineMigration(true, "NFS3", "svm1", null); + Mockito.when(agentManager.send(Mockito.eq(context.host.getId()), Mockito.any(CopyCommand.class))) + .thenReturn(new CopyCmdAnswer("copy blew up")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> + strategy.copyAsync(context.srcVolume, context.destVolume, (Host) null, context.callback)); + + assertEquals("copy blew up", thrown.getMessage()); + ArgumentCaptor captor = ArgumentCaptor.forClass(CopyCommandResult.class); + Mockito.verify(context.callback).complete(captor.capture()); + CopyCommandResult result = captor.getValue(); + assertTrue(result.isFailed()); + assertEquals("Primary storage migration failed due to an unexpected error: copy blew up", result.getResult()); + assertFalse(result.getAnswer().getResult()); + Mockito.verify(volumeService).revokeAccess(context.srcVolume, context.host, context.srcVolume.getDataStore()); + Mockito.verify(volumeDao, Mockito.never()).update(Mockito.eq(20L), Mockito.argThat(row -> "copied".equals(row.getPath()))); + } } diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/provider/StorageProviderFactoryTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/provider/StorageProviderFactoryTest.java new file mode 100644 index 000000000000..e897af98250e --- /dev/null +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/provider/StorageProviderFactoryTest.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.provider; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mockStatic; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import org.apache.cloudstack.storage.feign.model.OntapStorage; +import org.apache.cloudstack.storage.service.StorageStrategy; +import org.apache.cloudstack.storage.service.UnifiedNASStrategy; +import org.apache.cloudstack.storage.service.UnifiedSANStrategy; +import org.apache.cloudstack.storage.service.model.ProtocolType; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import com.cloud.utils.component.ComponentContext; + +class StorageProviderFactoryTest { + + private static String encoded(String plain) { + return Base64.getEncoder().encodeToString(plain.getBytes(StandardCharsets.UTF_8)); + } + + private static OntapStorage storage(String password, ProtocolType protocol) { + return new OntapStorage("admin", password, "10.0.0.1", "svm1", 1073741824L, protocol); + } + + @Test + void getStrategy_returnsNasStrategy_forNfs3() { + try (MockedStatic context = mockStatic(ComponentContext.class)) { + StorageStrategy strategy = StorageProviderFactory.getStrategy(storage(encoded("secret"), ProtocolType.NFS3)); + + assertInstanceOf(UnifiedNASStrategy.class, strategy); + context.verify(() -> ComponentContext.inject(any(UnifiedNASStrategy.class))); + } + } + + @Test + void getStrategy_returnsSanStrategy_forIscsi() { + try (MockedStatic context = mockStatic(ComponentContext.class)) { + StorageStrategy strategy = StorageProviderFactory.getStrategy(storage(encoded("secret"), ProtocolType.ISCSI)); + + assertInstanceOf(UnifiedSANStrategy.class, strategy); + context.verify(() -> ComponentContext.inject(any(UnifiedSANStrategy.class))); + } + } + + @Test + void getStrategy_rejectsPassword_thatIsNotBase64() { + try (MockedStatic context = mockStatic(ComponentContext.class)) { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> StorageProviderFactory.getStrategy(storage("not base64 !!", ProtocolType.ISCSI))); + + assertTrue(ex.getMessage() != null); + context.verifyNoInteractions(); + } + } + + @Test + void getStrategy_rejectsMissingProtocol() { + try (MockedStatic context = mockStatic(ComponentContext.class)) { + assertThrows(NullPointerException.class, + () -> StorageProviderFactory.getStrategy(storage(encoded("secret"), null))); + + context.verifyNoInteractions(); + } + } +} diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/StorageStrategyTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/StorageStrategyTest.java index 064a28ff512e..c243fd028c63 100644 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/StorageStrategyTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/StorageStrategyTest.java @@ -79,6 +79,25 @@ import feign.FeignException; import feign.Request; +import org.junit.jupiter.api.Nested; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; +import java.util.Arrays; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.cloudstack.storage.feign.client.EmsFeignClient; +import org.apache.cloudstack.storage.feign.client.NASFeignClient; +import org.apache.cloudstack.storage.feign.client.QosFeignClient; +import org.apache.cloudstack.storage.feign.model.EmsApplicationLog; +import org.apache.cloudstack.storage.feign.model.Version; +import org.apache.cloudstack.storage.feign.model.VolumeQosPolicy; +import org.apache.cloudstack.storage.utils.OntapStorageUtils; +import org.mockito.ArgumentCaptor; +import com.fasterxml.jackson.databind.ObjectMapper; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) @@ -1717,4 +1736,1616 @@ public void testUpdateStorageVolume_notFound_404_throwsCloudRuntimeException() { () -> storageStrategy.updateStorageVolume(volume)); assertTrue(ex.getMessage().contains("not found on ONTAP")); } + + /** + * Covers the {@link StorageStrategy} behaviour not exercised by {@link StorageStrategyTest}: + * QoS policy management, ASUP/cluster info, job polling, FlexVol snapshot deletion and the + * negative paths of volume/aggregate/iSCSI helpers. + */ + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + @Nested + class StorageStrategyQosAndOperationsTest { + + private static final String AUTH_USER = "admin"; + private static final String AUTH_PASSWORD = "password"; + + @Mock private AggregateFeignClient aggregateFeignClient; + @Mock private VolumeFeignClient volumeFeignClient; + @Mock private SvmFeignClient svmFeignClient; + @Mock private JobFeignClient jobFeignClient; + @Mock private SANFeignClient sanFeignClient; + @Mock private SnapshotFeignClient snapshotFeignClient; + @Mock private ClusterFeignClient clusterFeignClient; + @Mock private QosFeignClient qosFeignClient; + @Mock private EmsFeignClient emsFeignClient; + @Mock private NASFeignClient nasFeignClient; + @Mock private NetworkFeignClient networkFeignClient; + + private StorageStrategy strategy; + + /** Minimal concrete strategy; all protocol-specific operations are irrelevant here. */ + private class TestStrategy extends StorageStrategy { + TestStrategy(OntapStorage storage) { + super(storage); + } + + @Override public CloudStackVolume createCloudStackVolume(CloudStackVolume v) { + return null; + } + + @Override public CloudStackVolume createTemplateCache(StoragePoolVO pool, TemplateInfo template, + Map details, long sizeInBytes) { + return null; + } + + @Override public CloudStackVolume updateCloudStackVolume(CloudStackVolume v) { + return null; + } + + @Override public void deleteCloudStackVolume(CloudStackVolume v) { + } + + @Override public CloudStackVolume cloneCloudStackVolume(CloudStackVolume v) { + return null; + } + + @Override public CloudStackVolume copyCloudStackVolume(VolumeInfo src, VolumeInfo dest, + StoragePoolVO destPool, Map destDetails, int timeoutSeconds) { + return null; + } + + @Override public void resizeCloudStackVolume(CloudStackVolume v, long sizeInBytes) { + } + + @Override public CloudStackVolume getCloudStackVolume(Map m) { + return null; + } + + @Override public JobResponse revertSnapshotForCloudStackVolume(String snapshotName, String flexVolUuid, + String snapshotUuid, String volumePath, String lunUuid, String flexVolName) { + return null; + } + + @Override public AccessGroup createAccessGroup(AccessGroup g) { + return null; + } + + @Override public void deleteAccessGroup(AccessGroup g) { + } + + @Override public AccessGroup updateAccessGroup(AccessGroup g) { + return null; + } + + @Override public AccessGroup getAccessGroup(Map m) { + return null; + } + + @Override public String enableLogicalAccess(Map m) { + return null; + } + + @Override public void disableLogicalAccess(Map m) { + } + + @Override public String getLogicalAccess(Map m) { + return null; + } + } + + @BeforeEach + void setUp() { + strategy = newStrategy(ProtocolType.NFS3); + } + + private StorageStrategy newStrategy(ProtocolType protocol) { + StorageStrategy s = new TestStrategy( + new OntapStorage(AUTH_USER, AUTH_PASSWORD, "192.168.1.100", "svm1", 5_000_000_000L, protocol)); + s.aggregateFeignClient = aggregateFeignClient; + s.volumeFeignClient = volumeFeignClient; + s.svmFeignClient = svmFeignClient; + s.jobFeignClient = jobFeignClient; + s.sanFeignClient = sanFeignClient; + s.snapshotFeignClient = snapshotFeignClient; + s.clusterFeignClient = clusterFeignClient; + s.qosFeignClient = qosFeignClient; + s.emsFeignClient = emsFeignClient; + s.nasFeignClient = nasFeignClient; + s.networkFeignClient = networkFeignClient; + return s; + } + + // ------------------------------------------------------------------ helpers + + private FeignException feignError(int status, String message) { + Request request = Request.create(Request.HttpMethod.GET, "http://test", Collections.emptyMap(), + (byte[]) null, (Charset) null); + return new FeignException.FeignClientException(status, message, request, null); + } + + private Version version(String json) throws Exception { + return new ObjectMapper().readValue(json, Version.class); + } + + private Job job(String uuid, String state, String message) { + Job job = new Job(); + job.setUuid(uuid); + job.setState(state); + job.setMessage(message); + return job; + } + + private JobResponse jobResponse(String uuid) { + JobResponse response = new JobResponse(); + response.setJob(job(uuid, OntapStorageConstants.JOB_RUNNING, null)); + return response; + } + + private ClusterNode node(String model, Boolean allFlash, Boolean capacityOptimized) { + ClusterNode node = new ClusterNode(); + node.setModel(model); + node.setAllFlashOptimized(allFlash); + node.setCapacityOptimized(capacityOptimized); + return node; + } + + private OntapResponse records(List records) { + OntapResponse response = new OntapResponse<>(); + response.setRecords(records); + return response; + } + + private VolumeQosPolicy policy(String uuid, Integer objectCount) { + VolumeQosPolicy policy = new VolumeQosPolicy(); + policy.setUuid(uuid); + policy.setName("cs_policy"); + policy.setObjectCount(objectCount); + return policy; + } + + private Aggregate aggregate(String name, String uuid, Double availableBytes, String nodeName, + Aggregate.StateEnum state) { + Aggregate aggregate = new Aggregate(); + aggregate.setName(name); + aggregate.setUuid(uuid); + aggregate.setState(state); + if (availableBytes != null) { + Aggregate.AggregateSpaceBlockStorage blockStorage = new Aggregate.AggregateSpaceBlockStorage(); + blockStorage.setAvailable(availableBytes); + Aggregate.AggregateSpace space = new Aggregate.AggregateSpace(); + space.setBlockStorage(blockStorage); + aggregate.setSpace(space); + } + if (nodeName != null) { + Aggregate.Node node = new Aggregate.Node(); + node.setName(nodeName); + aggregate.setNode(node); + } + return aggregate; + } + + // ------------------------------------------------------------- simple accessors + + @Test + void accessors_exposeInjectedFeignClients() { + assertSame(snapshotFeignClient, strategy.getSnapshotFeignClient()); + assertSame(nasFeignClient, strategy.getNasFeignClient()); + } + + @Test + void getAuthHeader_matchesUtilsHeaderForConfiguredCredentials() { + assertEquals(OntapStorageUtils.generateAuthHeader(AUTH_USER, AUTH_PASSWORD), strategy.getAuthHeader()); + } + + @Test + void aggregates_roundTripThroughSetter() { + List aggregates = List.of(aggregate("a1", "u1", 1.0, "n1", Aggregate.StateEnum.ONLINE)); + + strategy.setAggregates(aggregates); + + assertSame(aggregates, strategy.getAggregates()); + } + + // ------------------------------------------------------------- getClusterInfo + + @Test + void getClusterInfo_returnsNull_whenClusterCallFails() { + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenThrow(feignError(500, "boom")); + + assertNull(strategy.getClusterInfo()); + verify(clusterFeignClient, never()).getClusterNodes(anyString(), anyMap()); + } + + @Test + void getClusterInfo_returnsNull_whenClusterIsNotReturned() { + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenReturn(null); + + assertNull(strategy.getClusterInfo()); + verify(clusterFeignClient, never()).getClusterNodes(anyString(), anyMap()); + } + + @Test + void getClusterInfo_rollsUpSingleFasNode() { + Cluster cluster = new Cluster(); + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenReturn(cluster); + when(clusterFeignClient.getClusterNodes(anyString(), anyMap())) + .thenReturn(records(List.of(node(" FAS8300 ", false, null)))); + + Cluster result = strategy.getClusterInfo(); + + assertSame(cluster, result); + assertEquals("FAS8300", result.getModel()); + assertEquals(OntapStorageConstants.ASUP_PLATFORM_TYPE_FAS, result.getPlatformType()); + } + + @Test + void getClusterInfo_reportsPerformance_forAllFlashNode() { + Cluster cluster = new Cluster(); + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenReturn(cluster); + when(clusterFeignClient.getClusterNodes(anyString(), anyMap())) + .thenReturn(records(List.of(node("AFF-A400", true, false)))); + + assertEquals(OntapStorageConstants.ASUP_PLATFORM_TYPE_PERFORMANCE, strategy.getClusterInfo().getPlatformType()); + } + + @Test + void getClusterInfo_reportsCapacity_forCapacityOptimizedNode() { + Cluster cluster = new Cluster(); + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenReturn(cluster); + when(clusterFeignClient.getClusterNodes(anyString(), anyMap())) + .thenReturn(records(List.of(node("AFF-C250", true, true)))); + + assertEquals(OntapStorageConstants.ASUP_PLATFORM_TYPE_CAPACITY, strategy.getClusterInfo().getPlatformType()); + } + + @Test + void getClusterInfo_reportsComposite_andDeduplicatesModels_forMixedNodes() { + Cluster cluster = new Cluster(); + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenReturn(cluster); + when(clusterFeignClient.getClusterNodes(anyString(), anyMap())).thenReturn(records(Arrays.asList( + node("AFF-A400", true, false), + node("AFF-A400", true, false), + node("FAS8300", false, null), + null, + node(" ", null, null)))); + + Cluster result = strategy.getClusterInfo(); + + assertEquals("AFF-A400,FAS8300", result.getModel()); + assertEquals(OntapStorageConstants.ASUP_PLATFORM_TYPE_COMPOSITE, result.getPlatformType()); + } + + @Test + void getClusterInfo_leavesPlatformTypeUnset_whenNodeOmitsAllFlashFlag() { + Cluster cluster = new Cluster(); + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenReturn(cluster); + when(clusterFeignClient.getClusterNodes(anyString(), anyMap())) + .thenReturn(records(List.of(node("AFF-A400", null, null)))); + + Cluster result = strategy.getClusterInfo(); + + assertEquals("AFF-A400", result.getModel()); + assertNull(result.getPlatformType()); + } + + @Test + void getClusterInfo_leavesHardwareUnset_whenNodeListIsEmptyOrMissing() { + Cluster cluster = new Cluster(); + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenReturn(cluster); + when(clusterFeignClient.getClusterNodes(anyString(), anyMap())) + .thenReturn(null) + .thenReturn(records(Collections.emptyList())) + .thenReturn(records(null)); + + for (int i = 0; i < 3; i++) { + Cluster result = strategy.getClusterInfo(); + assertNotNull(result); + assertNull(result.getModel()); + assertNull(result.getPlatformType()); + } + } + + @Test + void getClusterInfo_stillReturnsCluster_whenNodeCallFails() { + Cluster cluster = new Cluster(); + cluster.setName("cluster1"); + when(clusterFeignClient.getCluster(anyString(), eq(true))).thenReturn(cluster); + when(clusterFeignClient.getClusterNodes(anyString(), anyMap())).thenThrow(feignError(500, "nodes down")); + + Cluster result = strategy.getClusterInfo(); + + assertSame(cluster, result); + assertNull(result.getModel()); + } + + // ------------------------------------------------------------- getClusterVersion + + @Test + void getClusterVersion_returnsNull_forNullClusterOrVersion() { + assertNull(strategy.getClusterVersion(null)); + assertNull(strategy.getClusterVersion(new Cluster())); + } + + @Test + void getClusterVersion_prefersNumericGenerationMajorMinor() throws Exception { + Cluster cluster = new Cluster(); + cluster.setVersion(version("{\"generation\":9,\"major\":17,\"minor\":1,\"full\":\"NetApp Release 9.17.1: Mon\"}")); + + assertEquals("9.17.1", strategy.getClusterVersion(cluster)); + } + + @Test + void getClusterVersion_fallsBackToFull_whenNumericPartsIncomplete() throws Exception { + Cluster cluster = new Cluster(); + cluster.setVersion(version("{\"generation\":9,\"major\":17,\"full\":\"NetApp Release 9.17\"}")); + + assertEquals("NetApp Release 9.17", strategy.getClusterVersion(cluster)); + } + + @Test + void getClusterVersion_returnsNull_whenNothingUsable() throws Exception { + Cluster noFull = new Cluster(); + noFull.setVersion(version("{\"generation\":9}")); + Cluster emptyFull = new Cluster(); + emptyFull.setVersion(version("{\"full\":\"\"}")); + + assertNull(strategy.getClusterVersion(noFull)); + assertNull(strategy.getClusterVersion(emptyFull)); + } + + // ------------------------------------------------------------- sendAsupMessage + + @Test + void sendAsupMessage_ignoresNullMessage() { + strategy.sendAsupMessage(null); + + verifyNoInteractions(emsFeignClient); + } + + @Test + void sendAsupMessage_postsMessageToEms() { + EmsApplicationLog message = new EmsApplicationLog(); + message.setEventId("cloudstack.asup"); + + strategy.sendAsupMessage(message); + + verify(emsFeignClient).sendEmsApplicationLog(eq(strategy.getAuthHeader()), eq(message)); + } + + @Test + void sendAsupMessage_swallowsFailures() { + EmsApplicationLog message = new EmsApplicationLog(); + message.setEventId("cloudstack.asup"); + org.mockito.Mockito.doThrow(feignError(503, "ems down")).when(emsFeignClient) + .sendEmsApplicationLog(anyString(), any(EmsApplicationLog.class)); + + strategy.sendAsupMessage(message); + + verify(emsFeignClient, times(1)).sendEmsApplicationLog(anyString(), any(EmsApplicationLog.class)); + } + + // ------------------------------------------------------------- connect / svm + + private Svm svm(String state, Boolean nfs, Boolean iscsi) { + Svm svm = new Svm(); + svm.setName("svm1"); + svm.setUuid("svm-uuid"); + svm.setState(state); + svm.setNfsEnabled(nfs); + svm.setIscsiEnabled(iscsi); + return svm; + } + + @Test + void connect_recordsResolvedSvmUuid_whenAggregateValidationSkipped() { + when(svmFeignClient.getSvmResponse(anyMap(), anyString())) + .thenReturn(records(List.of(svm(OntapStorageConstants.RUNNING, true, false)))); + + assertNull(strategy.getResolvedSvmUuid()); + assertTrue(strategy.connect(false)); + + assertEquals("svm-uuid", strategy.getResolvedSvmUuid()); + verifyNoInteractions(aggregateFeignClient); + } + + @Test + void connect_fails_whenSvmNotFound() { + when(svmFeignClient.getSvmResponse(anyMap(), anyString())).thenReturn(records(Collections.emptyList())); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.connect(false)); + + assertTrue(ex.getMessage().contains("No SVM found"), ex.getMessage()); + } + + @Test + void connect_fails_whenSvmResponseIsNull() { + when(svmFeignClient.getSvmResponse(anyMap(), anyString())).thenReturn(null); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.connect(false)); + + assertEquals("No SVM found on the ONTAP cluster by the name svm1.", ex.getMessage()); + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(svmFeignClient).getSvmResponse(query.capture(), anyString()); + assertEquals("svm1", query.getValue().get(OntapStorageConstants.NAME)); + assertEquals(OntapStorageConstants.AGGREGATES + OntapStorageConstants.COMMA + OntapStorageConstants.STATE + + OntapStorageConstants.COMMA + OntapStorageConstants.NFS_ENABLED + OntapStorageConstants.COMMA + + OntapStorageConstants.ISCSI_ENABLED, query.getValue().get(OntapStorageConstants.FIELDS)); + } + + @Test + void connect_fails_whenSvmNotRunning() { + when(svmFeignClient.getSvmResponse(anyMap(), anyString())) + .thenReturn(records(List.of(svm("stopped", true, true)))); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.connect(false)); + + assertTrue(ex.getMessage().contains("not in running state"), ex.getMessage()); + } + + @Test + void connect_fails_whenNfsNotEnabledForNfsPool() { + when(svmFeignClient.getSvmResponse(anyMap(), anyString())) + .thenReturn(records(List.of(svm(OntapStorageConstants.RUNNING, false, true)))); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.connect(false)); + + assertTrue(ex.getMessage().contains("NFS protocol is not enabled"), ex.getMessage()); + } + + @Test + void connect_fails_whenIscsiNotEnabledForIscsiPool() { + StorageStrategy iscsi = newStrategy(ProtocolType.ISCSI); + when(svmFeignClient.getSvmResponse(anyMap(), anyString())) + .thenReturn(records(List.of(svm(OntapStorageConstants.RUNNING, true, false)))); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> iscsi.connect(false)); + + assertTrue(ex.getMessage().contains("ISCSI protocol is not enabled"), ex.getMessage()); + } + + @Test + void connect_wrapsUnexpectedFailures() { + when(svmFeignClient.getSvmResponse(anyMap(), anyString())).thenThrow(new IllegalStateException("socket closed")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.connect(false)); + + assertTrue(ex.getMessage().contains("Failed to connect to ONTAP cluster"), ex.getMessage()); + assertTrue(ex.getCause() instanceof IllegalStateException); + } + + @Test + void connect_failsWithAggregateError_whenSvmHasNoAggregates() { + Svm noAggregates = svm(OntapStorageConstants.RUNNING, true, true); + noAggregates.setAggregates(Collections.emptyList()); + when(svmFeignClient.getSvmResponse(anyMap(), anyString())).thenReturn(records(List.of(noAggregates))); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.connect(true)); + + assertTrue(ex.getMessage().contains("No aggregates are assigned"), ex.getMessage()); + } + + @Test + void connect_failsWhenNoAggregateIsOnlineWithEnoughSpace() { + Svm withAggregates = svm(OntapStorageConstants.RUNNING, true, true); + withAggregates.setAggregates(List.of( + aggregate("offline", "u-offline", null, null, null), + aggregate("missing", "u-missing", null, null, null), + aggregate("small", "u-small", null, null, null))); + when(svmFeignClient.getSvmResponse(anyMap(), anyString())).thenReturn(records(List.of(withAggregates))); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-offline"), anyMap())) + .thenReturn(aggregate("offline", "u-offline", 9e12, "n1", null)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-missing"), anyMap())).thenReturn(null); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-small"), anyMap())) + .thenReturn(aggregate("small", "u-small", 1.0, "n1", Aggregate.StateEnum.ONLINE)); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.connect(true)); + + assertTrue(ex.getMessage().contains("No suitable aggregates"), ex.getMessage()); + } + + // ------------------------------------------------------------- chooseAggregate + + @Test + void chooseAggregate_rejectsEmptyCandidates() { + CloudRuntimeException nullList = assertThrows(CloudRuntimeException.class, + () -> strategy.chooseAggregate(null, 10L)); + CloudRuntimeException emptyList = assertThrows(CloudRuntimeException.class, + () -> strategy.chooseAggregate(Collections.emptyList(), 10L)); + + assertEquals("No aggregates available to create volume on SVM svm1", nullList.getMessage()); + assertEquals("No aggregates available to create volume on SVM svm1", emptyList.getMessage()); + verifyNoInteractions(aggregateFeignClient); + } + + @Test + void chooseAggregate_rejectsInvalidSize() { + List candidates = List.of(aggregate("a1", "u1", null, null, null)); + + assertEquals("Invalid volume size provided: null", + assertThrows(CloudRuntimeException.class, () -> strategy.chooseAggregate(candidates, null)).getMessage()); + assertEquals("Invalid volume size provided: 0", + assertThrows(CloudRuntimeException.class, () -> strategy.chooseAggregate(candidates, 0L)).getMessage()); + assertEquals("Invalid volume size provided: -5", + assertThrows(CloudRuntimeException.class, () -> strategy.chooseAggregate(candidates, -5L)).getMessage()); + verifyNoInteractions(aggregateFeignClient); + } + + @Test + void chooseAggregate_picksLargestEligibleAggregate_andSkipsUnusableOnes() { + List candidates = Arrays.asList( + aggregate("gone", "u-gone", null, null, null), + aggregate("offline", "u-offline", null, null, null), + aggregate("nospace", "u-nospace", null, null, null), + aggregate("tiny", "u-tiny", null, null, null), + aggregate("small", "u-small", null, null, null), + aggregate("big", "u-big", null, null, null)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-gone"), anyMap())).thenReturn(null); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-offline"), anyMap())) + .thenReturn(aggregate("offline", "u-offline", 9e12, "n1", null)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-nospace"), anyMap())) + .thenReturn(aggregate("nospace", "u-nospace", null, "n1", Aggregate.StateEnum.ONLINE)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-tiny"), anyMap())) + .thenReturn(aggregate("tiny", "u-tiny", 100.0, "n1", Aggregate.StateEnum.ONLINE)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-small"), anyMap())) + .thenReturn(aggregate("small", "u-small", 5000.0, "n2", Aggregate.StateEnum.ONLINE)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-big"), anyMap())) + .thenReturn(aggregate("big", "u-big", 90000.0, "n3", Aggregate.StateEnum.ONLINE)); + + Aggregate chosen = strategy.chooseAggregate(candidates, 1000L); + + assertEquals("big", chosen.getName()); + assertEquals("n3", chosen.getNode().getName()); + } + + @Test + void chooseAggregate_fails_whenNoAggregateFitsRequestedSize() { + List candidates = List.of(aggregate("a1", "u1", null, null, null)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u1"), anyMap())) + .thenReturn(aggregate("a1", "u1", 1000.0, "n1", Aggregate.StateEnum.ONLINE)); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.chooseAggregate(candidates, 1000L)); + + assertTrue(ex.getMessage().contains("No suitable aggregates"), ex.getMessage()); + } + + @Test + void chooseAggregate_fails_whenChosenAggregateHasNoNodeName() { + List candidates = List.of(aggregate("a1", "u1", null, null, null)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u1"), anyMap())) + .thenReturn(aggregate("a1", "u1", 9000.0, null, Aggregate.StateEnum.ONLINE)); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.chooseAggregate(candidates, 1000L)); + + assertTrue(ex.getMessage().contains("node name"), ex.getMessage()); + } + + // ------------------------------------------------------------- createStorageVolume + + private StorageStrategy strategyWithInstantJobs() { + StorageStrategy spied = spy(strategy); + doReturn(true).when(spied).jobPollForSuccess(anyString(), anyInt(), anyInt()); + return spied; + } + + private Volume namedVolume(String name, String uuid) { + Volume volume = new Volume(); + volume.setName(name); + volume.setUuid(uuid); + return volume; + } + + private Aggregate chosenAggregate() { + return aggregate("aggr1", "aggr-uuid", null, "node1", Aggregate.StateEnum.ONLINE); + } + + private void assertVol1WasCreated(int times, long size) { + ArgumentCaptor request = ArgumentCaptor.forClass(Volume.class); + verify(volumeFeignClient, times(times)).createVolumeWithJob(anyString(), request.capture()); + for (Volume sent : request.getAllValues()) { + assertEquals("vol1", sent.getName()); + assertEquals(size, sent.getSize()); + assertEquals("svm1", sent.getSvm().getName()); + assertEquals("/vol1", sent.getNas().getPath()); + assertEquals("aggr-uuid", sent.getAggregates().get(0).getUuid()); + } + } + + @SuppressWarnings("unchecked") + private void assertVolumesWereListedByName(int times) { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(volumeFeignClient, times(times)).getAllVolumes(anyString(), query.capture()); + for (Map value : query.getAllValues()) { + assertEquals("vol1", value.get(OntapStorageConstants.NAME)); + } + } + + @SuppressWarnings("unchecked") + private void assertVolumeDetailsWereReadByName(int times) { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(volumeFeignClient, times(times)).getVolume(anyString(), query.capture()); + for (Map value : query.getAllValues()) { + assertEquals("vol1", value.get(OntapStorageConstants.NAME)); + } + } + + private void assertQosPolicyWasSent(int times) { + ArgumentCaptor sent = ArgumentCaptor.forClass(VolumeQosPolicy.class); + verify(qosFeignClient, times(times)).createPolicy(anyString(), sent.capture()); + for (VolumeQosPolicy policy : sent.getAllValues()) { + assertEquals("cs_policy", policy.getName()); + assertEquals("svm1", policy.getSvm().getName()); + assertNull(policy.getFixed().getMinThroughputIops()); + assertEquals(100L, policy.getFixed().getMaxThroughputIops()); + } + } + + @SuppressWarnings("unchecked") + private void assertQosPolicyWasLookedUp(int times) { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(qosFeignClient, times(times)).getPolicies(anyString(), query.capture()); + for (Map value : query.getAllValues()) { + assertEquals("cs_policy", value.get(OntapStorageConstants.NAME)); + assertEquals("svm1", value.get(OntapStorageConstants.SVM_DOT_NAME)); + } + } + + @SuppressWarnings("unchecked") + private void assertIscsiServiceWasQueried(int times) { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient, times(times)).getIscsiServices(anyString(), query.capture()); + for (Map value : query.getAllValues()) { + assertEquals("svm1", value.get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals("enabled,target", value.get(OntapStorageConstants.FIELDS)); + assertEquals("1", value.get("max_records")); + } + } + + @Test + void createStorageVolume_rejectsInvalidSize() { + assertThrows(CloudRuntimeException.class, () -> strategy.createStorageVolume("vol", null, chosenAggregate())); + assertThrows(CloudRuntimeException.class, () -> strategy.createStorageVolume("vol", 0L, chosenAggregate())); + verifyNoInteractions(volumeFeignClient); + } + + @Test + void createStorageVolume_rejectsIncompleteAggregate() { + assertThrows(CloudRuntimeException.class, () -> strategy.createStorageVolume("vol", 10L, null)); + assertThrows(CloudRuntimeException.class, + () -> strategy.createStorageVolume("vol", 10L, aggregate(null, "u", null, null, null))); + assertThrows(CloudRuntimeException.class, + () -> strategy.createStorageVolume("vol", 10L, aggregate("n", null, null, null, null))); + verifyNoInteractions(volumeFeignClient); + } + + @Test + void createStorageVolume_createsThinNasVolumeOnChosenAggregate() { + StorageStrategy spied = strategyWithInstantJobs(); + Volume created = namedVolume("vol1", "vol-uuid"); + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(jobResponse("job-1")); + when(volumeFeignClient.getAllVolumes(anyString(), anyMap())).thenReturn(records(List.of(created))); + when(volumeFeignClient.getVolume(anyString(), anyMap())).thenReturn(records(List.of(created))); + + Volume result = spied.createStorageVolume("vol1", 2048L, chosenAggregate()); + + assertSame(created, result); + ArgumentCaptor request = ArgumentCaptor.forClass(Volume.class); + verify(volumeFeignClient).createVolumeWithJob(anyString(), request.capture()); + assertEquals("vol1", request.getValue().getName()); + assertEquals(2048L, request.getValue().getSize()); + assertEquals("svm1", request.getValue().getSvm().getName()); + assertEquals("/vol1", request.getValue().getNas().getPath()); + assertEquals(Volume.Guarantee.TypeEnum.NONE, request.getValue().getGuarantee().getType()); + assertEquals("aggr-uuid", request.getValue().getAggregates().get(0).getUuid()); + } + + @Test + void createStorageVolume_fails_whenCreateCallReturnsNoJob() { + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(new JobResponse()); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.createStorageVolume("vol1", 10L, chosenAggregate())); + + assertEquals("Failed to create volume: Failed to initiate volume creation for vol1", ex.getMessage()); + assertVol1WasCreated(1, 10L); + verify(volumeFeignClient, never()).getAllVolumes(anyString(), anyMap()); + } + + @Test + void createStorageVolume_fails_whenCreateCallReturnsNull() { + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(null); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.createStorageVolume("vol1", 10L, chosenAggregate())); + + assertEquals("Failed to create volume: Failed to initiate volume creation for vol1", ex.getMessage()); + ArgumentCaptor request = ArgumentCaptor.forClass(Volume.class); + verify(volumeFeignClient).createVolumeWithJob(anyString(), request.capture()); + assertEquals("vol1", request.getValue().getName()); + assertEquals(10L, request.getValue().getSize()); + assertEquals("svm1", request.getValue().getSvm().getName()); + assertEquals("aggr-uuid", request.getValue().getAggregates().get(0).getUuid()); + verify(volumeFeignClient, never()).getAllVolumes(anyString(), anyMap()); + } + + @Test + void createStorageVolume_fails_whenJobDoesNotSucceed() { + StorageStrategy spied = spy(strategy); + doReturn(false).when(spied).jobPollForSuccess(eq("job-1"), eq(30), eq(2000)); + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(jobResponse("job-1")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> spied.createStorageVolume("vol1", 10L, chosenAggregate())); + + assertEquals("Failed to create volume: Volume creation job failed for volume: vol1", ex.getMessage()); + assertVol1WasCreated(1, 10L); + verify(spied).jobPollForSuccess("job-1", 30, 2000); + verify(volumeFeignClient, never()).getAllVolumes(anyString(), anyMap()); + } + + @Test + void createStorageVolume_wrapsFeignFailureOnCreate() { + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenThrow(feignError(400, "bad")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.createStorageVolume("vol1", 10L, chosenAggregate())); + + assertTrue(ex.getMessage().startsWith("Failed to create volume: "), ex.getMessage()); + assertTrue(ex.getMessage().contains("bad"), ex.getMessage()); + assertVol1WasCreated(1, 10L); + verify(volumeFeignClient, never()).getAllVolumes(anyString(), anyMap()); + } + + @Test + void createStorageVolume_fails_whenVolumeNotListedAfterCreation() { + StorageStrategy spied = strategyWithInstantJobs(); + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(jobResponse("job-1")); + when(volumeFeignClient.getAllVolumes(anyString(), anyMap())) + .thenReturn(null) + .thenReturn(records(null)) + .thenReturn(records(Collections.emptyList())); + + for (int i = 0; i < 3; i++) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> spied.createStorageVolume("vol1", 10L, chosenAggregate())); + assertEquals("Volume vol1 not found after creation.", ex.getMessage()); + } + assertVol1WasCreated(3, 10L); + assertVolumesWereListedByName(3); + } + + @Test + void createStorageVolume_fails_whenListedRecordIsNull() { + StorageStrategy spied = strategyWithInstantJobs(); + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(jobResponse("job-1")); + when(volumeFeignClient.getAllVolumes(anyString(), anyMap())) + .thenReturn(records(Collections.singletonList((Volume) null))); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> spied.createStorageVolume("vol1", 10L, chosenAggregate())); + + assertEquals("Failed to retrieve details of the created volume vol1", ex.getMessage()); + assertVol1WasCreated(1, 10L); + assertVolumesWereListedByName(1); + } + + @Test + void createStorageVolume_fails_whenListedVolumeNameDiffers() { + StorageStrategy spied = strategyWithInstantJobs(); + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(jobResponse("job-1")); + when(volumeFeignClient.getAllVolumes(anyString(), anyMap())) + .thenReturn(records(List.of(namedVolume("other", "u")))) + .thenReturn(records(List.of(namedVolume(null, "u")))); + + String[] expected = { + "Mismatch in created volume name. Expected: vol1, Found: other", + "Mismatch in created volume name. Expected: vol1, Found: null" + }; + for (String message : expected) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> spied.createStorageVolume("vol1", 10L, chosenAggregate())); + assertEquals(message, ex.getMessage()); + } + assertVol1WasCreated(2, 10L); + assertVolumesWereListedByName(2); + } + + @Test + void createStorageVolume_fails_whenVolumeDetailsCannotBeFetched() { + StorageStrategy spied = strategyWithInstantJobs(); + Volume created = namedVolume("vol1", "vol-uuid"); + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(jobResponse("job-1")); + when(volumeFeignClient.getAllVolumes(anyString(), anyMap())).thenReturn(records(List.of(created))); + when(volumeFeignClient.getVolume(anyString(), anyMap())) + .thenReturn(null) + .thenReturn(records(null)) + .thenReturn(records(Collections.emptyList())); + + String[] expected = { + "Failed to fetch volume: vol1. Error: Failed to fetch volume vol1: Response is null", + "Failed to fetch volume: vol1. Error: Failed to fetch volume vol1: Records list is null", + "Failed to fetch volume: vol1. Error: Failed to fetch volume vol1: No records found" + }; + for (String message : expected) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> spied.createStorageVolume("vol1", 10L, chosenAggregate())); + assertEquals(message, ex.getMessage()); + } + assertVol1WasCreated(3, 10L); + assertVolumesWereListedByName(3); + assertVolumeDetailsWereReadByName(3); + } + + // ------------------------------------------------------------- delete/get volume + + @Test + void deleteStorageVolume_treatsMissingVolumeAsNoOp() { + when(volumeFeignClient.deleteVolume(anyString(), eq("vol-uuid"))).thenThrow(feignError(404, "gone")); + + strategy.deleteStorageVolume(namedVolume("vol1", "vol-uuid")); + + verifyNoInteractions(jobFeignClient); + } + + @Test + void deleteStorageVolume_wrapsOtherFeignFailures() { + when(volumeFeignClient.deleteVolume(anyString(), eq("vol-uuid"))).thenThrow(feignError(500, "server error")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteStorageVolume(namedVolume("vol1", "vol-uuid"))); + + assertTrue(ex.getMessage().startsWith("Failed to delete volume"), ex.getMessage()); + } + + @Test + void getStorageVolume_rejectsBlankUuid() { + assertThrows(CloudRuntimeException.class, () -> strategy.getStorageVolume(null, null)); + assertThrows(CloudRuntimeException.class, () -> strategy.getStorageVolume(" ", null)); + verifyNoInteractions(volumeFeignClient); + } + + @Test + void getStorageVolume_usesEmptyQuery_whenNoneProvided() { + Volume volume = namedVolume("vol1", "u1"); + when(volumeFeignClient.getVolumeByUUID(anyString(), eq("u1"), eq(Collections.emptyMap()))).thenReturn(volume); + + assertSame(volume, strategy.getStorageVolume("u1", null)); + } + + @Test + void getStorageVolume_returnsNull_whenOntapReportsNotFound() { + when(volumeFeignClient.getVolumeByUUID(anyString(), eq("u1"), anyMap())).thenThrow(feignError(404, "missing")); + + assertNull(strategy.getStorageVolume("u1", Map.of("fields", "space.used"))); + + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(volumeFeignClient).getVolumeByUUID(anyString(), eq("u1"), query.capture()); + assertEquals("space.used", query.getValue().get("fields")); + } + + @Test + void getStorageVolume_wrapsOtherFailures() { + when(volumeFeignClient.getVolumeByUUID(anyString(), eq("u1"), anyMap())).thenThrow(feignError(500, "oops")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.getStorageVolume("u1", Map.of())); + + assertTrue(ex.getMessage().contains("Failed to fetch volume"), ex.getMessage()); + assertTrue(ex.getMessage().contains("oops"), ex.getMessage()); + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(volumeFeignClient).getVolumeByUUID(anyString(), eq("u1"), query.capture()); + assertTrue(query.getValue().isEmpty(), query.getValue().toString()); + } + + // ------------------------------------------------------------- getStoragePath + + private IscsiService iscsiService(String targetName) { + IscsiService service = new IscsiService(); + if (targetName != null) { + IscsiService.IscsiServiceTarget target = new IscsiService.IscsiServiceTarget(); + target.setName(targetName); + service.setTarget(target); + } + return service; + } + + @Test + void getStoragePath_returnsTargetIqn_forIscsi() { + StorageStrategy iscsi = newStrategy(ProtocolType.ISCSI); + when(sanFeignClient.getIscsiServices(anyString(), anyMap())) + .thenReturn(records(List.of(iscsiService("iqn.1992-08.com.netapp:sn.1:vs.3")))); + + assertEquals("iqn.1992-08.com.netapp:sn.1:vs.3", iscsi.getStoragePath()); + + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient).getIscsiServices(anyString(), query.capture()); + assertEquals("svm1", query.getValue().get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals("enabled,target", query.getValue().get(OntapStorageConstants.FIELDS)); + assertEquals("1", query.getValue().get("max_records")); + } + + @Test + void getStoragePath_fails_whenIscsiServiceMissing() { + StorageStrategy iscsi = newStrategy(ProtocolType.ISCSI); + when(sanFeignClient.getIscsiServices(anyString(), anyMap())) + .thenReturn(null) + .thenReturn(records(null)) + .thenReturn(records(Collections.emptyList())); + + for (int i = 0; i < 3; i++) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, iscsi::getStoragePath); + assertEquals("No iSCSI service found for SVM: svm1", ex.getMessage()); + } + assertIscsiServiceWasQueried(3); + } + + @Test + void getStoragePath_fails_whenIscsiTargetHasNoName() { + StorageStrategy iscsi = newStrategy(ProtocolType.ISCSI); + IscsiService noName = new IscsiService(); + noName.setTarget(new IscsiService.IscsiServiceTarget()); + when(sanFeignClient.getIscsiServices(anyString(), anyMap())) + .thenReturn(records(List.of(iscsiService(null)))) + .thenReturn(records(List.of(noName))); + + for (int i = 0; i < 2; i++) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, iscsi::getStoragePath); + assertEquals("iSCSI target IQN not found for SVM: svm1", ex.getMessage()); + } + assertIscsiServiceWasQueried(2); + } + + @Test + void getStoragePath_wrapsFeignClientErrors() { + StorageStrategy iscsi = newStrategy(ProtocolType.ISCSI); + when(sanFeignClient.getIscsiServices(anyString(), anyMap())).thenThrow(feignError(401, "unauthorized")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, iscsi::getStoragePath); + + assertTrue(ex.getMessage().startsWith("Failed to retrieve storage path: "), ex.getMessage()); + assertTrue(ex.getMessage().contains("unauthorized"), ex.getMessage()); + assertIscsiServiceWasQueried(1); + } + + @Test + void getStoragePath_returnsNull_forNfs() { + assertNull(strategy.getStoragePath()); + verifyNoInteractions(sanFeignClient); + } + + @Test + void getStoragePath_rejectsUnsupportedProtocol() { + StorageStrategy noProtocol = newStrategy(null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, noProtocol::getStoragePath); + + assertEquals("Unsupported protocol for path retrieval: null", thrown.getMessage()); + verifyNoInteractions(sanFeignClient); + } + + // ------------------------------------------------------------- QoS: create + + @Test + void createVolumeQosPolicy_buildsFixedPolicyForSvm_andReturnsLookedUpPolicy() { + VolumeQosPolicy found = policy("policy-uuid", 0); + when(qosFeignClient.createPolicy(anyString(), any(VolumeQosPolicy.class))).thenReturn(null); + when(qosFeignClient.getPolicies(anyString(), anyMap())).thenReturn(records(List.of(found))); + + VolumeQosPolicy result = strategy.createVolumeQosPolicy("cs_policy", 100L, 500L); + + assertSame(found, result); + ArgumentCaptor sent = ArgumentCaptor.forClass(VolumeQosPolicy.class); + verify(qosFeignClient).createPolicy(anyString(), sent.capture()); + assertEquals("cs_policy", sent.getValue().getName()); + assertEquals("svm1", sent.getValue().getSvm().getName()); + assertEquals(100L, sent.getValue().getFixed().getMinThroughputIops()); + assertEquals(500L, sent.getValue().getFixed().getMaxThroughputIops()); + assertFalse(sent.getValue().getFixed().getCapacityShared()); + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(qosFeignClient).getPolicies(anyString(), query.capture()); + assertEquals("cs_policy", query.getValue().get(OntapStorageConstants.NAME)); + assertEquals("svm1", query.getValue().get(OntapStorageConstants.SVM_DOT_NAME)); + } + + @Test + void createVolumeQosPolicy_omitsNonPositiveAndMissingLimits() { + when(qosFeignClient.getPolicies(anyString(), anyMap())).thenReturn(records(List.of(policy("u", 0)))); + + strategy.createVolumeQosPolicy("p1", 0L, null); + strategy.createVolumeQosPolicy("p2", null, -1L); + + ArgumentCaptor sent = ArgumentCaptor.forClass(VolumeQosPolicy.class); + verify(qosFeignClient, times(2)).createPolicy(anyString(), sent.capture()); + for (VolumeQosPolicy policy : sent.getAllValues()) { + assertNull(policy.getFixed().getMinThroughputIops()); + assertNull(policy.getFixed().getMaxThroughputIops()); + } + } + + @Test + void createVolumeQosPolicy_pollsAsyncJobWhenReturned() { + StorageStrategy spied = spy(strategy); + JobResponse response = jobResponse("qos-job"); + doNothing().when(spied).pollJobIfPresent(any(JobResponse.class), anyString()); + when(qosFeignClient.createPolicy(anyString(), any(VolumeQosPolicy.class))).thenReturn(response); + when(qosFeignClient.getPolicies(anyString(), anyMap())).thenReturn(records(List.of(policy("u", 0)))); + + spied.createVolumeQosPolicy("p1", null, 100L); + + verify(spied).pollJobIfPresent(eq(response), anyString()); + } + + @Test + void createVolumeQosPolicy_reusesExistingPolicy_onConflict() { + VolumeQosPolicy existing = policy("existing-uuid", 3); + when(qosFeignClient.createPolicy(anyString(), any(VolumeQosPolicy.class))).thenThrow(feignError(409, "exists")); + when(qosFeignClient.getPolicies(anyString(), anyMap())).thenReturn(records(List.of(existing))); + + assertSame(existing, strategy.createVolumeQosPolicy("cs_policy", null, 100L)); + + ArgumentCaptor sent = ArgumentCaptor.forClass(VolumeQosPolicy.class); + verify(qosFeignClient).createPolicy(anyString(), sent.capture()); + assertEquals("cs_policy", sent.getValue().getName()); + assertEquals("svm1", sent.getValue().getSvm().getName()); + assertNull(sent.getValue().getFixed().getMinThroughputIops()); + assertEquals(100L, sent.getValue().getFixed().getMaxThroughputIops()); + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(qosFeignClient).getPolicies(anyString(), query.capture()); + assertEquals("cs_policy", query.getValue().get(OntapStorageConstants.NAME)); + assertEquals("svm1", query.getValue().get(OntapStorageConstants.SVM_DOT_NAME)); + } + + @Test + void createVolumeQosPolicy_failsOnOtherCreateErrors_withoutLookup() { + when(qosFeignClient.createPolicy(anyString(), any(VolumeQosPolicy.class))).thenThrow(feignError(500, "bad")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.createVolumeQosPolicy("cs_policy", null, 100L)); + + assertTrue(ex.getMessage().contains("Failed to create ONTAP QoS policy [cs_policy]"), ex.getMessage()); + assertTrue(ex.getMessage().contains("bad"), ex.getMessage()); + assertQosPolicyWasSent(1); + verify(qosFeignClient, never()).getPolicies(anyString(), anyMap()); + } + + @Test + void createVolumeQosPolicy_failsWhenPolicyCannotBeFoundAfterCreate() { + when(qosFeignClient.getPolicies(anyString(), anyMap())) + .thenReturn(null) + .thenReturn(records(null)) + .thenReturn(records(Collections.emptyList())); + + for (int i = 0; i < 3; i++) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.createVolumeQosPolicy("cs_policy", null, 100L)); + assertEquals("Unable to get ONTAP QoS policy [cs_policy] after creation", ex.getMessage()); + } + assertQosPolicyWasSent(3); + assertQosPolicyWasLookedUp(3); + } + + @Test + void createVolumeQosPolicy_failsWhenLookedUpPolicyHasNoUuid() { + when(qosFeignClient.getPolicies(anyString(), anyMap())) + .thenReturn(records(Collections.singletonList((VolumeQosPolicy) null))) + .thenReturn(records(List.of(policy("", 0)))); + + for (int i = 0; i < 2; i++) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.createVolumeQosPolicy("cs_policy", null, 100L)); + assertEquals("Failed to fetch ONTAP QoS policy [cs_policy]: empty response", ex.getMessage()); + } + assertQosPolicyWasSent(2); + assertQosPolicyWasLookedUp(2); + } + + @Test + void createVolumeQosPolicy_failsWhenLookupThrows() { + when(qosFeignClient.getPolicies(anyString(), anyMap())).thenThrow(feignError(500, "lookup failed")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.createVolumeQosPolicy("cs_policy", null, 100L)); + + assertTrue(ex.getMessage().contains("Failed to fetch ONTAP QoS policy [cs_policy]"), ex.getMessage()); + assertTrue(ex.getMessage().contains("lookup failed"), ex.getMessage()); + assertQosPolicyWasSent(1); + assertQosPolicyWasLookedUp(1); + } + + // ------------------------------------------------------------- QoS: delete + + @Test + void deleteVolumeQosPolicy_ignoresNullOrEmptyUuid() { + strategy.deleteVolumeQosPolicy(null); + strategy.deleteVolumeQosPolicy(""); + + verifyNoInteractions(qosFeignClient); + } + + @Test + void deleteVolumeQosPolicy_skips_whenPolicyAlreadyGone() { + when(qosFeignClient.getPolicy(anyString(), eq("p-uuid"), anyMap())).thenThrow(feignError(404, "not found")); + + strategy.deleteVolumeQosPolicy("p-uuid"); + + verify(qosFeignClient, never()).deletePolicy(anyString(), anyString()); + } + + @Test + void deleteVolumeQosPolicy_failsWhenLookupFailsForOtherReasons() { + when(qosFeignClient.getPolicy(anyString(), eq("p-uuid"), anyMap())).thenThrow(feignError(500, "server error")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteVolumeQosPolicy("p-uuid")); + + assertTrue(ex.getMessage().contains("Failed to fetch ONTAP QoS policy"), ex.getMessage()); + verify(qosFeignClient, never()).deletePolicy(anyString(), anyString()); + } + + @Test + void deleteVolumeQosPolicy_failsWhenLookupReturnsEmptyPolicy() { + when(qosFeignClient.getPolicy(anyString(), eq("p-uuid"), anyMap())) + .thenReturn(null) + .thenReturn(policy("", 0)); + + for (int i = 0; i < 2; i++) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteVolumeQosPolicy("p-uuid")); + assertTrue(ex.getMessage().contains("empty response"), ex.getMessage()); + } + verify(qosFeignClient, never()).deletePolicy(anyString(), anyString()); + } + + @Test + void deleteVolumeQosPolicy_keepsPolicyThatIsStillInUse() { + when(qosFeignClient.getPolicy(anyString(), eq("p-uuid"), anyMap())).thenReturn(policy("p-uuid", 2)); + + strategy.deleteVolumeQosPolicy("p-uuid"); + + verify(qosFeignClient, never()).deletePolicy(anyString(), anyString()); + } + + @Test + void deleteVolumeQosPolicy_deletesUnusedPolicy() { + when(qosFeignClient.getPolicy(anyString(), eq("p-uuid"), anyMap())).thenReturn(policy("p-uuid", 0)); + + strategy.deleteVolumeQosPolicy("p-uuid"); + + verify(qosFeignClient).deletePolicy(anyString(), eq("p-uuid")); + } + + @Test + void deleteVolumeQosPolicy_deletesPolicyWithUnknownObjectCount_andPollsJob() { + StorageStrategy spied = spy(strategy); + JobResponse response = jobResponse("del-job"); + doNothing().when(spied).pollJobIfPresent(any(JobResponse.class), anyString()); + when(qosFeignClient.getPolicy(anyString(), eq("p-uuid"), anyMap())).thenReturn(policy("p-uuid", null)); + when(qosFeignClient.deletePolicy(anyString(), eq("p-uuid"))).thenReturn(response); + + spied.deleteVolumeQosPolicy("p-uuid"); + + verify(spied).pollJobIfPresent(eq(response), anyString()); + } + + @Test + void deleteVolumeQosPolicy_toleratesConflictAndMissingOnDelete() { + when(qosFeignClient.getPolicy(anyString(), eq("p-uuid"), anyMap())).thenReturn(policy("p-uuid", 0)); + when(qosFeignClient.deletePolicy(anyString(), eq("p-uuid"))) + .thenThrow(feignError(409, "in use")) + .thenThrow(feignError(404, "gone")) + .thenThrow(new IllegalStateException("entry doesn't exist")); + + strategy.deleteVolumeQosPolicy("p-uuid"); + strategy.deleteVolumeQosPolicy("p-uuid"); + strategy.deleteVolumeQosPolicy("p-uuid"); + + verify(qosFeignClient, times(3)).deletePolicy(anyString(), eq("p-uuid")); + } + + @Test + void deleteVolumeQosPolicy_failsOnUnexpectedDeleteErrors() { + when(qosFeignClient.getPolicy(anyString(), eq("p-uuid"), anyMap())).thenReturn(policy("p-uuid", 0)); + when(qosFeignClient.deletePolicy(anyString(), eq("p-uuid"))) + .thenThrow(feignError(500, "server error")) + .thenThrow(new IllegalStateException("boom")); + + for (int i = 0; i < 2; i++) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteVolumeQosPolicy("p-uuid")); + assertTrue(ex.getMessage().startsWith("Failed to delete ONTAP QoS policy"), ex.getMessage()); + } + } + + // ------------------------------------------------------------- job polling + + @Test + void jobPollUntilSuccess_returnsCompletedJob() { + Job done = job("j1", OntapStorageConstants.JOB_SUCCESS, "ok"); + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))).thenReturn(done); + + assertSame(done, strategy.jobPollUntilSuccess("j1", 3, 0)); + assertTrue(strategy.jobPollForSuccess("j1", 3, 0)); + } + + @Test + void jobPollUntilSuccess_keepsPolling_untilJobSucceeds() { + Job done = job("j1", OntapStorageConstants.JOB_SUCCESS, "ok"); + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))) + .thenReturn(null) + .thenReturn(job("j1", OntapStorageConstants.JOB_RUNNING, null)) + .thenReturn(done); + + assertSame(done, strategy.jobPollUntilSuccess("j1", 5, 0)); + verify(jobFeignClient, times(3)).getJobByUUID(anyString(), eq("j1")); + } + + @Test + void jobPollUntilSuccess_failsWhenJobReportsFailure() { + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))) + .thenReturn(job("j1", OntapStorageConstants.JOB_FAILURE, "disk full")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.jobPollUntilSuccess("j1", 3, 0)); + + assertTrue(ex.getMessage().contains("disk full"), ex.getMessage()); + } + + @Test + void jobPollUntilSuccess_failsWhenRetriesExhausted() { + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))) + .thenReturn(job("j1", OntapStorageConstants.JOB_RUNNING, null)); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.jobPollUntilSuccess("j1", 2, 0)); + + assertTrue(ex.getMessage().contains("did not complete"), ex.getMessage()); + verify(jobFeignClient, times(2)).getJobByUUID(anyString(), eq("j1")); + } + + @Test + void jobPollUntilSuccess_failsWhenJobStatusCannotBeFetched() { + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))).thenThrow(feignError(404, "no such job")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.jobPollUntilSuccess("j1", 3, 0)); + + assertTrue(ex.getMessage().contains("Failed to fetch job status"), ex.getMessage()); + } + + @Test + void jobPollUntilSuccess_restoresInterruptFlag_whenInterrupted() { + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))) + .thenReturn(job("j1", OntapStorageConstants.JOB_RUNNING, null)); + Thread.currentThread().interrupt(); + try { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.jobPollUntilSuccess("j1", 5, 10)); + + assertTrue(ex.getMessage().contains("Interrupted"), ex.getMessage()); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } + + @Test + void pollJobIfPresentAndGetCompletedJob_returnsNull_whenNoJobPresent() { + assertNull(strategy.pollJobIfPresentAndGetCompletedJob(null, "op")); + assertNull(strategy.pollJobIfPresentAndGetCompletedJob(new JobResponse(), "op")); + JobResponse noUuid = new JobResponse(); + noUuid.setJob(new Job()); + assertNull(strategy.pollJobIfPresentAndGetCompletedJob(noUuid, "op", 3, 0)); + verifyNoInteractions(jobFeignClient); + } + + @Test + void pollJobIfPresentAndGetCompletedJob_returnsCompletedJob() { + Job done = job("j1", OntapStorageConstants.JOB_SUCCESS, "ok"); + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))).thenReturn(done); + + assertSame(done, strategy.pollJobIfPresentAndGetCompletedJob(jobResponse("j1"), "op", 3, 0)); + } + + // ------------------------------------------------------------- FlexVol snapshot delete + + @Test + void deleteFlexVolSnapshot_requiresBothUuids() { + assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFlexVolSnapshotForCloudStackVolume(null, "snap-uuid", "snap")); + assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFlexVolSnapshotForCloudStackVolume("", "snap-uuid", "snap")); + assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFlexVolSnapshotForCloudStackVolume("vol-uuid", null, "snap")); + assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFlexVolSnapshotForCloudStackVolume("vol-uuid", "", "snap")); + verifyNoInteractions(snapshotFeignClient); + } + + @Test + void deleteFlexVolSnapshot_succeedsWithoutJob() { + when(snapshotFeignClient.deleteSnapshot(anyString(), eq("vol-uuid"), eq("snap-uuid"))) + .thenReturn(null); + + strategy.deleteFlexVolSnapshotForCloudStackVolume("vol-uuid", "snap-uuid", "snap"); + + verify(snapshotFeignClient).deleteSnapshot(anyString(), eq("vol-uuid"), eq("snap-uuid")); + verifyNoInteractions(jobFeignClient); + } + + @Test + void deleteFlexVolSnapshot_pollsDeleteJobWhenReturned() { + StorageStrategy spied = spy(strategy); + JobResponse response = jobResponse("snap-del-job"); + doNothing().when(spied).pollJobIfPresent(any(JobResponse.class), anyString(), anyInt(), anyInt()); + when(snapshotFeignClient.deleteSnapshot(anyString(), eq("vol-uuid"), eq("snap-uuid"))).thenReturn(response); + + spied.deleteFlexVolSnapshotForCloudStackVolume("vol-uuid", "snap-uuid", "snap"); + + verify(spied).pollJobIfPresent(eq(response), anyString(), + eq(OntapStorageConstants.ONTAP_SNAPSHOT_DELETE_JOB_MAX_RETRIES), + eq(OntapStorageConstants.ONTAP_SNAPSHOT_DELETE_JOB_POLL_INTERVAL_MS)); + } + + @Test + void deleteFlexVolSnapshot_treatsAlreadyDeletedSnapshotAsSuccess() { + when(snapshotFeignClient.deleteSnapshot(anyString(), eq("vol-uuid"), eq("snap-uuid"))) + .thenThrow(feignError(404, "snapshot not found")); + + strategy.deleteFlexVolSnapshotForCloudStackVolume("vol-uuid", "snap-uuid", "snap"); + + verify(snapshotFeignClient, times(1)).deleteSnapshot(anyString(), eq("vol-uuid"), eq("snap-uuid")); + } + + @Test + void deleteFlexVolSnapshot_propagatesCloudRuntimeErrorsUnchanged() { + CloudRuntimeException original = new CloudRuntimeException("job failed"); + when(snapshotFeignClient.deleteSnapshot(anyString(), eq("vol-uuid"), eq("snap-uuid"))).thenThrow(original); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFlexVolSnapshotForCloudStackVolume("vol-uuid", "snap-uuid", "snap")); + + assertSame(original, ex); + } + + @Test + void deleteFlexVolSnapshot_wrapsOtherFailures() { + when(snapshotFeignClient.deleteSnapshot(anyString(), eq("vol-uuid"), eq("snap-uuid"))) + .thenThrow(feignError(500, "internal")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFlexVolSnapshotForCloudStackVolume("vol-uuid", "snap-uuid", "snap")); + + assertTrue(ex.getMessage().startsWith("Failed to delete ONTAP FlexVol snapshot"), ex.getMessage()); + assertNotNull(ex.getCause()); + } + + // ===================================================================================== + // Mutation-hardening: exact requests, boundaries and LIF selection tiers + // ===================================================================================== + + private IpInterface lif(String address, String homeNode, String currentNode) { + IpInterface.IpInfo ip = new IpInterface.IpInfo(); + ip.setAddress(address); + IpInterface iface = new IpInterface(); + iface.setIp(ip); + iface.setState(OntapStorageConstants.LIF_STATE_UP); + iface.setEnabled(true); + IpInterface.Location location = new IpInterface.Location(); + if (homeNode != null) { + IpInterface.Node home = new IpInterface.Node(); + home.setName(homeNode); + location.setHomeNode(home); + } + if (currentNode != null) { + IpInterface.Node current = new IpInterface.Node(); + current.setName(currentNode); + location.setNode(current); + } + iface.setLocation(location); + return iface; + } + + private Map selectLif(StorageStrategy target, IpInterface... lifs) { + when(networkFeignClient.getNetworkIpInterfaces(anyString(), anyMap())).thenReturn(records(Arrays.asList(lifs))); + return target.getNetworkInterface(aggregate("aggr1", "u1", null, "node-a", Aggregate.StateEnum.ONLINE)); + } + + @Test + void getNetworkInterface_filtersByServiceForTheConfiguredProtocolOnly() { + selectLif(newStrategy(ProtocolType.NFS3), lif("10.0.0.1", "node-a", "node-a")); + selectLif(newStrategy(ProtocolType.ISCSI), lif("10.0.0.1", "node-a", "node-a")); + selectLif(newStrategy(null), lif("10.0.0.1", "node-a", "node-a")); + + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(networkFeignClient, times(3)).getNetworkIpInterfaces(anyString(), query.capture()); + assertEquals(OntapStorageConstants.DATA_NFS, query.getAllValues().get(0).get(OntapStorageConstants.SERVICES)); + assertEquals(OntapStorageConstants.DATA_ISCSI, query.getAllValues().get(1).get(OntapStorageConstants.SERVICES)); + assertFalse(query.getAllValues().get(2).containsKey(OntapStorageConstants.SERVICES)); + assertEquals("svm1", query.getAllValues().get(0).get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals(OntapStorageConstants.TRUE, query.getAllValues().get(0).get(OntapStorageConstants.RETURN_RECORDS)); + } + + @Test + void getNetworkInterface_neverSelectsIpv6Lifs() { + Map result = selectLif(strategy, lif("fe80::1", "node-a", "node-a"), lif("10.0.0.7", "node-a", "node-a")); + + assertEquals("10.0.0.7", result.get(OntapStorageConstants.DATA_LIF)); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> selectLif(strategy, lif("fe80::1", "node-a", "node-a"))); + assertTrue(ex.getMessage().contains("No operationally UP and enabled LIF"), ex.getMessage()); + } + + @Test + void getNetworkInterface_prefersHomeNodeLifOverEarlierFailoverAndFallbackLifs() { + Map result = selectLif(strategy, + lif("10.0.0.1", "node-b", "node-b"), + lif("10.0.0.2", "node-b", "node-a"), + lif("10.0.0.3", "node-a", "node-a")); + + assertEquals("10.0.0.3", result.get(OntapStorageConstants.DATA_LIF)); + assertNull(result.get(OntapStorageConstants.LIF_WARNING)); + } + + @Test + void getNetworkInterface_usesFirstFailoverLifRunningOnTheAggregateNode() { + Map result = selectLif(strategy, + lif("10.0.0.1", "node-b", "node-b"), + lif("10.0.0.2", "node-b", "node-a"), + lif("10.0.0.3", "node-c", "node-a")); + + assertEquals("10.0.0.2", result.get(OntapStorageConstants.DATA_LIF)); + assertTrue(result.get(OntapStorageConstants.LIF_WARNING).contains("currently running on that node"), + result.get(OntapStorageConstants.LIF_WARNING)); + } + + @Test + void getNetworkInterface_fallsBackToFirstUsableLifOnAnotherNodeWithWarning() { + IpInterface noLocation = lif("10.0.0.1", null, null); + noLocation.setLocation(null); + Map result = selectLif(strategy, noLocation, lif("10.0.0.2", "node-b", "node-b"), + lif("10.0.0.3", "node-c", null)); + + assertEquals("10.0.0.1", result.get(OntapStorageConstants.DATA_LIF)); + assertTrue(result.get(OntapStorageConstants.LIF_WARNING).contains("No operational LIF found on aggregate's home node"), + result.get(OntapStorageConstants.LIF_WARNING)); + assertTrue(result.get(OntapStorageConstants.LIF_WARNING).contains("10.0.0.1")); + } + + @Test + void getNetworkInterface_ignoresDisabledAndDownLifs() { + IpInterface disabled = lif("10.0.0.1", "node-a", "node-a"); + disabled.setEnabled(false); + IpInterface down = lif("10.0.0.2", "node-a", "node-a"); + down.setState("down"); + IpInterface unknownEnabled = lif("10.0.0.4", "node-a", "node-a"); + unknownEnabled.setEnabled(null); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> selectLif(strategy, disabled, down, unknownEnabled)); + assertTrue(ex.getMessage().contains("all 3 LIF(s)"), ex.getMessage()); + + assertEquals("10.0.0.5", selectLif(strategy, disabled, down, lif("10.0.0.5", "node-a", "node-a")) + .get(OntapStorageConstants.DATA_LIF)); + } + + @Test + void chooseAggregate_keepsFirstOfTwoAggregatesWithEqualAvailableSpace() { + List candidates = Arrays.asList( + aggregate("first", "u-first", null, null, null), + aggregate("second", "u-second", null, null, null)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-first"), anyMap())) + .thenReturn(aggregate("first", "u-first", 9000.0, "n1", Aggregate.StateEnum.ONLINE)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-second"), anyMap())) + .thenReturn(aggregate("second", "u-second", 9000.0, "n2", Aggregate.StateEnum.ONLINE)); + + assertEquals("first", strategy.chooseAggregate(candidates, 1000L).getName()); + } + + @Test + void chooseAggregate_acceptsAggregateWithOneByteMoreThanRequested() { + List candidates = List.of(aggregate("a1", "u1", null, null, null)); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u1"), anyMap())) + .thenReturn(aggregate("a1", "u1", 1001.0, "n1", Aggregate.StateEnum.ONLINE)); + + assertEquals("a1", strategy.chooseAggregate(candidates, 1000L).getName()); + } + + @Test + void connect_requiresAggregateStrictlyLargerThanPoolSize() { + Svm exact = svm(OntapStorageConstants.RUNNING, true, true); + exact.setAggregates(List.of(aggregate("exact", "u-exact", null, null, null))); + when(svmFeignClient.getSvmResponse(anyMap(), anyString())).thenReturn(records(List.of(exact))); + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-exact"), anyMap())) + .thenReturn(aggregate("exact", "u-exact", 5_000_000_000.0, "n1", Aggregate.StateEnum.ONLINE)); + + assertThrows(CloudRuntimeException.class, () -> strategy.connect(true)); + assertTrue(strategy.getAggregates() == null || strategy.getAggregates().isEmpty()); + + when(aggregateFeignClient.getAggregateByUUID(anyString(), eq("u-exact"), anyMap())) + .thenReturn(aggregate("exact", "u-exact", 5_000_000_001.0, "n1", Aggregate.StateEnum.ONLINE)); + assertTrue(strategy.connect(true)); + assertEquals(1, strategy.getAggregates().size()); + assertEquals("exact", strategy.getAggregates().get(0).getName()); + } + + @Test + void createStorageVolume_sendsChosenAggregateNameAndUuid() { + StorageStrategy spied = strategyWithInstantJobs(); + Volume created = namedVolume("vol1", "vol-uuid"); + when(volumeFeignClient.createVolumeWithJob(anyString(), any(Volume.class))).thenReturn(jobResponse("job-1")); + when(volumeFeignClient.getAllVolumes(anyString(), anyMap())).thenReturn(records(List.of(created))); + when(volumeFeignClient.getVolume(anyString(), anyMap())).thenReturn(records(List.of(created))); + + spied.createStorageVolume("vol1", 2048L, chosenAggregate()); + + ArgumentCaptor request = ArgumentCaptor.forClass(Volume.class); + verify(volumeFeignClient).createVolumeWithJob(anyString(), request.capture()); + assertEquals("aggr1", request.getValue().getAggregates().get(0).getName()); + assertEquals("aggr-uuid", request.getValue().getAggregates().get(0).getUuid()); + } + + @Test + void updateStorageVolume_sendsOnlyTheNewSizeForTheVolumeUuid() { + StorageStrategy spied = strategyWithInstantJobs(); + when(volumeFeignClient.updateVolume(anyString(), anyString(), any(Volume.class))).thenReturn(jobResponse("job-1")); + Volume resize = namedVolume("vol1", "vol-uuid"); + resize.setSize(4096L); + + spied.updateStorageVolume(resize); + + ArgumentCaptor body = ArgumentCaptor.forClass(Volume.class); + verify(volumeFeignClient).updateVolume(anyString(), eq("vol-uuid"), body.capture()); + assertEquals(4096L, body.getValue().getSize()); + assertNull(body.getValue().getName()); + } + + @Test + void createVolumeQosPolicy_treatsZeroAndOneIopsAsMissingAndPresentRespectively() { + when(qosFeignClient.getPolicies(anyString(), anyMap())).thenReturn(records(List.of(policy("u", 0)))); + + strategy.createVolumeQosPolicy("zero", 0L, 0L); + strategy.createVolumeQosPolicy("one", 1L, 1L); + + ArgumentCaptor sent = ArgumentCaptor.forClass(VolumeQosPolicy.class); + verify(qosFeignClient, times(2)).createPolicy(anyString(), sent.capture()); + VolumeQosPolicy zero = sent.getAllValues().get(0); + VolumeQosPolicy one = sent.getAllValues().get(1); + assertNull(zero.getFixed().getMinThroughputIops()); + assertNull(zero.getFixed().getMaxThroughputIops()); + assertEquals(1L, one.getFixed().getMinThroughputIops()); + assertEquals(1L, one.getFixed().getMaxThroughputIops()); + } + + @Test + void pollJobIfPresent_withDefaultSettingsPollsTheJobUntilItSucceeds() { + Job done = job("j1", OntapStorageConstants.JOB_SUCCESS, "ok"); + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))).thenReturn(done); + + strategy.pollJobIfPresent(jobResponse("j1"), "op"); + + verify(jobFeignClient).getJobByUUID(anyString(), eq("j1")); + } + + @Test + void pollJobIfPresent_withDefaultSettingsPropagatesJobFailure() { + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))) + .thenReturn(job("j1", OntapStorageConstants.JOB_FAILURE, "disk full")); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.pollJobIfPresent(jobResponse("j1"), "op")); + + assertTrue(ex.getMessage().contains("disk full"), ex.getMessage()); + } + + @Test + void pollJobIfPresentAndGetCompletedJob_withDefaultSettingsReturnsTheCompletedJob() { + Job done = job("j1", OntapStorageConstants.JOB_SUCCESS, "ok"); + when(jobFeignClient.getJobByUUID(anyString(), eq("j1"))).thenReturn(done); + + assertSame(done, strategy.pollJobIfPresentAndGetCompletedJob(jobResponse("j1"), "op")); + } + } } diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/UnifiedNASStrategyTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/UnifiedNASStrategyTest.java index b38017d49b9a..76725b13bbdf 100755 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/UnifiedNASStrategyTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/UnifiedNASStrategyTest.java @@ -42,12 +42,14 @@ import org.apache.cloudstack.storage.feign.client.SvmFeignClient; import org.apache.cloudstack.storage.feign.client.NetworkFeignClient; import org.apache.cloudstack.storage.feign.client.SANFeignClient; +import org.apache.cloudstack.storage.feign.client.SnapshotFeignClient; import org.apache.cloudstack.storage.feign.model.ExportPolicy; import org.apache.cloudstack.storage.feign.model.ExportRule; import org.apache.cloudstack.storage.feign.model.FileCloneRequest; import org.apache.cloudstack.storage.feign.model.FileInfo; import org.apache.cloudstack.storage.feign.model.Job; import org.apache.cloudstack.storage.feign.model.OntapStorage; +import org.apache.cloudstack.storage.feign.model.Volume; import org.apache.cloudstack.storage.feign.model.VolumeQosPolicy; import org.apache.cloudstack.storage.feign.model.response.JobResponse; import org.apache.cloudstack.storage.feign.model.response.OntapResponse; @@ -67,12 +69,14 @@ import org.mockito.quality.Strictness; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -107,6 +111,9 @@ public class UnifiedNASStrategyTest { @Mock private JobFeignClient jobFeignClient; + @Mock + private SnapshotFeignClient snapshotFeignClient; + @Mock private AggregateFeignClient aggregateFeignClient; @@ -135,6 +142,9 @@ public class UnifiedNASStrategyTest { private OntapStorage ontapStorage; + private static final long POOL_ID = 7L; + private static final String POLICY_ID = "policy-1"; + @BeforeEach public void setUp() throws Exception { ontapStorage = new OntapStorage( @@ -146,6 +156,7 @@ public void setUp() throws Exception { ProtocolType.NFS3 ); strategy = new TestableUnifiedNASStrategy(ontapStorage, nasFeignClient, volumeFeignClient, jobFeignClient, aggregateFeignClient, svmFeignClient, networkFeignClient, sanFeignClient); + strategy.snapshotFeignClient = snapshotFeignClient; injectField("volumeDao", volumeDao); injectField("epSelector", epSelector); injectField("storagePoolDetailsDao", storagePoolDetailsDao); @@ -1448,7 +1459,16 @@ public void testCloneCloudStackVolume_FeignException_Throws() { when(feignException.getMessage()).thenReturn("clone failed"); when(nasFeignClient.cloneFile(anyString(), any(FileCloneRequest.class))).thenThrow(feignException); - assertThrows(CloudRuntimeException.class, () -> strategy.cloneCloudStackVolume(request)); + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.cloneCloudStackVolume(request)); + + assertEquals("Failed to clone file: clone failed", thrown.getMessage()); + ArgumentCaptor sent = ArgumentCaptor.forClass(FileCloneRequest.class); + verify(nasFeignClient).cloneFile(anyString(), sent.capture()); + assertEquals("template-uuid", sent.getValue().getSourcePath()); + assertEquals("volume-uuid", sent.getValue().getDestinationPath()); + assertEquals("flexvol1", sent.getValue().getVolume().getName()); + assertEquals("flexvol-uuid-1", sent.getValue().getVolume().getUuid()); } @Test @@ -1606,4 +1626,1110 @@ public void testResizeCloudStackVolume_DeletedFile_ThrowsAgentError() { assertTrue(exception.getMessage().contains("No such file or directory")); assertTrue(exception.getMessage().contains("deleted-volume.qcow2")); } + + /** A real FeignException (mocks have no stack trace, which breaks logging of the cause). */ + private static FeignException feignException(int status, String message) { + feign.Request request = feign.Request.create(feign.Request.HttpMethod.GET, "http://ontap/api", + new HashMap<>(), null, java.nio.charset.StandardCharsets.UTF_8, null); + feign.Response response = feign.Response.builder().status(status).reason(message).request(request) + .headers(new HashMap<>()).body(message, java.nio.charset.StandardCharsets.UTF_8).build(); + return FeignException.errorStatus("ontapCall", response); + } + + private VolumeObject volumeObject() { + VolumeObject volume = mock(VolumeObject.class); + VolumeObjectTO to = new VolumeObjectTO(); + to.setFormat(Storage.ImageFormat.QCOW2); + when(volume.getId()).thenReturn(100L); + when(volume.getUuid()).thenReturn("vol-uuid"); + when(volume.getTO()).thenReturn(to); + VolumeVO volumeVO = mock(VolumeVO.class); + when(volumeDao.findById(100L)).thenReturn(volumeVO); + when(volumeDao.update(anyLong(), any(VolumeVO.class))).thenReturn(true); + return volume; + } + + private CloudStackVolume nfsVolume(VolumeObject volume, FileInfo file) { + CloudStackVolume cloudStackVolume = new CloudStackVolume(); + cloudStackVolume.setDatastoreId("1"); + cloudStackVolume.setVolumeInfo(volume); + cloudStackVolume.setFlexVolumeUuid("flex-uuid"); + cloudStackVolume.setFile(file); + return cloudStackVolume; + } + + private static FileInfo fileWithQos() { + VolumeQosPolicy qos = new VolumeQosPolicy(); + qos.setName("qos-1"); + FileInfo file = new FileInfo(); + file.setQosPolicy(qos); + return file; + } + + private static HostVO host(String storageIp, String privateIp) { + HostVO host = mock(HostVO.class); + when(host.getStorageIpAddress()).thenReturn(storageIp); + when(host.getPrivateIpAddress()).thenReturn(privateIp); + when(host.getName()).thenReturn("host-" + storageIp + "-" + privateIp); + return host; + } + + private AccessGroup accessGroup(AccessGroup.HostRuleAction action, HostVO... hosts) { + AccessGroup group = new AccessGroup(); + group.setStoragePoolId(POOL_ID); + group.setHostsToConnect(new ArrayList<>(List.of(hosts))); + group.setHostRuleAction(action); + return group; + } + + private static ExportRule.ExportClient client(String match) { + ExportRule.ExportClient client = new ExportRule.ExportClient(); + client.setMatch(match); + return client; + } + + private ExportPolicy policyWithClients(List clients) { + ExportRule rule = new ExportRule(); + rule.setClients(clients); + ExportPolicy policy = new ExportPolicy(); + policy.setName("policy-name"); + policy.setRules(new ArrayList<>(List.of(rule))); + return policy; + } + + private void poolHasExportPolicy() { + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(new HashMap<>(Map.of( + OntapStorageConstants.EXPORT_POLICY_ID, POLICY_ID, + OntapStorageConstants.EXPORT_POLICY_NAME, "policy-name"))); + } + + private void poolDetailsForCreate() { + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(new HashMap<>(Map.of( + OntapStorageConstants.SVM_NAME, "svm1", + OntapStorageConstants.VOLUME_UUID, "flex-uuid", + OntapStorageConstants.VOLUME_NAME, "flexvol"))); + } + + private void exportPolicyIsCreated() { + ExportPolicy created = new ExportPolicy(); + created.setName("created-policy"); + OntapResponse response = new OntapResponse<>(List.of(created)); + when(nasFeignClient.getExportPolicyResponse(anyString(), anyMap())).thenReturn(response); + } + + private void assertExportPolicyWasCreated(int times) { + ArgumentCaptor policy = ArgumentCaptor.forClass(ExportPolicy.class); + verify(nasFeignClient, times(times)).createExportPolicy(anyString(), policy.capture()); + for (ExportPolicy sent : policy.getAllValues()) { + assertEquals("cs-svm1-flexvol", sent.getName()); + assertNotNull(sent.getSvm()); + assertEquals("svm1", sent.getSvm().getName()); + assertEquals("10.1.1.1/32", sent.getRules().get(0).getClients().get(0).getMatch()); + } + } + + @SuppressWarnings("unchecked") + private void assertExportPolicyWasLookedUp(int times) { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(nasFeignClient, times(times)).getExportPolicyResponse(anyString(), query.capture()); + for (Map value : query.getAllValues()) { + assertEquals("cs-svm1-flexvol", value.get(OntapStorageConstants.NAME)); + } + } + + private static Volume exportPolicyUpdate(String policyName) { + return argThat(update -> update != null + && update.getNas() != null + && update.getNas().getExportPolicy() != null + && policyName.equals(update.getNas().getExportPolicy().getName())); + } + + private static Job job(String state, String message) { + Job job = new Job(); + job.setUuid("job-1"); + job.setState(state); + job.setMessage(message); + return job; + } + + private static JobResponse jobResponse() { + JobResponse response = new JobResponse(); + Job job = new Job(); + job.setUuid("job-1"); + response.setJob(job); + return response; + } + + // ------------------------------------------------- createCloudStackVolume + + @Test + public void setOntapStorageReplacesTheCredentialsUsedForAuthHeader() { + String before = strategy.getAuthHeader(); + strategy.setOntapStorage(new OntapStorage("other", "secret", "10.0.0.2", "svm2", 100L, ProtocolType.NFS3)); + + assertNotEquals(before, strategy.getAuthHeader()); + } + + @Test + public void createVolumeWithoutQosFileDoesNotTouchOntapFiles() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(CreateObjectCommand.class))).thenReturn(new Answer(null, true, "ok")); + + CloudStackVolume request = nfsVolume(volume, new FileInfo()); + CloudStackVolume result = strategy.createCloudStackVolume(request); + + assertSame(request, result); + verify(nasFeignClient, never()).updateFile(anyString(), anyString(), anyString(), any(FileInfo.class)); + } + + @Test + public void createVolumeFailsWithDefaultMessageWhenHostGivesNoAnswer() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(CreateObjectCommand.class))).thenReturn(null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createCloudStackVolume(nfsVolume(volume, new FileInfo()))); + + assertEquals("Failed to create qcow2 on KVM host", thrown.getMessage()); + } + + @Test + public void createVolumeFailsWithHostDetailsWhenHostRejectsTheCommand() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(CreateObjectCommand.class))).thenReturn(new Answer(null, false, "disk full")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createCloudStackVolume(nfsVolume(volume, new FileInfo()))); + + assertEquals("disk full", thrown.getMessage()); + } + + @Test + public void createVolumeFailsWhenNoEndpointIsAvailable() { + VolumeObject volume = volumeObject(); + when(epSelector.select(volume)).thenReturn(null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createCloudStackVolume(nfsVolume(volume, new FileInfo()))); + + assertTrue(thrown.getMessage().contains("No remote endpoint to send CreateObjectCommand"), thrown.getMessage()); + } + + @Test + public void createVolumeReportsEndpointExceptionsAsFailedAnswer() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(CreateObjectCommand.class))).thenThrow(new IllegalStateException("agent offline")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createCloudStackVolume(nfsVolume(volume, new FileInfo()))); + + assertTrue(thrown.getMessage().contains("agent offline"), thrown.getMessage()); + } + + @Test + public void createVolumeFailsWhenVolumeRecordIsMissing() { + VolumeObject volume = volumeObject(); + when(volumeDao.findById(100L)).thenReturn(null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createCloudStackVolume(nfsVolume(volume, new FileInfo()))); + + assertTrue(thrown.getMessage().contains("Volume not found with id: 100"), thrown.getMessage()); + verify(epSelector, never()).select(any(VolumeObject.class)); + } + + @Test + public void createVolumeWrapsUnexpectedFailuresInCloudRuntimeException() { + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> strategy.createCloudStackVolume(null)); + + assertTrue(thrown.getCause() instanceof NullPointerException); + } + + @Test + public void createVolumeLogsFailedLeftoverCleanupAndStillRethrowsQosError() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(CreateObjectCommand.class))).thenReturn(new Answer(null, true, "ok")); + when(endPoint.sendMessage(any(DeleteCommand.class))).thenReturn(new Answer(null, false, "cannot delete")); + doThrow(new IllegalStateException("qos rejected")).when(nasFeignClient) + .updateFile(anyString(), anyString(), anyString(), any(FileInfo.class)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createCloudStackVolume(nfsVolume(volume, fileWithQos()))); + + assertTrue(thrown.getMessage().contains("Failed to update NFS volume file"), thrown.getMessage()); + verify(endPoint).sendMessage(any(DeleteCommand.class)); + } + + @Test + public void createVolumeToleratesNullCleanupAnswerAfterQosFailure() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(CreateObjectCommand.class))).thenReturn(new Answer(null, true, "ok")); + when(endPoint.sendMessage(any(DeleteCommand.class))).thenReturn(null); + doThrow(new IllegalStateException("qos rejected")).when(nasFeignClient) + .updateFile(anyString(), anyString(), anyString(), any(FileInfo.class)); + + assertThrows(CloudRuntimeException.class, () -> strategy.createCloudStackVolume(nfsVolume(volume, fileWithQos()))); + + verify(endPoint).sendMessage(any(DeleteCommand.class)); + } + + // ------------------------------------------------- updateCloudStackVolume + + @Test + public void updateVolumeRejectsIncompleteRequests() { + VolumeObject volume = volumeObject(); + assertThrows(CloudRuntimeException.class, () -> strategy.updateCloudStackVolume(null)); + + CloudStackVolume noVolumeInfo = nfsVolume(volume, fileWithQos()); + noVolumeInfo.setVolumeInfo(null); + assertThrows(CloudRuntimeException.class, () -> strategy.updateCloudStackVolume(noVolumeInfo)); + + CloudStackVolume noFlexVol = nfsVolume(volume, fileWithQos()); + noFlexVol.setFlexVolumeUuid(null); + assertThrows(CloudRuntimeException.class, () -> strategy.updateCloudStackVolume(noFlexVol)); + + assertThrows(CloudRuntimeException.class, () -> strategy.updateCloudStackVolume(nfsVolume(volume, null))); + verify(nasFeignClient, never()).updateFile(anyString(), anyString(), anyString(), any(FileInfo.class)); + } + + @Test + public void updateVolumeWithoutQosPolicyIsANoOp() { + CloudStackVolume request = nfsVolume(volumeObject(), new FileInfo()); + + assertSame(request, strategy.updateCloudStackVolume(request)); + verify(nasFeignClient, never()).updateFile(anyString(), anyString(), anyString(), any(FileInfo.class)); + } + + @Test + public void updateVolumeWrapsFeignAndGenericFailures() { + CloudStackVolume request = nfsVolume(volumeObject(), fileWithQos()); + FeignException feign = feignException(500, "ontap down"); + doThrow(feign).when(nasFeignClient).updateFile(anyString(), anyString(), anyString(), any(FileInfo.class)); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> strategy.updateCloudStackVolume(request)); + assertTrue(feignFailure.getMessage().contains("ontap down"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(nasFeignClient) + .updateFile(anyString(), anyString(), anyString(), any(FileInfo.class)); + CloudRuntimeException genericFailure = assertThrows(CloudRuntimeException.class, () -> strategy.updateCloudStackVolume(request)); + assertTrue(genericFailure.getMessage().contains("boom"), genericFailure.getMessage()); + } + + // ------------------------------------------------- deleteCloudStackVolume + + @Test + public void deleteVolumeSucceedsWhenHostDeletesTheFile() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(DeleteCommand.class))).thenReturn(new Answer(null, true, "ok")); + + strategy.deleteCloudStackVolume(nfsVolume(volume, new FileInfo())); + + verify(endPoint).sendMessage(any(DeleteCommand.class)); + } + + @Test + public void deleteVolumeFailsForNullAnswerFailedAnswerAndMissingEndpoint() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + + when(endPoint.sendMessage(any(DeleteCommand.class))).thenReturn(null); + CloudRuntimeException noAnswer = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteCloudStackVolume(nfsVolume(volume, new FileInfo()))); + assertTrue(noAnswer.getMessage().contains("Failed to delete qcow2 on KVM host"), noAnswer.getMessage()); + + when(endPoint.sendMessage(any(DeleteCommand.class))).thenReturn(new Answer(null, false, "busy")); + CloudRuntimeException failed = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteCloudStackVolume(nfsVolume(volume, new FileInfo()))); + assertTrue(failed.getMessage().contains("busy"), failed.getMessage()); + + when(epSelector.select(volume)).thenReturn(null); + CloudRuntimeException noEndpoint = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteCloudStackVolume(nfsVolume(volume, new FileInfo()))); + assertTrue(noEndpoint.getMessage().contains("No remote endpoint to send DeleteCommand"), noEndpoint.getMessage()); + } + + @Test + public void deleteVolumeReportsEndpointExceptions() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(DeleteCommand.class))).thenThrow(new IllegalStateException("agent offline")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteCloudStackVolume(nfsVolume(volume, new FileInfo()))); + + assertTrue(thrown.getMessage().contains("agent offline"), thrown.getMessage()); + } + + // ------------------------------------------------- cloneCloudStackVolume + + private CloudStackVolume cloneRequest(String sourcePath, String destinationPath, String datastoreId) { + FileInfo file = new FileInfo(); + file.setPath(sourcePath); + CloudStackVolume request = nfsVolume(volumeObject(), file); + request.setDestinationPath(destinationPath); + request.setDatastoreId(datastoreId); + return request; + } + + @Test + public void cloneRejectsInvalidRequests() { + assertThrows(CloudRuntimeException.class, () -> strategy.cloneCloudStackVolume(null)); + + CloudStackVolume noFile = cloneRequest("src", "dst", "1"); + noFile.setFile(null); + assertThrows(CloudRuntimeException.class, () -> strategy.cloneCloudStackVolume(noFile)); + + assertThrows(CloudRuntimeException.class, () -> strategy.cloneCloudStackVolume(cloneRequest(null, "dst", "1"))); + assertThrows(CloudRuntimeException.class, () -> strategy.cloneCloudStackVolume(cloneRequest("src", null, "1"))); + + CloudRuntimeException noDatastore = assertThrows(CloudRuntimeException.class, + () -> strategy.cloneCloudStackVolume(cloneRequest("src", "dst", null))); + assertTrue(noDatastore.getMessage().contains("no datastore id"), noDatastore.getMessage()); + verify(nasFeignClient, never()).cloneFile(anyString(), any()); + } + + @Test + public void cloneFailsWhenFlexVolumeUuidIsMissingOrEmpty() { + when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(new HashMap<>()); + CloudRuntimeException missing = assertThrows(CloudRuntimeException.class, + () -> strategy.cloneCloudStackVolume(cloneRequest("src", "dst", "1"))); + assertTrue(missing.getMessage().contains("FlexVolume uuid is missing"), missing.getMessage()); + + when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(new HashMap<>(Map.of(OntapStorageConstants.VOLUME_UUID, ""))); + assertThrows(CloudRuntimeException.class, () -> strategy.cloneCloudStackVolume(cloneRequest("src", "dst", "1"))); + } + + @Test + public void cloneWrapsFeignAndGenericErrors() { + when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(new HashMap<>(Map.of( + OntapStorageConstants.VOLUME_UUID, "flex-uuid", OntapStorageConstants.VOLUME_NAME, "flexvol"))); + FeignException feign = feignException(500, "clone refused"); + when(nasFeignClient.cloneFile(anyString(), any())).thenThrow(feign); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, + () -> strategy.cloneCloudStackVolume(cloneRequest("src", "dst", "1"))); + assertTrue(feignFailure.getMessage().startsWith("Failed to clone file: "), feignFailure.getMessage()); + assertTrue(feignFailure.getMessage().contains("clone refused"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("npe-ish")).when(nasFeignClient).cloneFile(anyString(), any()); + CloudRuntimeException genericFailure = assertThrows(CloudRuntimeException.class, + () -> strategy.cloneCloudStackVolume(cloneRequest("src", "dst", "1"))); + assertTrue(genericFailure.getMessage().contains("npe-ish"), genericFailure.getMessage()); + + ArgumentCaptor request = ArgumentCaptor.forClass(FileCloneRequest.class); + verify(nasFeignClient, times(2)).cloneFile(anyString(), request.capture()); + for (FileCloneRequest sent : request.getAllValues()) { + assertEquals("flex-uuid", sent.getVolume().getUuid()); + assertEquals("flexvol", sent.getVolume().getName()); + assertEquals("src", sent.getSourcePath()); + assertEquals("dst", sent.getDestinationPath()); + } + } + + // ------------------------------------------------- resizeCloudStackVolume + + @Test + public void resizeRejectsMissingVolumeAndNonPositiveSize() { + assertThrows(CloudRuntimeException.class, () -> strategy.resizeCloudStackVolume(null, 1024L)); + + CloudStackVolume noInfo = new CloudStackVolume(); + assertThrows(CloudRuntimeException.class, () -> strategy.resizeCloudStackVolume(noInfo, 1024L)); + + CloudStackVolume valid = nfsVolume(volumeObject(), new FileInfo()); + assertThrows(CloudRuntimeException.class, () -> strategy.resizeCloudStackVolume(valid, 0L)); + assertThrows(CloudRuntimeException.class, () -> strategy.resizeCloudStackVolume(valid, -5L)); + } + + @Test + public void resizeWithQosPolicyReappliesQosOnTheFile() { + VolumeObject volume = volumeObject(); + VolumeVO volumeVO = volumeDao.findById(100L); + when(volumeVO.getPoolId()).thenReturn(5L); + when(primaryDataStoreDao.findById(5L)).thenReturn(mock(org.apache.cloudstack.storage.datastore.db.StoragePoolVO.class)); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(com.cloud.agent.api.storage.ResizeVolumeCommand.class))).thenReturn(new Answer(null, true, "ok")); + + strategy.resizeCloudStackVolume(nfsVolume(volume, fileWithQos()), 2048L); + + ArgumentCaptor updated = ArgumentCaptor.forClass(FileInfo.class); + verify(nasFeignClient).updateFile(anyString(), eq("flex-uuid"), eq("vol-uuid"), updated.capture()); + assertEquals("qos-1", updated.getValue().getQosPolicy().getName()); + } + + // ------------------------------------------------- getCloudStackVolume / files + + private Map fileLookup() { + return Map.of(OntapStorageConstants.VOLUME_UUID, "flex-uuid", OntapStorageConstants.FILE_PATH, "dir/file.qcow2"); + } + + @Test + public void getVolumeReturnsFileDetailsFromOntap() { + FileInfo file = new FileInfo(); + file.setPath("dir/file.qcow2"); + when(nasFeignClient.getFileResponse(anyString(), eq("flex-uuid"), eq("dir/file.qcow2"))) + .thenReturn(new OntapResponse<>(List.of(file))); + + CloudStackVolume result = strategy.getCloudStackVolume(fileLookup()); + + assertNotNull(result); + assertSame(file, result.getFile()); + assertEquals("flex-uuid", result.getFlexVolumeUuid()); + } + + @Test + public void getVolumeFailsWhenOntapKnowsNoSuchFile() { + when(nasFeignClient.getFileResponse(anyString(), anyString(), anyString())).thenReturn(null); + CloudRuntimeException nullResponse = assertThrows(CloudRuntimeException.class, () -> strategy.getCloudStackVolume(fileLookup())); + assertTrue(nullResponse.getMessage().contains("not found on ONTAP"), nullResponse.getMessage()); + + when(nasFeignClient.getFileResponse(anyString(), anyString(), anyString())).thenReturn(new OntapResponse<>(new ArrayList<>())); + assertThrows(CloudRuntimeException.class, () -> strategy.getCloudStackVolume(fileLookup())); + } + + @Test + public void getVolumeWrapsFeignAndGenericFailures() { + FeignException feign = feignException(500, "ontap down"); + when(nasFeignClient.getFileResponse(anyString(), anyString(), anyString())).thenThrow(feign); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> strategy.getCloudStackVolume(fileLookup())); + assertTrue(feignFailure.getMessage().startsWith("File not found: "), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(nasFeignClient).getFileResponse(anyString(), anyString(), anyString()); + CloudRuntimeException genericFailure = assertThrows(CloudRuntimeException.class, () -> strategy.getCloudStackVolume(fileLookup())); + assertTrue(genericFailure.getMessage().contains("Failed to get the file: boom"), genericFailure.getMessage()); + } + + @Test + public void deleteFileByPathDeletesExistingFile() { + strategy.deleteFileByPath("flex-uuid", "dir/file.qcow2"); + + verify(nasFeignClient).deleteFile(anyString(), eq("flex-uuid"), eq("dir/file.qcow2")); + } + + @Test + public void deleteFileByPathTreatsMissingFileAsDeleted() { + FeignException notFound = feignException(404, "gone"); + doThrow(notFound).when(nasFeignClient).deleteFile(anyString(), anyString(), anyString()); + + strategy.deleteFileByPath("flex-uuid", "dir/file.qcow2"); + + verify(nasFeignClient).deleteFile(anyString(), eq("flex-uuid"), eq("dir/file.qcow2")); + } + + @Test + public void deleteFileByPathFailsOnOtherErrors() { + FeignException serverError = feignException(500, "ontap down"); + doThrow(serverError).when(nasFeignClient).deleteFile(anyString(), eq("flex-uuid"), eq("f")); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFileByPath("flex-uuid", "f")); + assertTrue(feignFailure.getMessage().startsWith("Failed to delete file: "), feignFailure.getMessage()); + assertTrue(feignFailure.getMessage().contains("ontap down"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(nasFeignClient).deleteFile(anyString(), eq("flex-uuid"), eq("f")); + CloudRuntimeException genericFailure = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFileByPath("flex-uuid", "f")); + assertTrue(genericFailure.getMessage().contains("boom"), genericFailure.getMessage()); + verify(nasFeignClient, times(2)).deleteFile(anyString(), eq("flex-uuid"), eq("f")); + } + + // ------------------------------------------------- unused access-group hooks + + @Test + public void unsupportedAccessHooksReturnNothing() { + assertNull(strategy.getAccessGroup(Map.of())); + assertNull(strategy.enableLogicalAccess(Map.of())); + assertNull(strategy.getLogicalAccess(Map.of())); + strategy.disableLogicalAccess(Map.of()); + } + + // ------------------------------------------------- createAccessGroup failures + + @Test + public void createAccessGroupFailsWhenPolicyCannotBeVerifiedOnOntap() { + poolDetailsForCreate(); + when(nasFeignClient.getExportPolicyResponse(anyString(), anyMap())).thenReturn(null); + AccessGroup group = accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> strategy.createAccessGroup(group)); + + assertTrue(thrown.getMessage().contains( + "Export policy cs-svm1-flexvol was not created on ONTAP"), thrown.getMessage()); + verify(volumeFeignClient, never()).updateVolume(anyString(), anyString(), any()); + assertExportPolicyWasCreated(1); + assertExportPolicyWasLookedUp(1); + } + + @Test + public void createAccessGroupFailsWhenVerificationCallFailsOnOntap() { + poolDetailsForCreate(); + FeignException feign = feignException(500, "lookup failed"); + when(nasFeignClient.getExportPolicyResponse(anyString(), anyMap())).thenThrow(feign); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)))); + + assertTrue(thrown.getMessage().contains("Export policy creation verification failed"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("lookup failed"), thrown.getMessage()); + assertExportPolicyWasCreated(1); + assertExportPolicyWasLookedUp(1); + } + + @Test + public void createAccessGroupFailsWhenOntapRejectsPolicyCreation() { + poolDetailsForCreate(); + FeignException feign = feignException(400, "bad policy"); + doThrow(feign).when(nasFeignClient).createExportPolicy(anyString(), any(ExportPolicy.class)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)))); + + assertTrue(thrown.getMessage().contains("Failed to create export policy: "), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("bad policy"), thrown.getMessage()); + assertExportPolicyWasCreated(1); + verify(nasFeignClient, never()).getExportPolicyResponse(anyString(), anyMap()); + } + + @Test + public void createAccessGroupFailsWhenAttachingPolicyToVolumeReturnsNoJob() { + poolDetailsForCreate(); + exportPolicyIsCreated(); + when(volumeFeignClient.updateVolume(anyString(), anyString(), any())).thenReturn(null); + AccessGroup group = accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)); + CloudRuntimeException noResponse = assertThrows(CloudRuntimeException.class, () -> strategy.createAccessGroup(group)); + assertTrue(noResponse.getMessage().contains("Failed to attach policy created-policyto volume flex-uuid"), noResponse.getMessage()); + + when(volumeFeignClient.updateVolume(anyString(), eq("flex-uuid"), exportPolicyUpdate("created-policy"))).thenReturn(new JobResponse()); + CloudRuntimeException emptyJob = assertThrows(CloudRuntimeException.class, () -> strategy.createAccessGroup(group)); + assertTrue(emptyJob.getMessage().contains("Failed to attach policy created-policyto volume flex-uuid"), emptyJob.getMessage()); + verify(volumeFeignClient, times(2)).updateVolume(anyString(), eq("flex-uuid"), exportPolicyUpdate("created-policy")); + assertExportPolicyWasCreated(2); + assertExportPolicyWasLookedUp(2); + verify(storagePoolDetailsDao, never()).addDetail(anyLong(), anyString(), anyString(), org.mockito.ArgumentMatchers.anyBoolean()); + } + + @Test + public void createAccessGroupFailsWhenAttachJobFails() { + poolDetailsForCreate(); + exportPolicyIsCreated(); + when(volumeFeignClient.updateVolume(anyString(), eq("flex-uuid"), exportPolicyUpdate("created-policy"))).thenReturn(jobResponse()); + when(jobFeignClient.getJobByUUID(anyString(), eq("job-1"))).thenReturn(job(OntapStorageConstants.JOB_FAILURE, "volume busy")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)))); + + assertTrue(thrown.getMessage().contains("Job to update volume flex-uuid failed with error: volume busy"), thrown.getMessage()); + verify(volumeFeignClient).updateVolume(anyString(), eq("flex-uuid"), exportPolicyUpdate("created-policy")); + verify(jobFeignClient).getJobByUUID(anyString(), eq("job-1")); + assertExportPolicyWasCreated(1); + assertExportPolicyWasLookedUp(1); + } + + @Test + public void createAccessGroupFailsWhenJobStatusCannotBeFetched() { + poolDetailsForCreate(); + exportPolicyIsCreated(); + when(volumeFeignClient.updateVolume(anyString(), eq("flex-uuid"), exportPolicyUpdate("created-policy"))).thenReturn(jobResponse()); + FeignException clientException = feignException(403, "forbidden"); + assertTrue(clientException instanceof FeignException.FeignClientException); + when(jobFeignClient.getJobByUUID(anyString(), eq("job-1"))).thenThrow(clientException); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)))); + + assertTrue(thrown.getMessage().contains("Failed to fetch job status"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("forbidden"), thrown.getMessage()); + verify(volumeFeignClient).updateVolume(anyString(), eq("flex-uuid"), exportPolicyUpdate("created-policy")); + verify(jobFeignClient).getJobByUUID(anyString(), eq("job-1")); + assertExportPolicyWasCreated(1); + assertExportPolicyWasLookedUp(1); + } + + @Test + public void createAccessGroupRetriesWhenJobIsNotYetVisibleThenReportsItsFailure() { + poolDetailsForCreate(); + exportPolicyIsCreated(); + when(volumeFeignClient.updateVolume(anyString(), eq("flex-uuid"), exportPolicyUpdate("created-policy"))).thenReturn(jobResponse()); + when(jobFeignClient.getJobByUUID(anyString(), eq("job-1"))) + .thenReturn(null) + .thenReturn(job(OntapStorageConstants.JOB_FAILURE, "gave up")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.createAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)))); + + assertTrue(thrown.getMessage().contains("Job to update volume flex-uuid failed with error: gave up"), thrown.getMessage()); + verify(volumeFeignClient).updateVolume(anyString(), eq("flex-uuid"), exportPolicyUpdate("created-policy")); + verify(jobFeignClient, times(2)).getJobByUUID(anyString(), eq("job-1")); + assertExportPolicyWasCreated(1); + assertExportPolicyWasLookedUp(1); + } + + // ------------------------------------------------- createExportPolicyRequest + + private ExportPolicy buildExportPolicyRequest(AccessGroup group) throws Exception { + Method method = UnifiedNASStrategy.class.getDeclaredMethod("createExportPolicyRequest", + AccessGroup.class, String.class, String.class); + method.setAccessible(true); + return (ExportPolicy) method.invoke(strategy, group, "svm1", "flexvol"); + } + + @Test + public void exportPolicyRequestUsesStorageIpThenPrivateIpForEachHost() throws Exception { + AccessGroup group = accessGroup(AccessGroup.HostRuleAction.ADD, + host(" 10.1.1.1 ", "192.168.0.1"), + host(" ", "192.168.0.2"), + host(null, " 192.168.0.3 ")); + + ExportPolicy policy = buildExportPolicyRequest(group); + + List matches = new ArrayList<>(); + for (ExportRule.ExportClient client : policy.getRules().get(0).getClients()) { + matches.add(client.getMatch()); + } + assertEquals(List.of("10.1.1.1/32", "192.168.0.2/32", "192.168.0.3/32"), matches); + assertEquals("svm1", policy.getSvm().getName()); + assertEquals(List.of(ExportRule.ProtocolsEnum.NFS3), policy.getRules().get(0).getProtocols()); + } + + // ------------------------------------------------- deleteAccessGroup + + @Test + public void deleteAccessGroupDeletesThePolicyRecordedOnThePool() { + poolHasExportPolicy(); + + strategy.deleteAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null))); + + verify(nasFeignClient).deleteExportPolicyById(anyString(), eq(POLICY_ID)); + } + + @Test + public void deleteAccessGroupRejectsNullGroup() { + assertThrows(CloudRuntimeException.class, () -> strategy.deleteAccessGroup(null)); + } + + @Test + public void deleteAccessGroupTreatsPolicyAlreadyRemovedAsSuccess() { + poolHasExportPolicy(); + FeignException notFound = feignException(404, "policy gone"); + doThrow(notFound).when(nasFeignClient).deleteExportPolicyById(anyString(), anyString()); + + strategy.deleteAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null))); + + verify(nasFeignClient).deleteExportPolicyById(anyString(), eq(POLICY_ID)); + } + + @Test + public void deleteAccessGroupFailsWhenOntapReportsOtherErrors() { + poolHasExportPolicy(); + FeignException serverError = feignException(500, "ontap down"); + doThrow(serverError).when(nasFeignClient).deleteExportPolicyById(anyString(), anyString()); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)))); + + assertTrue(thrown.getMessage().contains("Failed to delete export policy"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("ontap down"), thrown.getMessage()); + verify(nasFeignClient).deleteExportPolicyById(anyString(), eq(POLICY_ID)); + } + + @Test + public void deleteAccessGroupFailsWhenPoolDetailsCannotBeRead() { + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenThrow(new IllegalStateException("db down")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)))); + + assertTrue(thrown.getMessage().contains("db down"), thrown.getMessage()); + } + + // ------------------------------------------------- updateAccessGroup validation + + @Test + public void updateAccessGroupRejectsInvalidInput() { + assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(null)); + + AccessGroup noPool = accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)); + noPool.setStoragePoolId(null); + assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(noPool)); + + AccessGroup nullHosts = accessGroup(AccessGroup.HostRuleAction.ADD); + nullHosts.setHostsToConnect(null); + assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(nullHosts)); + + assertThrows(CloudRuntimeException.class, + () -> strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD))); + } + + @Test + public void updateAccessGroupFailsWhenPoolHasNoDetailsOrNoPolicyId() { + AccessGroup group = accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)); + + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(null); + CloudRuntimeException nullDetails = assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(group)); + assertTrue(nullDetails.getMessage().contains("No storage pool poolDetails found"), nullDetails.getMessage()); + + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(new HashMap<>()); + assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(group)); + + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(new HashMap<>(Map.of(OntapStorageConstants.EXPORT_POLICY_ID, ""))); + CloudRuntimeException noPolicy = assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(group)); + assertTrue(noPolicy.getMessage().contains("No export policy found"), noPolicy.getMessage()); + } + + @Test + public void updateAccessGroupFailsWhenPolicyIsMissingOrHasNoRules() { + poolHasExportPolicy(); + AccessGroup group = accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)); + + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(null); + CloudRuntimeException missing = assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(group)); + assertTrue(missing.getMessage().contains("Failed to fetch existing export policy"), missing.getMessage()); + + ExportPolicy noRules = new ExportPolicy(); + noRules.setName("policy-name"); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(noRules); + CloudRuntimeException emptyRules = assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(group)); + assertTrue(emptyRules.getMessage().contains("has no rules"), emptyRules.getMessage()); + + noRules.setRules(new ArrayList<>()); + assertThrows(CloudRuntimeException.class, () -> strategy.updateAccessGroup(group)); + } + + // ------------------------------------------------- updateAccessGroup behaviour + + @Test + public void updateAccessGroupSkipsOntapCallWhenNoHostHasAnIp() { + poolHasExportPolicy(); + ExportPolicy existing = policyWithClients(new ArrayList<>()); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + + AccessGroup result = strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, + host(null, null), host(" ", " "))); + + assertSame(existing, result.getPolicy()); + verify(nasFeignClient, never()).updateExportPolicy(anyString(), anyString(), any(ExportPolicy.class)); + } + + @Test + public void updateAccessGroupAddsNewHostsToRuleWithoutClients() { + poolHasExportPolicy(); + ExportPolicy existing = policyWithClients(null); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + + AccessGroup result = strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null))); + + assertEquals("10.1.1.1/32", existing.getRules().get(0).getClients().get(0).getMatch()); + assertSame(existing, result.getPolicy()); + verify(nasFeignClient).updateExportPolicy(anyString(), eq(POLICY_ID), any(ExportPolicy.class)); + } + + @Test + public void updateAccessGroupAddIgnoresMalformedClientsAndSkipsDuplicates() { + poolHasExportPolicy(); + List clients = new ArrayList<>(); + clients.add(null); + clients.add(new ExportRule.ExportClient()); + clients.add(client("10.1.1.1/32")); + ExportPolicy existing = policyWithClients(clients); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + + strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null), host("10.1.1.2", null))); + + assertEquals(4, clients.size()); + assertEquals("10.1.1.2/32", clients.get(3).getMatch()); + verify(nasFeignClient).updateExportPolicy(anyString(), eq(POLICY_ID), any(ExportPolicy.class)); + } + + @Test + public void updateAccessGroupAddOfAlreadyPresentHostsMakesNoOntapCall() { + poolHasExportPolicy(); + ExportPolicy existing = policyWithClients(new ArrayList<>(List.of(client("10.1.1.1/32")))); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + + AccessGroup result = strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null))); + + assertSame(existing, result.getPolicy()); + verify(nasFeignClient, never()).updateExportPolicy(anyString(), anyString(), any(ExportPolicy.class)); + } + + @Test + public void updateAccessGroupRemoveDropsMatchingHostsOnly() { + poolHasExportPolicy(); + List clients = new ArrayList<>(); + clients.add(null); + clients.add(new ExportRule.ExportClient()); + clients.add(client("10.1.1.1/32")); + clients.add(client("10.1.1.9/32")); + ExportPolicy existing = policyWithClients(clients); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + + strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.REMOVE, host("10.1.1.1", null))); + + assertEquals(3, clients.size()); + assertTrue(clients.stream().noneMatch(c -> c != null && "10.1.1.1/32".equals(c.getMatch()))); + verify(nasFeignClient).updateExportPolicy(anyString(), eq(POLICY_ID), any(ExportPolicy.class)); + } + + @Test + public void updateAccessGroupRemoveOfUnknownHostMakesNoOntapCall() { + poolHasExportPolicy(); + ExportPolicy existing = policyWithClients(new ArrayList<>(List.of(client("10.1.1.9/32")))); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + + AccessGroup result = strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.REMOVE, host("10.1.1.1", null))); + + assertSame(existing, result.getPolicy()); + verify(nasFeignClient, never()).updateExportPolicy(anyString(), anyString(), any(ExportPolicy.class)); + } + + @Test + public void updateAccessGroupUsesPrivateIpWhenStorageIpIsBlank() { + poolHasExportPolicy(); + ExportPolicy existing = policyWithClients(new ArrayList<>()); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + + strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host(" ", "192.168.5.5"))); + + ArgumentCaptor sent = ArgumentCaptor.forClass(ExportPolicy.class); + verify(nasFeignClient).updateExportPolicy(anyString(), eq(POLICY_ID), sent.capture()); + assertEquals("192.168.5.5/32", sent.getValue().getRules().get(0).getClients().get(0).getMatch()); + } + + @Test + public void updateAccessGroupWrapsOntapUpdateFailure() { + poolHasExportPolicy(); + ExportPolicy existing = policyWithClients(new ArrayList<>()); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + doThrow(new IllegalStateException("patch failed")).when(nasFeignClient) + .updateExportPolicy(anyString(), anyString(), any(ExportPolicy.class)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)))); + + assertTrue(thrown.getMessage().contains("Failed to update export policy for NFS host connection"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("patch failed"), thrown.getMessage()); + ArgumentCaptor sent = ArgumentCaptor.forClass(ExportPolicy.class); + verify(nasFeignClient).updateExportPolicy(anyString(), eq(POLICY_ID), sent.capture()); + assertEquals("10.1.1.1/32", sent.getValue().getRules().get(0).getClients().get(0).getMatch()); + } + + // ------------------------------------------------- revertSnapshotForCloudStackVolume + + @Test + public void revertSnapshotAddsLeadingSlashAndCallsCliRestore() { + JobResponse expected = new JobResponse(); + when(snapshotFeignClient.restoreFileFromSnapshotCli(anyString(), any())).thenReturn(expected); + + JobResponse actual = strategy.revertSnapshotForCloudStackVolume("snap1", "flex-uuid", "snap-uuid", "dir/file.qcow2", null, "flexvol"); + + assertSame(expected, actual); + verify(snapshotFeignClient).restoreFileFromSnapshotCli(anyString(), org.mockito.ArgumentMatchers.argThat( + request -> "/dir/file.qcow2".equals(request.getPath()) && "svm1".equals(request.getVserver()) + && "flexvol".equals(request.getVolume()) && "snap1".equals(request.getSnapshot()))); + } + + @Test + public void revertSnapshotKeepsExistingLeadingSlash() { + strategy.revertSnapshotForCloudStackVolume("snap1", "flex-uuid", "snap-uuid", "/file.qcow2", null, "flexvol"); + + verify(snapshotFeignClient).restoreFileFromSnapshotCli(anyString(), org.mockito.ArgumentMatchers.argThat( + request -> "/file.qcow2".equals(request.getPath()) && "svm1".equals(request.getVserver()) + && "flexvol".equals(request.getVolume()) && "snap1".equals(request.getSnapshot()))); + } + + @Test + public void revertSnapshotRejectsMissingArguments() { + for (String[] args : new String[][] { + {null, "file", "flexvol"}, {"", "file", "flexvol"}, + {"snap", null, "flexvol"}, {"snap", "", "flexvol"}, + {"snap", "file", null}, {"snap", "file", ""}}) { + assertThrows(CloudRuntimeException.class, () -> + strategy.revertSnapshotForCloudStackVolume(args[0], "flex-uuid", "snap-uuid", args[1], null, args[2])); + } + verify(snapshotFeignClient, never()).restoreFileFromSnapshotCli(anyString(), any()); + } + + // =================================================================================== + // Assertions on the exact requests the NAS strategy sends to ONTAP and persists + // =================================================================================== + + private static ExportPolicy createdPolicy(int id, String name) throws Exception { + return new com.fasterxml.jackson.databind.ObjectMapper() + .readValue("{\"id\":" + id + ",\"name\":\"" + name + "\"}", ExportPolicy.class); + } + + @Test + public void createAccessGroupAttachesPolicyToTheFlexVolAndRecordsItOnThePool() throws Exception { + poolDetailsForCreate(); + ExportPolicy created = createdPolicy(9, "created-policy"); + when(nasFeignClient.getExportPolicyResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(created))); + when(volumeFeignClient.updateVolume(anyString(), anyString(), any())).thenReturn(jobResponse()); + when(jobFeignClient.getJobByUUID(anyString(), eq("job-1"))).thenReturn(job(OntapStorageConstants.JOB_SUCCESS, "done")); + AccessGroup group = accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null)); + + AccessGroup result = strategy.createAccessGroup(group); + + org.mockito.ArgumentCaptor volumeUpdate = + org.mockito.ArgumentCaptor.forClass(org.apache.cloudstack.storage.feign.model.Volume.class); + verify(volumeFeignClient).updateVolume(anyString(), eq("flex-uuid"), volumeUpdate.capture()); + assertEquals("created-policy", volumeUpdate.getValue().getNas().getExportPolicy().getName()); + verify(storagePoolDetailsDao).addDetail(POOL_ID, OntapStorageConstants.EXPORT_POLICY_ID, "9", true); + verify(storagePoolDetailsDao).addDetail(POOL_ID, OntapStorageConstants.EXPORT_POLICY_NAME, "created-policy", true); + assertSame(group, result); + assertEquals(org.apache.cloudstack.storage.utils.OntapStorageUtils.generateExportPolicyName("svm1", "flexvol"), + result.getPolicy().getName()); + assertEquals("10.1.1.1/32", result.getPolicy().getRules().get(0).getClients().get(0).getMatch()); + org.mockito.ArgumentCaptor sent = org.mockito.ArgumentCaptor.forClass(ExportPolicy.class); + verify(nasFeignClient).createExportPolicy(anyString(), sent.capture()); + assertSame(result.getPolicy(), sent.getValue()); + } + + @Test + public void exportPolicyRequestGrantsSysAuthenticationForReadWriteAndSuperuser() throws Exception { + ExportPolicy policy = buildExportPolicyRequest(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null))); + + ExportRule rule = policy.getRules().get(0); + assertEquals(List.of("sys"), rule.getRoRule()); + assertEquals(List.of("sys"), rule.getRwRule()); + assertEquals(List.of("sys"), rule.getSuperuser()); + assertEquals(org.apache.cloudstack.storage.utils.OntapStorageUtils.generateExportPolicyName("svm1", "flexvol"), policy.getName()); + } + + @Test + public void createVolumeWithoutAnyFileDoesNotTouchOntapFiles() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(CreateObjectCommand.class))).thenReturn(new Answer(null, true, "ok")); + + CloudStackVolume request = nfsVolume(volume, null); + assertSame(request, strategy.createCloudStackVolume(request)); + + verify(nasFeignClient, never()).updateFile(anyString(), anyString(), anyString(), any(FileInfo.class)); + } + + @Test + public void createVolumeWithQosFileSendsTheQosPolicyForTheVolumeFile() { + VolumeObject volume = volumeObject(); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(CreateObjectCommand.class))).thenReturn(new Answer(null, true, "ok")); + FileInfo file = fileWithQos(); + + strategy.createCloudStackVolume(nfsVolume(volume, file)); + + verify(nasFeignClient).updateFile(anyString(), eq("flex-uuid"), eq("vol-uuid"), + org.mockito.ArgumentMatchers.argThat(patch -> patch.getQosPolicy() == file.getQosPolicy())); + } + + @Test + public void cloneSendsRequestPollsJobPersistsVolumeRowAndReturnsTheClone() { + when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(new HashMap<>(Map.of( + OntapStorageConstants.VOLUME_UUID, "flex-uuid", OntapStorageConstants.VOLUME_NAME, "flexvol"))); + JobResponse job = jobResponse(); + when(nasFeignClient.cloneFile(anyString(), any())).thenReturn(job); + when(jobFeignClient.getJobByUUID(anyString(), eq("job-1"))) + .thenReturn(job(OntapStorageConstants.JOB_SUCCESS, "cloned")); + UnifiedNASStrategy spied = org.mockito.Mockito.spy(strategy); + CloudStackVolume request = cloneRequest("src.qcow2", "dst.qcow2", "1"); + VolumeVO volumeRow = volumeDao.findById(100L); + + CloudStackVolume clone = spied.cloneCloudStackVolume(request); + + verify(spied).pollJobIfPresent(job, "clone file [src.qcow2] to [dst.qcow2]"); + verify(jobFeignClient).getJobByUUID(anyString(), eq("job-1")); + verify(nasFeignClient).cloneFile(anyString(), org.mockito.ArgumentMatchers.argThat(body -> + "flex-uuid".equals(body.getVolume().getUuid()) && "flexvol".equals(body.getVolume().getName()) + && "src.qcow2".equals(body.getSourcePath()) && "dst.qcow2".equals(body.getDestinationPath()))); + verify(volumeRow).setPoolType(Storage.StoragePoolType.NetworkFilesystem); + verify(volumeRow).setPoolId(1L); + verify(volumeRow).setPath("vol-uuid"); + verify(volumeDao).update(volumeRow.getId(), volumeRow); + assertEquals("dst.qcow2", clone.getFile().getPath()); + assertEquals("1", clone.getDatastoreId()); + assertSame(request.getVolumeInfo(), clone.getVolumeInfo()); + } + + @Test + public void volumeMetadataUpdateReturnsTheVolumeUuidUsedAsPath() throws Exception { + VolumeObject volume = volumeObject(); + VolumeVO volumeRow = volumeDao.findById(100L); + when(volumeRow.getId()).thenReturn(100L); + Method method = UnifiedNASStrategy.class.getDeclaredMethod("updateCloudStackVolumeMetadata", String.class, + org.apache.cloudstack.engine.subsystem.api.storage.DataObject.class); + method.setAccessible(true); + + assertEquals("vol-uuid", method.invoke(strategy, "1", volume)); + + verify(volumeRow).setPoolType(Storage.StoragePoolType.NetworkFilesystem); + verify(volumeRow).setPoolId(1L); + verify(volumeRow).setPath("vol-uuid"); + verify(volumeDao).update(100L, volumeRow); + } + + @Test + public void resizeFailsWithTheEndpointMessageWhenNoHostIsAvailable() { + VolumeObject volume = volumeObject(); + VolumeVO volumeVO = volumeDao.findById(100L); + when(volumeVO.getPoolId()).thenReturn(5L); + when(primaryDataStoreDao.findById(5L)).thenReturn(mock(org.apache.cloudstack.storage.datastore.db.StoragePoolVO.class)); + when(epSelector.select(volume)).thenReturn(null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> strategy.resizeCloudStackVolume(nfsVolume(volume, new FileInfo()), 2048L)); + + assertTrue(thrown.getMessage().contains("No remote endpoint to send ResizeVolumeCommand"), thrown.getMessage()); + } + + @Test + public void resizeRejectsZeroSizeWithTheSizeInTheMessageButAcceptsOneByte() { + VolumeObject volume = volumeObject(); + CloudRuntimeException zero = assertThrows(CloudRuntimeException.class, + () -> strategy.resizeCloudStackVolume(nfsVolume(volume, new FileInfo()), 0L)); + assertTrue(zero.getMessage().contains("invalid size 0"), zero.getMessage()); + + VolumeVO volumeVO = volumeDao.findById(100L); + when(volumeVO.getPoolId()).thenReturn(5L); + when(primaryDataStoreDao.findById(5L)).thenReturn(mock(org.apache.cloudstack.storage.datastore.db.StoragePoolVO.class)); + EndPoint endPoint = mock(EndPoint.class); + when(epSelector.select(volume)).thenReturn(endPoint); + when(endPoint.sendMessage(any(com.cloud.agent.api.storage.ResizeVolumeCommand.class))).thenReturn(new Answer(null, true, "ok")); + + strategy.resizeCloudStackVolume(nfsVolume(volume, new FileInfo()), 1L); + + verify(endPoint).sendMessage(org.mockito.ArgumentMatchers.argThat(command -> + command instanceof com.cloud.agent.api.storage.ResizeVolumeCommand + && ((com.cloud.agent.api.storage.ResizeVolumeCommand) command).getNewSize() == 1L)); + } + + @Test + public void updateAccessGroupPatchesThePolicyWithTheUpdatedRules() { + poolHasExportPolicy(); + ExportPolicy existing = policyWithClients(new ArrayList<>(List.of(client("10.1.1.9/32")))); + when(nasFeignClient.getExportPolicyById(anyString(), eq(POLICY_ID))).thenReturn(existing); + + strategy.updateAccessGroup(accessGroup(AccessGroup.HostRuleAction.ADD, host("10.1.1.1", null))); + + org.mockito.ArgumentCaptor patch = org.mockito.ArgumentCaptor.forClass(ExportPolicy.class); + verify(nasFeignClient).updateExportPolicy(anyString(), eq(POLICY_ID), patch.capture()); + assertEquals(1, patch.getValue().getRules().size()); + List matches = new ArrayList<>(); + for (ExportRule.ExportClient c : patch.getValue().getRules().get(0).getClients()) { + matches.add(c.getMatch()); + } + assertEquals(List.of("10.1.1.9/32", "10.1.1.1/32"), matches); + } } diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/UnifiedSANStrategyTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/UnifiedSANStrategyTest.java index d58b095de042..4493bb96ab4f 100644 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/UnifiedSANStrategyTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/service/UnifiedSANStrategyTest.java @@ -25,22 +25,26 @@ import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.feign.client.SANFeignClient; +import org.apache.cloudstack.storage.feign.client.SnapshotFeignClient; import org.apache.cloudstack.storage.feign.model.Igroup; import org.apache.cloudstack.storage.feign.model.Initiator; import org.apache.cloudstack.storage.feign.model.Lun; import org.apache.cloudstack.storage.feign.model.LunMap; import org.apache.cloudstack.storage.feign.model.OntapStorage; import org.apache.cloudstack.storage.feign.model.VolumeQosPolicy; +import org.apache.cloudstack.storage.feign.model.response.JobResponse; import org.apache.cloudstack.storage.feign.model.response.OntapResponse; import org.apache.cloudstack.storage.service.model.AccessGroup; import org.apache.cloudstack.storage.service.model.CloudStackVolume; import org.apache.cloudstack.storage.service.model.ProtocolType; import org.apache.cloudstack.storage.utils.OntapStorageConstants; import org.apache.cloudstack.storage.utils.OntapStorageUtils; +import org.apache.cloudstack.storage.volume.VolumeObject; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -56,28 +60,40 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import org.mockito.Mock; import org.mockito.MockedStatic; import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.HostVO; +import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.VolumeDetailVO; import com.cloud.storage.dao.VolumeDetailsDao; import com.cloud.utils.exception.CloudRuntimeException; +import com.fasterxml.jackson.databind.ObjectMapper; + import feign.FeignException; @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class UnifiedSANStrategyTest { @Mock @@ -101,6 +117,11 @@ class UnifiedSANStrategyTest { @Mock private VolumeDetailsDao volumeDetailsDao; + @Mock + private SnapshotFeignClient snapshotFeignClient; + + private static final String LUN_UUID = "lun-uuid"; + private UnifiedSANStrategy unifiedSANStrategy; private String authHeader; @@ -137,6 +158,7 @@ void setUp() { java.lang.reflect.Field volumeDetailsDaoField = UnifiedSANStrategy.class.getDeclaredField("volumeDetailsDao"); volumeDetailsDaoField.setAccessible(true); volumeDetailsDaoField.set(unifiedSANStrategy, volumeDetailsDao); + unifiedSANStrategy.snapshotFeignClient = snapshotFeignClient; } catch (Exception e) { throw new RuntimeException(e); } @@ -264,9 +286,12 @@ void testCreateTemplateCache_CreateFails_BestEffortDeletesLeftoverLun() { when(sanFeignClient.createLun(eq(authHeader), eq(true), any(Lun.class))).thenThrow(createEx); when(sanFeignClient.getLunResponse(eq(authHeader), anyMap())).thenReturn(leftoverResponse); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createTemplateCache(storagePool, templateInfo, details, 5368709120L)); + assertTrue(thrown.getMessage().contains("Failed to create Lun: create failed"), thrown.getMessage()); + assertTemplateCacheCreateWasFor("/vol/vol1/cs_tmpl_50", "svm1", 5368709120L); + assertLunLookupWasFor("svm1", "/vol/vol1/cs_tmpl_50"); verify(sanFeignClient).deleteLun(eq(authHeader), eq("leftover-uuid"), anyMap()); } } @@ -298,9 +323,12 @@ void testCreateTemplateCache_CreateFails_NoLeftoverLun_SkipsDelete() { when(sanFeignClient.createLun(eq(authHeader), eq(true), any(Lun.class))).thenThrow(createEx); when(sanFeignClient.getLunResponse(eq(authHeader), anyMap())).thenReturn(empty); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createTemplateCache(storagePool, templateInfo, details, 5368709120L)); + assertTrue(thrown.getMessage().contains("Failed to create Lun: create failed"), thrown.getMessage()); + assertTemplateCacheCreateWasFor("/vol/vol1/cs_tmpl_50", "svm1", 5368709120L); + assertLunLookupWasFor("svm1", "/vol/vol1/cs_tmpl_50"); verify(sanFeignClient, never()).deleteLun(any(), any(), anyMap()); } } @@ -371,9 +399,13 @@ void testCreateCloudStackVolume_FeignException_ThrowsCloudRuntimeException() { when(sanFeignClient.createLun(eq(authHeader), eq(true), any(Lun.class))) .thenThrow(feignException); - // Execute & Verify - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createCloudStackVolume(request)); + + assertTrue(thrown.getMessage().contains("Failed to create Lun: Internal server error"), thrown.getMessage()); + ArgumentCaptor sent = ArgumentCaptor.forClass(Lun.class); + verify(sanFeignClient).createLun(eq(authHeader), eq(true), sent.capture()); + assertEquals("/vol/vol1/lun1", sent.getValue().getName()); } } @@ -423,6 +455,7 @@ void testDeleteCloudStackVolume_Success() { } @Test + @SuppressWarnings("unchecked") void testDeleteCloudStackVolume_NotFound_SkipsDeletion() { // Setup Lun lun = new Lun(); @@ -440,8 +473,11 @@ void testDeleteCloudStackVolume_NotFound_SkipsDeletion() { doThrow(feignException).when(sanFeignClient).deleteLun(eq(authHeader), eq("lun-uuid-123"), anyMap()); - // Execute - should not throw exception assertDoesNotThrow(() -> unifiedSANStrategy.deleteCloudStackVolume(request)); + + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient).deleteLun(eq(authHeader), eq("lun-uuid-123"), query.capture()); + assertEquals("true", query.getValue().get("allow_delete_while_mapped")); } } @@ -676,8 +712,10 @@ void testDeleteAccessGroup_NotFound_SkipsDeletion() { when(sanFeignClient.getIgroupResponse(eq(authHeader), anyMap())).thenThrow(feignException); - // Execute - should not throw exception assertDoesNotThrow(() -> unifiedSANStrategy.deleteAccessGroup(accessGroup)); + + assertIgroupLookupWasFor("igroup1"); + verify(sanFeignClient, never()).deleteIgroup(anyString(), anyString()); } } @@ -728,13 +766,13 @@ void testEnableLogicalAccess_Success() { String result = unifiedSANStrategy.enableLogicalAccess(values); assertEquals("", result); - verify(sanFeignClient).createLunMap(eq(authHeader), eq(false), any(LunMap.class)); + assertLunMapRequest("svm1", "/vol/vol1/lun1", "igroup1"); verify(sanFeignClient, never()).getLunMapResponse(any(), anyMap()); } } @Test - void testEnableLogicalAccess_AlreadyMapped_ReturnsLunNumber() { + void testEnableLogicalAccess_AlreadyMapped_ReturnsEmptyString() { // Setup Map values = new HashMap<>(); values.put(OntapStorageConstants.SVM_DOT_NAME, "svm1"); @@ -751,6 +789,7 @@ void testEnableLogicalAccess_AlreadyMapped_ReturnsLunNumber() { String result = unifiedSANStrategy.enableLogicalAccess(values); assertEquals("", result); + assertLunMapRequest("svm1", "/vol/vol1/lun1", "igroup1"); verify(sanFeignClient, never()).getLunMapResponse(any(), anyMap()); } } @@ -792,8 +831,9 @@ void testDisableLogicalAccess_NotFound_SkipsDeletion() { doThrow(feignException).when(sanFeignClient).deleteLunMap(eq(authHeader), eq("lun-uuid-123"), eq("igroup-uuid-123")); - // Execute - should not throw exception assertDoesNotThrow(() -> unifiedSANStrategy.disableLogicalAccess(values)); + + verify(sanFeignClient).deleteLunMap(eq(authHeader), eq("lun-uuid-123"), eq("igroup-uuid-123")); } } @@ -827,6 +867,7 @@ void testGetLogicalAccess_Success() { } @Test + @SuppressWarnings("unchecked") void testGetLogicalAccess_NotFound_ReturnsNull() { // Setup Map values = new HashMap<>(); @@ -839,13 +880,20 @@ void testGetLogicalAccess_NotFound_ReturnsNull() { .thenReturn(authHeader); when(sanFeignClient.getLunMapResponse(eq(authHeader), anyMap())) - .thenThrow(new RuntimeException("Not found")); + .thenThrow(new RuntimeException("Not found")) + .thenThrow(new RuntimeException("Connection failed")); - // Execute - String result = unifiedSANStrategy.getLogicalAccess(values); + assertNull(unifiedSANStrategy.getLogicalAccess(values)); + assertNull(unifiedSANStrategy.getLogicalAccess(values)); - // Verify - assertNull(result); + ArgumentCaptor> queries = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient, times(2)).getLunMapResponse(eq(authHeader), queries.capture()); + for (Map query : queries.getAllValues()) { + assertEquals("svm1", query.get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals("/vol/vol1/lun1", query.get(OntapStorageConstants.LUN_DOT_NAME)); + assertEquals("igroup1", query.get(OntapStorageConstants.IGROUP_DOT_NAME)); + assertEquals(OntapStorageConstants.LOGICAL_UNIT_NUMBER, query.get(OntapStorageConstants.FIELDS)); + } } } @@ -878,40 +926,27 @@ void testEnsureLunMapped_ExistingMapping_ReturnsLunNumber() { } @Test - void testEnsureLunMapped_CreatesNewMapping_ReturnsLunNumber() { - // Setup + void testEnsureLunMapped_CreatesNewMapping_ReturnsEmptyString() { String svmName = "svm1"; String lunName = "/vol/vol1/lun1"; String accessGroupName = "igroup1"; - LunMap lunMap = new LunMap(); - lunMap.setLogicalUnitNumber(4); - OntapResponse emptyResponse = new OntapResponse<>(); emptyResponse.setRecords(new ArrayList<>()); - OntapResponse response = new OntapResponse<>(); - response.setRecords(List.of(lunMap)); - try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) { utilityMock.when(() -> OntapStorageUtils.generateAuthHeader("admin", "password")) .thenReturn(authHeader); - // First call returns empty (no existing mapping), second call returns the new mapping - when(sanFeignClient.getLunMapResponse(eq(authHeader), anyMap())) - .thenReturn(emptyResponse) // First call - no records - .thenReturn(response); // Second call after creation - + when(sanFeignClient.getLunMapResponse(eq(authHeader), anyMap())).thenReturn(emptyResponse); when(sanFeignClient.createLunMap(eq(authHeader), eq(false), any(LunMap.class))) .thenReturn(new OntapResponse<>()); - // Execute String result = unifiedSANStrategy.ensureLunMapped(svmName, lunName, accessGroupName); - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(LunMap.class); - verify(sanFeignClient).createLunMap(eq(authHeader), eq(false), requestCaptor.capture()); - assertNull(requestCaptor.getValue().getLogicalUnitNumber()); assertEquals("", result); + assertLunMapQuery(svmName, lunName, accessGroupName); + assertLunMapRequest(svmName, lunName, accessGroupName); } } @@ -973,19 +1008,14 @@ void testValidateInitiatorInAccessGroup_EmptyInitiator_ReturnsFalse() { } @Test - void testValidateInitiatorInAccessGroup_IgroupNotFound_ReturnsFalse() { - // Setup - String hostInitiator = "iqn.1993-08.org.debian:01:host1"; - - Igroup emptyIgroup = new Igroup(); - emptyIgroup.setName("igroup1"); - emptyIgroup.setInitiators(null); - - // Execute - boolean result = unifiedSANStrategy.validateInitiatorInAccessGroup(hostInitiator, "svm1", emptyIgroup); + void testValidateInitiatorInAccessGroup_NullInitiatorList_ReturnsFalseWithoutOntapCall() { + Igroup igroup = new Igroup(); + igroup.setName("igroup1"); + igroup.setInitiators(null); - // Verify - assertFalse(result); + assertFalse(unifiedSANStrategy.validateInitiatorInAccessGroup( + "iqn.1993-08.org.debian:01:host1", "svm1", igroup)); + verifyNoInteractions(sanFeignClient); } @Test @@ -1637,8 +1667,15 @@ void testCloneCloudStackVolume_EmptyRecords_ThrowsException() { .thenReturn(authHeader); when(sanFeignClient.createLun(eq(authHeader), eq(true), any(Lun.class))).thenReturn(response); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(request)); + + assertEquals("Failed to clone Lun: /vol/vol1/cloned", thrown.getMessage()); + ArgumentCaptor sent = ArgumentCaptor.forClass(Lun.class); + verify(sanFeignClient).createLun(eq(authHeader), eq(true), sent.capture()); + assertEquals("/vol/vol1/cloned", sent.getValue().getName()); + assertEquals("source-lun-uuid", sent.getValue().getClone().getSource().getUuid()); + verify(sanFeignClient, never()).deleteLun(any(), any(), anyMap()); } } @@ -1664,8 +1701,14 @@ void testCloneCloudStackVolume_FeignException_ThrowsException() { .thenReturn(authHeader); when(sanFeignClient.createLun(eq(authHeader), eq(true), any(Lun.class))).thenThrow(feignException); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(request)); + + assertTrue(thrown.getMessage().contains("Failed to clone Lun: clone failed"), thrown.getMessage()); + ArgumentCaptor sent = ArgumentCaptor.forClass(Lun.class); + verify(sanFeignClient).createLun(eq(authHeader), eq(true), sent.capture()); + assertEquals("/vol/vol1/cloned", sent.getValue().getName()); + assertEquals("source-lun-uuid", sent.getValue().getClone().getSource().getUuid()); verify(sanFeignClient, never()).deleteLun(any(), any(), anyMap()); } } @@ -1673,7 +1716,10 @@ void testCloneCloudStackVolume_FeignException_ThrowsException() { @Test void testSetOntapStorage() { OntapStorage newStorage = mock(OntapStorage.class); - assertDoesNotThrow(() -> unifiedSANStrategy.setOntapStorage(newStorage)); + + unifiedSANStrategy.setOntapStorage(newStorage); + + assertSame(newStorage, unifiedSANStrategy.storage); } @Test @@ -1890,6 +1936,7 @@ void testCreateAccessGroup_FeignExceptionNon409_ThrowsException() { List hosts = new ArrayList<>(); HostVO host1 = mock(HostVO.class); + when(host1.getUuid()).thenReturn("host1"); when(host1.getStorageUrl()).thenReturn("iqn.1993-08.org.debian:01:host1"); hosts.add(host1); accessGroup.setHostsToConnect(hosts); @@ -1907,8 +1954,15 @@ void testCreateAccessGroup_FeignExceptionNon409_ThrowsException() { when(sanFeignClient.createIgroup(eq(authHeader), eq(true), any(Igroup.class))) .thenThrow(feignException); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createAccessGroup(accessGroup)); + + assertTrue(thrown.getMessage().contains("Failed to create Igroup: Internal server error"), thrown.getMessage()); + ArgumentCaptor sent = ArgumentCaptor.forClass(Igroup.class); + verify(sanFeignClient).createIgroup(eq(authHeader), eq(true), sent.capture()); + assertEquals("igroup1", sent.getValue().getName()); + assertEquals("svm1", sent.getValue().getSvm().getName()); + assertEquals("iqn.1993-08.org.debian:01:host1", sent.getValue().getInitiators().get(0).getName()); } } @@ -2026,8 +2080,12 @@ void testDeleteAccessGroup_FeignExceptionNon404_ThrowsException() { when(sanFeignClient.getIgroupResponse(eq(authHeader), anyMap())).thenThrow(feignException); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.deleteAccessGroup(accessGroup)); + + assertTrue(thrown.getMessage().contains("Internal server error"), thrown.getMessage()); + assertIgroupLookupWasFor("igroup1"); + verify(sanFeignClient, never()).deleteIgroup(anyString(), anyString()); } } @@ -2163,7 +2221,7 @@ void testEnableLogicalAccess_MissingIgroupName_ThrowsException() { } @Test - void testEnableLogicalAccess_FetchLunMapFails_ThrowsException() { + void testEnableLogicalAccess_CreateFails_ThrowsOntapError() { Map values = new HashMap<>(); values.put(OntapStorageConstants.SVM_DOT_NAME, "svm1"); values.put(OntapStorageConstants.LUN_DOT_NAME, "/vol/vol1/lun1"); @@ -2176,8 +2234,11 @@ void testEnableLogicalAccess_FetchLunMapFails_ThrowsException() { doThrow(new RuntimeException("ONTAP unavailable")).when(sanFeignClient) .createLunMap(eq(authHeader), eq(false), any(LunMap.class)); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.enableLogicalAccess(values)); + + assertTrue(thrown.getMessage().contains("Failed to create LunMap: ONTAP unavailable"), thrown.getMessage()); + assertLunMapRequest("svm1", "/vol/vol1/lun1", "igroup1"); } } @@ -2219,8 +2280,11 @@ void testDisableLogicalAccess_FeignExceptionNon404_ThrowsException() { doThrow(feignException).when(sanFeignClient).deleteLunMap(eq(authHeader), eq("lun-uuid-123"), eq("igroup-uuid-123")); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.disableLogicalAccess(values)); + + assertTrue(thrown.getMessage().contains("Internal server error"), thrown.getMessage()); + verify(sanFeignClient).deleteLunMap(eq(authHeader), eq("lun-uuid-123"), eq("igroup-uuid-123")); } } @@ -2284,8 +2348,12 @@ void testEnsureLunMapped_FailedToMap_ThrowsException() { doThrow(new RuntimeException("ONTAP unavailable")).when(sanFeignClient) .createLunMap(eq(authHeader), eq(false), any(LunMap.class)); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.ensureLunMapped(svmName, lunName, accessGroupName)); + + assertTrue(thrown.getMessage().contains("Failed to create LunMap: ONTAP unavailable"), thrown.getMessage()); + assertLunMapQuery(svmName, lunName, accessGroupName); + assertLunMapRequest(svmName, lunName, accessGroupName); } } @@ -2470,12 +2538,16 @@ void testDeleteCloudStackVolume_FeignException_ThrowsCloudRuntimeException() { doThrow(feignException).when(sanFeignClient).deleteLun(eq(authHeader), eq("lun-uuid-123"), anyMap()); - assertThrows(CloudRuntimeException.class, + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.deleteCloudStackVolume(request)); + + assertTrue(thrown.getMessage().contains("Internal server error"), thrown.getMessage()); + verify(sanFeignClient).deleteLun(eq(authHeader), eq("lun-uuid-123"), anyMap()); } } @Test + @SuppressWarnings("unchecked") void testGetCloudStackVolume_FeignException404_ReturnsNull() { Map values = new HashMap<>(); values.put(OntapStorageConstants.SVM_DOT_NAME, "svm1"); @@ -2490,9 +2562,12 @@ void testGetCloudStackVolume_FeignException404_ReturnsNull() { when(sanFeignClient.getLunResponse(eq(authHeader), anyMap())).thenThrow(feignException); - CloudStackVolume result = unifiedSANStrategy.getCloudStackVolume(values); + assertNull(unifiedSANStrategy.getCloudStackVolume(values)); - assertNull(result); + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient).getLunResponse(eq(authHeader), query.capture()); + assertEquals("svm1", query.getValue().get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals("/vol/vol1/lun1", query.getValue().get(OntapStorageConstants.NAME)); } } @@ -2612,26 +2687,6 @@ void testDisableLogicalAccess_EmptyIgroupUuid_ThrowsException() { () -> unifiedSANStrategy.disableLogicalAccess(values)); } - @Test - void testDisableLogicalAccess_FeignException404_SkipsDeletion() { - Map values = new HashMap<>(); - values.put(OntapStorageConstants.LUN_DOT_UUID, "lun-uuid-123"); - values.put(OntapStorageConstants.IGROUP_DOT_UUID, "igroup-uuid-123"); - - FeignException feignException = mock(FeignException.class); - when(feignException.status()).thenReturn(404); - - try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) { - utilityMock.when(() -> OntapStorageUtils.generateAuthHeader("admin", "password")) - .thenReturn(authHeader); - - doThrow(feignException).when(sanFeignClient).deleteLunMap(eq(authHeader), eq("lun-uuid-123"), eq("igroup-uuid-123")); - - // Should not throw exception for 404 - assertDoesNotThrow(() -> unifiedSANStrategy.disableLogicalAccess(values)); - } - } - @Test void testGetLogicalAccess_MissingLunName_ThrowsException() { Map values = new HashMap<>(); @@ -2674,26 +2729,6 @@ void testGetLogicalAccess_EmptyResponse_ReturnsNull() { } } - @Test - void testGetLogicalAccess_ExceptionThrown_ReturnsNull() { - Map values = new HashMap<>(); - values.put(OntapStorageConstants.SVM_DOT_NAME, "svm1"); - values.put(OntapStorageConstants.LUN_DOT_NAME, "/vol/vol1/lun1"); - values.put(OntapStorageConstants.IGROUP_DOT_NAME, "igroup1"); - - try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) { - utilityMock.when(() -> OntapStorageUtils.generateAuthHeader("admin", "password")) - .thenReturn(authHeader); - - when(sanFeignClient.getLunMapResponse(eq(authHeader), anyMap())) - .thenThrow(new RuntimeException("Connection failed")); - - String result = unifiedSANStrategy.getLogicalAccess(values); - - assertNull(result); - } - } - @Test void testValidateInitiatorInAccessGroup_NullInitiator_ReturnsFalse() { Igroup igroup = new Igroup(); @@ -2702,51 +2737,6 @@ void testValidateInitiatorInAccessGroup_NullInitiator_ReturnsFalse() { assertFalse(result); } - @Test - void testValidateInitiatorInAccessGroup_AccessGroupNotFound_ReturnsFalse() { - String hostInitiator = "iqn.1993-08.org.debian:01:host1"; - String svmName = "svm1"; - - Igroup igroup = new Igroup(); - igroup.setName("igroup1"); - igroup.setInitiators(null); - - try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) { - utilityMock.when(() -> OntapStorageUtils.generateAuthHeader("admin", "password")) - .thenReturn(authHeader); - - boolean result = unifiedSANStrategy.validateInitiatorInAccessGroup(hostInitiator, svmName, igroup); - - assertFalse(result); - } - } - - @Test - void testDeleteAccessGroup_FeignException404_SkipsDeletion() { - AccessGroup accessGroup = new AccessGroup(); - accessGroup.setStoragePoolId(1L); - List hosts = new ArrayList<>(); - HostVO host1 = mock(HostVO.class); - when(host1.getUuid()).thenReturn("host1"); - hosts.add(host1); - accessGroup.setHostsToConnect(hosts); - - FeignException feignException = mock(FeignException.class); - when(feignException.status()).thenReturn(404); - - try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) { - utilityMock.when(() -> OntapStorageUtils.generateAuthHeader("admin", "password")) - .thenReturn(authHeader); - utilityMock.when(() -> OntapStorageUtils.getIgroupName("svm1", "host1")) - .thenReturn("igroup1"); - - when(sanFeignClient.getIgroupResponse(eq(authHeader), anyMap())).thenThrow(feignException); - - // Should not throw exception for 404 - assertDoesNotThrow(() -> unifiedSANStrategy.deleteAccessGroup(accessGroup)); - } - } - @Test void testDeleteAccessGroup_NotFoundInResponse_SkipsDeletion() { AccessGroup accessGroup = new AccessGroup(); @@ -2768,8 +2758,10 @@ void testDeleteAccessGroup_NotFoundInResponse_SkipsDeletion() { when(sanFeignClient.getIgroupResponse(eq(authHeader), anyMap())).thenReturn(emptyResponse); - // Should not throw exception when not found assertDoesNotThrow(() -> unifiedSANStrategy.deleteAccessGroup(accessGroup)); + + assertIgroupLookupWasFor("igroup1"); + verify(sanFeignClient, never()).deleteIgroup(anyString(), anyString()); } } @@ -2832,4 +2824,1505 @@ void testCreateCloudStackVolume_PassesQosPolicyOnLunCreate() { assertEquals("cs_100_to200_iops_svm1", lunCaptor.getValue().getQosPolicy().getName()); } } + + /** A real FeignException (mocks have no stack trace, which breaks logging of the cause). */ + private static FeignException feignException(int status, String body) { + feign.Request request = feign.Request.create(feign.Request.HttpMethod.GET, "http://ontap/api", + new HashMap<>(), null, java.nio.charset.StandardCharsets.UTF_8, null); + feign.Response response = feign.Response.builder().status(status).reason("reason").request(request) + .headers(new HashMap<>()).body(body, java.nio.charset.StandardCharsets.UTF_8).build(); + return FeignException.errorStatus("ontapCall", response); + } + + private static Lun lun(String name, String uuid) { + Lun lun = new Lun(); + lun.setName(name); + lun.setUuid(uuid); + return lun; + } + + private static CloudStackVolume lunVolume(Lun lun) { + CloudStackVolume volume = new CloudStackVolume(); + volume.setLun(lun); + return volume; + } + + private static Lun cloneRequestLun() { + Lun.Source source = new Lun.Source(); + source.setName("/vol/v/src"); + Lun.Clone clone = new Lun.Clone(); + clone.setSource(source); + Lun lun = lun("/vol/v/dst", null); + lun.setClone(clone); + return lun; + } + + private static Igroup igroup(String uuid, String name) throws Exception { + return new ObjectMapper().readValue("{\"uuid\":\"" + uuid + "\",\"name\":\"" + name + "\"}", Igroup.class); + } + + private static HostVO host(String uuid, String storageUrl) { + HostVO host = mock(HostVO.class); + when(host.getUuid()).thenReturn(uuid); + when(host.getStorageUrl()).thenReturn(storageUrl); + return host; + } + + private static AccessGroup accessGroup(HostVO... hosts) { + AccessGroup group = new AccessGroup(); + group.setStoragePoolId(5L); + group.setHostsToConnect(new ArrayList<>(java.util.Arrays.asList(hosts))); + return group; + } + + private void poolDetails(String svmName, String protocol) { + Map details = new HashMap<>(); + if (svmName != null) { + details.put(OntapStorageConstants.SVM_NAME, svmName); + } + details.put(OntapStorageConstants.PROTOCOL, protocol); + when(storagePoolDetailsDao.listDetailsKeyPairs(5L)).thenReturn(details); + } + + private static Lun withCopyProgress(Lun lun, Integer percent, String state) { + Lun.Progress progress = new Lun.Progress(); + progress.setPercentComplete(percent); + progress.setState(state); + Lun.Source source = new Lun.Source(); + source.setProgress(progress); + Lun.Copy copy = new Lun.Copy(); + copy.setSource(source); + lun.setCopy(copy); + return lun; + } + + // -------------------------------------------------------- createCloudStackVolume + + @Test + public void createVolumeRejectsMissingRequestOrLun() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createCloudStackVolume(null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createCloudStackVolume(new CloudStackVolume())); + verify(sanFeignClient, never()).createLun(anyString(), anyBoolean(), any(Lun.class)); + } + + @Test + public void createVolumeFailsWhenOntapReturnsNoRecords() { + CloudStackVolume request = lunVolume(lun("/vol/v/l", null)); + + when(sanFeignClient.createLun(anyString(), eq(true), lunNamed("/vol/v/l"))).thenReturn(null); + CloudRuntimeException missing = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createCloudStackVolume(request)); + assertEquals("Failed to create Lun: /vol/v/l", missing.getMessage()); + + OntapResponse nullRecords = new OntapResponse<>(); + nullRecords.setRecords(null); + when(sanFeignClient.createLun(anyString(), eq(true), lunNamed("/vol/v/l"))).thenReturn(nullRecords); + CloudRuntimeException noRecords = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createCloudStackVolume(request)); + assertEquals("Failed to create Lun: /vol/v/l", noRecords.getMessage()); + + when(sanFeignClient.createLun(anyString(), eq(true), lunNamed("/vol/v/l"))) + .thenReturn(new OntapResponse<>(new ArrayList<>())); + CloudRuntimeException empty = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createCloudStackVolume(request)); + assertEquals("Failed to create Lun: /vol/v/l", empty.getMessage()); + verify(sanFeignClient, org.mockito.Mockito.times(3)).createLun(anyString(), eq(true), lunNamed("/vol/v/l")); + } + + @Test + public void createVolumeRejectsIncompleteLunFromOntap() { + when(sanFeignClient.createLun(anyString(), eq(true), lunNamed("/vol/v/l"))) + .thenReturn(new OntapResponse<>(List.of(lun("/vol/v/l", null)))); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createCloudStackVolume(lunVolume(lun("/vol/v/l", null)))); + + assertEquals("ONTAP returned incomplete LUN for: /vol/v/l", thrown.getMessage()); + verify(sanFeignClient).createLun(anyString(), eq(true), lunNamed("/vol/v/l")); + } + + @Test + public void createVolumeWrapsFeignAndUnexpectedErrors() { + CloudStackVolume request = lunVolume(lun("/vol/v/l", null)); + FeignException feign = feignException(500, "ontap down"); + when(sanFeignClient.createLun(anyString(), eq(true), lunNamed("/vol/v/l"))).thenThrow(feign); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createCloudStackVolume(request)); + assertSame(feign, feignFailure.getCause()); + assertTrue(feignFailure.getMessage().startsWith("Failed to create Lun: "), feignFailure.getMessage()); + assertTrue(feignFailure.getMessage().contains("ontap down"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(sanFeignClient).createLun(anyString(), eq(true), lunNamed("/vol/v/l")); + CloudRuntimeException generic = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createCloudStackVolume(request)); + assertTrue(generic.getMessage().contains("boom"), generic.getMessage()); + verify(sanFeignClient, org.mockito.Mockito.times(2)).createLun(anyString(), eq(true), lunNamed("/vol/v/l")); + } + + // -------------------------------------------------------- createTemplateCache + + private StoragePoolVO pool() { + StoragePoolVO pool = mock(StoragePoolVO.class); + when(pool.getId()).thenReturn(5L); + when(pool.getName()).thenReturn("flexvol"); + when(pool.getHypervisor()).thenReturn(HypervisorType.KVM); + return pool; + } + + private static TemplateInfo template() { + TemplateInfo template = mock(TemplateInfo.class); + when(template.getId()).thenReturn(42L); + return template; + } + + private static Map svmDetails() { + return Map.of(OntapStorageConstants.SVM_NAME, "svm1"); + } + + @Test + public void createTemplateCacheRejectsUnknownTemplateSize() { + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createTemplateCache(pool(), template(), svmDetails(), 0L)); + + assertTrue(thrown.getMessage().contains("Unknown virtual size for template [42]"), thrown.getMessage()); + verify(sanFeignClient, never()).createLun(anyString(), anyBoolean(), any(Lun.class)); + } + + @Test + public void createTemplateCacheCreatesLunSizedToTheTemplate() { + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))) + .thenReturn(new OntapResponse<>(List.of(lun("/vol/flexvol/template_42", "created-uuid")))); + + CloudStackVolume created = unifiedSANStrategy.createTemplateCache(pool(), template(), svmDetails(), 1024L); + + assertEquals("created-uuid", created.getLun().getUuid()); + verify(sanFeignClient).createLun(anyString(), eq(true), argThat(request -> + request.getSpace().getSize() == 1024L && "svm1".equals(request.getSvm().getName()))); + } + + @Test + public void createTemplateCacheRemovesLeftoverLunFoundOnOntapAfterCreateFailure() { + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))).thenThrow(feignException(500, "timeout")); + when(sanFeignClient.getLunResponse(anyString(), anyMap())) + .thenReturn(new OntapResponse<>(List.of(lun("/vol/flexvol/template_42", "leftover-uuid")))); + + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createTemplateCache(pool(), template(), svmDetails(), 1024L)); + + verify(sanFeignClient).deleteLun(anyString(), eq("leftover-uuid"), anyMap()); + } + + @Test + public void createTemplateCacheDoesNotDeleteAnythingWhenNoLeftoverLunExists() { + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))).thenThrow(feignException(500, "timeout")); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(new ArrayList<>())); + + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createTemplateCache(pool(), template(), svmDetails(), 1024L)); + + verify(sanFeignClient, never()).deleteLun(anyString(), anyString(), anyMap()); + } + + @Test + public void createTemplateCacheKeepsOriginalErrorWhenCleanupFails() { + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))).thenThrow(feignException(500, "timeout")); + when(sanFeignClient.getLunResponse(anyString(), anyMap())) + .thenReturn(new OntapResponse<>(List.of(lun("/vol/flexvol/template_42", "leftover-uuid")))); + doThrow(feignException(500, "cannot delete")).when(sanFeignClient).deleteLun(anyString(), anyString(), anyMap()); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createTemplateCache(pool(), template(), svmDetails(), 1024L)); + + assertTrue(thrown.getMessage().contains("Failed to create Lun"), thrown.getMessage()); + } + + @Test + public void createTemplateCacheWrapsUnexpectedErrorsAndCleansUp() { + UnifiedSANStrategy spied = spy(unifiedSANStrategy); + // A result without a LUN makes the success logging fail with a NullPointerException. + doReturn(new CloudStackVolume()).when(spied).createCloudStackVolume(any(CloudStackVolume.class)); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(null); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> spied.createTemplateCache(pool(), template(), svmDetails(), 1024L)); + + assertTrue(thrown.getMessage().contains("Failed to create template cache LUN for template [42]"), thrown.getMessage()); + assertTrue(thrown.getCause() instanceof NullPointerException); + } + + // -------------------------------------------------------- updateCloudStackVolume + + @Test + public void updateVolumeRejectsRequestsWithoutLunUuid() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.updateCloudStackVolume(null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.updateCloudStackVolume(new CloudStackVolume())); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.updateCloudStackVolume(lunVolume(lun("l", null)))); + } + + @Test + public void updateVolumeWithoutQosPolicyDoesNothing() { + CloudStackVolume request = lunVolume(lun("l", LUN_UUID)); + + assertSame(request, unifiedSANStrategy.updateCloudStackVolume(request)); + verify(sanFeignClient, never()).updateLun(anyString(), anyString(), any(Lun.class)); + } + + @Test + public void updateVolumeAppliesQosPolicyAndWrapsFailures() { + Lun withQos = lun("l", LUN_UUID); + VolumeQosPolicy qos = new VolumeQosPolicy(); + qos.setName("qos-1"); + withQos.setQosPolicy(qos); + CloudStackVolume request = lunVolume(withQos); + + assertSame(request, unifiedSANStrategy.updateCloudStackVolume(request)); + verify(sanFeignClient).updateLun(anyString(), eq(LUN_UUID), argThat(update -> update.getQosPolicy() == qos)); + + when(sanFeignClient.updateLun(anyString(), anyString(), any(Lun.class))).thenThrow(feignException(500, "ontap down")); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.updateCloudStackVolume(request)); + assertTrue(feignFailure.getMessage().startsWith("Failed to update LUN"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(sanFeignClient).updateLun(anyString(), anyString(), any(Lun.class)); + CloudRuntimeException generic = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.updateCloudStackVolume(request)); + assertTrue(generic.getMessage().contains("boom"), generic.getMessage()); + } + + // -------------------------------------------------------- cloneCloudStackVolume + + @Test + public void cloneRejectsInvalidRequests() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(new CloudStackVolume())); + + CloudStackVolume noClone = lunVolume(lun("/vol/v/dst", null)); + CloudRuntimeException noCloneEx = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(noClone)); + assertTrue(noCloneEx.getMessage().contains("no clone source"), noCloneEx.getMessage()); + + Lun emptyClone = lun("/vol/v/dst", null); + emptyClone.setClone(new Lun.Clone()); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(lunVolume(emptyClone))); + verify(sanFeignClient, never()).createLun(anyString(), anyBoolean(), any(Lun.class)); + } + + @Test + public void cloneFailsWhenOntapReturnsNothingOrAnIncompleteLun() { + CloudStackVolume request = lunVolume(cloneRequestLun()); + + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))).thenReturn(null); + CloudRuntimeException missing = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(request)); + assertTrue(missing.getMessage().contains("Failed to clone Lun: /vol/v/dst"), missing.getMessage()); + + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))).thenReturn(new OntapResponse<>(new ArrayList<>())); + CloudRuntimeException empty = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(request)); + assertTrue(empty.getMessage().contains("Failed to clone Lun: /vol/v/dst"), empty.getMessage()); + + // A create record with a uuid and no name is not rejected immediately. Clone then reads that uuid back. + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))) + .thenReturn(new OntapResponse<>(List.of(lun(null, "uuid")))); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenThrow(feignException(500, "get failed")); + CloudRuntimeException unread = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(request)); + assertTrue(unread.getMessage().contains("Failed to fetch cloned Lun"), unread.getMessage()); + } + + @Test + public void cloneWrapsFeignAndUnexpectedErrors() { + CloudStackVolume request = lunVolume(cloneRequestLun()); + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))).thenThrow(feignException(500, "ontap down")); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(request)); + assertTrue(feignFailure.getMessage().startsWith("Failed to clone Lun: "), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(sanFeignClient).createLun(anyString(), anyBoolean(), any(Lun.class)); + CloudRuntimeException generic = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.cloneCloudStackVolume(request)); + assertTrue(generic.getMessage().contains("boom"), generic.getMessage()); + } + + // -------------------------------------------------------- copyCloudStackVolume + + private CloudStackVolume copy(int timeoutSeconds, String srcLunName, String destVolumeName) { + VolumeInfo src = mock(VolumeInfo.class); + VolumeInfo dest = mock(VolumeInfo.class); + StoragePoolVO destPool = mock(StoragePoolVO.class); + when(src.getId()).thenReturn(11L); + when(dest.getName()).thenReturn(destVolumeName); + when(destPool.getName()).thenReturn("dest"); + when(volumeDetailsDao.findDetail(11L, OntapStorageConstants.LUN_DOT_UUID)) + .thenReturn(new VolumeDetailVO(11L, OntapStorageConstants.LUN_DOT_UUID, "source-uuid", false)); + when(volumeDetailsDao.findDetail(11L, OntapStorageConstants.LUN_DOT_NAME)) + .thenReturn(srcLunName == null ? null : new VolumeDetailVO(11L, OntapStorageConstants.LUN_DOT_NAME, srcLunName, false)); + return unifiedSANStrategy.copyCloudStackVolume(src, dest, destPool, Map.of(OntapStorageConstants.SVM_NAME, "svm1"), timeoutSeconds); + } + + private static Igroup igroupNamed(String igroupName, String initiator) { + return argThat(request -> request != null + && igroupName.equals(request.getName()) + && request.getSvm() != null + && "svm1".equals(request.getSvm().getName()) + && request.getInitiators() != null + && request.getInitiators().size() == 1 + && initiator.equals(request.getInitiators().get(0).getName()) + && Igroup.ProtocolEnum.iscsi == request.getProtocol()); + } + + private static Lun lunNamed(String lunName) { + return argThat(request -> request != null && lunName.equals(request.getName())); + } + + private static Lun destinationCopy(String lunName) { + return argThat(request -> request != null + && lunName.equals(request.getName()) + && request.getSvm() != null + && "svm1".equals(request.getSvm().getName()) + && request.getCopy() != null + && request.getCopy().getSource() != null + && "source-uuid".equals(request.getCopy().getSource().getUuid()) + && "src".equals(request.getCopy().getSource().getName())); + } + + private static Lun createdCopy() { + return lun("/vol/dest/lun", "copied-uuid"); + } + + @Test + public void copyWithoutSourceLunNameStillCopiesBySourceUuid() { + Lun created = createdCopy(); + withCopyProgress(created, 100, null); + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))).thenReturn(new OntapResponse<>(List.of(created))); + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenReturn(created); + + CloudStackVolume result = copy(10, null, "lun"); + + assertSame(created, result.getLun()); + verify(sanFeignClient).createLun(anyString(), eq(true), argThat(request -> + "source-uuid".equals(request.getCopy().getSource().getUuid()) && request.getCopy().getSource().getName() == null)); + } + + @Test + public void copyRejectsInvalidDestinationLunName() { + InvalidParameterValueException thrown = assertThrows(InvalidParameterValueException.class, () -> copy(10, null, "1 bad name!")); + + assertTrue(thrown.getMessage().contains("Invalid dataObject name"), thrown.getMessage()); + verify(sanFeignClient, never()).createLun(anyString(), anyBoolean(), any(Lun.class)); + } + + @Test + public void copyFailsWhenSourceVolumeHasNoLunUuid() { + VolumeInfo src = mock(VolumeInfo.class); + when(src.getId()).thenReturn(11L); + when(volumeDetailsDao.findDetail(11L, OntapStorageConstants.LUN_DOT_UUID)) + .thenReturn(new VolumeDetailVO(11L, OntapStorageConstants.LUN_DOT_UUID, " ", false)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.copyCloudStackVolume( + src, mock(VolumeInfo.class), mock(StoragePoolVO.class), svmDetails(), 5)); + + assertTrue(thrown.getMessage().contains("has no ONTAP LUN UUID"), thrown.getMessage()); + } + + @Test + public void copyFailsWhenOntapReturnsNoRecords() { + when(sanFeignClient.createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun"))).thenReturn(null); + CloudRuntimeException noResponse = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + assertEquals("Failed to copy Lun: /vol/dest/lun", noResponse.getMessage()); + + when(sanFeignClient.createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun"))) + .thenReturn(new OntapResponse<>(new ArrayList<>())); + CloudRuntimeException empty = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + assertEquals("Failed to copy Lun: /vol/dest/lun", empty.getMessage()); + verify(sanFeignClient, org.mockito.Mockito.times(2)) + .createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + } + + @Test + public void copyFailsFastOnNonRetryableCreateError() { + when(sanFeignClient.createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun"))) + .thenThrow(feignException(400, "bad request")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + + assertTrue(thrown.getMessage().startsWith("Failed to copy Lun: "), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("bad request"), thrown.getMessage()); + verify(sanFeignClient).createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + } + + @Test + public void copyGivesUpWhenSourceStaysBusyPastTheDeadline() { + when(sanFeignClient.createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun"))) + .thenThrow(feignException(500, "{\"code\":\"5375060\"}")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(0, "src", "lun")); + + assertTrue(thrown.getMessage().startsWith("Failed to copy Lun: "), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("5375060"), thrown.getMessage()); + verify(sanFeignClient).createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + } + + @Test + public void copyRetriesWhenSourceIsBusyAndThenSucceeds() { + Lun created = withCopyProgress(createdCopy(), 100, null); + when(sanFeignClient.createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun"))) + .thenThrow(feignException(500, "{\"code\":\"5375060\"}")) + .thenReturn(new OntapResponse<>(List.of(created))); + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenReturn(created); + + CloudStackVolume result = copy(30, "src", "lun"); + + assertSame(created, result.getLun()); + verify(sanFeignClient, org.mockito.Mockito.times(2)) + .createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + verify(sanFeignClient).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + } + + @Test + public void copyResumesExistingCopyWhenOntapReportsItAlreadyStarted() { + Lun existing = withCopyProgress(createdCopy(), 100, null); + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))) + .thenThrow(feignException(500, "{\"code\":\"5375060\"}")) + .thenThrow(feignException(409, "{\"code\":\"7018919\"}")); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(existing))); + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenReturn(existing); + + CloudStackVolume result = copy(30, "src", "lun"); + + assertSame(existing, result.getLun()); + verify(sanFeignClient, org.mockito.Mockito.times(2)) + .createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + verify(sanFeignClient).getLunResponse(anyString(), argThat(query -> query != null + && "svm1".equals(query.get(OntapStorageConstants.SVM_DOT_NAME)) + && "/vol/dest/lun".equals(query.get(OntapStorageConstants.NAME)))); + verify(sanFeignClient).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + } + + @Test + public void copyKeepsRetryingWhenAlreadyStartedCopyCannotBeFound() { + when(sanFeignClient.createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun"))) + .thenThrow(feignException(500, "{\"code\":\"5375060\"}")) + .thenThrow(feignException(409, "{\"code\":\"7018919\"}")); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(null); + + // A 1s deadline lets exactly one retry sleep happen before giving up on the conflict. + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(1, "src", "lun")); + + assertTrue(thrown.getMessage().contains("7018919"), thrown.getMessage()); + verify(sanFeignClient, org.mockito.Mockito.times(2)) + .createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + verify(sanFeignClient, org.mockito.Mockito.atLeastOnce()).getLunResponse(anyString(), argThat(query -> + query != null + && "svm1".equals(query.get(OntapStorageConstants.SVM_DOT_NAME)) + && "/vol/dest/lun".equals(query.get(OntapStorageConstants.NAME)))); + } + + @Test + public void copyStopsWhenInterruptedWhileWaitingToRetryCreate() { + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))) + .thenThrow(feignException(500, "{\"code\":\"5375060\"}")); + Thread.currentThread().interrupt(); + try { + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(30, "src", "lun")); + + assertEquals("Interrupted while retrying ONTAP LUN copy for [/vol/dest/lun]", thrown.getMessage()); + assertTrue(Thread.currentThread().isInterrupted()); + verify(sanFeignClient).createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + } finally { + Thread.interrupted(); + } + } + + private void createReturns(Lun created) { + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))).thenReturn(new OntapResponse<>(List.of(created))); + } + + @Test + public void copyFailsAndRemovesPartialLunWhenOntapReportsCopyFailure() { + for (String state : new String[] {"failed", "FAILURE", "Error"}) { + Lun created = withCopyProgress(createdCopy(), 40, state); + createReturns(created); + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenReturn(created); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + + assertEquals("ONTAP LUN copy failed for Lun [copied-uuid]", thrown.getMessage()); + } + verify(sanFeignClient, org.mockito.Mockito.times(3)) + .createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + verify(sanFeignClient, org.mockito.Mockito.times(3)).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + verify(sanFeignClient, org.mockito.Mockito.times(3)).deleteLun(anyString(), eq("copied-uuid"), anyMap()); + } + + @Test + public void copyTimesOutWhileProgressIsIncomplete() { + Lun created = withCopyProgress(createdCopy(), 50, "running"); + createReturns(created); + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenReturn(created); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(0, "src", "lun")); + + assertEquals("Timed out waiting for ONTAP LUN copy for Lun [copied-uuid]", thrown.getMessage()); + verify(sanFeignClient).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + verify(sanFeignClient).deleteLun(anyString(), eq("copied-uuid"), anyMap()); + } + + @Test + public void copyKeepsGoingWhenCleanupOfPartialLunFails() { + Lun created = withCopyProgress(createdCopy(), 50, "running"); + createReturns(created); + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenReturn(created); + doThrow(feignException(500, "cannot delete")).when(sanFeignClient) + .deleteLun(anyString(), eq("copied-uuid"), anyMap()); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(0, "src", "lun")); + + assertEquals("Timed out waiting for ONTAP LUN copy for Lun [copied-uuid]", thrown.getMessage()); + verify(sanFeignClient).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + verify(sanFeignClient).deleteLun(anyString(), eq("copied-uuid"), anyMap()); + } + + @Test + public void copyStopsWhenInterruptedWhileWaitingForProgress() { + Lun created = withCopyProgress(createdCopy(), 50, "running"); + createReturns(created); + when(sanFeignClient.getLunByUUID(anyString(), anyString(), anyMap())).thenReturn(created); + Thread.currentThread().interrupt(); + try { + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(30, "src", "lun")); + + assertTrue(thrown.getMessage().contains( + "Interrupted while waiting for ONTAP LUN copy for Lun [copied-uuid]"), thrown.getMessage()); + assertTrue(Thread.currentThread().isInterrupted()); + verify(sanFeignClient).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + } finally { + Thread.interrupted(); + } + } + + @Test + public void copyFailsWhenCopyStatusCannotBeRead() { + createReturns(createdCopy()); + + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenReturn(null); + CloudRuntimeException nullStatus = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + assertEquals("Unable to retrieve ONTAP LUN copy status for Lun [copied-uuid]", nullStatus.getMessage()); + + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenThrow(feignException(500, "ontap down")); + CloudRuntimeException serverError = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + assertTrue(serverError.getMessage().startsWith("Failed to copy Lun: "), serverError.getMessage()); + assertTrue(serverError.getMessage().contains("ontap down"), serverError.getMessage()); + verify(sanFeignClient, org.mockito.Mockito.times(2)) + .createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + verify(sanFeignClient, org.mockito.Mockito.times(2)).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + } + + @Test + public void copyFailsWhenOntapNeverExposesCopyDetailsWithinGracePeriod() { + unifiedSANStrategy.lunCopyStatusGraceMs = 0L; + createReturns(createdCopy()); + + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenThrow(feignException(404, "not yet")); + CloudRuntimeException notFound = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + assertEquals("ONTAP did not return copy details for Lun [copied-uuid] within 0s", notFound.getMessage()); + assertNotNull(notFound.getCause()); + + doReturn(createdCopy()).when(sanFeignClient).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + CloudRuntimeException noCopyObject = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + assertEquals("ONTAP did not return copy details for Lun [copied-uuid] within 0s", noCopyObject.getMessage()); + assertNull(noCopyObject.getCause()); + verify(sanFeignClient, org.mockito.Mockito.times(2)).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + } + + // -------------------------------------------------------- resizeCloudStackVolume (extra) + + @Test + public void resizeResolvesLunUuidFromVolumeDetailsAndKeepsExistingQos() { + VolumeObject volumeInfo = mock(VolumeObject.class); + when(volumeInfo.getId()).thenReturn(77L); + when(volumeDetailsDao.findDetail(77L, OntapStorageConstants.LUN_DOT_UUID)) + .thenReturn(new VolumeDetailVO(77L, OntapStorageConstants.LUN_DOT_UUID, "resolved-uuid", false)); + CloudStackVolume request = new CloudStackVolume(); + request.setVolumeInfo(volumeInfo); + + unifiedSANStrategy.resizeCloudStackVolume(request, 4096L); + + assertEquals("resolved-uuid", request.getLun().getUuid()); + verify(sanFeignClient).updateLun(anyString(), eq("resolved-uuid"), argThat(patch -> patch.getSpace().getSize() == 4096L)); + } + + @Test + public void resizeFailsWhenLunUuidCannotBeResolved() { + VolumeObject volumeInfo = mock(VolumeObject.class); + when(volumeInfo.getId()).thenReturn(77L); + CloudStackVolume request = new CloudStackVolume(); + request.setVolumeInfo(volumeInfo); + + when(volumeDetailsDao.findDetail(77L, OntapStorageConstants.LUN_DOT_UUID)).thenReturn(null); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.resizeCloudStackVolume(request, 4096L)); + + when(volumeDetailsDao.findDetail(77L, OntapStorageConstants.LUN_DOT_UUID)) + .thenReturn(new VolumeDetailVO(77L, OntapStorageConstants.LUN_DOT_UUID, "", false)); + CloudRuntimeException blank = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.resizeCloudStackVolume(request, 4096L)); + assertTrue(blank.getMessage().contains("LUN UUID not found"), blank.getMessage()); + } + + @Test + public void resizeReportsMissingLunAndOtherFailuresDistinctly() { + VolumeObject volumeInfo = mock(VolumeObject.class); + CloudStackVolume request = lunVolume(lun("l", LUN_UUID)); + request.setVolumeInfo(volumeInfo); + + when(sanFeignClient.updateLun(anyString(), anyString(), any(Lun.class))).thenThrow(feignException(404, "gone")); + CloudRuntimeException gone = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.resizeCloudStackVolume(request, 4096L)); + assertTrue(gone.getMessage().contains("no longer exists on ONTAP"), gone.getMessage()); + + doThrow(feignException(500, "ontap down")).when(sanFeignClient).updateLun(anyString(), anyString(), any(Lun.class)); + CloudRuntimeException failed = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.resizeCloudStackVolume(request, 4096L)); + assertTrue(failed.getMessage().contains("Failed to resize LUN"), failed.getMessage()); + + doThrow(new IllegalStateException("boom")).when(sanFeignClient).updateLun(anyString(), anyString(), any(Lun.class)); + CloudRuntimeException unexpected = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.resizeCloudStackVolume(request, 4096L)); + assertTrue(unexpected.getMessage().contains("Unexpected error while resizing LUN"), unexpected.getMessage()); + } + + // -------------------------------------------------------- getCloudStackVolume / serial number + + @Test + public void getVolumeRejectsInvalidLookups() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getCloudStackVolume(null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getCloudStackVolume(Map.of())); + for (Map values : List.of( + Map.of(OntapStorageConstants.NAME, "lun"), + Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1"), + Map.of(OntapStorageConstants.SVM_DOT_NAME, "", OntapStorageConstants.NAME, "lun"), + Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.NAME, ""))) { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getCloudStackVolume(values)); + } + } + + @Test + public void getVolumeReturnsNullWhenLunIsNotFound() { + Map lookup = Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.NAME, "lun"); + + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(null); + assertNull(unifiedSANStrategy.getCloudStackVolume(lookup)); + + OntapResponse nullRecords = new OntapResponse<>(); + nullRecords.setRecords(null); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(nullRecords); + assertNull(unifiedSANStrategy.getCloudStackVolume(lookup)); + + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(new ArrayList<>())); + assertNull(unifiedSANStrategy.getCloudStackVolume(lookup)); + + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenThrow(feignException(404, "gone")); + assertNull(unifiedSANStrategy.getCloudStackVolume(lookup)); + + assertLunLookups(4, "svm1", "lun", null); + } + + @Test + public void getVolumeWrapsOtherErrors() { + Map lookup = Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.NAME, "lun"); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenThrow(feignException(500, "ontap down")); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getCloudStackVolume(lookup)); + assertTrue(feignFailure.getMessage().startsWith("Failed to fetch Lun poolDetails"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(sanFeignClient).getLunResponse(anyString(), anyMap()); + CloudRuntimeException generic = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getCloudStackVolume(lookup)); + assertTrue(generic.getMessage().contains("boom"), generic.getMessage()); + } + + @Test + public void getLunSerialNumberReadsSerialFromOntap() throws Exception { + Lun lun = new ObjectMapper().readValue("{\"name\":\"lun\",\"serial_number\":\"serial-1\"}", Lun.class); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(lun))); + + assertEquals("serial-1", unifiedSANStrategy.getLunSerialNumber("svm1", "lun")); + assertLunLookups(1, "svm1", "lun", OntapStorageConstants.SERIAL_NUMBER); + } + + @Test + public void getLunSerialNumberRejectsInvalidNames() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLunSerialNumber(null, "lun")); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLunSerialNumber("", "lun")); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLunSerialNumber("svm1", null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLunSerialNumber("svm1", "")); + } + + @Test + public void getLunSerialNumberReturnsNullWhenLunIsMissing() { + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(null); + assertNull(unifiedSANStrategy.getLunSerialNumber("svm1", "lun")); + + OntapResponse nullRecords = new OntapResponse<>(); + nullRecords.setRecords(null); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(nullRecords); + assertNull(unifiedSANStrategy.getLunSerialNumber("svm1", "lun")); + + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(new ArrayList<>())); + assertNull(unifiedSANStrategy.getLunSerialNumber("svm1", "lun")); + + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenThrow(feignException(404, "gone")); + assertNull(unifiedSANStrategy.getLunSerialNumber("svm1", "lun")); + + assertLunLookups(4, "svm1", "lun", OntapStorageConstants.SERIAL_NUMBER); + } + + @Test + public void getLunSerialNumberWrapsOtherErrors() { + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenThrow(feignException(500, "ontap down")); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLunSerialNumber("svm1", "lun")); + assertTrue(feignFailure.getMessage().contains("ontap down"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(sanFeignClient).getLunResponse(anyString(), anyMap()); + CloudRuntimeException generic = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLunSerialNumber("svm1", "lun")); + assertTrue(generic.getMessage().contains("boom"), generic.getMessage()); + assertLunLookups(2, "svm1", "lun", OntapStorageConstants.SERIAL_NUMBER); + } + + // -------------------------------------------------------- createAccessGroup + + @Test + public void createAccessGroupRejectsInvalidRequests() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createAccessGroup(null)); + + AccessGroup noPool = accessGroup(host("h1", "iqn.1")); + noPool.setStoragePoolId(null); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createAccessGroup(noPool)); + + AccessGroup nullHosts = accessGroup(); + nullHosts.setHostsToConnect(null); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createAccessGroup(nullHosts)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createAccessGroup(accessGroup())); + verify(sanFeignClient, never()).createIgroup(anyString(), anyBoolean(), any(Igroup.class)); + } + + @Test + public void createAccessGroupRejectsHostsWithoutIscsiInitiator() { + poolDetails("svm1", "ISCSI"); + for (String storageUrl : new String[] {null, "", " ", "nfs-host"}) { + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", storageUrl)))); + assertTrue(thrown.getMessage().contains("support the protocol"), thrown.getMessage()); + } + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.createAccessGroup(accessGroup((HostVO) null))); + verify(sanFeignClient, never()).createIgroup(anyString(), anyBoolean(), any(Igroup.class)); + } + + @Test + public void createAccessGroupWithoutSvmNameStillCreatesIgroup() throws Exception { + poolDetails(null, "ISCSI"); + Igroup created = igroup("ig-1", "cs_h1_null"); + when(sanFeignClient.createIgroup(anyString(), anyBoolean(), any(Igroup.class))).thenReturn(new OntapResponse<>(List.of(created))); + + AccessGroup result = unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1994-05.com.example:host1"))); + + assertSame(created, result.getIgroup()); + verify(sanFeignClient).createIgroup(anyString(), eq(true), argThat(request -> + request.getSvm() == null + && "cs_h1_null".equals(request.getName()) + && "iqn.1994-05.com.example:host1".equals(request.getInitiators().get(0).getName()))); + } + + @Test + public void createAccessGroupFailsWhenOntapReturnsNoIgroup() { + poolDetails("svm1", "ISCSI"); + when(sanFeignClient.createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1"))) + .thenReturn(new OntapResponse<>(new ArrayList<>())); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1")))); + + assertTrue(thrown.getMessage().contains("Failed to create Igroup: cs_h1_svm1"), thrown.getMessage()); + verify(sanFeignClient).createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1")); + } + + @Test + public void createAccessGroupReusesIgroupThatAlreadyExists() throws Exception { + poolDetails("svm1", "ISCSI"); + Igroup existing = igroup("ig-1", "existing"); + when(sanFeignClient.createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1"))) + .thenThrow(feignException(409, "duplicate")); + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(existing))); + + AccessGroup result = unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1"))); + + assertSame(existing, result.getIgroup()); + verify(sanFeignClient).createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1")); + assertIgroupWasFoundByName(1, "svm1", "cs_h1_svm1"); + } + + @Test + public void createAccessGroupReportsConflictWhenExistingIgroupCannotBeFetched() { + poolDetails("svm1", "ISCSI"); + when(sanFeignClient.createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1"))) + .thenThrow(feignException(409, "duplicate igroup")); + + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(null); + CloudRuntimeException withBody = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1")))); + assertTrue(withBody.getMessage().contains("Igroup [cs_h1_svm1] already exists but was not returned"), withBody.getMessage()); + assertTrue(withBody.getMessage().contains("duplicate igroup"), withBody.getMessage()); + + doThrow(feignException(409, "")).when(sanFeignClient).createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1")); + OntapResponse nullRecords = new OntapResponse<>(); + nullRecords.setRecords(null); + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(nullRecords); + CloudRuntimeException blankBody = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1")))); + assertTrue(blankBody.getMessage().contains("Igroup [cs_h1_svm1] already exists but was not returned"), blankBody.getMessage()); + verify(sanFeignClient, times(2)) + .createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1")); + assertIgroupWasFoundByName(2, "svm1", "cs_h1_svm1"); + } + + @Test + public void createAccessGroupWrapsOtherOntapErrors() { + poolDetails("svm1", "ISCSI"); + when(sanFeignClient.createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1"))) + .thenThrow(feignException(500, "ontap down")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1")))); + + assertTrue(thrown.getMessage().startsWith("Failed to create Igroup: "), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("ontap down"), thrown.getMessage()); + verify(sanFeignClient).createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1")); + } + + // -------------------------------------------------------- deleteAccessGroup + + @Test + public void deleteAccessGroupRejectsInvalidRequests() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.deleteAccessGroup(null)); + AccessGroup noPool = accessGroup(host("h1", "iqn.1")); + noPool.setStoragePoolId(null); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.deleteAccessGroup(noPool)); + } + + @Test + public void deleteAccessGroupWithoutHostsDoesNothing() { + AccessGroup group = accessGroup(); + group.setHostsToConnect(null); + + unifiedSANStrategy.deleteAccessGroup(group); + unifiedSANStrategy.deleteAccessGroup(accessGroup()); + + verify(sanFeignClient, never()).getIgroupResponse(anyString(), anyMap()); + } + + @Test + public void deleteAccessGroupDeletesIgroupByUuid() throws Exception { + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(igroup("ig-1", "g")))); + + unifiedSANStrategy.deleteAccessGroup(accessGroup(host("h1", "iqn.1"))); + + verify(sanFeignClient).deleteIgroup(anyString(), eq("ig-1")); + assertIgroupWasFoundByName(1, "svm1", "cs_h1_svm1"); + } + + @Test + public void deleteAccessGroupIsNoOpWhenIgroupIsAlreadyGone() { + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(null); + unifiedSANStrategy.deleteAccessGroup(accessGroup(host("h1", "iqn.1"))); + + OntapResponse nullRecords = new OntapResponse<>(); + nullRecords.setRecords(null); + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(nullRecords); + unifiedSANStrategy.deleteAccessGroup(accessGroup(host("h1", "iqn.1"))); + + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(new ArrayList<>())); + unifiedSANStrategy.deleteAccessGroup(accessGroup(host("h1", "iqn.1"))); + + verify(sanFeignClient, never()).deleteIgroup(anyString(), anyString()); + assertIgroupWasFoundByName(3, "svm1", "cs_h1_svm1"); + } + + @Test + public void deleteAccessGroupToleratesIgroupDisappearingDuringDelete() throws Exception { + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(igroup("ig-1", "g")))); + doThrow(feignException(404, "gone")).when(sanFeignClient).deleteIgroup(anyString(), anyString()); + + unifiedSANStrategy.deleteAccessGroup(accessGroup(host("h1", "iqn.1"))); + + verify(sanFeignClient).deleteIgroup(anyString(), eq("ig-1")); + assertIgroupWasFoundByName(1, "svm1", "cs_h1_svm1"); + } + + @Test + public void deleteAccessGroupFailsOnOtherErrorsAndMissingUuid() throws Exception { + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(igroup("ig-1", "g")))); + doThrow(feignException(500, "ontap down")).when(sanFeignClient).deleteIgroup(anyString(), anyString()); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.deleteAccessGroup(accessGroup(host("h1", "iqn.1")))); + assertTrue(feignFailure.getMessage().startsWith("Failed to delete iGroup"), feignFailure.getMessage()); + assertTrue(feignFailure.getMessage().contains("ontap down"), feignFailure.getMessage()); + + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(igroup("", "g")))); + CloudRuntimeException noUuid = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.deleteAccessGroup(accessGroup(host("h1", "iqn.1")))); + assertTrue(noUuid.getMessage().contains("iGroup UUID is null or empty for iGroup: cs_h1_svm1"), noUuid.getMessage()); + verify(sanFeignClient).deleteIgroup(anyString(), eq("ig-1")); + assertIgroupWasFoundByName(2, "svm1", "cs_h1_svm1"); + } + + // -------------------------------------------------------- unsupported / getAccessGroup + + @Test + public void updateAccessGroupIsNotSupportedForIscsi() { + assertNull(unifiedSANStrategy.updateAccessGroup(new AccessGroup())); + } + + @Test + public void getAccessGroupRejectsInvalidLookups() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getAccessGroup(null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getAccessGroup(Map.of())); + for (Map values : List.of( + Map.of(OntapStorageConstants.NAME, "g"), + Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1"), + Map.of(OntapStorageConstants.SVM_DOT_NAME, "", OntapStorageConstants.NAME, "g"), + Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.NAME, ""))) { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getAccessGroup(values)); + } + } + + @Test + public void getAccessGroupReturnsNullWhenIgroupIsNotFound() { + Map lookup = Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.NAME, "g"); + + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(null); + assertNull(unifiedSANStrategy.getAccessGroup(lookup)); + + OntapResponse nullRecords = new OntapResponse<>(); + nullRecords.setRecords(null); + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(nullRecords); + assertNull(unifiedSANStrategy.getAccessGroup(lookup)); + + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(new ArrayList<>())); + assertNull(unifiedSANStrategy.getAccessGroup(lookup)); + + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenThrow(feignException(404, "gone")); + assertNull(unifiedSANStrategy.getAccessGroup(lookup)); + + assertIgroupLookups(4, "svm1", "g"); + } + + @Test + public void getAccessGroupReturnsIgroupAndWrapsOtherErrors() throws Exception { + Map lookup = Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.NAME, "g"); + Igroup found = igroup("ig-1", "g"); + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(found))); + assertSame(found, unifiedSANStrategy.getAccessGroup(lookup).getIgroup()); + + when(sanFeignClient.getIgroupResponse(anyString(), anyMap())).thenThrow(feignException(500, "ontap down")); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getAccessGroup(lookup)); + assertTrue(feignFailure.getMessage().startsWith("Failed to fetch Igroup poolDetails"), feignFailure.getMessage()); + assertTrue(feignFailure.getMessage().contains("ontap down"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(sanFeignClient).getIgroupResponse(anyString(), anyMap()); + CloudRuntimeException generic = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getAccessGroup(lookup)); + assertTrue(generic.getMessage().contains("boom"), generic.getMessage()); + assertIgroupLookups(3, "svm1", "g"); + } + + // -------------------------------------------------------- LUN mapping + + private static Map mapValues() { + return Map.of(OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.LUN_DOT_NAME, "lun", + OntapStorageConstants.IGROUP_DOT_NAME, "g"); + } + + @Test + public void enableLogicalAccessRejectsInvalidValues() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.enableLogicalAccess(null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.enableLogicalAccess(Map.of())); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.enableLogicalAccess(Map.of( + OntapStorageConstants.SVM_DOT_NAME, "", OntapStorageConstants.LUN_DOT_NAME, "lun", OntapStorageConstants.IGROUP_DOT_NAME, "g"))); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.enableLogicalAccess(Map.of( + OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.LUN_DOT_NAME, "", OntapStorageConstants.IGROUP_DOT_NAME, "g"))); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.enableLogicalAccess(Map.of( + OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.LUN_DOT_NAME, "lun", OntapStorageConstants.IGROUP_DOT_NAME, ""))); + } + + @Test + public void enableLogicalAccessAcceptsAlreadyMappedLunAndFailsOnOtherErrors() { + assertEquals("", unifiedSANStrategy.enableLogicalAccess(mapValues())); + + when(sanFeignClient.createLunMap(anyString(), anyBoolean(), any(LunMap.class))) + .thenThrow(new IllegalStateException("LUN already mapped to this group")); + assertEquals("", unifiedSANStrategy.enableLogicalAccess(mapValues())); + + doThrow(new IllegalStateException("ontap down")).when(sanFeignClient).createLunMap(anyString(), anyBoolean(), any(LunMap.class)); + CloudRuntimeException failed = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.enableLogicalAccess(mapValues())); + + doThrow(new IllegalStateException((String) null)).when(sanFeignClient).createLunMap(anyString(), anyBoolean(), any(LunMap.class)); + CloudRuntimeException blank = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.enableLogicalAccess(mapValues())); + assertEquals("Failed to create LunMap: null", blank.getMessage()); + assertEquals("Failed to create LunMap: ontap down", failed.getMessage()); + assertLunMapRequests(4, "svm1", "lun", "g"); + } + + @Test + public void disableLogicalAccessValidatesInputAndHandlesErrors() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.disableLogicalAccess(null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.disableLogicalAccess(Map.of())); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.disableLogicalAccess(Map.of( + OntapStorageConstants.LUN_DOT_UUID, "", OntapStorageConstants.IGROUP_DOT_UUID, "ig"))); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.disableLogicalAccess(Map.of( + OntapStorageConstants.LUN_DOT_UUID, "lun", OntapStorageConstants.IGROUP_DOT_UUID, ""))); + + Map values = Map.of(OntapStorageConstants.LUN_DOT_UUID, "lun-1", OntapStorageConstants.IGROUP_DOT_UUID, "ig-1"); + unifiedSANStrategy.disableLogicalAccess(values); + verify(sanFeignClient).deleteLunMap(anyString(), eq("lun-1"), eq("ig-1")); + + doThrow(feignException(404, "gone")).when(sanFeignClient).deleteLunMap(anyString(), anyString(), anyString()); + unifiedSANStrategy.disableLogicalAccess(values); + + doThrow(feignException(500, "ontap down")).when(sanFeignClient).deleteLunMap(anyString(), anyString(), anyString()); + CloudRuntimeException feignFailure = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.disableLogicalAccess(values)); + assertTrue(feignFailure.getMessage().startsWith("Failed to delete LunMap"), feignFailure.getMessage()); + assertTrue(feignFailure.getMessage().contains("ontap down"), feignFailure.getMessage()); + + doThrow(new IllegalStateException("boom")).when(sanFeignClient).deleteLunMap(anyString(), anyString(), anyString()); + CloudRuntimeException generic = assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.disableLogicalAccess(values)); + assertTrue(generic.getMessage().contains("boom"), generic.getMessage()); + verify(sanFeignClient, times(4)).deleteLunMap(anyString(), eq("lun-1"), eq("ig-1")); + } + + @Test + public void getLogicalAccessValidatesInput() { + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLogicalAccess(null)); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLogicalAccess(Map.of())); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLogicalAccess(Map.of( + OntapStorageConstants.SVM_DOT_NAME, "", OntapStorageConstants.LUN_DOT_NAME, "lun", OntapStorageConstants.IGROUP_DOT_NAME, "g"))); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLogicalAccess(Map.of( + OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.LUN_DOT_NAME, "", OntapStorageConstants.IGROUP_DOT_NAME, "g"))); + assertThrows(CloudRuntimeException.class, () -> unifiedSANStrategy.getLogicalAccess(Map.of( + OntapStorageConstants.SVM_DOT_NAME, "svm1", OntapStorageConstants.LUN_DOT_NAME, "lun", OntapStorageConstants.IGROUP_DOT_NAME, ""))); + } + + @Test + public void getLogicalAccessReturnsLunNumberOrNull() { + LunMap withNumber = new LunMap(); + withNumber.setLogicalUnitNumber(3); + when(sanFeignClient.getLunMapResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(withNumber))); + assertEquals("3", unifiedSANStrategy.getLogicalAccess(mapValues())); + + when(sanFeignClient.getLunMapResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(new LunMap()))); + assertNull(unifiedSANStrategy.getLogicalAccess(mapValues())); + + when(sanFeignClient.getLunMapResponse(anyString(), anyMap())).thenReturn(null); + assertNull(unifiedSANStrategy.getLogicalAccess(mapValues())); + + OntapResponse nullRecords = new OntapResponse<>(); + nullRecords.setRecords(null); + when(sanFeignClient.getLunMapResponse(anyString(), anyMap())).thenReturn(nullRecords); + assertNull(unifiedSANStrategy.getLogicalAccess(mapValues())); + + when(sanFeignClient.getLunMapResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(new ArrayList<>())); + assertNull(unifiedSANStrategy.getLogicalAccess(mapValues())); + + when(sanFeignClient.getLunMapResponse(anyString(), anyMap())).thenThrow(feignException(500, "ontap down")); + assertNull(unifiedSANStrategy.getLogicalAccess(mapValues())); + + assertLunMapQueries(6, "svm1", "lun", "g"); + } + + @Test + public void ensureLunMappedReusesExistingMapOrCreatesOne() { + LunMap existing = new LunMap(); + existing.setLogicalUnitNumber(5); + when(sanFeignClient.getLunMapResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(existing))); + assertEquals("5", unifiedSANStrategy.ensureLunMapped("svm1", "lun", "g")); + verify(sanFeignClient, never()).createLunMap(anyString(), anyBoolean(), any(LunMap.class)); + + when(sanFeignClient.getLunMapResponse(anyString(), anyMap())).thenReturn(null); + assertEquals("", unifiedSANStrategy.ensureLunMapped("svm1", "lun", "g")); + assertLunMapQueries(2, "svm1", "lun", "g"); + assertLunMapRequests(1, "svm1", "lun", "g"); + } + + @Test + public void ensureLunMappedFailsWhenMappingReturnsNothing() { + UnifiedSANStrategy spied = spy(unifiedSANStrategy); + doReturn(null).when(spied).getLogicalAccess(anyMap()); + doReturn(null).when(spied).enableLogicalAccess(anyMap()); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> spied.ensureLunMapped("svm1", "lun", "g")); + + assertTrue(thrown.getMessage().contains("Failed to map LUN [lun] to iGroup [g]"), thrown.getMessage()); + } + + // -------------------------------------------------------- revertSnapshotForCloudStackVolume + + @Test + public void revertSnapshotCallsCliRestoreWithNormalisedLunPath() { + JobResponse expected = new JobResponse(); + when(snapshotFeignClient.restoreFileFromSnapshotCli(anyString(), any())).thenReturn(expected); + + assertSame(expected, unifiedSANStrategy.revertSnapshotForCloudStackVolume("snap", "flex-uuid", "snap-uuid", "vol/lun1", LUN_UUID, "flexvol")); + verify(snapshotFeignClient).restoreFileFromSnapshotCli(anyString(), argThat(request -> + "/vol/lun1".equals(request.getPath()) && "svm1".equals(request.getVserver()) + && "flexvol".equals(request.getVolume()) && "snap".equals(request.getSnapshot()))); + + unifiedSANStrategy.revertSnapshotForCloudStackVolume("snap", "flex-uuid", "snap-uuid", "/vol/lun2", LUN_UUID, "flexvol"); + verify(snapshotFeignClient).restoreFileFromSnapshotCli(anyString(), argThat(request -> "/vol/lun2".equals(request.getPath()))); + } + + @Test + public void revertSnapshotRejectsMissingArguments() { + for (String[] args : new String[][] { + {null, "flexvol", "lun"}, {"", "flexvol", "lun"}, + {"snap", null, "lun"}, {"snap", "", "lun"}, + {"snap", "flexvol", null}, {"snap", "flexvol", ""}}) { + assertThrows(CloudRuntimeException.class, () -> + unifiedSANStrategy.revertSnapshotForCloudStackVolume(args[0], "flex-uuid", "snap-uuid", args[2], LUN_UUID, args[1])); + } + verify(snapshotFeignClient, never()).restoreFileFromSnapshotCli(anyString(), any()); + } + + @Test + public void deleteVolumeIgnoresMissingLunButFailsOnOtherErrors() { + CloudStackVolume request = lunVolume(lun("/vol/v/l", LUN_UUID)); + doThrow(feignException(404, "gone")).when(sanFeignClient).deleteLun(anyString(), anyString(), anyMap()); + unifiedSANStrategy.deleteCloudStackVolume(request); + + doThrow(feignException(500, "ontap down")).when(sanFeignClient).deleteLun(anyString(), anyString(), anyMap()); + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.deleteCloudStackVolume(request)); + + assertTrue(thrown.getMessage().contains("Failed to delete Lun:"), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("ontap down"), thrown.getMessage()); + assertLunDeletes(2, LUN_UUID); + } + + // =================================================================================== + // Assertions on the exact requests the SAN strategy sends to ONTAP + // =================================================================================== + + private static org.mockito.ArgumentCaptor captor(Class type) { + return org.mockito.ArgumentCaptor.forClass(type); + } + + private void assertLunMapRequests(int times, String svmName, String lunName, String igroupName) { + ArgumentCaptor requests = ArgumentCaptor.forClass(LunMap.class); + verify(sanFeignClient, times(times)).createLunMap(eq(authHeader), eq(false), requests.capture()); + assertEquals(times, requests.getAllValues().size()); + for (LunMap request : requests.getAllValues()) { + assertEquals(svmName, request.getSvm().getName()); + assertEquals(lunName, request.getLun().getName()); + assertEquals(igroupName, request.getIgroup().getName()); + } + } + + private void assertLunMapRequest(String svmName, String lunName, String igroupName) { + ArgumentCaptor request = ArgumentCaptor.forClass(LunMap.class); + verify(sanFeignClient).createLunMap(eq(authHeader), eq(false), request.capture()); + assertEquals(svmName, request.getValue().getSvm().getName()); + assertEquals(lunName, request.getValue().getLun().getName()); + assertEquals(igroupName, request.getValue().getIgroup().getName()); + } + + @SuppressWarnings("unchecked") + private void assertLunMapQueries(int times, String svmName, String lunName, String igroupName) { + ArgumentCaptor> queries = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient, times(times)).getLunMapResponse(eq(authHeader), queries.capture()); + assertEquals(times, queries.getAllValues().size()); + for (Map query : queries.getAllValues()) { + assertEquals(svmName, query.get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals(lunName, query.get(OntapStorageConstants.LUN_DOT_NAME)); + assertEquals(igroupName, query.get(OntapStorageConstants.IGROUP_DOT_NAME)); + assertEquals(OntapStorageConstants.LOGICAL_UNIT_NUMBER, query.get(OntapStorageConstants.FIELDS)); + } + } + + @SuppressWarnings("unchecked") + private void assertLunLookups(int times, String svmName, String lunName, String fields) { + ArgumentCaptor> queries = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient, times(times)).getLunResponse(eq(authHeader), queries.capture()); + assertEquals(times, queries.getAllValues().size()); + for (Map query : queries.getAllValues()) { + assertEquals(svmName, query.get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals(lunName, query.get(OntapStorageConstants.NAME)); + if (fields == null) { + assertFalse(query.containsKey(OntapStorageConstants.FIELDS)); + } else { + assertEquals(fields, query.get(OntapStorageConstants.FIELDS)); + } + } + } + + @SuppressWarnings("unchecked") + private void assertIgroupWasFoundByName(int times, String svmName, String igroupName) { + ArgumentCaptor> queries = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient, times(times)).getIgroupResponse(eq(authHeader), queries.capture()); + assertEquals(times, queries.getAllValues().size()); + for (Map query : queries.getAllValues()) { + assertEquals(svmName, query.get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals(igroupName, query.get(OntapStorageConstants.NAME)); + } + } + + @SuppressWarnings("unchecked") + private void assertIgroupLookups(int times, String svmName, String igroupName) { + ArgumentCaptor> queries = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient, times(times)).getIgroupResponse(eq(authHeader), queries.capture()); + assertEquals(times, queries.getAllValues().size()); + for (Map query : queries.getAllValues()) { + assertEquals(svmName, query.get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals(igroupName, query.get(OntapStorageConstants.NAME)); + assertEquals(OntapStorageConstants.INITIATORS, query.get(OntapStorageConstants.FIELDS)); + } + } + + @SuppressWarnings("unchecked") + private void assertLunDeletes(int times, String lunUuid) { + ArgumentCaptor> queries = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient, times(times)).deleteLun(eq(authHeader), eq(lunUuid), queries.capture()); + assertEquals(times, queries.getAllValues().size()); + for (Map query : queries.getAllValues()) { + assertEquals("true", query.get("allow_delete_while_mapped")); + } + } + + @SuppressWarnings("unchecked") + private void assertLunMapQuery(String svmName, String lunName, String igroupName) { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient).getLunMapResponse(eq(authHeader), query.capture()); + assertEquals(svmName, query.getValue().get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals(lunName, query.getValue().get(OntapStorageConstants.LUN_DOT_NAME)); + assertEquals(igroupName, query.getValue().get(OntapStorageConstants.IGROUP_DOT_NAME)); + assertEquals(OntapStorageConstants.LOGICAL_UNIT_NUMBER, query.getValue().get(OntapStorageConstants.FIELDS)); + } + + private void assertTemplateCacheCreateWasFor(String lunName, String svmName, long sizeInBytes) { + ArgumentCaptor sent = ArgumentCaptor.forClass(Lun.class); + verify(sanFeignClient).createLun(eq(authHeader), eq(true), sent.capture()); + assertEquals(lunName, sent.getValue().getName()); + assertEquals(svmName, sent.getValue().getSvm().getName()); + assertEquals(sizeInBytes, sent.getValue().getSpace().getSize()); + } + + @SuppressWarnings("unchecked") + private void assertLunLookupWasFor(String svmName, String lunName) { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient).getLunResponse(eq(authHeader), query.capture()); + assertEquals(svmName, query.getValue().get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals(lunName, query.getValue().get(OntapStorageConstants.NAME)); + } + + @SuppressWarnings("unchecked") + private void assertIgroupLookupWasFor(String igroupName) { + ArgumentCaptor> query = ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient).getIgroupResponse(eq(authHeader), query.capture()); + assertEquals("svm1", query.getValue().get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals(igroupName, query.getValue().get(OntapStorageConstants.NAME)); + } + + @Test + public void createAccessGroupSendsIgroupWithSvmOsTypeInitiatorProtocolAndDeleteOnUnmap() throws Exception { + poolDetails("svm1", "ISCSI"); + when(sanFeignClient.createIgroup(anyString(), anyBoolean(), any(Igroup.class))) + .thenReturn(new OntapResponse<>(List.of(igroup("ig-1", "cs_h1_svm1")))); + + unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1994-05.com.example:host1"))); + + org.mockito.ArgumentCaptor request = captor(Igroup.class); + verify(sanFeignClient).createIgroup(anyString(), eq(true), request.capture()); + Igroup sent = request.getValue(); + assertEquals("svm1", sent.getSvm().getName()); + assertEquals(Igroup.OsTypeEnum.Linux, sent.getOsType()); + assertEquals("cs_h1_svm1", sent.getName()); + assertEquals(1, sent.getInitiators().size()); + assertEquals("iqn.1994-05.com.example:host1", sent.getInitiators().get(0).getName()); + assertEquals(Boolean.TRUE, sent.isDeleteOnUnmap()); + assertEquals(Igroup.ProtocolEnum.iscsi, sent.getProtocol()); + } + + @Test + public void createAccessGroupOmitsSvmWhenPoolHasEmptySvmName() throws Exception { + poolDetails("", "ISCSI"); + when(sanFeignClient.createIgroup(anyString(), anyBoolean(), any(Igroup.class))) + .thenReturn(new OntapResponse<>(List.of(igroup("ig-1", "cs_h1_")))); + + unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1"))); + + verify(sanFeignClient).createIgroup(anyString(), eq(true), argThat(request -> + request.getSvm() == null + && "cs_h1_".equals(request.getName()) + && "iqn.1".equals(request.getInitiators().get(0).getName()))); + } + + @Test + public void createAccessGroupFailsWhenOntapReturnsNullRecords() { + poolDetails("svm1", "ISCSI"); + OntapResponse nullRecords = new OntapResponse<>(); + nullRecords.setRecords(null); + when(sanFeignClient.createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1"))).thenReturn(nullRecords); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, + () -> unifiedSANStrategy.createAccessGroup(accessGroup(host("h1", "iqn.1")))); + + assertTrue(thrown.getMessage().contains("Failed to create Igroup: cs_h1_svm1"), thrown.getMessage()); + verify(sanFeignClient).createIgroup(anyString(), eq(true), igroupNamed("cs_h1_svm1", "iqn.1")); + } + + @Test + public void enableLogicalAccessSendsLunMapWithSvmLunAndIgroupNames() { + unifiedSANStrategy.enableLogicalAccess(mapValues()); + + org.mockito.ArgumentCaptor request = captor(LunMap.class); + verify(sanFeignClient).createLunMap(anyString(), eq(false), request.capture()); + Map expected = mapValues(); + assertEquals(expected.get(OntapStorageConstants.SVM_DOT_NAME), request.getValue().getSvm().getName()); + assertEquals(expected.get(OntapStorageConstants.LUN_DOT_NAME), request.getValue().getLun().getName()); + assertEquals(expected.get(OntapStorageConstants.IGROUP_DOT_NAME), request.getValue().getIgroup().getName()); + } + + @Test + public void createTemplateCacheSendsLunNamedAfterPoolAndTemplateWithLinuxOsType() { + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))) + .thenReturn(new OntapResponse<>(List.of(lun("/vol/flexvol/template_42", "created-uuid")))); + + unifiedSANStrategy.createTemplateCache(pool(), template(), svmDetails(), 1024L); + + org.mockito.ArgumentCaptor request = captor(Lun.class); + verify(sanFeignClient).createLun(anyString(), eq(true), request.capture()); + assertEquals("/vol/flexvol/" + OntapStorageConstants.TEMPLATE_LUN_PREFIX + "42", request.getValue().getName()); + assertEquals(Lun.OsTypeEnum.LINUX, request.getValue().getOsType()); + assertEquals(1024L, request.getValue().getSpace().getSize()); + } + + @Test + public void deleteVolumePollsTheDeleteJobNamingTheLun() { + UnifiedSANStrategy spied = spy(unifiedSANStrategy); + JobResponse job = new JobResponse(); + when(sanFeignClient.deleteLun(anyString(), eq("lun-1"), anyMap())).thenReturn(job); + + spied.deleteCloudStackVolume(lunVolume(lun("/vol/v/l", "lun-1"))); + + verify(spied).pollJobIfPresent(job, "delete Lun [/vol/v/l]"); + org.mockito.ArgumentCaptor> query = org.mockito.ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient).deleteLun(anyString(), eq("lun-1"), query.capture()); + assertEquals("true", query.getValue().get("allow_delete_while_mapped")); + } + + @Test + public void updateVolumePollsTheUpdateJobAndSendsOnlyTheQosPolicy() { + UnifiedSANStrategy spied = spy(unifiedSANStrategy); + JobResponse job = new JobResponse(); + when(sanFeignClient.updateLun(anyString(), eq("lun-1"), any(Lun.class))).thenReturn(job); + Lun target = lun("/vol/v/l", "lun-1"); + org.apache.cloudstack.storage.feign.model.VolumeQosPolicy policy = new org.apache.cloudstack.storage.feign.model.VolumeQosPolicy(); + policy.setName("qos-1"); + target.setQosPolicy(policy); + + spied.updateCloudStackVolume(lunVolume(target)); + + verify(spied).pollJobIfPresent(job, "update LUN [lun-1]"); + verify(sanFeignClient).updateLun(anyString(), eq("lun-1"), argThat(patch -> + patch.getQosPolicy() == policy && patch.getName() == null && patch.getSpace() == null)); + } + + @Test + public void resizePollsTheResizeJobAndSendsTheNewSize() { + UnifiedSANStrategy spied = spy(unifiedSANStrategy); + JobResponse job = new JobResponse(); + when(sanFeignClient.updateLun(anyString(), eq("lun-1"), any(Lun.class))).thenReturn(job); + VolumeInfo volumeInfo = mock(VolumeInfo.class); + when(volumeInfo.getId()).thenReturn(10L); + CloudStackVolume volume = lunVolume(lun("/vol/v/l", "lun-1")); + volume.setVolumeInfo(volumeInfo); + + spied.resizeCloudStackVolume(volume, 4096L); + + verify(spied).pollJobIfPresent(job, "resize Lun [lun-1]"); + verify(sanFeignClient).updateLun(anyString(), eq("lun-1"), argThat(patch -> + patch.getSpace().getSize() == 4096L && patch.getQosPolicy() == null)); + } + + @Test + public void copyRejectsAnIncompleteLunReturnedByOntap() { + createReturns(lun("/vol/dest/lun", null)); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + + assertTrue(thrown.getMessage().contains("incomplete LUN"), thrown.getMessage()); + verify(sanFeignClient, never()).getLunByUUID(anyString(), anyString(), anyMap()); + } + + @Test + public void copyRemovesPartialLunWhenOntapStatusCallFails() { + createReturns(createdCopy()); + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenThrow(feignException(500, "ontap down")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + + assertTrue(thrown.getMessage().startsWith("Failed to copy Lun: "), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("ontap down"), thrown.getMessage()); + verify(sanFeignClient).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + verify(sanFeignClient).deleteLun(anyString(), eq("copied-uuid"), anyMap()); + } + + @Test + public void copyDoesNotResumeWhenConflictIsNotTheAlreadyStartedCopy() { + when(sanFeignClient.createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun"))) + .thenThrow(feignException(500, "{\"code\":\"5375060\"}")) + .thenThrow(feignException(409, "{\"code\":\"1234567\"}")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(30, "src", "lun")); + + assertTrue(thrown.getMessage().startsWith("Failed to copy Lun: "), thrown.getMessage()); + assertTrue(thrown.getMessage().contains("1234567"), thrown.getMessage()); + verify(sanFeignClient, never()).getLunResponse(anyString(), anyMap()); + verify(sanFeignClient, org.mockito.Mockito.times(2)) + .createLun(anyString(), eq(true), destinationCopy("/vol/dest/lun")); + } + + @Test + public void copyLooksUpAnAlreadyStartedCopyInTheDestinationSvm() { + Lun existing = withCopyProgress(createdCopy(), 100, null); + when(sanFeignClient.createLun(anyString(), anyBoolean(), any(Lun.class))) + .thenThrow(feignException(500, "{\"code\":\"5375060\"}")) + .thenThrow(feignException(409, "{\"code\":\"7018919\"}")); + when(sanFeignClient.getLunResponse(anyString(), anyMap())).thenReturn(new OntapResponse<>(List.of(existing))); + when(sanFeignClient.getLunByUUID(anyString(), anyString(), anyMap())).thenReturn(existing); + VolumeInfo src = mock(VolumeInfo.class); + VolumeInfo dest = mock(VolumeInfo.class); + StoragePoolVO destPool = mock(StoragePoolVO.class); + when(src.getId()).thenReturn(11L); + when(dest.getName()).thenReturn("lun"); + when(destPool.getName()).thenReturn("dest"); + when(volumeDetailsDao.findDetail(11L, OntapStorageConstants.LUN_DOT_UUID)) + .thenReturn(new VolumeDetailVO(11L, OntapStorageConstants.LUN_DOT_UUID, "source-uuid", false)); + + unifiedSANStrategy.copyCloudStackVolume(src, dest, destPool, Map.of(OntapStorageConstants.SVM_NAME, "other-svm"), 30); + + @SuppressWarnings("unchecked") + org.mockito.ArgumentCaptor> query = org.mockito.ArgumentCaptor.forClass(Map.class); + verify(sanFeignClient).getLunResponse(anyString(), query.capture()); + assertEquals("other-svm", query.getValue().get(OntapStorageConstants.SVM_DOT_NAME)); + assertEquals("/vol/dest/lun", query.getValue().get(OntapStorageConstants.NAME)); + } + + @Test + public void copyKeepsInterruptFlagAfterBeingInterruptedWhileWaitingForProgress() { + Lun created = withCopyProgress(createdCopy(), 50, "running"); + createReturns(created); + when(sanFeignClient.getLunByUUID(anyString(), anyString(), anyMap())).thenReturn(created); + Thread.currentThread().interrupt(); + try { + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(30, "src", "lun")); + + assertTrue(thrown.getMessage().contains( + "Interrupted while waiting for ONTAP LUN copy for Lun [copied-uuid]"), thrown.getMessage()); + assertTrue(Thread.currentThread().isInterrupted()); + verify(sanFeignClient).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + } finally { + Thread.interrupted(); + } + } + + @Test + public void copyReportsTheGracePeriodInSecondsWhenCopyDetailsNeverAppear() { + unifiedSANStrategy.lunCopyStatusGraceMs = 1000L; + createReturns(createdCopy()); + when(sanFeignClient.getLunByUUID(anyString(), eq("copied-uuid"), anyMap())).thenThrow(feignException(404, "not yet")); + + CloudRuntimeException thrown = assertThrows(CloudRuntimeException.class, () -> copy(10, "src", "lun")); + + assertEquals("ONTAP did not return copy details for Lun [copied-uuid] within 1s", thrown.getMessage()); + assertNotNull(thrown.getCause()); + verify(sanFeignClient, org.mockito.Mockito.atLeastOnce()).getLunByUUID(anyString(), eq("copied-uuid"), anyMap()); + } } diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/utils/OntapStorageUtilsTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/utils/OntapStorageUtilsTest.java index 1fa61966af88..418673bab2b2 100644 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/utils/OntapStorageUtilsTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/utils/OntapStorageUtilsTest.java @@ -24,6 +24,28 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.apache.cloudstack.storage.feign.model.OntapStorage; +import org.apache.cloudstack.storage.provider.StorageProviderFactory; +import org.apache.cloudstack.storage.service.StorageStrategy; +import org.apache.cloudstack.storage.service.model.ProtocolType; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import com.cloud.alert.AlertManager; +import com.cloud.exception.InvalidParameterValueException; +import feign.FeignException; public class OntapStorageUtilsTest { @@ -118,4 +140,436 @@ public void toLunCloneSourcePathInSnapshot_rejectsBlankInputs() { org.junit.jupiter.api.Assertions.assertThrows(com.cloud.exception.InvalidParameterValueException.class, () -> OntapStorageUtils.toLunCloneSourcePathInSnapshot("", "vol1", "snap")); } + + + private static final int MAX_NAME = OntapStorageConstants.MAX_SNAPSHOT_NAME_LENGTH; + + // ------------------------------------------------------- auth header + + @Test + void generateAuthHeader_returnsBasicBase64OfUserAndPassword() { + assertEquals("Basic YWRtaW46cGFzcw==", OntapStorageUtils.generateAuthHeader("admin", "pass")); + } + + // ------------------------------------------------------- isValidName + + @Test + void isValidName_acceptsLettersDigitsAndUnderscores() { + assertTrue(OntapStorageUtils.isValidName("vol_01")); + } + + @Test + void isValidName_acceptsNameOfExactlyTwoHundredCharacters() { + assertTrue(OntapStorageUtils.isValidName("a".repeat(200))); + } + + @Test + void isValidName_rejectsNull() { + assertFalse(OntapStorageUtils.isValidName(null)); + } + + @Test + void isValidName_rejectsEmptyName() { + assertFalse(OntapStorageUtils.isValidName("")); + } + + @Test + void isValidName_rejectsNameLongerThanTwoHundredCharacters() { + assertFalse(OntapStorageUtils.isValidName("a".repeat(201))); + } + + @Test + void isValidName_rejectsNameStartingWithDigitOrUnderscore() { + assertFalse(OntapStorageUtils.isValidName("1vol")); + assertFalse(OntapStorageUtils.isValidName("_vol")); + } + + @Test + void isValidName_rejectsHyphenAndOtherSpecialCharacters() { + assertFalse(OntapStorageUtils.isValidName("vol-01")); + assertFalse(OntapStorageUtils.isValidName("vol 01")); + assertFalse(OntapStorageUtils.isValidName("vol.01")); + } + + // ------------------------------------------------ getOSTypeFromHypervisor + + @Test + void getOSTypeFromHypervisor_returnsLinux_forKvm() { + assertEquals("LINUX", OntapStorageUtils.getOSTypeFromHypervisor(OntapStorageConstants.KVM)); + } + + @Test + void getOSTypeFromHypervisor_throws_forUnsupportedHypervisor() { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> OntapStorageUtils.getOSTypeFromHypervisor("VMware")); + + assertTrue(ex.getMessage().contains("Unsupported hypervisor type VMware"), ex.getMessage()); + } + + // ------------------------------------------------------ sendStorageAlert + + @Test + void sendStorageAlert_doesNothing_whenAlertManagerIsNull() { + assertDoesNotThrow(() -> OntapStorageUtils.sendStorageAlert(null, 1L, 2L, "subject", "body")); + } + + @Test + void sendStorageAlert_forwardsZoneAndPod_whenProvided() { + AlertManager alertMgr = mock(AlertManager.class); + + OntapStorageUtils.sendStorageAlert(alertMgr, 7L, 3L, "subject", "body"); + + verify(alertMgr).sendAlert(AlertManager.AlertType.ALERT_TYPE_STORAGE_MISC, 7L, 3L, "subject", "body"); + } + + @Test + void sendStorageAlert_usesZoneZero_whenZoneIsNull() { + AlertManager alertMgr = mock(AlertManager.class); + + OntapStorageUtils.sendStorageAlert(alertMgr, null, null, "subject", "body"); + + verify(alertMgr).sendAlert(AlertManager.AlertType.ALERT_TYPE_STORAGE_MISC, 0L, null, "subject", "body"); + } + + // -------------------------------------------- strategy resolution + + private Map poolDetails(String protocol) { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.USERNAME, "admin"); + details.put(OntapStorageConstants.PASSWORD, "c2VjcmV0"); + details.put(OntapStorageConstants.STORAGE_IP, "10.0.0.1"); + details.put(OntapStorageConstants.SVM_NAME, "svm1"); + details.put(OntapStorageConstants.SIZE, "1073741824"); + details.put(OntapStorageConstants.PROTOCOL, protocol); + return details; + } + + @Test + void resolveStrategyFromPoolDetails_throws_whenDetailsAreNull() { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> OntapStorageUtils.resolveStrategyFromPoolDetails(null)); + + assertTrue(ex.getMessage().contains("null or empty"), ex.getMessage()); + } + + @Test + void resolveStrategyFromPoolDetails_throws_whenDetailsAreEmpty() { + assertThrows(CloudRuntimeException.class, + () -> OntapStorageUtils.resolveStrategyFromPoolDetails(Collections.emptyMap())); + } + + @Test + void resolveStrategyFromPoolDetails_buildsOntapStorageFromDetails() { + StorageStrategy strategy = mock(StorageStrategy.class); + try (MockedStatic factory = mockStatic(StorageProviderFactory.class)) { + factory.when(() -> StorageProviderFactory.getStrategy(any(OntapStorage.class))).thenReturn(strategy); + + StorageStrategy resolved = OntapStorageUtils.resolveStrategyFromPoolDetails(poolDetails("ISCSI")); + + assertSame(strategy, resolved); + ArgumentCaptor captor = ArgumentCaptor.forClass(OntapStorage.class); + factory.verify(() -> StorageProviderFactory.getStrategy(captor.capture())); + assertEquals("admin", captor.getValue().getUsername()); + assertEquals("c2VjcmV0", captor.getValue().getPassword()); + assertEquals("10.0.0.1", captor.getValue().getStorageIP()); + assertEquals("svm1", captor.getValue().getSvmName()); + assertEquals(1073741824L, captor.getValue().getSize()); + assertEquals(ProtocolType.ISCSI, captor.getValue().getProtocol()); + } + } + + @Test + void resolveStrategyFromPoolDetails_throws_whenSizeIsNotNumeric() { + Map details = poolDetails("ISCSI"); + details.put(OntapStorageConstants.SIZE, "big"); + + assertThrows(NumberFormatException.class, () -> OntapStorageUtils.resolveStrategyFromPoolDetails(details)); + } + + @Test + void resolveStrategyFromPoolDetails_throws_whenProtocolIsUnknown() { + assertThrows(IllegalArgumentException.class, + () -> OntapStorageUtils.resolveStrategyFromPoolDetails(poolDetails("FC"))); + } + + @Test + void getStrategyByStoragePoolDetails_returnsConnectedStrategy() { + StorageStrategy strategy = mock(StorageStrategy.class); + when(strategy.connect(false)).thenReturn(true); + try (MockedStatic factory = mockStatic(StorageProviderFactory.class)) { + factory.when(() -> StorageProviderFactory.getStrategy(any(OntapStorage.class))).thenReturn(strategy); + + assertSame(strategy, OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails("NFS3"))); + } + } + + @Test + void getStrategyByStoragePoolDetails_passesAggregateValidationFlagToConnect() { + StorageStrategy strategy = mock(StorageStrategy.class); + when(strategy.connect(true)).thenReturn(true); + try (MockedStatic factory = mockStatic(StorageProviderFactory.class)) { + factory.when(() -> StorageProviderFactory.getStrategy(any(OntapStorage.class))).thenReturn(strategy); + + assertSame(strategy, OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails("NFS3"), true)); + verify(strategy).connect(true); + } + } + + @Test + void getStrategyByStoragePoolDetails_throws_whenConnectionFails() { + StorageStrategy strategy = mock(StorageStrategy.class); + when(strategy.connect(anyBoolean())).thenReturn(false); + try (MockedStatic factory = mockStatic(StorageProviderFactory.class)) { + factory.when(() -> StorageProviderFactory.getStrategy(any(OntapStorage.class))).thenReturn(strategy); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails("NFS3"))); + + assertTrue(ex.getMessage().contains("svm1"), ex.getMessage()); + assertTrue(ex.getMessage().contains("failed"), ex.getMessage()); + } + } + + @Test + void getStrategyByStoragePoolDetails_doesNotConnect_whenDetailsAreInvalid() { + try (MockedStatic factory = mockStatic(StorageProviderFactory.class)) { + assertThrows(CloudRuntimeException.class, () -> OntapStorageUtils.getStrategyByStoragePoolDetails(null)); + + factory.verifyNoInteractions(); + } + } + + // ------------------------------------------ simple name/path builders + + @Test + void generateExportPolicyName_joinsSvmAndVolumeWithHyphens() { + assertEquals("cs-svm1-vol1", OntapStorageUtils.generateExportPolicyName("svm1", "vol1")); + } + + @Test + void getLunName_buildsUnifiedLunPath() { + assertEquals("/vol/flexvol/lun1", OntapStorageUtils.getLunName("flexvol", "lun1")); + } + + // ------------------------------------------ toFlexVolRelativePath + + @Test + void toFlexVolRelativePath_returnsNull_forNullPath() { + assertNull(OntapStorageUtils.toFlexVolRelativePath(null, "fv")); + } + + @Test + void toFlexVolRelativePath_returnsEmpty_forEmptyPath() { + assertEquals("", OntapStorageUtils.toFlexVolRelativePath("", "fv")); + } + + @Test + void toFlexVolRelativePath_stripsFlexVolPrefix_forAbsoluteLunPath() { + assertEquals("dir/lun1", OntapStorageUtils.toFlexVolRelativePath("/vol/fv/dir/lun1", "fv")); + } + + @Test + void toFlexVolRelativePath_keepsRelativePathUnchanged() { + assertEquals("uuid-file", OntapStorageUtils.toFlexVolRelativePath("uuid-file", "fv")); + } + + @Test + void toFlexVolRelativePath_stripsLeadingSlash_whenFlexVolNameMissing() { + assertEquals("abs/path", OntapStorageUtils.toFlexVolRelativePath("/abs/path", null)); + assertEquals("abs/path", OntapStorageUtils.toFlexVolRelativePath("/abs/path", "")); + } + + @Test + void toFlexVolRelativePath_stripsLeadingSlash_whenPathBelongsToOtherFlexVol() { + assertEquals("vol/other/lun1", OntapStorageUtils.toFlexVolRelativePath("/vol/other/lun1", "fv")); + } + + // ------------------------------------ toLunCloneSourcePathInSnapshot + + @Test + void toLunCloneSourcePathInSnapshot_buildsPathInsideSnapshotDirectory() { + assertEquals("/vol/fv/.snapshot/snap1/lun1", + OntapStorageUtils.toLunCloneSourcePathInSnapshot("/vol/fv/lun1", "fv", "snap1")); + } + + @Test + void toLunCloneSourcePathInSnapshot_throws_whenFlexVolNameMissing() { + assertThrows(InvalidParameterValueException.class, + () -> OntapStorageUtils.toLunCloneSourcePathInSnapshot("/vol/fv/lun1", null, "snap1")); + assertThrows(InvalidParameterValueException.class, + () -> OntapStorageUtils.toLunCloneSourcePathInSnapshot("/vol/fv/lun1", "", "snap1")); + } + + @Test + void toLunCloneSourcePathInSnapshot_throws_whenSnapshotNameMissing() { + assertThrows(InvalidParameterValueException.class, + () -> OntapStorageUtils.toLunCloneSourcePathInSnapshot("/vol/fv/lun1", "fv", null)); + assertThrows(InvalidParameterValueException.class, + () -> OntapStorageUtils.toLunCloneSourcePathInSnapshot("/vol/fv/lun1", "fv", "")); + } + + @Test + void toLunCloneSourcePathInSnapshot_throws_whenLunPathMissingOrOnlyFlexVol() { + assertThrows(InvalidParameterValueException.class, + () -> OntapStorageUtils.toLunCloneSourcePathInSnapshot(null, "fv", "snap1")); + assertThrows(InvalidParameterValueException.class, + () -> OntapStorageUtils.toLunCloneSourcePathInSnapshot("/vol/fv/", "fv", "snap1")); + } + + // ------------------------------------------------ getOntapSnapshotName + + @Test + void getOntapSnapshotName_throws_forNullOrBlankName() { + assertThrows(InvalidParameterValueException.class, () -> OntapStorageUtils.getOntapSnapshotName(null)); + assertThrows(InvalidParameterValueException.class, () -> OntapStorageUtils.getOntapSnapshotName(" ")); + } + + @Test + void getOntapSnapshotName_replacesInvalidCharactersWithUnderscores() { + assertEquals("my_snap_1", OntapStorageUtils.getOntapSnapshotName("my snap-1")); + } + + @Test + void getOntapSnapshotName_prefixesNamesThatDoNotStartWithLetter() { + assertEquals("s_1abc", OntapStorageUtils.getOntapSnapshotName("1abc")); + assertEquals("s___", OntapStorageUtils.getOntapSnapshotName("@@")); + } + + @Test + void getOntapSnapshotName_truncatesToMaximumLength() { + String result = OntapStorageUtils.getOntapSnapshotName("a".repeat(MAX_NAME + 50)); + + assertEquals(MAX_NAME, result.length()); + } + + // --------------------------------------------- buildOntapSnapshotName + + @Test + void buildOntapSnapshotName_appendsSanitizedSuffix() { + assertEquals("daily_cs_77", OntapStorageUtils.buildOntapSnapshotName("daily", "cs-77")); + } + + @Test + void buildOntapSnapshotName_usesDefaultBase_whenNameIsNullOrBlank() { + assertEquals("snapshot_cs1", OntapStorageUtils.buildOntapSnapshotName(null, "cs1")); + assertEquals("snapshot_cs1", OntapStorageUtils.buildOntapSnapshotName(" ", "cs1")); + } + + @Test + void buildOntapSnapshotName_omitsSeparator_whenSuffixIsNullOrEmpty() { + assertEquals("daily", OntapStorageUtils.buildOntapSnapshotName("daily", null)); + assertEquals("daily", OntapStorageUtils.buildOntapSnapshotName("daily", "")); + } + + @Test + void buildOntapSnapshotName_truncatesBaseSoSuffixAlwaysFits() { + String result = OntapStorageUtils.buildOntapSnapshotName("a".repeat(MAX_NAME + 10), "cs9"); + + assertEquals(MAX_NAME, result.length()); + assertTrue(result.endsWith("_cs9")); + } + + @Test + void buildOntapSnapshotName_returnsTruncatedBaseWithoutSuffix_whenSuffixConsumesWholeBudget() { + String hugeSuffix = "x".repeat(MAX_NAME); + + String result = OntapStorageUtils.buildOntapSnapshotName("a".repeat(MAX_NAME + 20), hugeSuffix); + + assertEquals("a".repeat(MAX_NAME), result); + } + + @Test + void buildOntapSnapshotName_dropsSuffixWhenItExactlyFillsTheBudget() { + String suffixFillingBudget = "x".repeat(MAX_NAME - 1); + + String result = OntapStorageUtils.buildOntapSnapshotName("a".repeat(MAX_NAME + 20), suffixFillingBudget); + + assertEquals("a".repeat(MAX_NAME), result); + } + + @Test + void extractUuid_findsSegmentAtTheVeryStartOfTheDescription() { + assertEquals("u-1", OntapStorageUtils.extractUuidFromOntapJobDescription("/snapshots/u-1", "/snapshots/")); + } + + // ------------------------------- extractUuidFromOntapJobDescription + + @Test + void extractUuid_returnsNull_forNullInputs() { + assertNull(OntapStorageUtils.extractUuidFromOntapJobDescription(null, "/snapshots/")); + assertNull(OntapStorageUtils.extractUuidFromOntapJobDescription("POST /x/snapshots/u1", null)); + assertNull(OntapStorageUtils.extractUuidFromOntapJobDescription("POST /x/snapshots/u1", "")); + } + + @Test + void extractUuid_returnsNull_whenSegmentNotPresent() { + assertNull(OntapStorageUtils.extractUuidFromOntapJobDescription("POST /x/other/u1", "/snapshots/")); + } + + @Test + void extractUuid_returnsNull_whenNothingFollowsSegment() { + assertNull(OntapStorageUtils.extractUuidFromOntapJobDescription("POST /x/snapshots/ ", "/snapshots/")); + } + + @Test + void extractUuid_returnsUuid_afterSegment() { + assertEquals("u-123", + OntapStorageUtils.extractUuidFromOntapJobDescription("POST /api/cg/c1/snapshots/u-123", "/snapshots/")); + } + + @Test + void extractUuid_stripsQueryStringAndTrailingPath() { + assertEquals("u-123", + OntapStorageUtils.extractUuidFromOntapJobDescription("POST /snapshots/u-123?return_timeout=0", "/snapshots/")); + assertEquals("u-123", + OntapStorageUtils.extractUuidFromOntapJobDescription("POST /snapshots/u-123/files", "/snapshots/")); + } + + @Test + void extractUuid_returnsNull_whenOnlyQueryOrSlashFollowsSegment() { + assertNull(OntapStorageUtils.extractUuidFromOntapJobDescription("POST /snapshots/?x=1", "/snapshots/")); + assertNull(OntapStorageUtils.extractUuidFromOntapJobDescription("POST /snapshots//rest", "/snapshots/")); + } + + // ------------------------------------- isOntapObjectNotFoundError + + @Test + void isOntapObjectNotFoundError_returnsFalse_forNull() { + assertFalse(OntapStorageUtils.isOntapObjectNotFoundError(null)); + } + + @Test + void isOntapObjectNotFoundError_returnsTrue_forFeignHttp404() { + FeignException notFound = mock(FeignException.class); + when(notFound.status()).thenReturn(404); + + assertTrue(OntapStorageUtils.isOntapObjectNotFoundError(notFound)); + } + + @Test + void isOntapObjectNotFoundError_returnsFalse_forFeignServerErrorWithoutMessage() { + FeignException serverError = mock(FeignException.class); + when(serverError.status()).thenReturn(500); + when(serverError.getMessage()).thenReturn(null); + + assertFalse(OntapStorageUtils.isOntapObjectNotFoundError(serverError)); + } + + @Test + void isOntapObjectNotFoundError_returnsTrue_forKnownNotFoundMessages() { + assertTrue(OntapStorageUtils.isOntapObjectNotFoundError(new RuntimeException("HTTP 404 returned"))); + assertTrue(OntapStorageUtils.isOntapObjectNotFoundError(new RuntimeException("Snapshot Not Found"))); + assertTrue(OntapStorageUtils.isOntapObjectNotFoundError(new RuntimeException("LUN does not exist"))); + assertTrue(OntapStorageUtils.isOntapObjectNotFoundError(new RuntimeException("entry doesn't exist"))); + } + + @Test + void isOntapObjectNotFoundError_returnsFalse_forUnrelatedMessage() { + assertFalse(OntapStorageUtils.isOntapObjectNotFoundError(new RuntimeException("volume is busy"))); + } + + @Test + void isOntapObjectNotFoundError_returnsFalse_forErrorWithoutMessage() { + assertFalse(OntapStorageUtils.isOntapObjectNotFoundError(new RuntimeException((String) null))); + } } diff --git a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/vmsnapshot/OntapVMSnapshotStrategyTest.java b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/vmsnapshot/OntapVMSnapshotStrategyTest.java index aa0d48c2e850..880574865b7b 100644 --- a/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/vmsnapshot/OntapVMSnapshotStrategyTest.java +++ b/plugins/storage/volume/ontap/src/test/java/org/apache/cloudstack/storage/vmsnapshot/OntapVMSnapshotStrategyTest.java @@ -20,6 +20,8 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; @@ -95,6 +97,17 @@ import com.cloud.vm.snapshot.VMSnapshotVO; import com.cloud.vm.snapshot.dao.VMSnapshotDao; import com.cloud.vm.snapshot.dao.VMSnapshotDetailsDao; +import org.junit.jupiter.api.Nested; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import org.apache.cloudstack.storage.utils.OntapStorageUtils; +import org.mockito.MockedStatic; +import org.mockito.Mockito; /** * Unit tests for {@link OntapVMSnapshotStrategy}. @@ -149,6 +162,8 @@ class OntapVMSnapshotStrategyTest { private StorageStrategy storageStrategy; @Mock private SnapshotFeignClient snapshotFeignClient; + @Mock + private org.apache.cloudstack.framework.config.dao.ConfigurationDao configurationDao; @Spy @InjectMocks @@ -1269,4 +1284,1174 @@ private void setupTemporaryCgFlowMocks(String snapshotName) { when(snapshotFeignClient.getSnapshots(any(), eq("flexvol-uuid-2"), any())) .thenReturn(flexVolSnapshots2); } + + // ══════════════════════════════════════════════════════════════════════════ + // Assertions on what takeVMSnapshot reports, freezes, thaws and cleans up + // ══════════════════════════════════════════════════════════════════════════ + + private void stubFreezeAndThawSuccess() throws Exception { + FreezeThawVMAnswer freezeAnswer = mock(FreezeThawVMAnswer.class); + when(freezeAnswer.getResult()).thenReturn(true); + FreezeThawVMAnswer thawAnswer = mock(FreezeThawVMAnswer.class); + when(thawAnswer.getResult()).thenReturn(true); + when(agentMgr.send(eq(HOST_ID), any(FreezeThawVMCommand.class))) + .thenReturn(freezeAnswer) + .thenReturn(thawAnswer); + } + + private List freezeThawCommandsSent(int expectedCount) throws Exception { + org.mockito.ArgumentCaptor captor = org.mockito.ArgumentCaptor.forClass(FreezeThawVMCommand.class); + verify(agentMgr, times(expectedCount)).send(eq(HOST_ID), captor.capture()); + return captor.getAllValues(); + } + + @Test + void testTakeVMSnapshot_ReturnsTheSnapshot_FinalizesWithVolumes_AndPublishesUsageWithChainSizeDelta() throws Exception { + VMSnapshotVO vmSnapshot = createTakeSnapshotVmSnapshot(); + UserVmVO userVm = setupTakeSnapshotCommon(vmSnapshot); + setupSingleVolumeForTakeSnapshot(); + VolumeVO volumeRow = volumeDao.findById(VOLUME_ID_1); + when(volumeRow.getVmSnapshotChainSize()).thenReturn(4000L); + setupSingleFlexVolFlowMocks(strategy.buildSnapshotName(vmSnapshot)); + stubFreezeAndThawSuccess(); + VolumeObjectTO volumeTO = vmSnapshotHelper.getVolumeTOList(VM_ID).get(0); + + assertSame(vmSnapshot, strategy.takeVMSnapshot(vmSnapshot)); + + org.mockito.ArgumentCaptor answer = org.mockito.ArgumentCaptor.forClass(com.cloud.agent.api.Answer.class); + verify(strategy).processAnswer(eq(vmSnapshot), eq(userVm), answer.capture(), eq(null)); + assertTrue(answer.getValue() instanceof com.cloud.agent.api.CreateVMSnapshotAnswer); + assertTrue(answer.getValue().getResult()); + assertEquals(List.of(volumeTO), ((com.cloud.agent.api.CreateVMSnapshotAnswer)answer.getValue()).getVolumeTOs()); + verify(strategy).publishUsageEvent(eq(com.cloud.event.EventTypes.EVENT_VM_SNAPSHOT_CREATE), eq(vmSnapshot), eq(userVm), eq(volumeTO)); + verify(strategy).publishUsageEvent(eq(com.cloud.event.EventTypes.EVENT_VM_SNAPSHOT_ON_PRIMARY), eq(vmSnapshot), eq(userVm), + eq(10737418240L - 4000L), eq(10737418240L)); + verify(vmSnapshotHelper, never()).vmSnapshotStateTransitTo(any(), eq(VMSnapshot.Event.OperationFailed)); + } + + @Test + void testTakeVMSnapshot_SendsFreezeThenThawCommands() throws Exception { + VMSnapshotVO vmSnapshot = createTakeSnapshotVmSnapshot(); + setupTakeSnapshotCommon(vmSnapshot); + setupSingleVolumeForTakeSnapshot(); + setupSingleFlexVolFlowMocks(strategy.buildSnapshotName(vmSnapshot)); + stubFreezeAndThawSuccess(); + + strategy.takeVMSnapshot(vmSnapshot); + + List sent = freezeThawCommandsSent(2); + assertEquals(FreezeThawVMCommand.FREEZE, sent.get(0).getOption()); + assertEquals(FreezeThawVMCommand.THAW, sent.get(1).getOption()); + } + + @Test + void testTakeVMSnapshot_StoppedVm_SkipsFreezeThawButStillSnapshots() throws Exception { + VMSnapshotVO vmSnapshot = createTakeSnapshotVmSnapshot(); + UserVmVO userVm = setupTakeSnapshotCommon(vmSnapshot); + when(userVm.getState()).thenReturn(VirtualMachine.State.Stopped); + setupSingleVolumeForTakeSnapshot(); + setupSingleFlexVolFlowMocks(strategy.buildSnapshotName(vmSnapshot)); + + assertSame(vmSnapshot, strategy.takeVMSnapshot(vmSnapshot)); + + verify(agentMgr, never()).send(eq(HOST_ID), any(FreezeThawVMCommand.class)); + verify(snapshotFeignClient, times(1)).createSnapshot(any(), eq("flexvol-uuid-1"), any()); + } + + @Test + void testTakeVMSnapshot_FreezeRejectedByGuest_DoesNotSendThawAndReportsDetails() throws Exception { + VMSnapshotVO vmSnapshot = createTakeSnapshotVmSnapshot(); + setupTakeSnapshotCommon(vmSnapshot); + setupSingleVolumeForTakeSnapshot(); + FreezeThawVMAnswer freezeAnswer = mock(FreezeThawVMAnswer.class); + when(freezeAnswer.getResult()).thenReturn(false); + when(freezeAnswer.getDetails()).thenReturn("guest agent is down"); + when(agentMgr.send(eq(HOST_ID), any(FreezeThawVMCommand.class))).thenReturn(freezeAnswer); + when(vmSnapshotDetailsDao.listDetails(SNAPSHOT_ID)).thenReturn(Collections.emptyList()); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.takeVMSnapshot(vmSnapshot)); + + assertTrue(ex.getMessage().contains("guest agent is down"), ex.getMessage()); + assertEquals(1, freezeThawCommandsSent(1).size()); + verify(snapshotFeignClient, never()).createSnapshot(any(), any(), any()); + verify(vmSnapshotHelper).vmSnapshotStateTransitTo(any(), eq(VMSnapshot.Event.OperationFailed)); + } + + @Test + void testTakeVMSnapshot_NoFreezeAnswer_ReportsNoResponse() throws Exception { + VMSnapshotVO vmSnapshot = createTakeSnapshotVmSnapshot(); + setupTakeSnapshotCommon(vmSnapshot); + setupSingleVolumeForTakeSnapshot(); + when(agentMgr.send(eq(HOST_ID), any(FreezeThawVMCommand.class))).thenReturn(null); + when(vmSnapshotDetailsDao.listDetails(SNAPSHOT_ID)).thenReturn(Collections.emptyList()); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.takeVMSnapshot(vmSnapshot)); + + assertTrue(ex.getMessage().contains("no response from agent"), ex.getMessage()); + assertEquals(1, freezeThawCommandsSent(1).size()); + } + + @Test + void testTakeVMSnapshot_FailureAfterSuccessfulThaw_DoesNotThawAgain() throws Exception { + VMSnapshotVO vmSnapshot = createTakeSnapshotVmSnapshot(); + setupTakeSnapshotCommon(vmSnapshot); + setupSingleVolumeForTakeSnapshot(); + setupSingleFlexVolFlowMocks(strategy.buildSnapshotName(vmSnapshot)); + stubFreezeAndThawSuccess(); + doThrow(new CloudRuntimeException("persist failed")).when(vmSnapshotDetailsDao).persist(any(VMSnapshotDetailsVO.class)); + when(vmSnapshotDetailsDao.listDetails(SNAPSHOT_ID)).thenReturn(Collections.emptyList()); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeVMSnapshot(vmSnapshot)); + + List sent = freezeThawCommandsSent(2); + assertEquals(FreezeThawVMCommand.FREEZE, sent.get(0).getOption()); + assertEquals(FreezeThawVMCommand.THAW, sent.get(1).getOption()); + } + + @Test + void testTakeVMSnapshot_ThawThrows_ThenLaterFailure_ThawsAgainDuringCleanup() throws Exception { + VMSnapshotVO vmSnapshot = createTakeSnapshotVmSnapshot(); + setupTakeSnapshotCommon(vmSnapshot); + setupSingleVolumeForTakeSnapshot(); + setupSingleFlexVolFlowMocks(strategy.buildSnapshotName(vmSnapshot)); + FreezeThawVMAnswer freezeAnswer = mock(FreezeThawVMAnswer.class); + when(freezeAnswer.getResult()).thenReturn(true); + FreezeThawVMAnswer thawAnswer = mock(FreezeThawVMAnswer.class); + when(thawAnswer.getResult()).thenReturn(true); + when(agentMgr.send(eq(HOST_ID), any(FreezeThawVMCommand.class))) + .thenReturn(freezeAnswer) + .thenThrow(new OperationTimedoutException(null, HOST_ID, 0, 0, false)) + .thenReturn(thawAnswer); + doThrow(new CloudRuntimeException("persist failed")).when(vmSnapshotDetailsDao).persist(any(VMSnapshotDetailsVO.class)); + when(vmSnapshotDetailsDao.listDetails(SNAPSHOT_ID)).thenReturn(Collections.emptyList()); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.takeVMSnapshot(vmSnapshot)); + + assertEquals("persist failed", ex.getMessage()); + List sent = freezeThawCommandsSent(3); + assertEquals(FreezeThawVMCommand.FREEZE, sent.get(0).getOption()); + assertEquals(FreezeThawVMCommand.THAW, sent.get(1).getOption()); + assertEquals(FreezeThawVMCommand.THAW, sent.get(2).getOption()); + } + + @Test + void testTakeVMSnapshot_Failure_RemovesOnlyFlexVolDetailsAndMarksOperationFailed() throws Exception { + VMSnapshotVO vmSnapshot = createTakeSnapshotVmSnapshot(); + setupTakeSnapshotCommon(vmSnapshot); + setupSingleVolumeForTakeSnapshot(); + setupSingleFlexVolFlowMocks(strategy.buildSnapshotName(vmSnapshot)); + stubFreezeAndThawSuccess(); + doThrow(new CloudRuntimeException("persist failed")).when(vmSnapshotDetailsDao).persist(any(VMSnapshotDetailsVO.class)); + VMSnapshotDetailsVO flexVolRow = mock(VMSnapshotDetailsVO.class); + when(flexVolRow.getId()).thenReturn(11L); + when(flexVolRow.getName()).thenReturn(OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT); + VMSnapshotDetailsVO unrelatedRow = mock(VMSnapshotDetailsVO.class); + when(unrelatedRow.getId()).thenReturn(12L); + when(unrelatedRow.getName()).thenReturn("unrelated-detail"); + when(vmSnapshotDetailsDao.listDetails(SNAPSHOT_ID)).thenReturn(List.of(flexVolRow, unrelatedRow)); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeVMSnapshot(vmSnapshot)); + + verify(vmSnapshotDetailsDao).remove(11L); + verify(vmSnapshotDetailsDao, never()).remove(12L); + verify(vmSnapshotHelper).vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationFailed); + } + + @Test + void testCanHandle_AllocatedDiskType_OneVolumeOnNonOntapPool_ReturnsCantHandle() { + setupAllVolumesOnOntap(); + StoragePoolVO foreignPool = mock(StoragePoolVO.class); + when(foreignPool.isManaged()).thenReturn(false); + when(foreignPool.getStorageProviderName()).thenReturn("DefaultPrimary"); + when(storagePool.findById(POOL_ID_2)).thenReturn(foreignPool); + VMSnapshotVO vmSnapshot = createMockVmSnapshot(VMSnapshot.State.Allocated, VMSnapshot.Type.Disk); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(vmSnapshot)); + } + + @Test + void testConfigure_DelegatesToParentAndSucceeds() throws Exception { + when(configurationDao.getValue("vmsnapshot.create.wait")).thenReturn("42"); + Map params = new HashMap<>(); + params.put("marker", "ontap"); + + assertTrue(strategy.configure("ontap-vm-snapshot", params)); + + verify(configurationDao).getValue("vmsnapshot.create.wait"); + assertEquals(42, strategy._wait); + } + + /** + * Covers the delete/revert flows, FlexVol helpers and consistency-group helpers of + * {@link OntapVMSnapshotStrategy} that are not exercised by {@link OntapVMSnapshotStrategyTest}. + */ + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + @Nested + class OntapVMSnapshotStrategyOperationsTest { + + private static final long VM_ID = 100L; + private static final long SNAPSHOT_ID = 200L; + private static final long POOL_ID = 401L; + private static final long OTHER_POOL_ID = 402L; + private static final String AUTH = "Basic abc"; + + @Mock private UserVmDao userVmDao; + @Mock private VolumeDao volumeDao; + @Mock private PrimaryDataStoreDao storagePool; + @Mock private StoragePoolDetailsDao storagePoolDetailsDao; + @Mock private VMSnapshotDetailsDao vmSnapshotDetailsDao; + @Mock private VMSnapshotHelper vmSnapshotHelper; + @Mock private VMSnapshotDao vmSnapshotDao; + @Mock private AgentManager agentMgr; + @Mock private GuestOSDao guestOSDao; + @Mock private VolumeDetailsDao volumeDetailsDao; + @Mock private StorageStrategy storageStrategy; + @Mock private SnapshotFeignClient snapshotClient; + + @Spy + @InjectMocks + private OntapVMSnapshotStrategy strategy; + + // ------------------------------------------------------------------ helpers + + private VMSnapshotDetailsVO detailRow(long id, String value) { + VMSnapshotDetailsVO row = mock(VMSnapshotDetailsVO.class); + when(row.getId()).thenReturn(id); + when(row.getValue()).thenReturn(value); + return row; + } + + private String detailValue(String flexVol, String snapUuid, String snapName, String path, long poolId) { + return String.join("::", flexVol, snapUuid, snapName, path, String.valueOf(poolId), "NFS3"); + } + + private VMSnapshotVO vmSnapshot() { + VMSnapshotVO snapshot = mock(VMSnapshotVO.class); + when(snapshot.getId()).thenReturn(SNAPSHOT_ID); + when(snapshot.getVmId()).thenReturn(VM_ID); + when(snapshot.getName()).thenReturn("snap-one"); + when(snapshot.getType()).thenReturn(VMSnapshot.Type.Disk); + when(snapshot.getDescription()).thenReturn("a description"); + when(snapshot.getCreated()).thenReturn(new Date()); + return snapshot; + } + + private List prepareVmForDeleteOrRevert(VMSnapshotVO snapshot) { + UserVmVO userVm = mock(UserVmVO.class); + when(userVm.getId()).thenReturn(VM_ID); + when(userVm.getInstanceName()).thenReturn("i-2-100-VM"); + when(userVm.getUuid()).thenReturn("vm-uuid"); + when(userVm.getGuestOSId()).thenReturn(50L); + when(userVmDao.findById(VM_ID)).thenReturn(userVm); + GuestOSVO guestOs = mock(GuestOSVO.class); + when(guestOs.getDisplayName()).thenReturn("Ubuntu"); + when(guestOSDao.findById(50L)).thenReturn(guestOs); + VolumeObjectTO volume = mock(VolumeObjectTO.class); + when(volume.getSize()).thenReturn(1024L); + List volumes = List.of(volume); + when(vmSnapshotHelper.getVolumeTOList(VM_ID)).thenReturn(volumes); + when(vmSnapshotHelper.getSnapshotWithParents(snapshot)).thenReturn(mock(VMSnapshotTO.class)); + return volumes; + } + + private void stubPool(long poolId, String volumeName) { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.VOLUME_NAME, volumeName); + when(storagePoolDetailsDao.listDetailsKeyPairs(poolId)).thenReturn(details); + doReturn(storageStrategy).when(strategy).resolveStorageStrategy(any()); + } + + private OntapResponse cgSnapshots(ConsistencyGroupSnapshot... records) { + OntapResponse response = new OntapResponse<>(); + response.setRecords(Arrays.asList(records)); + return response; + } + + private ConsistencyGroupSnapshot cgSnapshot(String name, String uuid) { + ConsistencyGroupSnapshot snapshot = new ConsistencyGroupSnapshot(name); + snapshot.setUuid(uuid); + return snapshot; + } + + private OntapVMSnapshotStrategy.FlexVolGroupInfo group(long poolId, String ip, String svmName, String svmUuid) { + Map details = new HashMap<>(); + if (ip != null) { + details.put(OntapStorageConstants.STORAGE_IP, ip); + } + if (svmName != null) { + details.put(OntapStorageConstants.SVM_NAME, svmName); + } + if (svmUuid != null) { + details.put(OntapStorageConstants.SVM_UUID, svmUuid); + } + return new OntapVMSnapshotStrategy.FlexVolGroupInfo(details, poolId); + } + + // ------------------------------------------------------------------ deleteVMSnapshot + + @Test + void deleteVMSnapshot_deletesFlexVolSnapshotRemovesDetailAndPublishesUsage() throws Exception { + VMSnapshotVO snapshot = vmSnapshot(); + prepareVmForDeleteOrRevert(snapshot); + stubPool(POOL_ID, "vol1"); + VMSnapshotDetailsVO row = detailRow(7L, detailValue("fv-1", "snap-uuid", "snap-name", "disk.qcow2", POOL_ID)); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(List.of(row)); + doNothing().when(strategy).processAnswer(any(), any(), any(), any()); + doNothing().when(strategy).publishUsageEvent(anyString(), any(), any(), any(VolumeObjectTO.class)); + doNothing().when(strategy).publishUsageEvent(anyString(), any(), any(), anyLong(), anyLong()); + + assertTrue(strategy.deleteVMSnapshot(snapshot)); + + verify(vmSnapshotHelper).vmSnapshotStateTransitTo(snapshot, VMSnapshot.Event.ExpungeRequested); + verify(storageStrategy).deleteFlexVolSnapshotForCloudStackVolume("fv-1", "snap-uuid", "snap-name"); + verify(vmSnapshotDetailsDao).remove(7L); + verify(strategy).processAnswer(eq(snapshot), any(), any(), eq(null)); + verify(strategy).publishUsageEvent(anyString(), any(), any(), any(VolumeObjectTO.class)); + verify(strategy).publishUsageEvent(anyString(), any(), any(), eq(1024L), eq(0L)); + } + + @Test + void deleteVMSnapshot_alsoCleansLegacyStorageSnapshots() throws Exception { + VMSnapshotVO snapshot = vmSnapshot(); + prepareVmForDeleteOrRevert(snapshot); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(Collections.emptyList()); + VMSnapshotDetailsVO hoistedRow1 = detailRow(8L, "legacy"); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, StorageVMSnapshotStrategy.STORAGE_SNAPSHOT)) + .thenReturn(List.of(hoistedRow1)); + doNothing().when(strategy).deleteDiskSnapshot(any()); + doNothing().when(strategy).processAnswer(any(), any(), any(), any()); + doNothing().when(strategy).publishUsageEvent(anyString(), any(), any(), any(VolumeObjectTO.class)); + doNothing().when(strategy).publishUsageEvent(anyString(), any(), any(), anyLong(), anyLong()); + + assertTrue(strategy.deleteVMSnapshot(snapshot)); + + verify(strategy).deleteDiskSnapshot(snapshot); + verify(storageStrategy, never()).deleteFlexVolSnapshotForCloudStackVolume(any(), any(), any()); + } + + @Test + void deleteVMSnapshot_failsFast_whenStateTransitionIsRejected() throws Exception { + VMSnapshotVO snapshot = vmSnapshot(); + when(userVmDao.findById(VM_ID)).thenReturn(mock(UserVmVO.class)); + doThrow(new NoTransitionException("cannot expunge")).when(vmSnapshotHelper) + .vmSnapshotStateTransitTo(snapshot, VMSnapshot.Event.ExpungeRequested); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.deleteVMSnapshot(snapshot)); + + assertEquals("cannot expunge", ex.getMessage()); + verify(vmSnapshotDetailsDao, never()).findDetails(anyLong(), anyString()); + } + + @Test + void deleteVMSnapshot_wrapsOntapFailure_andDoesNotCompleteDeletion() { + VMSnapshotVO snapshot = vmSnapshot(); + prepareVmForDeleteOrRevert(snapshot); + stubPool(POOL_ID, "vol1"); + VMSnapshotDetailsVO row = detailRow(7L, detailValue("fv-1", "snap-uuid", "snap-name", "disk.qcow2", POOL_ID)); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(List.of(row)); + doThrow(new CloudRuntimeException("ontap down")).when(storageStrategy) + .deleteFlexVolSnapshotForCloudStackVolume("fv-1", "snap-uuid", "snap-name"); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.deleteVMSnapshot(snapshot)); + + assertTrue(ex.getMessage().contains("Delete of ONTAP VM Snapshot [snap-one]"), ex.getMessage()); + assertTrue(ex.getMessage().contains("ontap down"), ex.getMessage()); + verify(storageStrategy).deleteFlexVolSnapshotForCloudStackVolume("fv-1", "snap-uuid", "snap-name"); + verify(vmSnapshotDetailsDao, never()).remove(anyLong()); + verify(strategy, never()).processAnswer(any(), any(), any(), any()); + } + + // ------------------------------------------------------------------ revertVMSnapshot + + @Test + void revertVMSnapshot_restoresEachVolumeFromItsSnapshot() throws Exception { + VMSnapshotVO snapshot = vmSnapshot(); + List volumes = prepareVmForDeleteOrRevert(snapshot); + stubPool(POOL_ID, "vol1"); + JobResponse job = new JobResponse(); + when(storageStrategy.revertSnapshotForCloudStackVolume(any(), any(), any(), any(), any(), any())).thenReturn(job); + VMSnapshotDetailsVO row = detailRow(7L, detailValue("fv-1", "snap-uuid", "snap-name", "disk.qcow2", POOL_ID)); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(List.of(row)); + doNothing().when(strategy).processAnswer(any(), any(), any(), any()); + + assertTrue(strategy.revertVMSnapshot(snapshot)); + + org.mockito.ArgumentCaptor answer = org.mockito.ArgumentCaptor.forClass(com.cloud.agent.api.Answer.class); + verify(strategy).processAnswer(eq(snapshot), any(), answer.capture(), eq(null)); + assertTrue(answer.getValue() instanceof com.cloud.agent.api.RevertToVMSnapshotAnswer); + assertTrue(answer.getValue().getResult()); + assertEquals(volumes, ((com.cloud.agent.api.RevertToVMSnapshotAnswer)answer.getValue()).getVolumeTOs()); + verify(vmSnapshotHelper).vmSnapshotStateTransitTo(snapshot, VMSnapshot.Event.RevertRequested); + verify(storageStrategy).revertSnapshotForCloudStackVolume("snap-name", "fv-1", "snap-uuid", "disk.qcow2", null, "vol1"); + verify(storageStrategy).executeCliSfsrRestore(eq(job), anyString()); + verify(vmSnapshotHelper, never()).vmSnapshotStateTransitTo(any(), eq(VMSnapshot.Event.OperationFailed)); + } + + @Test + void revertVMSnapshot_alsoRevertsLegacyStorageSnapshots() throws Exception { + VMSnapshotVO snapshot = vmSnapshot(); + prepareVmForDeleteOrRevert(snapshot); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(Collections.emptyList()); + VMSnapshotDetailsVO hoistedRow2 = detailRow(8L, "legacy"); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, StorageVMSnapshotStrategy.STORAGE_SNAPSHOT)) + .thenReturn(List.of(hoistedRow2)); + doNothing().when(strategy).revertDiskSnapshot(any()); + doNothing().when(strategy).processAnswer(any(), any(), any(), any()); + + assertTrue(strategy.revertVMSnapshot(snapshot)); + + verify(strategy).revertDiskSnapshot(snapshot); + } + + @Test + void revertVMSnapshot_failsFast_whenStateTransitionIsRejected() throws Exception { + VMSnapshotVO snapshot = vmSnapshot(); + when(userVmDao.findById(VM_ID)).thenReturn(mock(UserVmVO.class)); + doThrow(new NoTransitionException("cannot revert")).when(vmSnapshotHelper) + .vmSnapshotStateTransitTo(snapshot, VMSnapshot.Event.RevertRequested); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.revertVMSnapshot(snapshot)); + + assertEquals("cannot revert", ex.getMessage()); + verify(vmSnapshotHelper, never()).vmSnapshotStateTransitTo(any(), eq(VMSnapshot.Event.OperationFailed)); + } + + @Test + void revertVMSnapshot_marksSnapshotFailed_whenRestoreFails() throws Exception { + VMSnapshotVO snapshot = vmSnapshot(); + prepareVmForDeleteOrRevert(snapshot); + stubPool(POOL_ID, "vol1"); + doThrow(new CloudRuntimeException("restore failed")).when(storageStrategy) + .revertSnapshotForCloudStackVolume("snap-name", "fv-1", "snap-uuid", "disk.qcow2", null, "vol1"); + VMSnapshotDetailsVO row = detailRow(7L, detailValue("fv-1", "snap-uuid", "snap-name", "disk.qcow2", POOL_ID)); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(List.of(row)); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.revertVMSnapshot(snapshot)); + + assertEquals("Revert ONTAP VM Snapshot [snap-one] failed.", ex.getMessage()); + verify(storageStrategy).revertSnapshotForCloudStackVolume("snap-name", "fv-1", "snap-uuid", "disk.qcow2", null, "vol1"); + verify(vmSnapshotHelper).vmSnapshotStateTransitTo(snapshot, VMSnapshot.Event.OperationFailed); + verify(strategy, never()).processAnswer(any(), any(), any(), any()); + } + + @Test + void revertVMSnapshot_stillReportsRestoreError_whenFailureTransitionIsAlsoRejected() throws Exception { + VMSnapshotVO snapshot = vmSnapshot(); + prepareVmForDeleteOrRevert(snapshot); + stubPool(POOL_ID, "vol1"); + doThrow(new CloudRuntimeException("restore failed")).when(storageStrategy) + .revertSnapshotForCloudStackVolume("n", "fv-1", "s", "disk.qcow2", null, "vol1"); + VMSnapshotDetailsVO hoistedRow3 = detailRow(7L, detailValue("fv-1", "s", "n", "disk.qcow2", POOL_ID)); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(List.of(hoistedRow3)); + doThrow(new NoTransitionException("stuck")).when(vmSnapshotHelper) + .vmSnapshotStateTransitTo(snapshot, VMSnapshot.Event.OperationFailed); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.revertVMSnapshot(snapshot)); + + assertTrue(ex.getMessage().contains("failed"), ex.getMessage()); + verify(storageStrategy).revertSnapshotForCloudStackVolume("n", "fv-1", "s", "disk.qcow2", null, "vol1"); + } + + // ------------------------------------------------------------------ deleteFlexVolSnapshots + + @Test + void deleteFlexVolSnapshots_deletesSharedSnapshotOnce_andRemovesAllItsRows() { + stubPool(POOL_ID, "vol1"); + VMSnapshotDetailsVO first = detailRow(1L, detailValue("fv-1", "snap-uuid", "snap", "a.qcow2", POOL_ID)); + VMSnapshotDetailsVO second = detailRow(2L, detailValue("fv-1", "snap-uuid", "snap", "b.qcow2", POOL_ID)); + + strategy.deleteFlexVolSnapshots(List.of(first, second)); + + verify(storageStrategy, times(1)).deleteFlexVolSnapshotForCloudStackVolume("fv-1", "snap-uuid", "snap"); + verify(vmSnapshotDetailsDao).remove(1L); + verify(vmSnapshotDetailsDao).remove(2L); + } + + @Test + void deleteFlexVolSnapshots_keepsFailedRow_butStillProcessesRemainingRows_thenThrowsFirstFailure() { + stubPool(POOL_ID, "vol1"); + VMSnapshotDetailsVO failing = detailRow(1L, detailValue("fv-1", "snap-a", "snap-a", "a.qcow2", POOL_ID)); + VMSnapshotDetailsVO succeeding = detailRow(2L, detailValue("fv-2", "snap-b", "snap-b", "b.qcow2", POOL_ID)); + doThrow(new CloudRuntimeException("first failed")).when(storageStrategy) + .deleteFlexVolSnapshotForCloudStackVolume("fv-1", "snap-a", "snap-a"); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFlexVolSnapshots(List.of(failing, succeeding))); + + assertEquals("first failed", ex.getMessage()); + verify(vmSnapshotDetailsDao, never()).remove(1L); + verify(vmSnapshotDetailsDao).remove(2L); + verify(storageStrategy).deleteFlexVolSnapshotForCloudStackVolume("fv-2", "snap-b", "snap-b"); + } + + @Test + void deleteFlexVolSnapshots_wrapsNonCloudStackExceptions() { + stubPool(POOL_ID, "vol1"); + doThrow(new IllegalStateException("boom")).when(storageStrategy) + .deleteFlexVolSnapshotForCloudStackVolume("fv-1", "snap", "snap"); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.deleteFlexVolSnapshots( + List.of(detailRow(1L, detailValue("fv-1", "snap", "snap", "a.qcow2", POOL_ID))))); + + assertTrue(ex.getMessage().contains("boom"), ex.getMessage()); + assertTrue(ex.getCause() instanceof IllegalStateException); + verify(storageStrategy).deleteFlexVolSnapshotForCloudStackVolume("fv-1", "snap", "snap"); + verify(vmSnapshotDetailsDao, never()).remove(anyLong()); + } + + @Test + void deleteFlexVolSnapshots_rejectsMalformedDetailValue() { + VMSnapshotDetailsVO malformed = detailRow(1L, "only::three::parts"); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.deleteFlexVolSnapshots(List.of(malformed))); + + assertTrue(ex.getMessage().contains("Invalid ONTAP FlexVol snapshot detail format"), ex.getMessage()); + verify(storageStrategy, never()).deleteFlexVolSnapshotForCloudStackVolume(any(), any(), any()); + } + + // ------------------------------------------------------------------ revertFlexVolSnapshots + + @Test + void revertFlexVolSnapshots_skipsLegacyRowsWithoutVolumePath() { + VMSnapshotDetailsVO legacy = detailRow(1L, "fv-1::snap-uuid::snap-name::" + POOL_ID); + + strategy.revertFlexVolSnapshots(List.of(legacy)); + + verify(storageStrategy, never()).revertSnapshotForCloudStackVolume(any(), any(), any(), any(), any(), any()); + verify(storageStrategy, never()).executeCliSfsrRestore(any(), any()); + } + + @Test + void revertFlexVolSnapshots_failsWhenFlexVolNameMissingFromPoolDetails() { + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(new HashMap<>()); + doReturn(storageStrategy).when(strategy).resolveStorageStrategy(any()); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> strategy.revertFlexVolSnapshots( + List.of(detailRow(1L, detailValue("fv-1", "snap", "snap", "a.qcow2", POOL_ID))))); + + assertTrue(ex.getMessage().contains("FlexVolume name not found"), ex.getMessage()); + } + + @Test + void revertFlexVolSnapshots_restoresEveryRow_includingLunPathsWithLeadingSlash() { + stubPool(POOL_ID, "vol1"); + stubPool(OTHER_POOL_ID, "vol2"); + JobResponse nfsJob = new JobResponse(); + JobResponse lunJob = new JobResponse(); + when(storageStrategy.revertSnapshotForCloudStackVolume(eq("snap-a"), any(), any(), eq("a.qcow2"), any(), any())) + .thenReturn(nfsJob); + when(storageStrategy.revertSnapshotForCloudStackVolume(eq("snap-b"), any(), any(), eq("/vol/vol2/lun1"), any(), any())) + .thenReturn(lunJob); + + strategy.revertFlexVolSnapshots(List.of( + detailRow(1L, detailValue("fv-1", "uuid-a", "snap-a", "a.qcow2", POOL_ID)), + detailRow(2L, detailValue("fv-2", "uuid-b", "snap-b", "/vol/vol2/lun1", OTHER_POOL_ID)))); + + verify(storageStrategy).executeCliSfsrRestore(eq(nfsJob), org.mockito.ArgumentMatchers.contains("/a.qcow2")); + verify(storageStrategy).executeCliSfsrRestore(eq(lunJob), org.mockito.ArgumentMatchers.contains("/vol/vol2/lun1")); + } + + // ------------------------------------------------------------------ scope helpers + + @Test + void consistencyGroupScopeFromPoolDetails_trimsValues_andTreatsBlankUuidAsMissing() { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.STORAGE_IP, " 10.0.0.1 "); + details.put(OntapStorageConstants.SVM_NAME, " svm1 "); + details.put(OntapStorageConstants.SVM_UUID, " "); + + OntapVMSnapshotStrategy.ConsistencyGroupScope scope = strategy.consistencyGroupScopeFromPoolDetails(details, POOL_ID); + + assertEquals("10.0.0.1|svm1", scope.identityKey()); + assertNull(scope.svmUuid); + } + + @Test + void consistencyGroupScopeFromPoolDetails_requiresStorageIpAndSvmName() { + Map noIp = new HashMap<>(); + noIp.put(OntapStorageConstants.SVM_NAME, "svm1"); + Map noSvm = new HashMap<>(); + noSvm.put(OntapStorageConstants.STORAGE_IP, "10.0.0.1"); + + assertTrue(assertThrows(CloudRuntimeException.class, + () -> strategy.consistencyGroupScopeFromPoolDetails(noIp, POOL_ID)).getMessage().contains("management IP")); + assertTrue(assertThrows(CloudRuntimeException.class, + () -> strategy.consistencyGroupScopeFromPoolDetails(noSvm, POOL_ID)).getMessage().contains("SVM name")); + } + + @Test + void resolveConsistencyGroupScope_returnsSharedScope() { + Map groups = new LinkedHashMap<>(); + groups.put("fv-1", group(POOL_ID, "10.0.0.1", "svm1", "svm-uuid")); + groups.put("fv-2", group(OTHER_POOL_ID, "10.0.0.1", "svm1-alias", "svm-uuid")); + + OntapVMSnapshotStrategy.ConsistencyGroupScope scope = strategy.resolveConsistencyGroupScope(groups); + + assertEquals("10.0.0.1|svm-uuid", scope.identityKey()); + } + + @Test + void resolveConsistencyGroupScope_rejectsVolumesFromDifferentSvmsOrClusters() { + Map differentSvm = new LinkedHashMap<>(); + differentSvm.put("fv-1", group(POOL_ID, "10.0.0.1", "svm1", null)); + differentSvm.put("fv-2", group(OTHER_POOL_ID, "10.0.0.1", "svm2", null)); + Map differentCluster = new LinkedHashMap<>(); + differentCluster.put("fv-1", group(POOL_ID, "10.0.0.1", "vs0", null)); + differentCluster.put("fv-2", group(OTHER_POOL_ID, "10.0.0.2", "vs0", null)); + + CloudRuntimeException differentSvmFailure = assertThrows(CloudRuntimeException.class, + () -> strategy.resolveConsistencyGroupScope(differentSvm)); + CloudRuntimeException differentClusterFailure = assertThrows(CloudRuntimeException.class, + () -> strategy.resolveConsistencyGroupScope(differentCluster)); + + assertEquals("ONTAP consistency groups require all VM volumes on the same ONTAP cluster and SVM. " + + "Found [storageIP=10.0.0.1, svmName=svm1] and [storageIP=10.0.0.1, svmName=svm2]", + differentSvmFailure.getMessage()); + assertEquals("ONTAP consistency groups require all VM volumes on the same ONTAP cluster and SVM. " + + "Found [storageIP=10.0.0.1, svmName=vs0] and [storageIP=10.0.0.2, svmName=vs0]", + differentClusterFailure.getMessage()); + } + + @Test + void resolveConsistencyGroupScope_returnsNull_forNoGroups() { + assertNull(strategy.resolveConsistencyGroupScope(new HashMap<>())); + } + + @Test + void consistencyGroupScope_buildsOntapReferencesByUuidWhenAvailableOtherwiseName() { + OntapVMSnapshotStrategy.ConsistencyGroupScope byUuid = + new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", "svm-uuid"); + OntapVMSnapshotStrategy.ConsistencyGroupScope byName = + new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", null); + + assertEquals(Map.of("uuid", "svm-uuid"), byUuid.toOntapSvmReference()); + assertEquals(Map.of("name", "svm1"), byName.toOntapSvmReference()); + assertEquals("svm-uuid", byUuid.toOntapSvm().getUuid()); + assertNull(byUuid.toOntapSvm().getName()); + assertEquals("svm1", byName.toOntapSvm().getName()); + assertNull(byName.toOntapSvm().getUuid()); + + Map uuidQuery = new HashMap<>(); + byUuid.applySvmQueryFilter(uuidQuery); + Map nameQuery = new HashMap<>(); + byName.applySvmQueryFilter(nameQuery); + assertEquals(Map.of("svm.uuid", "svm-uuid"), uuidQuery); + assertEquals(Map.of("svm.name", "svm1"), nameQuery); + + assertEquals("storageIP=10.0.0.1, svmUUID=svm-uuid, svmName=svm1", byUuid.toString()); + assertEquals("storageIP=10.0.0.1, svmName=svm1", byName.toString()); + } + + @Test + void consistencyGroupScope_matchesOnlyIdenticalIdentity() { + OntapVMSnapshotStrategy.ConsistencyGroupScope scope = + new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", null); + + assertTrue(scope.matches(new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", null))); + assertFalse(scope.matches(new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", "uuid"))); + assertFalse(scope.matches(null)); + } + + // ------------------------------------------------------------------ CG operations + + @Test + void buildTemporaryConsistencyGroupName_usesPrefixAndSnapshotId() { + assertEquals(OntapStorageConstants.ONTAP_TEMP_CG_PREFIX + SNAPSHOT_ID, + strategy.buildTemporaryConsistencyGroupName(vmSnapshot())); + } + + @Test + void createTemporaryConsistencyGroup_requiresScope() { + assertThrows(CloudRuntimeException.class, () -> strategy.createTemporaryConsistencyGroup( + snapshotClient, storageStrategy, AUTH, "cg", null, new LinkedHashSet<>(List.of("fv-1")))); + verify(snapshotClient, never()).createConsistencyGroup(any(), any()); + } + + @Test + void createTemporaryConsistencyGroup_createsGroupWithAllFlexVols_andReturnsResolvedUuid() { + OntapVMSnapshotStrategy.ConsistencyGroupScope scope = + new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", null); + JobResponse job = new JobResponse(); + when(snapshotClient.createConsistencyGroup(eq(AUTH), any(ConsistencyGroup.class))).thenReturn(job); + ConsistencyGroup found = new ConsistencyGroup("cg"); + found.setUuid("cg-uuid"); + OntapResponse groups = new OntapResponse<>(); + groups.setRecords(List.of(found)); + when(snapshotClient.getConsistencyGroups(eq(AUTH), anyMap())).thenReturn(groups); + + String uuid = strategy.createTemporaryConsistencyGroup(snapshotClient, storageStrategy, AUTH, "cg", scope, + new LinkedHashSet<>(List.of("fv-1", "fv-2"))); + + assertEquals("cg-uuid", uuid); + org.mockito.ArgumentCaptor payload = org.mockito.ArgumentCaptor.forClass(ConsistencyGroup.class); + verify(snapshotClient).createConsistencyGroup(eq(AUTH), payload.capture()); + assertEquals("cg", payload.getValue().getName()); + assertEquals("svm1", payload.getValue().getSvm().getName()); + assertEquals(2, payload.getValue().getVolumes().size()); + assertEquals("fv-1", payload.getValue().getVolumes().get(0).getUuid()); + verify(storageStrategy).pollJobIfPresent(eq(job), anyString()); + } + + @Test + void createTemporaryConsistencyGroup_fails_whenCreatedGroupCannotBeResolved() { + OntapVMSnapshotStrategy.ConsistencyGroupScope scope = + new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", null); + when(snapshotClient.getConsistencyGroups(eq(AUTH), anyMap())).thenReturn(new OntapResponse<>()); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.createTemporaryConsistencyGroup(snapshotClient, storageStrategy, AUTH, "cg", scope, + new LinkedHashSet<>(List.of("fv-1")))); + + assertTrue(ex.getMessage().contains("Unable to resolve temporary consistency group UUID"), ex.getMessage()); + } + + @Test + void resolveConsistencyGroupUuidByName_handlesMissingRecords() { + OntapVMSnapshotStrategy.ConsistencyGroupScope scope = + new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", "svm-uuid"); + OntapResponse nullRecord = new OntapResponse<>(); + nullRecord.setRecords(Collections.singletonList(null)); + OntapResponse empty = new OntapResponse<>(); + empty.setRecords(Collections.emptyList()); + when(snapshotClient.getConsistencyGroups(eq(AUTH), anyMap())) + .thenReturn(null) + .thenReturn(empty) + .thenReturn(nullRecord); + + assertNull(strategy.resolveConsistencyGroupUuidByName(snapshotClient, AUTH, "cg", scope)); + assertNull(strategy.resolveConsistencyGroupUuidByName(snapshotClient, AUTH, "cg", scope)); + assertNull(strategy.resolveConsistencyGroupUuidByName(snapshotClient, AUTH, "cg", scope)); + + org.mockito.ArgumentCaptor> queries = org.mockito.ArgumentCaptor.forClass(Map.class); + verify(snapshotClient, times(3)).getConsistencyGroups(eq(AUTH), queries.capture()); + for (Map query : queries.getAllValues()) { + assertEquals("cg", query.get("name")); + assertEquals("svm-uuid", query.get("svm.uuid")); + assertEquals("uuid,name", query.get("fields")); + } + } + + @Test + void startConsistencyGroupSnapshot_extractsSnapshotUuidFromJobDescription() { + Job completed = new Job(); + completed.setDescription("POST /api/application/consistency-groups/cg-uuid/snapshots/cg-snap-uuid?action=start"); + when(storageStrategy.pollJobIfPresentAndGetCompletedJob(any(), anyString())).thenReturn(completed); + + assertEquals("cg-snap-uuid", + strategy.startConsistencyGroupSnapshot(snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap")); + + org.mockito.ArgumentCaptor payload = + org.mockito.ArgumentCaptor.forClass(ConsistencyGroupSnapshot.class); + verify(snapshotClient).createConsistencyGroupSnapshot(eq(AUTH), eq("cg-uuid"), payload.capture()); + assertEquals("snap", payload.getValue().getName()); + assertEquals("start", payload.getValue().getAction()); + } + + @Test + void startConsistencyGroupSnapshot_returnsNull_whenJobGivesNoUuid() { + Job withoutUuid = new Job(); + withoutUuid.setDescription("POST /api/something/else"); + when(storageStrategy.pollJobIfPresentAndGetCompletedJob(any(), anyString())) + .thenReturn(null) + .thenReturn(withoutUuid); + + assertNull(strategy.startConsistencyGroupSnapshot(snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap")); + assertNull(strategy.startConsistencyGroupSnapshot(snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap")); + + org.mockito.ArgumentCaptor payloads = + org.mockito.ArgumentCaptor.forClass(ConsistencyGroupSnapshot.class); + verify(snapshotClient, times(2)).createConsistencyGroupSnapshot(eq(AUTH), eq("cg-uuid"), payloads.capture()); + for (ConsistencyGroupSnapshot payload : payloads.getAllValues()) { + assertEquals("snap", payload.getName()); + assertEquals("start", payload.getAction()); + } + } + + @Test + void commitAndDeleteConsistencyGroup_pollTheirJobs() { + JobResponse commitJob = new JobResponse(); + JobResponse deleteJob = new JobResponse(); + when(snapshotClient.commitConsistencyGroupSnapshot(eq(AUTH), eq("cg-uuid"), eq("snap-uuid"), any())) + .thenReturn(commitJob); + when(snapshotClient.deleteConsistencyGroup(AUTH, "cg-uuid")).thenReturn(deleteJob); + + strategy.commitConsistencyGroupSnapshot(snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap-uuid"); + strategy.deleteTemporaryConsistencyGroup(snapshotClient, storageStrategy, AUTH, "cg-uuid"); + + org.mockito.ArgumentCaptor commitPayload = + org.mockito.ArgumentCaptor.forClass(ConsistencyGroupSnapshot.class); + verify(snapshotClient).commitConsistencyGroupSnapshot(eq(AUTH), eq("cg-uuid"), eq("snap-uuid"), commitPayload.capture()); + assertEquals("commit", commitPayload.getValue().getAction()); + + verify(storageStrategy).pollJobIfPresent(eq(commitJob), anyString()); + verify(storageStrategy).pollJobIfPresent(eq(deleteJob), anyString()); + } + + @Test + void resolveStartedConsistencyGroupSnapshotUuid_prefersUuidFromJob() { + doReturn("from-job").when(strategy).startConsistencyGroupSnapshot(any(), any(), any(), any(), any()); + + assertEquals("from-job", strategy.resolveStartedConsistencyGroupSnapshotUuid( + snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap")); + verify(strategy, never()).resolveConsistencyGroupSnapshotUuid(any(), any(), any(), any(), any()); + } + + @Test + void resolveStartedConsistencyGroupSnapshotUuid_fallsBackToLookup_whenJobGivesNone() { + doReturn(null).doReturn("").when(strategy).startConsistencyGroupSnapshot( + snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap"); + doReturn("from-lookup").when(strategy).resolveConsistencyGroupSnapshotUuid( + snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap"); + + assertEquals("from-lookup", strategy.resolveStartedConsistencyGroupSnapshotUuid( + snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap")); + assertEquals("from-lookup", strategy.resolveStartedConsistencyGroupSnapshotUuid( + snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap")); + verify(strategy, times(2)).startConsistencyGroupSnapshot( + snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap"); + verify(strategy, times(2)).resolveConsistencyGroupSnapshotUuid( + snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap"); + } + + @Test + void resolveConsistencyGroupSnapshotUuid_returnsOnFirstSuccessfulLookup() { + doReturn("cg-snap-uuid").when(strategy).lookupConsistencyGroupSnapshotUuid( + snapshotClient, AUTH, "cg-uuid", "snap"); + + assertEquals("cg-snap-uuid", strategy.resolveConsistencyGroupSnapshotUuid( + snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap")); + verify(strategy, times(1)).lookupConsistencyGroupSnapshotUuid(snapshotClient, AUTH, "cg-uuid", "snap"); + } + + @Test + void resolveConsistencyGroupSnapshotUuid_restoresInterruptFlag_whenInterruptedWhileWaiting() { + doReturn(null).when(strategy).lookupConsistencyGroupSnapshotUuid(snapshotClient, AUTH, "cg-uuid", "snap"); + Thread.currentThread().interrupt(); + try { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> + strategy.resolveConsistencyGroupSnapshotUuid(snapshotClient, storageStrategy, AUTH, "cg-uuid", "snap")); + + assertEquals("Interrupted while resolving CG snapshot [snap]", ex.getMessage()); + assertTrue(Thread.currentThread().isInterrupted()); + verify(strategy).lookupConsistencyGroupSnapshotUuid(snapshotClient, AUTH, "cg-uuid", "snap"); + } finally { + Thread.interrupted(); + } + } + + @Test + void lookupConsistencyGroupSnapshotUuid_matchesByNameFirst() { + when(snapshotClient.getConsistencyGroupSnapshots(eq(AUTH), eq("cg-uuid"), anyMap())) + .thenReturn(cgSnapshots(cgSnapshot("snap", "uuid-1"))); + + assertEquals("uuid-1", strategy.lookupConsistencyGroupSnapshotUuid(snapshotClient, AUTH, "cg-uuid", "snap")); + verify(snapshotClient, times(1)).getConsistencyGroupSnapshots(eq(AUTH), eq("cg-uuid"), anyMap()); + } + + @Test + void lookupConsistencyGroupSnapshotUuid_fallsBackToListingAllSnapshots() { + when(snapshotClient.getConsistencyGroupSnapshots(eq(AUTH), eq("cg-uuid"), anyMap())) + .thenReturn(cgSnapshots()) + .thenReturn(cgSnapshots(cgSnapshot("other", "uuid-0"), cgSnapshot("snap", "uuid-1"))); + + assertEquals("uuid-1", strategy.lookupConsistencyGroupSnapshotUuid(snapshotClient, AUTH, "cg-uuid", "snap")); + verify(snapshotClient, times(2)).getConsistencyGroupSnapshots(eq(AUTH), eq("cg-uuid"), anyMap()); + } + + @Test + void lookupConsistencyGroupSnapshotUuid_returnsNull_whenNoUsableMatch() { + when(snapshotClient.getConsistencyGroupSnapshots(eq(AUTH), eq("cg-uuid"), anyMap())) + .thenReturn(null) + .thenReturn(cgSnapshots(cgSnapshot("other", "uuid-0"), cgSnapshot("snap", ""), cgSnapshot("snap", null))); + + assertNull(strategy.lookupConsistencyGroupSnapshotUuid(snapshotClient, AUTH, "cg-uuid", "snap")); + + org.mockito.ArgumentCaptor> queries = org.mockito.ArgumentCaptor.forClass(Map.class); + verify(snapshotClient, times(2)).getConsistencyGroupSnapshots(eq(AUTH), eq("cg-uuid"), queries.capture()); + assertEquals("snap", queries.getAllValues().get(0).get("name")); + assertEquals("uuid,name", queries.getAllValues().get(0).get("fields")); + assertNull(queries.getAllValues().get(1).get("name")); + assertEquals("uuid,name", queries.getAllValues().get(1).get("fields")); + } + + @Test + void resolveSnapshotUuid_returnsUuidOfFirstRecord() { + FlexVolSnapshot record = new FlexVolSnapshot("snap", "comment"); + record.setUuid("snap-uuid"); + OntapResponse response = new OntapResponse<>(); + response.setRecords(List.of(record)); + when(snapshotClient.getSnapshots(eq(AUTH), eq("fv-1"), anyMap())).thenReturn(response); + + assertEquals("snap-uuid", strategy.resolveSnapshotUuid(snapshotClient, AUTH, "fv-1", "snap")); + } + + @Test + void resolveSnapshotUuid_failsWhenSnapshotNotVisibleAfterCreation() { + OntapResponse empty = new OntapResponse<>(); + empty.setRecords(Collections.emptyList()); + when(snapshotClient.getSnapshots(eq(AUTH), eq("fv-1"), anyMap())) + .thenReturn(null) + .thenReturn(empty); + + for (int i = 0; i < 2; i++) { + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.resolveSnapshotUuid(snapshotClient, AUTH, "fv-1", "snap")); + assertTrue(ex.getMessage().contains("Could not find FlexVolume snapshot"), ex.getMessage()); + } + } + + // ------------------------------------------------------------------ groupVolumesByFlexVol + + @Test + void groupVolumesByFlexVol_groupsVolumesSharingAFlexVol() { + VolumeObjectTO to1 = mock(VolumeObjectTO.class); + when(to1.getId()).thenReturn(1L); + VolumeObjectTO to2 = mock(VolumeObjectTO.class); + when(to2.getId()).thenReturn(2L); + VolumeVO vol1 = mock(VolumeVO.class); + when(vol1.getId()).thenReturn(1L); + when(vol1.getPoolId()).thenReturn(POOL_ID); + VolumeVO vol2 = mock(VolumeVO.class); + when(vol2.getId()).thenReturn(2L); + when(vol2.getPoolId()).thenReturn(POOL_ID); + when(volumeDao.findById(1L)).thenReturn(vol1); + when(volumeDao.findById(2L)).thenReturn(vol2); + Map details = new HashMap<>(); + details.put(OntapStorageConstants.VOLUME_UUID, "fv-1"); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(details); + + Map groups = strategy.groupVolumesByFlexVol(List.of(to1, to2)); + + assertEquals(1, groups.size()); + assertEquals(List.of(1L, 2L), groups.get("fv-1").volumeIds); + assertEquals(POOL_ID, groups.get("fv-1").poolId); + } + + @Test + void groupVolumesByFlexVol_failsForUnknownVolumeOrMissingFlexVolUuid() { + VolumeObjectTO unknown = mock(VolumeObjectTO.class); + when(unknown.getId()).thenReturn(1L); + when(volumeDao.findById(1L)).thenReturn(null); + VolumeObjectTO noPool = mock(VolumeObjectTO.class); + when(noPool.getId()).thenReturn(2L); + VolumeVO noPoolVolume = mock(VolumeVO.class); + when(noPoolVolume.getPoolId()).thenReturn(null); + when(volumeDao.findById(2L)).thenReturn(noPoolVolume); + VolumeObjectTO noFlexVol = mock(VolumeObjectTO.class); + when(noFlexVol.getId()).thenReturn(3L); + VolumeVO noFlexVolVolume = mock(VolumeVO.class); + when(noFlexVolVolume.getPoolId()).thenReturn(POOL_ID); + when(volumeDao.findById(3L)).thenReturn(noFlexVolVolume); + when(storagePoolDetailsDao.listDetailsKeyPairs(POOL_ID)).thenReturn(new HashMap<>()); + + assertThrows(CloudRuntimeException.class, () -> strategy.groupVolumesByFlexVol(List.of(unknown))); + assertThrows(CloudRuntimeException.class, () -> strategy.groupVolumesByFlexVol(List.of(noPool))); + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, + () -> strategy.groupVolumesByFlexVol(List.of(noFlexVol))); + assertTrue(ex.getMessage().contains("FlexVolume UUID not found"), ex.getMessage()); + } + + // ------------------------------------------------------------------ single-FlexVol create negatives + + @Test + void createVmSnapshotsViaSingleFlexVol_failsWhenOntapReturnsNoJob() { + VMSnapshotVO snapshot = vmSnapshot(); + UserVmVO userVm = mock(UserVmVO.class); + when(userVm.getInstanceName()).thenReturn("i-2-100-VM"); + doReturn(storageStrategy).when(strategy).resolveStorageStrategy(any()); + when(storageStrategy.getSnapshotFeignClient()).thenReturn(snapshotClient); + when(storageStrategy.getAuthHeader()).thenReturn(AUTH); + when(snapshotClient.createSnapshot(eq(AUTH), eq("fv-1"), any(FlexVolSnapshot.class))).thenReturn(null); + Map groups = new LinkedHashMap<>(); + groups.put("fv-1", group(POOL_ID, "10.0.0.1", "svm1", null)); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> + strategy.createVmSnapshotsViaSingleFlexVol(snapshot, userVm, groups, "snap", new java.util.ArrayList<>())); + + assertTrue(ex.getMessage().contains("Failed to initiate FlexVolume snapshot"), ex.getMessage()); + } + + @Test + void createVmSnapshotsViaSingleFlexVol_failsWhenSnapshotJobDoesNotSucceed() { + VMSnapshotVO snapshot = vmSnapshot(); + UserVmVO userVm = mock(UserVmVO.class); + when(userVm.getInstanceName()).thenReturn("i-2-100-VM"); + doReturn(storageStrategy).when(strategy).resolveStorageStrategy(any()); + when(storageStrategy.getSnapshotFeignClient()).thenReturn(snapshotClient); + when(storageStrategy.getAuthHeader()).thenReturn(AUTH); + JobResponse response = new JobResponse(); + Job job = new Job(); + job.setUuid("job-1"); + response.setJob(job); + when(snapshotClient.createSnapshot(eq(AUTH), eq("fv-1"), any(FlexVolSnapshot.class))).thenReturn(response); + when(storageStrategy.jobPollForSuccess(eq("job-1"), org.mockito.ArgumentMatchers.anyInt(), + org.mockito.ArgumentMatchers.anyInt())).thenReturn(false); + Map groups = new LinkedHashMap<>(); + groups.put("fv-1", group(POOL_ID, "10.0.0.1", "svm1", null)); + + CloudRuntimeException ex = assertThrows(CloudRuntimeException.class, () -> + strategy.createVmSnapshotsViaSingleFlexVol(snapshot, userVm, groups, "snap", new java.util.ArrayList<>())); + + assertTrue(ex.getMessage().contains("snapshot job failed"), ex.getMessage()); + verify(snapshotClient, never()).getSnapshots(any(), any(), anyMap()); + } + + // ------------------------------------------------------------------ canHandle / eligibility edge cases + + private void stubVmWithVolume(VirtualMachine.State vmState, Long poolId, StoragePoolVO pool) { + UserVmVO userVm = mock(UserVmVO.class); + when(userVm.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(userVm.getState()).thenReturn(vmState); + when(userVmDao.findById(VM_ID)).thenReturn(userVm); + VolumeVO volume = mock(VolumeVO.class); + when(volume.getId()).thenReturn(1L); + when(volume.getPoolId()).thenReturn(poolId); + when(volumeDao.findByInstance(VM_ID)).thenReturn(List.of(volume)); + if (poolId != null) { + when(storagePool.findById(poolId)).thenReturn(pool); + } + } + + @Test + void canHandleVm_rejectsVmsThatAreNeitherRunningNorStopped() { + stubVmWithVolume(VirtualMachine.State.Migrating, POOL_ID, mock(StoragePoolVO.class)); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(VM_ID, POOL_ID, false)); + verify(volumeDao, never()).findByInstance(anyLong()); + } + + @Test + void canHandleVm_rejectsVolumeWithoutPool() { + stubVmWithVolume(VirtualMachine.State.Running, null, null); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(VM_ID, POOL_ID, false)); + } + + @Test + void canHandleVm_rejectsVolumeWhosePoolNoLongerExists() { + stubVmWithVolume(VirtualMachine.State.Running, POOL_ID, null); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(VM_ID, POOL_ID, false)); + } + + @Test + void canHandleVm_rejectsMemorySnapshotsWithoutLookingUpTheVm() { + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(VM_ID, POOL_ID, true)); + verify(userVmDao, never()).findById(anyLong()); + } + + @Test + void canHandleSnapshot_rejectsExistingSnapshotWhenVolumesMovedOffOntap() { + VMSnapshotVO existing = vmSnapshot(); + when(existing.getState()).thenReturn(VMSnapshot.State.Ready); + VMSnapshotDetailsVO hoistedRow4 = detailRow(1L, "x"); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(List.of(hoistedRow4)); + when(userVmDao.findById(VM_ID)).thenReturn(null); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(existing)); + } + + @Test + void canHandleSnapshot_handlesExistingSnapshotWithOntapDetailsWhenVolumesStillOnOntap() { + VMSnapshotVO existing = vmSnapshot(); + when(existing.getState()).thenReturn(VMSnapshot.State.Ready); + VMSnapshotDetailsVO hoistedRow5 = detailRow(1L, "x"); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(List.of(hoistedRow5)); + StoragePoolVO pool = mock(StoragePoolVO.class); + when(pool.isManaged()).thenReturn(true); + when(pool.getStorageProviderName()).thenReturn(OntapStorageConstants.ONTAP_PLUGIN_NAME); + stubVmWithVolume(VirtualMachine.State.Running, POOL_ID, pool); + + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(existing)); + } + + @Test + void canHandleSnapshot_rejectsExistingSnapshotWithNoOntapOrLegacyDetails() { + VMSnapshotVO existing = vmSnapshot(); + when(existing.getState()).thenReturn(VMSnapshot.State.Ready); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(Collections.emptyList()); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, StorageVMSnapshotStrategy.STORAGE_SNAPSHOT)) + .thenReturn(Collections.emptyList()); + + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(existing)); + } + + @Test + void canHandleSnapshot_acceptsLegacyStorageSnapshotsWhileVolumesAreOnOntap() { + VMSnapshotVO existing = vmSnapshot(); + when(existing.getState()).thenReturn(VMSnapshot.State.Ready); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, OntapStorageConstants.ONTAP_FLEXVOL_SNAPSHOT)) + .thenReturn(Collections.emptyList()); + VMSnapshotDetailsVO hoistedRow6 = detailRow(1L, "legacy"); + when(vmSnapshotDetailsDao.findDetails(SNAPSHOT_ID, StorageVMSnapshotStrategy.STORAGE_SNAPSHOT)) + .thenReturn(List.of(hoistedRow6)); + StoragePoolVO pool = mock(StoragePoolVO.class); + when(pool.isManaged()).thenReturn(true); + when(pool.getStorageProviderName()).thenReturn(OntapStorageConstants.ONTAP_PLUGIN_NAME); + stubVmWithVolume(VirtualMachine.State.Stopped, POOL_ID, pool); + + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(existing)); + } + + @Test + void resolveConsistencyGroupUuidByName_queriesByNameAndSvmUuid_whenUuidIsKnown() { + OntapVMSnapshotStrategy.ConsistencyGroupScope scope = + new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", "svm-uuid"); + ConsistencyGroup found = new ConsistencyGroup("cg"); + found.setUuid("cg-uuid"); + OntapResponse groups = new OntapResponse<>(); + groups.setRecords(List.of(found)); + when(snapshotClient.getConsistencyGroups(eq(AUTH), anyMap())).thenReturn(groups); + + assertEquals("cg-uuid", strategy.resolveConsistencyGroupUuidByName(snapshotClient, AUTH, "cg", scope)); + + @SuppressWarnings("unchecked") + org.mockito.ArgumentCaptor> query = org.mockito.ArgumentCaptor.forClass(Map.class); + verify(snapshotClient).getConsistencyGroups(eq(AUTH), query.capture()); + assertEquals("cg", query.getValue().get("name")); + assertEquals("svm-uuid", query.getValue().get("svm.uuid")); + assertFalse(query.getValue().containsKey("svm.name")); + assertEquals("uuid,name", query.getValue().get("fields")); + } + + @Test + void resolveConsistencyGroupUuidByName_queriesBySvmName_whenUuidIsUnknown() { + OntapVMSnapshotStrategy.ConsistencyGroupScope scope = + new OntapVMSnapshotStrategy.ConsistencyGroupScope("10.0.0.1", "svm1", null); + when(snapshotClient.getConsistencyGroups(eq(AUTH), anyMap())).thenReturn(new OntapResponse<>()); + + assertNull(strategy.resolveConsistencyGroupUuidByName(snapshotClient, AUTH, "cg", scope)); + + @SuppressWarnings("unchecked") + org.mockito.ArgumentCaptor> query = org.mockito.ArgumentCaptor.forClass(Map.class); + verify(snapshotClient).getConsistencyGroups(eq(AUTH), query.capture()); + assertEquals("svm1", query.getValue().get("svm.name")); + assertFalse(query.getValue().containsKey("svm.uuid")); + } + + @Test + void resolveStorageStrategy_delegatesToStorageUtilsWithTheGivenPoolDetails() { + Map details = new HashMap<>(); + details.put(OntapStorageConstants.SVM_NAME, "svm1"); + try (MockedStatic utils = Mockito.mockStatic(OntapStorageUtils.class)) { + utils.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(details)).thenReturn(storageStrategy); + + assertSame(storageStrategy, strategy.resolveStorageStrategy(details)); + + utils.verify(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(details)); + } + } + } }