diff --git a/plugins/storage/volume/ontap/pom.xml b/plugins/storage/volume/ontap/pom.xml
index 1ffb2ceb4808..449c77dcbf06 100644
--- a/plugins/storage/volume/ontap/pom.xml
+++ b/plugins/storage/volume/ontap/pom.xml
@@ -209,6 +209,13 @@
report
+
+
+
+ org/apache/cloudstack/storage/feign/**
+
+
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