diff --git a/api/src/main/java/com/cloud/vm/VmDetailConstants.java b/api/src/main/java/com/cloud/vm/VmDetailConstants.java
index 521633a0c597..13b6d28e6ed3 100644
--- a/api/src/main/java/com/cloud/vm/VmDetailConstants.java
+++ b/api/src/main/java/com/cloud/vm/VmDetailConstants.java
@@ -70,6 +70,10 @@ public interface VmDetailConstants {
String CPU_SPEED = "cpuSpeed";
String MEMORY = "memory";
+ // VM deployment with custom root disk offering params
+ String MIN_IOPS = "minIops";
+ String MAX_IOPS = "maxIops";
+
// Misc details for internal usage (not to be set/changed by user or admin)
String CPU_OVER_COMMIT_RATIO = "cpuOvercommitRatio";
String MEMORY_OVER_COMMIT_RATIO = "memoryOvercommitRatio";
diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java
index fa55b424eaf3..4640480d29e7 100644
--- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java
+++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java
@@ -53,7 +53,7 @@ public class UpdateStoragePoolCmd extends BaseCmd {
@Parameter(name = ApiConstants.TAGS, type = CommandType.LIST, collectionType = CommandType.STRING, description = "Comma-separated list of tags for the storage pool")
private List tags;
- @Parameter(name = ApiConstants.CAPACITY_IOPS, type = CommandType.LONG, required = false, description = "IOPS CloudStack can provision from this storage pool", validations={ApiArgValidator.PositiveNumber})
+ @Parameter(name = ApiConstants.CAPACITY_IOPS, type = CommandType.LONG, required = false, description = "IOPS CloudStack can provision from this storage pool", validations = {ApiArgValidator.PositiveNumber})
private Long capacityIops;
@Parameter(name = ApiConstants.CAPACITY_BYTES, type = CommandType.LONG, required = false, description = "Bytes CloudStack can provision from this storage pool",validations={ApiArgValidator.PositiveNumber})
diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java
index f8f744285c04..60f4f308503d 100644
--- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java
+++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java
@@ -15,14 +15,14 @@
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.command.user.volume;
-import org.apache.cloudstack.api.BaseAsyncCmd;
-
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.api.ACL;
import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiArgValidator;
import org.apache.cloudstack.api.ApiCommandResourceType;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ResponseObject.ResponseView;
import org.apache.cloudstack.api.ServerApiException;
@@ -60,7 +60,7 @@ public class ResizeVolumeCmd extends BaseAsyncCmd implements UserCmd {
@Parameter(name = ApiConstants.MAX_IOPS, type = CommandType.LONG, required = false, description = "New maximum number of IOPS")
private Long maxIops;
- @Parameter(name = ApiConstants.SIZE, type = CommandType.LONG, required = false, description = "New volume size in GB")
+ @Parameter(name = ApiConstants.SIZE, type = CommandType.LONG, required = false, description = "New volume size in GB",validations = {ApiArgValidator.PositiveNumber})
private Long size;
@Parameter(name = ApiConstants.SHRINK_OK, type = CommandType.BOOLEAN, required = false, description = "Verify OK to Shrink")
diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/CloudOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/CloudOrchestrator.java
index 9f6d02cc1234..9a06e7285e4d 100644
--- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/CloudOrchestrator.java
+++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/CloudOrchestrator.java
@@ -61,14 +61,12 @@
import com.cloud.vm.NicProfile;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.VmDetailConstants;
import com.cloud.vm.VmDiskInfo;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDetailsDao;
import com.cloud.vm.dao.VMInstanceDao;
-import static org.apache.cloudstack.api.ApiConstants.MAX_IOPS;
-import static org.apache.cloudstack.api.ApiConstants.MIN_IOPS;
-
@Component
public class CloudOrchestrator implements OrchestrationService {
@@ -205,8 +203,8 @@ public VirtualMachineEntity createVirtualMachine(String id, String owner, String
Map userVmDetails = _vmInstanceDetailsDao.listDetailsKeyPairs(vm.getId());
if (userVmDetails != null) {
- String minIops = userVmDetails.get(MIN_IOPS);
- String maxIops = userVmDetails.get(MAX_IOPS);
+ String minIops = userVmDetails.get(VmDetailConstants.MIN_IOPS);
+ String maxIops = userVmDetails.get(VmDetailConstants.MAX_IOPS);
rootDiskOfferingInfo.setMinIops(minIops != null && minIops.trim().length() > 0 ? Long.parseLong(minIops) : null);
rootDiskOfferingInfo.setMaxIops(maxIops != null && maxIops.trim().length() > 0 ? Long.parseLong(maxIops) : null);
diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/CloudOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/CloudOrchestratorTest.java
new file mode 100644
index 000000000000..fd7deac04548
--- /dev/null
+++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/CloudOrchestratorTest.java
@@ -0,0 +1,111 @@
+// 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.engine.orchestration;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.offering.DiskOfferingInfo;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.service.dao.ServiceOfferingDao;
+import com.cloud.storage.DiskOfferingVO;
+import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.dao.DiskOfferingDao;
+import com.cloud.storage.dao.VMTemplateDao;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.vm.VMInstanceVO;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.VmDetailConstants;
+import com.cloud.vm.dao.VMInstanceDao;
+import com.cloud.vm.dao.VMInstanceDetailsDao;
+import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntityImpl;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class CloudOrchestratorTest {
+
+ private static final long VM_ID = 1L;
+ private static final long SERVICE_OFFERING_ID = 2L;
+ private static final long ROOT_DISK_OFFERING_ID = 3L;
+ private static final String TEMPLATE_ID = "4";
+
+ @InjectMocks
+ private CloudOrchestrator cloudOrchestrator = new CloudOrchestrator();
+
+ @Mock
+ private VirtualMachineManager _itMgr;
+ @Mock
+ private VMTemplateDao _templateDao;
+ @Mock
+ private VMInstanceDao _vmDao;
+ @Mock
+ private VMInstanceDetailsDao _vmInstanceDetailsDao;
+ @Mock
+ private ServiceOfferingDao _serviceOfferingDao;
+ @Mock
+ private DiskOfferingDao _diskOfferingDao;
+
+ @Test
+ public void createVirtualMachineSetsCustomIopsFromVmDetails() throws Exception {
+ VMInstanceVO vm = Mockito.mock(VMInstanceVO.class);
+ ServiceOfferingVO serviceOffering = Mockito.mock(ServiceOfferingVO.class);
+ DiskOfferingVO rootDiskOffering = Mockito.mock(DiskOfferingVO.class);
+ VMTemplateVO template = Mockito.mock(VMTemplateVO.class);
+ VirtualMachineEntityImpl vmEntity = Mockito.mock(VirtualMachineEntityImpl.class);
+
+ Mockito.when(_vmDao.findByUuid("vm-uuid")).thenReturn(vm);
+ Mockito.when(vm.getId()).thenReturn(VM_ID);
+ Mockito.when(vm.getServiceOfferingId()).thenReturn(SERVICE_OFFERING_ID);
+ Mockito.when(vm.getInstanceName()).thenReturn("i-1-1-VM");
+ Mockito.when(_serviceOfferingDao.findById(VM_ID, SERVICE_OFFERING_ID)).thenReturn(serviceOffering);
+ Mockito.when(_diskOfferingDao.findById(ROOT_DISK_OFFERING_ID)).thenReturn(rootDiskOffering);
+ Mockito.when(rootDiskOffering.isCustomizedIops()).thenReturn(true);
+ Mockito.when(_templateDao.findById(Long.valueOf(TEMPLATE_ID))).thenReturn(template);
+
+ Map details = new HashMap<>();
+ details.put(VmDetailConstants.MIN_IOPS, "100");
+ details.put(VmDetailConstants.MAX_IOPS, "1000");
+ Mockito.when(_vmInstanceDetailsDao.listDetailsKeyPairs(VM_ID)).thenReturn(details);
+
+ try (MockedStatic componentContext = Mockito.mockStatic(ComponentContext.class)) {
+ componentContext.when(() -> ComponentContext.inject(VirtualMachineEntityImpl.class)).thenReturn(vmEntity);
+
+ cloudOrchestrator.createVirtualMachine("vm-uuid", "owner", TEMPLATE_ID, "host", "display", HypervisorType.KVM.name(),
+ 1, 1000, 1024, null, Collections.emptyList(), Collections.emptyList(), Collections.emptyMap(), null,
+ null, null, null, null, ROOT_DISK_OFFERING_ID, null, null, null, null);
+ }
+
+ ArgumentCaptor rootDiskOfferingInfo = ArgumentCaptor.forClass(DiskOfferingInfo.class);
+ Mockito.verify(_itMgr).allocate(Mockito.eq("i-1-1-VM"), Mockito.eq(template), Mockito.eq(serviceOffering), rootDiskOfferingInfo.capture(),
+ Mockito.anyList(), Mockito.anyList(), Mockito.any(LinkedHashMap.class), Mockito.isNull(), Mockito.eq(HypervisorType.KVM),
+ Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull());
+
+ Assert.assertEquals(Long.valueOf(100), rootDiskOfferingInfo.getValue().getMinIops());
+ Assert.assertEquals(Long.valueOf(1000), rootDiskOfferingInfo.getValue().getMaxIops());
+ }
+}
diff --git a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java
index 05bbf13c9745..06dcb125ada5 100644
--- a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java
+++ b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java
@@ -1007,7 +1007,6 @@ private TemplateInfo createManagedTemplateVolume(TemplateInfo srcTemplateInfo, P
} else {
errMesg = callback.result.getResult();
}
- templateOnPrimary.processEvent(Event.OperationFailed);
throw new CloudRuntimeException(String.format("Unable to create template %s on primary storage %s: %s", templateOnPrimary.getImage(), destPrimaryDataStore, errMesg));
}
@@ -1015,8 +1014,12 @@ private TemplateInfo createManagedTemplateVolume(TemplateInfo srcTemplateInfo, P
} catch (Throwable e) {
logger.debug("Failed to create template volume on storage", e);
- templateOnPrimary.processEvent(Event.OperationFailed);
- throw new CloudRuntimeException(e.getMessage());
+ try {
+ templateOnPrimary.processEvent(Event.OperationFailed);
+ } catch (Exception stateEx) {
+ logger.warn("Unable to mark template {} as failed on primary storage {}: {}", templateOnPrimary.getImage(), destPrimaryDataStore, stateEx.getMessage());
+ }
+ throw new CloudRuntimeException(e.getMessage(), e);
} finally {
_tmpltPoolDao.releaseFromLockTable(templatePoolRefId);
}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/driver/OntapPrimaryDatastoreDriver.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/driver/OntapPrimaryDatastoreDriver.java
index 0feb570a6c12..4188a23ad424 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/driver/OntapPrimaryDatastoreDriver.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/driver/OntapPrimaryDatastoreDriver.java
@@ -23,11 +23,13 @@
import com.cloud.agent.api.to.DataObjectType;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.agent.api.to.DataTO;
+import com.cloud.agent.api.to.DiskTO;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
-import com.cloud.agent.api.to.DiskTO;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.storage.DataStoreRole;
+import com.cloud.storage.ResizeVolumePayload;
import com.cloud.storage.Storage;
import com.cloud.storage.StoragePool;
import com.cloud.storage.Volume;
@@ -35,9 +37,11 @@
import com.cloud.storage.VolumeVO;
import com.cloud.storage.ScopeType;
import com.cloud.storage.SnapshotVO;
+import com.cloud.storage.VMTemplateStoragePoolVO;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.SnapshotDetailsDao;
import com.cloud.storage.dao.SnapshotDetailsVO;
+import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.dao.VolumeDetailsDao;
import com.cloud.utils.Pair;
@@ -48,40 +52,51 @@
import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreCapabilities;
+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.SnapshotInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
import org.apache.cloudstack.storage.command.CommandResult;
+import org.apache.cloudstack.storage.command.CopyCmdAnswer;
import org.apache.cloudstack.storage.command.CreateObjectAnswer;
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.feign.client.SnapshotFeignClient;
+import org.apache.cloudstack.storage.feign.model.FileInfo;
import org.apache.cloudstack.storage.feign.model.FlexVolSnapshot;
import org.apache.cloudstack.storage.feign.model.Lun;
+import org.apache.cloudstack.storage.feign.model.LunSpace;
+import org.apache.cloudstack.storage.feign.model.Svm;
+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.SANStrategy;
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.AccessGroup;
import org.apache.cloudstack.storage.service.model.CloudStackVolume;
import org.apache.cloudstack.storage.service.model.ProtocolType;
import org.apache.cloudstack.storage.to.SnapshotObjectTO;
import org.apache.cloudstack.storage.utils.OntapStorageUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import javax.inject.Inject;
-import java.util.Arrays;
import java.util.ArrayList;
+import java.util.Arrays;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
/**
* Primary datastore driver for NetApp ONTAP storage systems.
@@ -97,6 +112,7 @@ public class OntapPrimaryDatastoreDriver implements PrimaryDataStoreDriver {
@Inject private VolumeDetailsDao volumeDetailsDao;
@Inject private SnapshotDetailsDao snapshotDetailsDao;
@Inject private SnapshotDao snapshotDao;
+ @Inject private VMTemplatePoolDao vmTemplatePoolDao;
@Override
public Map getCapabilities() {
@@ -105,6 +121,14 @@ public Map getCapabilities() {
mapCapabilities.put(DataStoreCapabilities.STORAGE_SYSTEM_SNAPSHOT.toString(), Boolean.TRUE.toString());
mapCapabilities.put(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_SNAPSHOT.toString(), Boolean.TRUE.toString());
mapCapabilities.put(DataStoreCapabilities.CAN_REVERT_VOLUME_TO_SNAPSHOT.toString(), Boolean.TRUE.toString());
+ // Enables the framework to cache a template on the FlexVolume once and serve every later
+ // deployment with an array-side clone instead of another copy from secondary storage.
+ mapCapabilities.put(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString(), Boolean.TRUE.toString());
+ // createTemplate(snapshotid) reads the snapshot from this pool instead of backing it up to secondary first.
+ mapCapabilities.put(DataStoreCapabilities.CAN_CREATE_TEMPLATE_FROM_SNAPSHOT.toString(), Boolean.TRUE.toString());
+ // Must be present and false: StorageSystemDataMotionStrategy then clones the snapshot into a
+ // temporary volume (see copyAsync) and copies that volume to secondary storage.
+ mapCapabilities.put(OntapStorageConstants.CAN_DIRECT_ATTACH_SNAPSHOT, Boolean.FALSE.toString());
return mapCapabilities;
}
@@ -167,36 +191,43 @@ public void createAsync(DataStore dataStore, DataObject dataObject, AsyncComplet
// Update CloudStack volume record with storage pool association and protocol-specific details
VolumeVO volumeVO = volumeDao.findById(volInfo.getId());
if (volumeVO != null) {
- // Create the backend storage object (LUN for iSCSI, no-op for NFS)
- CloudStackVolume created = createCloudStackVolume(storagePool, volInfo, details);
-
- volumeVO.setPoolType(storagePool.getPoolType());
- volumeVO.setPoolId(storagePool.getId());
- volumeVO.setFormat(getImageFormat(storagePool));
- logger.info("createAsync: Volume format set to [{}] for hypervisor [{}] and protocol [{}]", volumeVO.getFormat(), storagePool.getHypervisor(), details.get(OntapStorageConstants.PROTOCOL));
- if (ProtocolType.ISCSI.name().equalsIgnoreCase(details.get(OntapStorageConstants.PROTOCOL))) {
- String lunName = created != null && created.getLun() != null ? created.getLun().getName() : null;
- if (lunName == null) {
- throw new CloudRuntimeException("Missing LUN name for volume " + volInfo.getId());
- }
-
- // Persist LUN details for future operations (delete, grant/revoke access)
- volumeDetailsDao.addDetail(volInfo.getId(), OntapStorageConstants.LUN_DOT_UUID, created.getLun().getUuid(), false);
- volumeDetailsDao.addDetail(volInfo.getId(), OntapStorageConstants.LUN_DOT_NAME, lunName, false);
- if (created.getLun().getUuid() != null) {
- volumeVO.setFolder(created.getLun().getUuid());
- }
-
- logger.info("createAsync: Created LUN [{}] for volume [{}]. LUN mapping will occur during grantAccess() to per-host igroup.",
- lunName, volumeVO.getId());
- createCmdResult = new CreateCmdResult(lunName, new Answer(null, true, null));
- } else if (ProtocolType.NFS3.name().equalsIgnoreCase(details.get(OntapStorageConstants.PROTOCOL))) {
- createCmdResult = new CreateCmdResult(volInfo.getUuid(), new Answer(null, true, null));
- logger.info("createAsync: Managed NFS volume [{}] with path [{}] associated with pool {}",
- volumeVO.getId(), volInfo.getUuid(), storagePool.getId());
+ /*
+ * Create-volume combinations on ONTAP primary (v1):
+ *
+ * 1) cloneOfSnapshot — StorageSystemDataMotionStrategy sets volume_details.cloneOfSnapshot
+ * when createVolume(snapshotid) targets a managed backend snapshot.
+ * - Same primary pool / FlexVol only (PRIMARY_POOL_ID must match dataStore).
+ * - DATA or ROOT snapshot → new attachable data volume (ROOT is never bootable
+ * via this path; bootable recovery is createTemplate(snapshotid) → deploy).
+ * - Backend: iSCSI → POST /api/storage/luns (clone.source in .snapshot/);
+ * NFS → POST /api/storage/file/clone with snapshot.name.
+ * - IOPS: the new volume's min/max (snapshot values, or the root offering when one
+ * is supplied). Applied here; the temporary template clone does not get a policy.
+ *
+ * 2) cloneOfTemplate — deploy / create from cached template on this pool.
+ *
+ * 3) else — blank LUN (iSCSI) or qcow2 (NFS).
+ *
+ * Mutually exclusive from the motion/orchestrator layer; snapshot is checked first
+ * (SolidFire-style) so a create-from-snapshot never accidentally falls through to blank create.
+ */
+ Long cloneOfSnapshotId = getSnapshotIdForCloning(volInfo.getId());
+ Long cloneOfTemplateId = getTemplateIdForCloning(volInfo.getId());
+ CloudStackVolume clonedCloudStackVolume;
+ if (cloneOfSnapshotId != null) {
+ clonedCloudStackVolume = cloneCloudStackVolumeFromSnapshot(
+ storagePool, volInfo, details, cloneOfSnapshotId, true);
+ } else if (cloneOfTemplateId != null) {
+ clonedCloudStackVolume = cloneCloudStackVolumeFromTemplate(
+ storagePool, volInfo, details, cloneOfTemplateId);
+ } else {
+ clonedCloudStackVolume = createCloudStackVolume(storagePool, volInfo, details);
}
- volumeDao.update(volumeVO.getId(), volumeVO);
+
+ createCmdResult = recordCreatedVolume(storagePool, volInfo, volumeVO, details, clonedCloudStackVolume);
}
+ } else if (dataObject.getType() == DataObjectType.TEMPLATE) {
+ createCmdResult = createTemplateOnPrimary(storagePool, (TemplateInfo) dataObject, details);
} else {
errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to createAsync";
logger.error(errMsg);
@@ -206,7 +237,7 @@ public void createAsync(DataStore dataStore, DataObject dataObject, AsyncComplet
errMsg = e.getMessage();
logger.error("createAsync: Failed for dataObject name [{}]: {}", dataObject.getName(), errMsg);
createCmdResult = new CreateCmdResult(null, new Answer(null, false, errMsg));
- createCmdResult.setResult(e.toString());
+ createCmdResult.setResult(errMsg);
} finally {
if (createCmdResult != null && createCmdResult.isSuccess()) {
logger.info("createAsync: Operation completed successfully for {}", dataObject.getType());
@@ -215,13 +246,534 @@ public void createAsync(DataStore dataStore, DataObject dataObject, AsyncComplet
}
}
+ /**
+ * Records pool association, image format and protocol-specific identity (LUN name/uuid for iSCSI)
+ * of a volume that was just created or cloned on ONTAP, and returns the create result whose path
+ * the framework stores on the volume.
+ */
+ private CreateCmdResult recordCreatedVolume(StoragePoolVO storagePool, VolumeInfo volInfo, VolumeVO volumeVO,
+ Map details, CloudStackVolume createdCloudStackVolume) {
+ CreateCmdResult createCmdResult = null;
+ volumeVO.setPoolType(storagePool.getPoolType());
+ volumeVO.setPoolId(storagePool.getId());
+ volumeVO.setFormat(getImageFormat(storagePool));
+ logger.info("createAsync: Volume format set to [{}] for pool type [{}]", volumeVO.getFormat(), storagePool.getPoolType());
+
+ if (ProtocolType.ISCSI.name().equalsIgnoreCase(details.get(OntapStorageConstants.PROTOCOL))) {
+ // createCloudStackVolume validates the Feign response (LUN name + uuid) before returning
+ Lun createdLun = createdCloudStackVolume.getLun();
+ String lunName = createdLun.getName();
+
+ // Persist LUN details for future operations (delete, grant/revoke access)
+ volumeDetailsDao.addDetail(volInfo.getId(), OntapStorageConstants.LUN_DOT_UUID, createdLun.getUuid(), false);
+ volumeDetailsDao.addDetail(volInfo.getId(), OntapStorageConstants.LUN_DOT_NAME, lunName, false);
+ volumeVO.setFolder(createdLun.getUuid());
+
+ logger.info("createAsync: Created LUN [{}] for volume [{}]. LUN mapping will occur during grantAccess() to per-host igroup.",
+ lunName, volumeVO.getId());
+ createCmdResult = new CreateCmdResult(lunName, new Answer(null, true, null));
+ } else if (ProtocolType.NFS3.name().equalsIgnoreCase(details.get(OntapStorageConstants.PROTOCOL))) {
+ createCmdResult = new CreateCmdResult(volInfo.getUuid(), new Answer(null, true, null));
+ logger.info("createAsync: Managed NFS volume [{}] with path [{}] associated with pool {}",
+ volumeVO.getId(), volInfo.getUuid(), storagePool.getId());
+ }
+ volumeDao.update(volumeVO.getId(), volumeVO);
+ return createCmdResult;
+ }
+
/**
* Creates a volume on the ONTAP backend.
*/
private CloudStackVolume createCloudStackVolume(StoragePoolVO storagePool, VolumeInfo volumeObject, Map details) {
+ verifySufficientIopsForStoragePool(storagePool, volumeObject.getMinIops(), volumeObject.getId());
+ StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
+ VolumeQosPolicy qosPolicy = null;
+ Volume.Type volumeType = volumeObject.getVolumeType();
+ if (volumeType == Volume.Type.DATADISK || volumeType == Volume.Type.ROOT) {
+ qosPolicy = createQosPolicyIfNeeded(storageStrategy, details,
+ volumeObject.getMinIops(), volumeObject.getMaxIops(), storagePool.getId());
+ }
+ CloudStackVolume request = createCloudStackVolumeRequestByProtocol(
+ storagePool, details, volumeObject, qosPolicy);
+ try {
+ CloudStackVolume created = storageStrategy.createCloudStackVolume(request);
+ persistQosPolicyDetails(volumeObject.getId(), qosPolicy);
+ return created;
+ } catch (RuntimeException e) {
+ if (qosPolicy != null) {
+ storageStrategy.deleteVolumeQosPolicy(qosPolicy.getUuid());
+ }
+ throw e;
+ }
+ }
+
+ private VolumeQosPolicy createQosPolicyIfNeeded(StorageStrategy storageStrategy, Map details,
+ Long minIops, Long maxIops, Long poolId) {
+ if (!validateIops(storageStrategy, details, poolId, minIops, maxIops)) {
+ return null;
+ }
+ String policyName = getQosPolicyName(details.get(OntapStorageConstants.SVM_NAME), minIops, maxIops);
+ return storageStrategy.createVolumeQosPolicy(policyName, minIops, maxIops);
+ }
+
+ private boolean validateIops(StorageStrategy storageStrategy, Map details,
+ Long poolId, Long minIops, Long maxIops) {
+ long min = minIops == null ? 0 : minIops;
+ long max = maxIops == null ? 0 : maxIops;
+ if (min <= 0 && max <= 0) {
+ return false;
+ }
+ if (min > 0 && max > 0 && min > max) {
+ throw new CloudRuntimeException("Minimum IOPS cannot be greater than maximum IOPS");
+ }
+ if (min > 0) {
+ String isAff = details.get(OntapStorageConstants.IS_AFF);
+ if (StringUtils.isBlank(isAff)) {
+ try {
+ isAff = Boolean.toString(storageStrategy.isAff());
+ details.put(OntapStorageConstants.IS_AFF, isAff);
+ storagePoolDetailsDao.addDetail(poolId, OntapStorageConstants.IS_AFF, isAff, false);
+ } catch (Exception e) {
+ logger.error("Unable to determine whether storage pool [{}] is AFF or FAS: {}",
+ poolId, e.getMessage());
+ return true;
+ }
+ }
+ if (!Boolean.parseBoolean(isAff)) {
+ throw new CloudRuntimeException(OntapStorageConstants.MIN_IOPS_NOT_SUPPORTED_ON_FAS);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Builds a reusable SVM-scoped QoS policy name: cs_{min}_to_{max}_iops_{svmName}.
+ * Dots in the SVM name are replaced with underscores (ONTAP QoS names cannot contain '.').
+ */
+ private String getQosPolicyName(String svmName, Long minIops, Long maxIops) {
+ String sanitizedSvmName = svmName == null ? "" : svmName.replace(".", OntapStorageConstants.UNDERSCORE);
+ long min = minIops != null && minIops > 0 ? minIops : 0;
+ long max = maxIops != null && maxIops > 0 ? maxIops : 0;
+ return OntapStorageConstants.QOS_POLICY_NAME_PREFIX + min + OntapStorageConstants.UNDERSCORE
+ + OntapStorageConstants.QOS_POLICY_NAME_TO + max + OntapStorageConstants.UNDERSCORE
+ + OntapStorageConstants.QOS_POLICY_NAME_IOPS + sanitizedSvmName;
+ }
+
+ private void persistQosPolicyDetails(long volumeId, VolumeQosPolicy qosPolicy) {
+ volumeDetailsDao.removeDetail(volumeId, OntapStorageConstants.QOS_POLICY_UUID);
+ if (qosPolicy == null) {
+ return;
+ }
+ volumeDetailsDao.addDetail(volumeId, OntapStorageConstants.QOS_POLICY_UUID, qosPolicy.getUuid(), false);
+ }
+
+ /**
+ * Creates the backend object that caches a template on this pool's FlexVolume.
+ *
+ * Protocol-specific work is delegated to {@link StorageStrategy#createTemplateCache}.
+ * This method maps the result to {@link CreateCmdResult} and records SAN identity on
+ * {@code template_spool_ref} ({@code local_download_path} = LUN uuid).
+ */
+ private CreateCmdResult createTemplateOnPrimary(StoragePoolVO storagePool, TemplateInfo templateInfo, Map details) {
+ StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
+ long sizeInBytes = getDataObjectSizeIncludingHypervisorSnapshotReserve(templateInfo, storagePool);
+ CloudStackVolume created = null;
+ try {
+ created = storageStrategy.createTemplateCache(storagePool, templateInfo, details, sizeInBytes);
+ String path = recordTemplateCacheOnSpoolRef(storagePool, templateInfo, created, sizeInBytes);
+ return new CreateCmdResult(path, new Answer(null, true, null));
+ } catch (Exception e) {
+ // Compensating delete for SAN: strategy cleans create-time LUN failures; this covers
+ // post-create failures (e.g. template_spool_ref update) after a LUN was returned.
+ if (created != null && created.getLun() != null) {
+ bestEffortDeleteTemplateCacheLun(storageStrategy, details.get(OntapStorageConstants.SVM_NAME),
+ created.getLun().getName(), created.getLun().getUuid());
+ }
+ if (e instanceof CloudRuntimeException) {
+ throw (CloudRuntimeException) e;
+ }
+ throw new CloudRuntimeException("Failed to create template cache for template [" + templateInfo.getId()
+ + "]: " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Persists SAN cache identity on {@code template_spool_ref} when a LUN was created.
+ * NFS returns the template uuid as the create path; {@code install_path} is filled later.
+ */
+ private String recordTemplateCacheOnSpoolRef(StoragePoolVO storagePool, TemplateInfo templateInfo,
+ CloudStackVolume created, long sizeInBytes) {
+ if (created == null || created.getLun() == null) {
+ return templateInfo.getUuid();
+ }
+ Lun lun = created.getLun();
+ VMTemplateStoragePoolVO templatePoolRef = findTemplatePoolRef(storagePool.getId(), templateInfo.getId());
+ templatePoolRef.setLocalDownloadPath(lun.getUuid());
+ templatePoolRef.setTemplateSize(sizeInBytes);
+ vmTemplatePoolDao.update(templatePoolRef.getId(), templatePoolRef);
+ return lun.getName();
+ }
+
+ /**
+ * Clones the cached template into a new volume on the same FlexVolume.
+ *
+ * Invoked when {@code StorageSystemDataMotionStrategy} has recorded a
+ * {@code cloneOfTemplate} detail on the volume.
+ */
+ private CloudStackVolume cloneCloudStackVolumeFromTemplate(StoragePoolVO storagePool, VolumeInfo volumeInfo,
+ Map details, long templateId) {
+ VMTemplateStoragePoolVO templatePoolRef = findTemplatePoolRef(storagePool.getId(), templateId);
+ StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
+ boolean iscsi = isIscsi(details);
+
+ verifySufficientIopsForStoragePool(storagePool, volumeInfo.getMinIops(), volumeInfo.getId());
+ VolumeQosPolicy qosPolicy = null;
+ Volume.Type volumeType = volumeInfo.getVolumeType();
+ if (volumeType == Volume.Type.DATADISK || volumeType == Volume.Type.ROOT) {
+ qosPolicy = createQosPolicyIfNeeded(storageStrategy, details,
+ volumeInfo.getMinIops(), volumeInfo.getMaxIops(), storagePool.getId());
+ }
+
+ CloudStackVolume request = iscsi
+ ? createCloneLunRequest(storagePool, details, volumeInfo, templatePoolRef, templateId, qosPolicy)
+ : createCloneFileRequest(storagePool, volumeInfo, templatePoolRef, templateId);
+
+ try {
+ CloudStackVolume cloned = storageStrategy.cloneCloudStackVolume(request);
+ if (cloned == null) {
+ throw new CloudRuntimeException("ONTAP returned nothing when cloning template [" + templateId
+ + "] for volume [" + volumeInfo.getId() + "]");
+ }
+
+ logger.info("cloneCloudStackVolumeFromTemplate: Cloned template [{}] for volume [{}] on pool [{}]",
+ templateId, volumeInfo.getId(), storagePool.getId());
+
+ long requestedSize = getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, storagePool);
+ if (requestedSize > templatePoolRef.getTemplateSize()) {
+ logger.info("cloneCloudStackVolumeFromTemplate: Growing clone of template [{}] from {} to {} bytes for volume [{}]",
+ templateId, templatePoolRef.getTemplateSize(), requestedSize, volumeInfo.getId());
+ resizeClonedVolumeOrCleanup(storageStrategy, cloned, requestedSize,
+ "cloneCloudStackVolumeFromTemplate template [" + templateId + "] volume [" + volumeInfo.getId() + "]");
+ }
+
+ if (!iscsi && qosPolicy != null) {
+ CloudStackVolume cloudStackVolume = createCloudStackVolumeRequestByProtocol(
+ storagePool, details, volumeInfo, qosPolicy);
+ storageStrategy.updateCloudStackVolume(cloudStackVolume);
+ }
+ persistQosPolicyDetails(volumeInfo.getId(), qosPolicy);
+ return cloned;
+ } catch (Exception e) {
+ if (qosPolicy != null) {
+ storageStrategy.deleteVolumeQosPolicy(qosPolicy.getUuid());
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * Returns the CloudStack template id the volume should be cloned from, or null for a blank volume.
+ *
+ * {@code StorageSystemDataMotionStrategy} persists this detail immediately before calling
+ * {@code createAsync} and removes it right after, so it is only visible during creation.
+ */
+ private Long getTemplateIdForCloning(long volumeId) {
+ VolumeDetailVO detail = volumeDetailsDao.findDetail(volumeId, OntapStorageConstants.CLONE_OF_TEMPLATE);
+ if (detail == null || detail.getValue() == null || detail.getValue().isEmpty()) {
+ return null;
+ }
+ return Long.valueOf(detail.getValue());
+ }
+
+ /**
+ * Returns the CloudStack snapshot id to clone from when {@code volume_details.cloneOfSnapshot}
+ * is set, or null when this create is not a create-volume-from-snapshot.
+ *
+ * Set by {@code StorageSystemDataMotionStrategy.handleCreateManagedVolumeFromManagedSnapshot}
+ * for the duration of {@code createAsync} only (same pattern as {@link #getTemplateIdForCloning}).
+ */
+ private Long getSnapshotIdForCloning(long volumeId) {
+ VolumeDetailVO detail = volumeDetailsDao.findDetail(volumeId, OntapStorageConstants.CLONE_OF_SNAPSHOT);
+ if (detail == null || detail.getValue() == null || detail.getValue().isEmpty()) {
+ return null;
+ }
+ return Long.valueOf(detail.getValue());
+ }
+
+ /**
+ * Creates a new volume on this pool by cloning a file/LUN from a CloudStack volume snapshot
+ * that already lives on the same FlexVolume.
+ *
+ * Combinations (product + plugin v1):
+ *
+ * - Same pool only — {@code snapshot_details.PRIMARY_POOL_ID} must equal this
+ * {@code storagePool}. Creating the volume on a different pool is descoped; use migrate later if needed.
+ * - DATA snapshot → attachable data disk (disk offering usually inherited).
+ * - ROOT snapshot → still a data disk here (not bootable). Bootable path remains
+ * {@code createTemplate(snapshotid)} then deploy.
+ * - iSCSI — {@code POST /api/storage/luns} with
+ * {@code clone.source.name=/vol/<fv>/.snapshot/<snap>/<lun>}
+ * - NFS3 — {@code POST /api/storage/file/clone} with {@code snapshot.name}
+ * - Not this path — in-place revert ({@code revertSnapshot}); VM/instance snapshots;
+ * secondary-storage archive restore.
+ *
+ *
+ * Optional grow when the disk offering is larger than the snapshot size (same pattern as
+ * clone-from-template).
+ *
+ * When {@code applyQos} is true, the new volume's min and max IOPS are applied the same way
+ * as a template clone: iSCSI carries the policy on the clone request, NFS attaches it after
+ * the file exists. The temporary volume used for {@code createTemplate(snapshotid)} passes
+ * false and is left without a policy.
+ */
+ private CloudStackVolume cloneCloudStackVolumeFromSnapshot(StoragePoolVO storagePool, VolumeInfo volumeInfo,
+ Map details, long csSnapshotId,
+ boolean applyQos) {
+ String snapshotName = requireSnapshotDetail(csSnapshotId, OntapStorageConstants.ONTAP_SNAP_NAME);
+ String volumePath = requireSnapshotDetail(csSnapshotId, OntapStorageConstants.VOLUME_PATH);
+ String primaryPoolId = requireSnapshotDetail(csSnapshotId, OntapStorageConstants.PRIMARY_POOL_ID);
+ String snapProtocol = requireSnapshotDetail(csSnapshotId, OntapStorageConstants.PROTOCOL);
+
+ // Same-pool / same-protocol gate (v1). Fail before any ONTAP call.
+ if (!String.valueOf(storagePool.getId()).equals(primaryPoolId)) {
+ throw new CloudRuntimeException("Create volume from snapshot [" + csSnapshotId
+ + "] requires the snapshot's primary pool [" + primaryPoolId
+ + "]; requested pool is [" + storagePool.getId() + "] (creating a volume from a snapshot on a different pool is not supported)");
+ }
+ String poolProtocol = details.get(OntapStorageConstants.PROTOCOL);
+ if (poolProtocol == null || !poolProtocol.equalsIgnoreCase(snapProtocol)) {
+ throw new CloudRuntimeException("Create volume from snapshot [" + csSnapshotId
+ + "] protocol mismatch: snapshot=[" + snapProtocol + "], pool=[" + poolProtocol + "]");
+ }
+
+ StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
+ boolean iscsi = isIscsi(details);
+ VolumeQosPolicy qosPolicy = null;
+
+ logger.info("cloneCloudStackVolumeFromSnapshot: Cloning from CS snapshot [{}] (ONTAP snap [{}], path [{}]) "
+ + "for volume [{}] on pool [{}] protocol [{}]",
+ csSnapshotId, snapshotName, volumePath, volumeInfo.getId(), storagePool.getId(), poolProtocol);
+
+ try {
+ if (applyQos) {
+ verifySufficientIopsForStoragePool(storagePool, volumeInfo.getMinIops(), volumeInfo.getId());
+ Volume.Type volumeType = volumeInfo.getVolumeType();
+ if (volumeType == Volume.Type.DATADISK || volumeType == Volume.Type.ROOT) {
+ qosPolicy = createQosPolicyIfNeeded(storageStrategy, details,
+ volumeInfo.getMinIops(), volumeInfo.getMaxIops(), storagePool.getId());
+ }
+ }
+
+ CloudStackVolume request = iscsi
+ ? createCloneLunFromSnapshotRequest(storagePool, details, volumeInfo, volumePath, snapshotName, qosPolicy)
+ : createCloneFileFromSnapshotRequest(storagePool, details, volumeInfo, volumePath, snapshotName);
+ CloudStackVolume cloned = storageStrategy.cloneCloudStackVolume(request);
+ if (cloned == null) {
+ throw new CloudRuntimeException("ONTAP returned nothing when cloning snapshot [" + csSnapshotId
+ + "] for volume [" + volumeInfo.getId() + "]");
+ }
+
+ long requestedSize = getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, storagePool);
+ long snapshotSize = resolveSnapshotSizeBytes(csSnapshotId);
+ if (snapshotSize > 0 && requestedSize > snapshotSize) {
+ logger.info("cloneCloudStackVolumeFromSnapshot: Growing clone of snapshot [{}] from {} to {} bytes for volume [{}]",
+ csSnapshotId, snapshotSize, requestedSize, volumeInfo.getId());
+ resizeClonedVolumeOrCleanup(storageStrategy, cloned, requestedSize,
+ "cloneCloudStackVolumeFromSnapshot snapshot [" + csSnapshotId + "] volume [" + volumeInfo.getId() + "]");
+ }
+
+ if (!iscsi && qosPolicy != null) {
+ CloudStackVolume cloudStackVolume = createCloudStackVolumeRequestByProtocol(
+ storagePool, details, volumeInfo, qosPolicy);
+ storageStrategy.updateCloudStackVolume(cloudStackVolume);
+ }
+ if (applyQos) {
+ persistQosPolicyDetails(volumeInfo.getId(), qosPolicy);
+ }
+ return cloned;
+ } catch (Exception e) {
+ if (qosPolicy != null) {
+ storageStrategy.deleteVolumeQosPolicy(qosPolicy.getUuid());
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * Grows a just-created ONTAP clone to the requested size. If resize fails, deletes the clone
+ * so the CloudStack create-failure path does not leave an orphaned LUN/file on the array.
+ */
+ private void resizeClonedVolumeOrCleanup(StorageStrategy storageStrategy, CloudStackVolume cloned,
+ long requestedSize, String context) {
+ try {
+ storageStrategy.resizeCloudStackVolume(cloned, requestedSize);
+ } catch (RuntimeException resizeEx) {
+ logger.error("{}: Resize to {} bytes failed; deleting orphaned ONTAP clone: {}",
+ context, requestedSize, resizeEx.getMessage());
+ bestEffortDeleteOrphanedClone(storageStrategy, cloned);
+ throw resizeEx;
+ }
+ }
+
+ private void bestEffortDeleteOrphanedClone(StorageStrategy storageStrategy, CloudStackVolume cloned) {
+ try {
+ storageStrategy.deleteCloudStackVolume(cloned);
+ logger.info("Deleted orphaned ONTAP clone after resize failure");
+ } catch (Exception cleanupEx) {
+ logger.warn("Failed to delete orphaned ONTAP clone after resize failure: {}", cleanupEx.getMessage());
+ }
+ }
+
+ private String requireSnapshotDetail(long csSnapshotId, String key) {
+ String value = getSnapshotDetail(csSnapshotId, key);
+ if (value == null || value.isEmpty()) {
+ throw new CloudRuntimeException("Missing snapshot_details [" + key + "] for snapshot [" + csSnapshotId
+ + "]; cannot create volume from snapshot");
+ }
+ return value;
+ }
+
+ private long resolveSnapshotSizeBytes(long csSnapshotId) {
+ SnapshotVO snapshotVO = snapshotDao.findById(csSnapshotId);
+ if (snapshotVO == null || snapshotVO.getSize() <= 0) {
+ return 0L;
+ }
+ return snapshotVO.getSize();
+ }
+
+ private VMTemplateStoragePoolVO findTemplatePoolRef(long poolId, long templateId) {
+ VMTemplateStoragePoolVO templatePoolRef = vmTemplatePoolDao.findByPoolTemplate(poolId, templateId, null);
+ if (templatePoolRef == null) {
+ throw new CloudRuntimeException("No template_spool_ref row for template [" + templateId + "] on pool [" + poolId + "]");
+ }
+ return templatePoolRef;
+ }
+
+ /**
+ * Deletes the LUN caching a template on this pool, invoked by template eviction
+ * ({@code TemplateManagerImpl.evictTemplateFromStoragePool}).
+ *
+ * Volumes previously cloned from this LUN are unaffected: an ONTAP sis-clone shares blocks
+ * with its source through reference counting rather than depending on it, so the source can be
+ * removed while its clones stay online.
+ *
+ * {@code deleteCloudStackVolume} already unmaps as it deletes ({@code allow_delete_while_mapped})
+ * and treats a missing LUN as success.
+ */
+ private void deleteTemplateOnPrimary(DataStore store, TemplateInfo templateInfo) {
+ StoragePoolVO storagePool = storagePoolDao.findById(store.getId());
+ if (storagePool == null) {
+ throw new CloudRuntimeException("Storage Pool not found for id: " + store.getId());
+ }
+
+ Map details = storagePoolDetailsDao.listDetailsKeyPairs(store.getId());
+ VMTemplateStoragePoolVO templatePoolRef = vmTemplatePoolDao.findByPoolTemplate(storagePool.getId(), templateInfo.getId(), null);
+ if (templatePoolRef == null) {
+ logger.warn("deleteTemplateOnPrimary: No template_spool_ref for template [{}] on pool [{}]; nothing to delete",
+ templateInfo.getId(), storagePool.getId());
+ return;
+ }
+
StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
- CloudStackVolume cloudStackVolumeRequest = OntapStorageUtils.createCloudStackVolumeRequestByProtocol(storagePool, details, volumeObject);
- return storageStrategy.createCloudStackVolume(cloudStackVolumeRequest);
+ if (isIscsi(details)) {
+ deleteIscsiTemplateCache(storagePool, templateInfo, templatePoolRef, storageStrategy, details);
+ } else {
+ deleteNfsTemplateCache(details, templateInfo, templatePoolRef, storageStrategy);
+ }
+ }
+
+ private void deleteIscsiTemplateCache(StoragePoolVO storagePool, TemplateInfo templateInfo,
+ VMTemplateStoragePoolVO templatePoolRef, StorageStrategy storageStrategy,
+ Map details) {
+ String lunName = getTemplateLunName(storagePool, templateInfo.getId());
+ String lunUuid = templatePoolRef.getLocalDownloadPath();
+ deleteTemplateCacheLun(storageStrategy, details.get(OntapStorageConstants.SVM_NAME), lunName, lunUuid);
+ logger.info("deleteIscsiTemplateCache: Deleted template cache LUN [{}] for template [{}] on pool [{}]",
+ lunName, templateInfo.getId(), storagePool.getId());
+ }
+
+ /**
+ * Deletes a template-cache LUN. When {@code lunUuid} is missing, resolves the LUN by its
+ * deterministic name so eviction and create-time rollback still work.
+ */
+ private void deleteTemplateCacheLun(StorageStrategy storageStrategy, String svmName, String lunName, String lunUuid) {
+ String uuid = lunUuid;
+ if (uuid == null || uuid.isEmpty()) {
+ CloudStackVolume existing = getCloudStackVolumeByName(storageStrategy, svmName, lunName);
+ if (existing == null || existing.getLun() == null || existing.getLun().getUuid() == null) {
+ logger.warn("deleteTemplateCacheLun: LUN [{}] not found on SVM [{}]; nothing to delete", lunName, svmName);
+ return;
+ }
+ uuid = existing.getLun().getUuid();
+ }
+
+ Lun lun = new Lun();
+ lun.setUuid(uuid);
+ lun.setName(lunName);
+
+ CloudStackVolume deleteRequest = new CloudStackVolume();
+ deleteRequest.setLun(lun);
+ storageStrategy.deleteCloudStackVolume(deleteRequest);
+ }
+
+ /**
+ * Best-effort cleanup of a template-cache LUN after a failed create. Never masks the original
+ * create failure.
+ */
+ private void bestEffortDeleteTemplateCacheLun(StorageStrategy storageStrategy, String svmName, String lunName,
+ String lunUuid) {
+ try {
+ deleteTemplateCacheLun(storageStrategy, svmName, lunName, lunUuid);
+ logger.info("bestEffortDeleteTemplateCacheLun: Removed leftover template cache LUN [{}] on SVM [{}]",
+ lunName, svmName);
+ } catch (Exception cleanupEx) {
+ logger.warn("bestEffortDeleteTemplateCacheLun: Failed to remove leftover template cache LUN [{}] on SVM [{}]: {}",
+ lunName, svmName, cleanupEx.getMessage());
+ }
+ }
+
+ private void deleteNfsTemplateCache(Map details, TemplateInfo templateInfo,
+ VMTemplateStoragePoolVO templatePoolRef, StorageStrategy storageStrategy) {
+ String filePath = templatePoolRef.getInstallPath();
+ if (filePath == null || filePath.isEmpty()) {
+ logger.warn("deleteNfsTemplateCache: No install_path recorded for template [{}]; nothing to delete",
+ templateInfo.getId());
+ return;
+ }
+ String flexVolUuid = details.get(OntapStorageConstants.VOLUME_UUID);
+ if (flexVolUuid == null || flexVolUuid.isEmpty()) {
+ // Misconfigured pool detail — fail eviction rather than calling ONTAP with a null
+ // volume UUID (which would hit /api/storage/volumes/null and still look like success
+ // upstream if we swallowed the error).
+ throw new CloudRuntimeException("FlexVolume UUID (volumeUUID) is missing from storage pool details; "
+ + "cannot delete NFS template cache file [" + filePath + "] for template ["
+ + templateInfo.getId() + "]");
+ }
+ ((UnifiedNASStrategy) storageStrategy).deleteFileByPath(flexVolUuid, filePath);
+ logger.info("deleteNfsTemplateCache: Deleted template cache file [{}] for template [{}]",
+ filePath, templateInfo.getId());
+ }
+
+ /**
+ * Rejects the request when the minimum IOPS being asked for would push the pool past its
+ * configured IOPS capacity. Pools without an IOPS capacity enforce no ceiling.
+ *
+ * Used IOPS include volumes still in {@link Volume.State#Creating} so a second overlapping
+ * create sees the first reservation. The volume being checked is omitted so its own min IOPS
+ * are not counted twice (CloudStack has already moved it to Creating before this runs).
+ */
+ private void verifySufficientIopsForStoragePool(StoragePoolVO storagePool, Long requestedMinIops, long excludeVolumeId) {
+ Long capacityIops = storagePool.getCapacityIops();
+ if (capacityIops == null || requestedMinIops == null || requestedMinIops <= 0) {
+ return;
+ }
+
+ long requestedTotalIops = getAllocatedMinIops(storagePool, excludeVolumeId) + requestedMinIops;
+ if (requestedTotalIops > capacityIops) {
+ throw new CloudRuntimeException(String.format(
+ "Insufficient IOPS capacity on storage pool %s: requested total of %d IOPS exceeds the pool IOPS capacity of %d",
+ storagePool.getName(), requestedTotalIops, capacityIops));
+ }
}
/**
@@ -254,9 +806,33 @@ public void deleteAsync(DataStore store, DataObject data, AsyncCompletionCallbac
StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
logger.info("createCloudStackVolumeForTypeVolume: Connection to Ontap SVM [{}] successful, preparing CloudStackVolumeRequest", details.get(OntapStorageConstants.SVM_NAME));
VolumeInfo volumeInfo = (VolumeInfo) data;
- CloudStackVolume cloudStackVolumeRequest = createDeleteCloudStackVolumeRequest(storagePool, details, volumeInfo);
- storageStrategy.deleteCloudStackVolume(cloudStackVolumeRequest);
+ VolumeDetailVO qosPolicyDetail = volumeDetailsDao.findDetail(volumeInfo.getId(), OntapStorageConstants.QOS_POLICY_UUID);
+
+ // NFS file delete leaves the QoS assignment in place unless the file is set to none first.
+ // iSCSI LUN delete already drops object_count.
+ // TODO: revisit this NFS none-policy step when the file is deleted from ONTAP instead of KVM.
+ boolean qosCleared = false;
+ if (!isIscsi(details)) {
+ qosCleared = clearQosPolicyBeforeDelete(storageStrategy, storagePool, details, volumeInfo, qosPolicyDetail);
+ }
+ try {
+ CloudStackVolume cloudStackVolumeRequest = createDeleteCloudStackVolumeRequest(storagePool, details, volumeInfo);
+ storageStrategy.deleteCloudStackVolume(cloudStackVolumeRequest);
+ } catch (Exception e) {
+ if (qosCleared) {
+ restoreQosPolicyAfterFailedDelete(storageStrategy, storagePool, details, volumeInfo, qosPolicyDetail);
+ }
+ throw e;
+ }
+ if (qosPolicyDetail != null) {
+ deleteUnusedQosPolicy(storageStrategy, qosPolicyDetail.getValue());
+ }
logger.info("deleteAsync: Volume deleted: " + volumeInfo.getId());
+ removeTemporarySnapshotCopyRecord(volumeInfo.getId());
+ commandResult.setResult(null);
+ commandResult.setSuccess(true);
+ } else if (data.getType() == DataObjectType.TEMPLATE) {
+ deleteTemplateOnPrimary(store, (TemplateInfo) data);
commandResult.setResult(null);
commandResult.setSuccess(true);
} else if (data.getType() == DataObjectType.SNAPSHOT) {
@@ -271,7 +847,55 @@ public void deleteAsync(DataStore store, DataObject data, AsyncCompletionCallbac
commandResult.setSuccess(false);
commandResult.setResult(e.getMessage());
} finally {
- callback.complete(commandResult);
+ // StorageSystemDataMotionStrategy deletes its temporary snapshot copy with a null callback.
+ if (callback != null) {
+ callback.complete(commandResult);
+ }
+ }
+ }
+
+ /**
+ * Sets the NFS file QoS policy to {@code none} before the file is deleted.
+ * Failure must not block volume delete.
+ *
+ * @return true when the file was moved off its policy
+ */
+ private boolean clearQosPolicyBeforeDelete(StorageStrategy storageStrategy, StoragePoolVO storagePool,
+ Map details, VolumeInfo volumeInfo,
+ VolumeDetailVO qosPolicyDetail) {
+ if (qosPolicyDetail == null || qosPolicyDetail.getValue() == null) {
+ return false;
+ }
+ VolumeQosPolicy nonePolicy = new VolumeQosPolicy();
+ nonePolicy.setName(OntapStorageConstants.QOS_POLICY_NONE);
+ try {
+ CloudStackVolume request = createCloudStackVolumeRequestByProtocol(storagePool, details, volumeInfo, nonePolicy);
+ storageStrategy.updateCloudStackVolume(request);
+ return true;
+ } catch (Exception e) {
+ logger.warn("Could not clear QoS policy [{}] on volume [{}] before delete: {}",
+ qosPolicyDetail.getValue(), volumeInfo.getId(), e.getMessage());
+ return false;
+ }
+ }
+
+ /**
+ * Puts the previous QoS policy back on an NFS file when delete fails after the policy was cleared.
+ */
+ private void restoreQosPolicyAfterFailedDelete(StorageStrategy storageStrategy, StoragePoolVO storagePool,
+ Map details, VolumeInfo volumeInfo,
+ VolumeDetailVO qosPolicyDetail) {
+ if (qosPolicyDetail == null || qosPolicyDetail.getValue() == null) {
+ return;
+ }
+ VolumeQosPolicy previousPolicy = new VolumeQosPolicy();
+ previousPolicy.setUuid(qosPolicyDetail.getValue());
+ try {
+ CloudStackVolume request = createCloudStackVolumeRequestByProtocol(storagePool, details, volumeInfo, previousPolicy);
+ storageStrategy.updateCloudStackVolume(request);
+ } catch (Exception e) {
+ logger.warn("Could not restore QoS policy [{}] on volume [{}] after delete failed: {}",
+ qosPolicyDetail.getValue(), volumeInfo.getId(), e.getMessage());
}
}
@@ -362,21 +986,246 @@ private long resolveSnapshotPoolId(String poolIdStr, long snapshotId) {
@Override
public void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback) {
- throw new UnsupportedOperationException("Copy operation is not supported for ONTAP primary storage.");
+ copyAsync(srcData, destData, null, callback);
}
+ /**
+ * Dispatches a driver-level copy by (source type, destination type). Only the pairs accepted by
+ * {@link #canCopy} are handled; everything else is left to the data motion strategies.
+ *
+ * Callers may pass a null callback (for example {@code StorageSystemDataMotionStrategy} for the
+ * temporary snapshot copy), in which case a failed copy is thrown.
+ */
@Override
public void copyAsync(DataObject srcData, DataObject destData, Host destHost, AsyncCompletionCallback callback) {
- throw new UnsupportedOperationException("Copy operation is not supported for ONTAP primary storage.");
+ CopyCommandResult result;
+ if (isSnapshotToTemporaryVolumeCopy(srcData, destData)) {
+ result = copySnapshotToTemporaryVolume(srcData, (VolumeInfo) destData);
+ } else {
+ throw new UnsupportedOperationException("Copy from " + describeForCopy(srcData) + " to "
+ + describeForCopy(destData) + " is not supported for ONTAP primary storage.");
+ }
+
+ if (callback != null) {
+ callback.complete(result);
+ } else if (!result.isSuccess()) {
+ throw new CloudRuntimeException("Failed to copy " + srcData.getType() + " [" + srcData.getId() + "] to "
+ + destData.getType() + " [" + destData.getId() + "]: " + result.getResult());
+ }
}
+ /**
+ * Returns true only for the (source type, destination type) pairs the driver copies itself.
+ *
+ * {@code DataMotionServiceImpl} consults {@code canCopy} before choosing a data motion strategy,
+ * so any pair accepted here bypasses {@code StorageSystemDataMotionStrategy} (volume migration,
+ * createVolume(snapshotid), template caching). Add a pair only together with its handler in
+ * {@link #copyAsync}.
+ */
@Override
public boolean canCopy(DataObject srcData, DataObject destData) {
- return false;
+ if (srcData == null || destData == null || srcData.getDataStore() == null || destData.getDataStore() == null) {
+ return false;
+ }
+ return isSnapshotToTemporaryVolumeCopy(srcData, destData);
+ }
+
+ private String describeForCopy(DataObject data) {
+ return data == null ? "null" : data.getType() + " [" + data.getId() + "]";
+ }
+
+ /**
+ * Matches the temporary volume {@code StorageSystemDataMotionStrategy} creates on the snapshot's own
+ * pool while copying the snapshot to secondary storage for {@code createTemplate(snapshotid)}.
+ */
+ private boolean isSnapshotToTemporaryVolumeCopy(DataObject srcData, DataObject destData) {
+ if (srcData == null || destData == null || srcData.getDataStore() == null || destData.getDataStore() == null) {
+ return false;
+ }
+ if (srcData.getType() != DataObjectType.SNAPSHOT || destData.getType() != DataObjectType.VOLUME) {
+ return false;
+ }
+ if (srcData.getDataStore().getRole() != DataStoreRole.Primary
+ || srcData.getDataStore().getId() != destData.getDataStore().getId()) {
+ return false;
+ }
+ return isTemporarySnapshotCopyVolume(volumeDao.findById(destData.getId()));
}
+ /**
+ * Clones a CloudStack volume snapshot into the temporary volume used for
+ * {@code createTemplate(snapshotid)}. The strategy then maps that volume to a KVM host, copies it
+ * into the template and deletes it again through {@link #deleteAsync}.
+ */
+ private CopyCommandResult copySnapshotToTemporaryVolume(DataObject srcData, VolumeInfo volInfo) {
+ try {
+ StoragePoolVO storagePool = storagePoolDao.findById(volInfo.getDataStore().getId());
+ if (storagePool == null) {
+ throw new CloudRuntimeException("Storage Pool not found for id: " + volInfo.getDataStore().getId());
+ }
+ Map details = storagePoolDetailsDao.listDetailsKeyPairs(storagePool.getId());
+ validateProtocol(details, volInfo.getDataStore());
+ VolumeVO volumeVO = volumeDao.findById(volInfo.getId());
+
+ renameTemporarySnapshotCopy(volInfo, volumeVO, srcData.getId());
+ logger.info("copySnapshotToTemporaryVolume: Cloning CS snapshot [{}] into temporary volume [{}] on pool [{}] for template creation",
+ srcData.getId(), volInfo.getId(), storagePool.getId());
+ CloudStackVolume cloned = cloneCloudStackVolumeFromSnapshot(storagePool, volInfo, details, srcData.getId(), false);
+ if (ProtocolType.NFS3.name().equalsIgnoreCase(details.get(OntapStorageConstants.PROTOCOL))) {
+ volumeVO.setPath(volInfo.getUuid());
+ }
+ recordCreatedVolume(storagePool, volInfo, volumeVO, details, cloned);
+ return new CopyCommandResult(null, new CopyCmdAnswer(volInfo.getTO()));
+ } catch (Exception e) {
+ logger.error("copySnapshotToTemporaryVolume: Failed to clone snapshot [{}] into volume [{}]: {}",
+ srcData.getId(), volInfo.getId(), e.getMessage());
+ CopyCommandResult result = new CopyCommandResult(null, new CopyCmdAnswer(e.getMessage()));
+ result.setResult(e.getMessage());
+ return result;
+ }
+ }
+
+ /**
+ * The temporary volume created by {@code StorageSystemDataMotionStrategy} for a snapshot copy is
+ * persisted in Allocated state without a disk offering; user volumes always carry a disk offering.
+ */
+ private boolean isTemporarySnapshotCopyVolume(VolumeVO volumeVO) {
+ if (volumeVO == null || volumeVO.getState() != Volume.State.Allocated) {
+ return false;
+ }
+ Long diskOfferingId = volumeVO.getDiskOfferingId();
+ return diskOfferingId == null || diskOfferingId == 0L;
+ }
+
+ /**
+ * The framework names the temporary volume {@code _.TMP}, which is not a valid
+ * ONTAP LUN name, so it is renamed before cloning. The in-memory object is updated as well because the
+ * SAN clone derives the LUN name from {@link VolumeInfo#getName()}.
+ */
+ private void renameTemporarySnapshotCopy(VolumeInfo volInfo, VolumeVO volumeVO, long csSnapshotId) {
+ String name = OntapStorageConstants.TEMP_SNAPSHOT_COPY_NAME_PREFIX + csSnapshotId + OntapStorageConstants.UNDERSCORE + volInfo.getId();
+ volumeVO.setName(name);
+ if (volInfo.getVolume() instanceof VolumeVO) {
+ ((VolumeVO) volInfo.getVolume()).setName(name);
+ }
+ }
+
+ /**
+ * {@code StorageSystemDataMotionStrategy} deletes the temporary snapshot copy on the array but leaves its
+ * volume row behind on success, so it is removed here once the backend object is gone.
+ */
+ private void removeTemporarySnapshotCopyRecord(long volumeId) {
+ VolumeVO volumeVO = volumeDao.findById(volumeId);
+ if (!isTemporarySnapshotCopyVolume(volumeVO)
+ || volumeVO.getName() == null || !volumeVO.getName().startsWith(OntapStorageConstants.TEMP_SNAPSHOT_COPY_NAME_PREFIX)) {
+ return;
+ }
+ volumeDetailsDao.removeDetails(volumeId);
+ volumeDao.remove(volumeId);
+ logger.info("deleteAsync: Removed temporary snapshot copy volume record [{}]", volumeId);
+ }
+
+ /**
+ * Resizes a volume. Size and QoS from the resize window are applied together by
+ * {@link StorageStrategy#resizeCloudStackVolume}.
+ */
@Override
- public void resize(DataObject data, AsyncCompletionCallback callback) {}
+ public void resize(DataObject data, AsyncCompletionCallback callback) {
+ CreateCmdResult result = null;
+ try {
+ if (data != null && data.getType() == DataObjectType.VOLUME) {
+ if (data instanceof VolumeInfo) {
+ VolumeQosPolicy policyToApply = null;
+ VolumeInfo volumeInfo = (VolumeInfo) data;
+ Object rawPayload = volumeInfo.getpayload();
+ ResizeVolumePayload payload = (rawPayload instanceof ResizeVolumePayload)
+ ? (ResizeVolumePayload) rawPayload : null;
+ if (payload == null || payload.newSize == null) {
+ throw new CloudRuntimeException("Invalid resize payload for volume " + volumeInfo.getId());
+ }
+ if (volumeInfo.getDataStore() == null) {
+ throw new CloudRuntimeException("Data store not found for volume " + volumeInfo.getId());
+ }
+
+ StoragePoolVO storagePool = storagePoolDao.findById(volumeInfo.getDataStore().getId());
+ if (storagePool == null) {
+ throw new CloudRuntimeException("Storage pool not found for volume " + volumeInfo.getId());
+ }
+ Map details = storagePoolDetailsDao.listDetailsKeyPairs(storagePool.getId());
+
+ VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId());
+ if (volumeVO == null) {
+ throw new CloudRuntimeException("Volume not found for id " + volumeInfo.getId());
+ }
+ if (payload.newSize < volumeVO.getSize()) {
+ throw new CloudRuntimeException("Unable to shrink volume.");
+ }
+
+ verifySufficientIopsForStoragePool(storagePool, payload.newMinIops, volumeVO.getId());
+ StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
+ VolumeDetailVO qosDetail = volumeDetailsDao.findDetail(volumeVO.getId(), OntapStorageConstants.QOS_POLICY_UUID);
+ String previousUuid = qosDetail != null ? qosDetail.getValue() : null;
+ VolumeQosPolicy qosPolicy = createQosPolicyIfNeeded(storageStrategy, details,
+ payload.newMinIops, payload.newMaxIops, storagePool.getId());
+
+ if (qosPolicy != null && !Objects.equals(previousUuid, qosPolicy.getUuid())) {
+ policyToApply = qosPolicy;
+ } else if (qosPolicy == null && previousUuid != null) {
+ policyToApply = new VolumeQosPolicy();
+ policyToApply.setName(OntapStorageConstants.QOS_POLICY_NONE);
+ }
+
+ try {
+ CloudStackVolume cloudStackVolume = resizeCloudStackVolumeRequest(details, volumeInfo, policyToApply);
+ storageStrategy.resizeCloudStackVolume(cloudStackVolume, payload.newSize);
+ } catch (RuntimeException e) {
+ if (qosPolicy != null && !Objects.equals(previousUuid, qosPolicy.getUuid())) {
+ deleteUnusedQosPolicy(storageStrategy, qosPolicy.getUuid());
+ }
+ throw e;
+ }
+ if (policyToApply != null) {
+ persistQosPolicyDetails(volumeVO.getId(), qosPolicy);
+ deleteUnusedQosPolicy(storageStrategy, previousUuid);
+ }
+
+ volumeVO.setSize(payload.newSize);
+ if (!volumeDao.update(volumeVO.getId(), volumeVO)) {
+ throw new CloudRuntimeException("Failed to update volume " + volumeVO.getId()
+ + " after resizing the ONTAP backing object");
+ }
+ result = new CreateCmdResult(volumeVO.getPath(), new Answer(null, true, null));
+ logger.info("resize: Successfully resized volume [{}] to [{}] bytes", volumeInfo.getId(), payload.newSize);
+ }else{
+ String errorMessage = "Invalid DataObjectType (" + data.getType() + ") passed to resize";
+ result = new CreateCmdResult(null, new Answer(null, false, errorMessage));
+ result.setResult(errorMessage);
+ return;
+ }
+ } else {
+ throw new CloudRuntimeException("Expected a VOLUME DataObject but received " +
+ (data != null ? data.getType() : "null"));
+ }
+ } catch (Exception e) {
+ String errMsg = e.getMessage();
+ logger.error("resize: Failed for volume [{}]: {}", data != null ? data.getId() : null, errMsg, e);
+ result = new CreateCmdResult(null, new Answer(null, false, errMsg));
+ result.setResult(errMsg);
+ } finally {
+ callback.complete(result);
+ }
+ }
+
+ private void deleteUnusedQosPolicy(StorageStrategy storageStrategy, String policyUuid) {
+ if (policyUuid == null || policyUuid.isEmpty()) {
+ return;
+ }
+ try {
+ storageStrategy.deleteVolumeQosPolicy(policyUuid);
+ } catch (Exception e) {
+ logger.error("Unused QoS policy [{}] was not deleted: {}", policyUuid, e.getMessage());
+ }
+ }
@Override
public ChapInfo getChapInfo(DataObject dataObject) {
@@ -432,6 +1281,9 @@ public boolean grantAccess(DataObject dataObject, Host host, DataStore dataStore
volumeVO.setPoolType(storagePool.getPoolType());
volumeVO.setPoolId(storagePool.getId());
volumeDao.update(volumeVO.getId(), volumeVO);
+ syncTemporarySnapshotCopyPath(dataObject, volumeVO);
+ } else if (dataObject.getType() == DataObjectType.TEMPLATE) {
+ grantAccessTemplate((TemplateInfo) dataObject, host, dataStore, storagePool);
} else {
logger.error("Invalid DataObjectType (" + dataObject.getType() + ") passed to grantAccess");
throw new CloudRuntimeException("Invalid DataObjectType (" + dataObject.getType() + ") passed to grantAccess");
@@ -443,28 +1295,117 @@ public boolean grantAccess(DataObject dataObject, Host host, DataStore dataStore
}
}
+ /**
+ * For the temporary snapshot copy, {@code StorageSystemDataMotionStrategy} builds the CopyCommand from
+ * the same in-memory volume object it passed to grantAccess, so the iSCSI path resolved by the LUN
+ * mapping must be reflected on that object too.
+ */
+ private void syncTemporarySnapshotCopyPath(DataObject dataObject, VolumeVO volumeVO) {
+ if (!isTemporarySnapshotCopyVolume(volumeVO) || !(dataObject instanceof VolumeInfo)) {
+ return;
+ }
+ Volume inMemoryVolume = ((VolumeInfo) dataObject).getVolume();
+ if (inMemoryVolume instanceof VolumeVO) {
+ ((VolumeVO) inMemoryVolume).setPath(volumeVO.getPath());
+ ((VolumeVO) inMemoryVolume).set_iScsiName(volumeVO.get_iScsiName());
+ }
+ }
+
private void grantAccessIscsi(Host host, VolumeVO volumeVO, Map details, String svmName, StoragePoolVO storagePool) {
String cloudStackVolumeName = volumeDetailsDao.findDetail(volumeVO.getId(), OntapStorageConstants.LUN_DOT_NAME).getValue();
UnifiedSANStrategy sanStrategy = (UnifiedSANStrategy) OntapStorageUtils.getStrategyByStoragePoolDetails(details);
String accessGroupName = OntapStorageUtils.getIgroupName(svmName, host.getUuid());
- // Validate if Igroup exist ONTAP for this host as we may be using delete_on_unmap= true and igroup may be deleted by ONTAP automatically
+ ensureAccessGroupForHost(sanStrategy, host, storagePool, svmName, accessGroupName);
+
+ // Create or retrieve existing LUN mapping.
+ String lunNumber = sanStrategy.ensureLunMapped(svmName, cloudStackVolumeName, accessGroupName);
+ String lunWwid = resolveVolumeLunWwid(sanStrategy, svmName, cloudStackVolumeName, volumeVO.getId());
+ logger.debug("grantAccessIscsi: LUN [{}] mapped to igroup [{}] as logical unit number [{}], WWID [{}]",
+ cloudStackVolumeName, accessGroupName, lunNumber, lunWwid);
+
+ // Update volume path if changed (e.g. the WWID was not yet known for a pre-existing volume)
+ String iscsiPath = buildIscsiPath(storagePool, lunWwid);
+ if (volumeVO.getPath() == null || !volumeVO.getPath().equals(iscsiPath)) {
+ volumeVO.set_iScsiName(iscsiPath);
+ volumeVO.setPath(iscsiPath);
+ }
+ }
+
+ /**
+ * Maps the cached template LUN to the host so the KVM agent can write the image into it.
+ *
+ * Called by the framework from {@code copyTemplateToManagedTemplateVolume} just before it
+ * issues the {@code CopyCommand}. That method reads {@code managedStoreTarget} from the pool
+ * details before this call, when the LUN number does not exist yet, so the stale
+ * value is corrected here. The datastore details are re-read when the command is built, so the
+ * update lands in time.
+ */
+ private void grantAccessTemplate(TemplateInfo templateInfo, Host host, DataStore dataStore, StoragePoolVO storagePool) {
+ Map details = storagePoolDetailsDao.listDetailsKeyPairs(storagePool.getId());
+ if (!ProtocolType.ISCSI.name().equalsIgnoreCase(details.get(OntapStorageConstants.PROTOCOL))) {
+ logger.debug("grantAccessTemplate: NFS template [{}], no igroup mapping required", templateInfo.getUuid());
+ return;
+ }
+
+ String svmName = details.get(OntapStorageConstants.SVM_NAME);
+ VMTemplateStoragePoolVO templatePoolRef = findTemplatePoolRef(storagePool.getId(), templateInfo.getId());
+ String lunName = getTemplateLunName(storagePool, templateInfo.getId());
+
+ UnifiedSANStrategy sanStrategy = (UnifiedSANStrategy) OntapStorageUtils.getStrategyByStoragePoolDetails(details);
+ String accessGroupName = OntapStorageUtils.getIgroupName(svmName, host.getUuid());
+
+ ensureAccessGroupForHost(sanStrategy, host, storagePool, svmName, accessGroupName);
+
+ boolean lunMapped = false;
+ try {
+ String lunNumber = sanStrategy.ensureLunMapped(svmName, lunName, accessGroupName);
+ lunMapped = true;
+ String iscsiPath = buildIscsiPath(storagePool, lunNumber);
+
+ templatePoolRef.setInstallPath(iscsiPath);
+ vmTemplatePoolDao.update(templatePoolRef.getId(), templatePoolRef);
+ refreshManagedStoreTarget(dataStore, iscsiPath);
+
+ logger.info("grantAccessTemplate: Mapped template cache LUN [{}] to igroup [{}] as [{}] for template [{}]",
+ lunName, accessGroupName, iscsiPath, templateInfo.getId());
+ } catch (RuntimeException e) {
+ // Undo only this call's side effect (map). Do not delete the cache LUN — create already succeeded.
+ if (lunMapped) {
+ try {
+ unmapLunFromHost(sanStrategy, svmName, lunName, accessGroupName, host);
+ } catch (Exception rollbackEx) {
+ logger.warn("grantAccessTemplate: Failed to unmap template cache LUN [{}] from igroup [{}] after grant failure: {}",
+ lunName, accessGroupName, rollbackEx.getMessage());
+ }
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * Ensures an igroup containing this host's initiator exists on the SVM.
+ *
+ * The igroup may be absent even for a host that used the pool before, because LUN maps are
+ * created with {@code delete_on_unmap}, which lets ONTAP remove the igroup on its own.
+ */
+ private void ensureAccessGroupForHost(UnifiedSANStrategy sanStrategy, Host host, StoragePoolVO storagePool,
+ String svmName, String accessGroupName) {
Map getAccessGroupMap = Map.of(
OntapStorageConstants.NAME, accessGroupName,
OntapStorageConstants.SVM_DOT_NAME, svmName
);
AccessGroup accessGroup = sanStrategy.getAccessGroup(getAccessGroupMap);
- if(accessGroup == null || accessGroup.getIgroup() == null) {
- logger.info("grantAccess: Igroup {} does not exist for the host {} : Need to create Igroup for the host ", accessGroupName, host.getName());
- // create the igroup for the host and perform lun-mapping
+ if (accessGroup == null || accessGroup.getIgroup() == null) {
+ logger.info("ensureAccessGroupForHost: Igroup {} does not exist for the host {} : Need to create Igroup for the host ", accessGroupName, host.getName());
accessGroup = new AccessGroup();
List hosts = new ArrayList<>();
hosts.add((HostVO) host);
accessGroup.setHostsToConnect(hosts);
accessGroup.setStoragePoolId(storagePool.getId());
accessGroup = sanStrategy.createAccessGroup(accessGroup);
- }else{
- logger.info("grantAccess: Igroup {} already exist for the host {}: ", accessGroup.getIgroup().getName() , host.getName());
+ } else {
+ logger.info("ensureAccessGroupForHost: Igroup {} already exist for the host {}: ", accessGroup.getIgroup().getName(), host.getName());
/* TODO Below cases will be covered later, for now they will be a pre-requisite on customer side
1. Igroup exist with the same name but host initiator has been removed
2. Igroup exist with the same name but host initiator has been changed may be due to new NIC or new adapter
@@ -472,18 +1413,28 @@ private void grantAccessIscsi(Host host, VolumeVO volumeVO, Map
Incase it is not , add it and proceed for lun-mapping
*/
}
- logger.info("grantAccess: Igroup {} is present now with initiators {} ", accessGroup.getIgroup().getName(), accessGroup.getIgroup().getInitiators());
- // Create or retrieve existing LUN mapping
- String lunNumber = sanStrategy.ensureLunMapped(svmName, cloudStackVolumeName, accessGroupName);
- String lunWwid = resolveVolumeLunWwid(sanStrategy, svmName, cloudStackVolumeName, volumeVO.getId());
- logger.debug("grantAccessIscsi: LUN [{}] mapped to igroup [{}] as logical unit number [{}], WWID [{}]",
- cloudStackVolumeName, accessGroupName, lunNumber, lunWwid);
- // Update volume path if changed (e.g. the WWID was not yet known for a pre-existing volume)
- String iscsiPath = buildIscsiPath(storagePool, lunWwid);
- if (volumeVO.getPath() == null || !volumeVO.getPath().equals(iscsiPath)) {
- volumeVO.set_iScsiName(iscsiPath);
- volumeVO.setPath(iscsiPath);
+ logger.info("ensureAccessGroupForHost: Igroup {} is present now with initiators {} ", accessGroup.getIgroup().getName(), accessGroup.getIgroup().getInitiators());
+ }
+
+ /**
+ * Builds the volume path the KVM agent expects for managed iSCSI: {@code //}.
+ */
+ private String buildIscsiPath(StoragePoolVO storagePool, String lunNumber) {
+ return OntapStorageConstants.SLASH + storagePool.getPath() + OntapStorageConstants.SLASH + lunNumber;
+ }
+
+ private void refreshManagedStoreTarget(DataStore dataStore, String iscsiPath) {
+ if (!(dataStore instanceof PrimaryDataStore)) {
+ return;
}
+ PrimaryDataStore primaryDataStore = (PrimaryDataStore) dataStore;
+ Map storeDetails = primaryDataStore.getDetails();
+ if (storeDetails == null) {
+ return;
+ }
+ Map updated = new HashMap<>(storeDetails);
+ updated.put(PrimaryDataStore.MANAGED_STORE_TARGET, iscsiPath);
+ primaryDataStore.setDetails(updated);
}
/**
@@ -520,6 +1471,8 @@ public void revokeAccess(DataObject dataObject, Host host, DataStore dataStore)
throw new CloudRuntimeException("CloudStack Volume not found for id: " + dataObject.getId());
}
revokeAccessForVolume(storagePool, volumeVO, host);
+ } else if (dataObject.getType() == DataObjectType.TEMPLATE) {
+ revokeAccessForTemplate(storagePool, (TemplateInfo) dataObject, host);
} else {
logger.error("revokeAccess: Invalid DataObjectType (" + dataObject.getType() + ") passed to revokeAccess");
throw new CloudRuntimeException("Invalid DataObjectType (" + dataObject.getType() + ") passed to revokeAccess");
@@ -545,46 +1498,73 @@ private void revokeAccessForVolume(StoragePoolVO storagePool, VolumeVO volumeVO,
// Retrieve LUN name from volume details; if missing, volume may not have been fully created
VolumeDetailVO lunDetail = volumeDetailsDao.findDetail(volumeVO.getId(), OntapStorageConstants.LUN_DOT_NAME);
- ValidateRevoke result = getValidateRevoke(volumeVO, host, lunDetail, storageStrategy, svmName, accessGroupName);
- if (result == null) return;
-
- // Remove the LUN mapping from the igroup
- Map disableLogicalAccessMap = new HashMap<>();
- disableLogicalAccessMap.put(OntapStorageConstants.LUN_DOT_UUID, result.cloudStackVolume.getLun().getUuid());
- disableLogicalAccessMap.put(OntapStorageConstants.IGROUP_DOT_UUID, result.accessGroup.getIgroup().getUuid());
- storageStrategy.disableLogicalAccess(disableLogicalAccessMap);
+ String lunName = lunDetail != null ? lunDetail.getValue() : null;
+ if (lunName == null) {
+ logger.warn("revokeAccessForVolume: No LUN name found for volume [{}]; skipping revoke", volumeVO.getId());
+ return;
+ }
+ unmapLunFromHost(storageStrategy, svmName, lunName, accessGroupName, host);
+ }
+ }
- logger.info("revokeAccessForVolume: Successfully revoked access to LUN [{}] for host [{}]",
- result.lunName, host.getName());
+ /**
+ * Unmaps the cached template LUN once the framework has finished writing the image into it.
+ */
+ private void revokeAccessForTemplate(StoragePoolVO storagePool, TemplateInfo templateInfo, Host host) {
+ Map details = storagePoolDetailsDao.listDetailsKeyPairs(storagePool.getId());
+ if (!ProtocolType.ISCSI.name().equalsIgnoreCase(details.get(OntapStorageConstants.PROTOCOL))) {
+ logger.debug("revokeAccessForTemplate: NFS template [{}], no igroup mapping to remove", templateInfo.getUuid());
+ return;
}
+
+ String svmName = details.get(OntapStorageConstants.SVM_NAME);
+ StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
+ String accessGroupName = OntapStorageUtils.getIgroupName(svmName, host.getUuid());
+ String lunName = getTemplateLunName(storagePool, templateInfo.getId());
+
+ logger.info("revokeAccessForTemplate: Revoking access to template cache LUN [{}] for host [{}]", lunName, host.getName());
+ unmapLunFromHost(storageStrategy, svmName, lunName, accessGroupName, host);
}
- @Nullable
- private ValidateRevoke getValidateRevoke(VolumeVO volumeVO, Host host, VolumeDetailVO lunDetail, StorageStrategy storageStrategy, String svmName, String accessGroupName) {
- String lunName = lunDetail != null ? lunDetail.getValue() : null;
- if (lunName == null) {
- logger.warn("revokeAccessForVolume: No LUN name found for volume [{}]; skipping revoke", volumeVO.getId());
- return null;
+ /**
+ * Removes a LUN-to-igroup mapping, skipping quietly when the LUN, the igroup or the host
+ * initiator is already gone.
+ */
+ private void unmapLunFromHost(StorageStrategy storageStrategy, String svmName, String lunName,
+ String accessGroupName, Host host) {
+ ValidateRevoke result = getValidateRevoke(lunName, host, storageStrategy, svmName, accessGroupName);
+ if (result == null) {
+ return;
}
+ Map disableLogicalAccessMap = new HashMap<>();
+ disableLogicalAccessMap.put(OntapStorageConstants.LUN_DOT_UUID, result.cloudStackVolume.getLun().getUuid());
+ disableLogicalAccessMap.put(OntapStorageConstants.IGROUP_DOT_UUID, result.accessGroup.getIgroup().getUuid());
+ storageStrategy.disableLogicalAccess(disableLogicalAccessMap);
+
+ logger.info("unmapLunFromHost: Successfully revoked access to LUN [{}] for host [{}]", result.lunName, host.getName());
+ }
+
+ @Nullable
+ private ValidateRevoke getValidateRevoke(String lunName, Host host, StorageStrategy storageStrategy, String svmName, String accessGroupName) {
// Verify LUN still exists on ONTAP (may have been manually deleted)
CloudStackVolume cloudStackVolume = getCloudStackVolumeByName(storageStrategy, svmName, lunName);
if (cloudStackVolume == null || cloudStackVolume.getLun() == null || cloudStackVolume.getLun().getUuid() == null) {
- logger.warn("revokeAccessForVolume: LUN for volume [{}] not found on ONTAP, skipping revoke", volumeVO.getId());
+ logger.warn("getValidateRevoke: LUN [{}] not found on ONTAP, skipping revoke", lunName);
return null;
}
// Verify igroup still exists on ONTAP
AccessGroup accessGroup = getAccessGroupByName(storageStrategy, svmName, accessGroupName);
if (accessGroup == null || accessGroup.getIgroup() == null || accessGroup.getIgroup().getUuid() == null) {
- logger.warn("revokeAccessForVolume: iGroup [{}] not found on ONTAP, skipping revoke", accessGroupName);
+ logger.warn("getValidateRevoke: iGroup [{}] not found on ONTAP, skipping revoke", accessGroupName);
return null;
}
// Verify host initiator is in the igroup before attempting to remove mapping
SANStrategy sanStrategy = (UnifiedSANStrategy) storageStrategy;
if (!sanStrategy.validateInitiatorInAccessGroup(host.getStorageUrl(), svmName, accessGroup.getIgroup())) {
- logger.warn("revokeAccessForVolume: Initiator [{}] is not in iGroup [{}], skipping revoke",
+ logger.warn("getValidateRevoke: Initiator [{}] is not in iGroup [{}], skipping revoke",
host.getStorageUrl(), accessGroupName);
return null;
}
@@ -635,24 +1615,138 @@ private AccessGroup getAccessGroupByName(StorageStrategy storageStrategy, String
return accessGroup;
}
+ /**
+ * ONTAP is only supported with KVM, which does not take hypervisor-side snapshots into the
+ * volume itself, so no reserve is added on top of the requested size.
+ *
+ * For a template this returns the virtual size ({@code VMTemplateVO.size}), not the
+ * compressed size on secondary storage. The cached template LUN is written by the KVM agent
+ * with {@code qemu-img convert} from QCOW2 to RAW, so it must be able to hold the fully
+ * expanded image.
+ */
@Override
public long getDataObjectSizeIncludingHypervisorSnapshotReserve(DataObject dataObject, StoragePool storagePool) {
- return 0;
+ if (dataObject == null) {
+ return 0;
+ }
+ Long size = dataObject.getSize();
+ return size != null && size > 0 ? size : 0;
}
@Override
public long getBytesRequiredForTemplate(TemplateInfo templateInfo, StoragePool storagePool) {
- return 0;
+ if (templateInfo == null || storagePool == null) {
+ return 0;
+ }
+ // template_spool_ref is inserted in Allocated before the cache exists;
+ // only skip reservation when the template is Ready and has a backend identity.
+ VMTemplateStoragePoolVO templatePoolRef =
+ vmTemplatePoolDao.findByPoolTemplate(storagePool.getId(), templateInfo.getId(), null);
+ Map details = storagePoolDetailsDao.listDetailsKeyPairs(storagePool.getId());
+ if (isTemplateCachedOnPool(templatePoolRef, details)) {
+ return 0;
+ }
+ return getDataObjectSizeIncludingHypervisorSnapshotReserve(templateInfo, storagePool);
+ }
+
+ /**
+ * Returns true when the primary template cache is present and usable for clone/deploy.
+ * A spool_ref row alone is not enough: CloudStack creates it in Allocated before the LUN/file exists.
+ * Ready is sufficient; downloadState is set alongside Ready on the managed-cache success path.
+ */
+ private boolean isTemplateCachedOnPool(VMTemplateStoragePoolVO templatePoolRef, Map details) {
+ if (templatePoolRef == null) {
+ return false;
+ }
+ if (templatePoolRef.getState() != ObjectInDataStoreStateMachine.State.Ready) {
+ return false;
+ }
+ if (details != null && isIscsi(details)) {
+ return StringUtils.isNotBlank(templatePoolRef.getLocalDownloadPath());
+ }
+ return StringUtils.isNotBlank(templatePoolRef.getInstallPath());
}
+ /**
+ * Returns the bytes used on the FlexVolume backing this pool, read directly from ONTAP
+ * ({@code space.used}).
+ *
+ * Fails closed when ONTAP cannot provide trustworthy usage data. Returning zero for an
+ * unreachable or incomplete backend would make capacity checks treat an unknown pool as empty
+ * and could incorrectly authorize a volume grow.
+ *
+ * @throws InvalidParameterValueException if {@code storagePool} is null
+ * @throws CloudRuntimeException if the pool has no FlexVolume UUID in its details, ONTAP
+ * cannot be queried, or used-space data is missing
+ */
@Override
public long getUsedBytes(StoragePool storagePool) {
- return 0;
+ if (storagePool == null) {
+ throw new InvalidParameterValueException("storagePool is null, ensure the pool exists and is fully initialised before querying used bytes");
+ }
+
+ Map poolDetails = storagePoolDetailsDao.listDetailsKeyPairs(storagePool.getId());
+ String flexVolUuid = poolDetails != null ? poolDetails.get(OntapStorageConstants.VOLUME_UUID) : null;
+
+ if (StringUtils.isBlank(flexVolUuid)) {
+ throw new CloudRuntimeException("FlexVolume UUID not found in pool details for pool " + storagePool.getId());
+ }
+
+ try {
+ StorageStrategy strategy = OntapStorageUtils.getStrategyByStoragePoolDetails(poolDetails);
+ Map queryParams = new HashMap<>();
+ queryParams.put(OntapStorageConstants.FIELDS, OntapStorageConstants.SPACE_USED);
+ var flexVol = strategy.getStorageVolume(flexVolUuid, queryParams);
+
+ if (flexVol == null) {
+ throw new CloudRuntimeException(String.format(
+ "FlexVolume [%s] backing pool [%s] was not found on ONTAP",
+ flexVolUuid, storagePool.getId()));
+ }
+ if (flexVol.getSpace() == null) {
+ throw new CloudRuntimeException(String.format(
+ "ONTAP returned no space information for FlexVolume [%s] backing pool [%s]",
+ flexVolUuid, storagePool.getId()));
+ }
+
+ logger.debug("getUsedBytes: FlexVolume [{}] backing pool [{}] reports {} bytes used",
+ flexVolUuid, storagePool.getId(), flexVol.getSpace().getUsed());
+ return flexVol.getSpace().getUsed();
+ } catch (CloudRuntimeException e) {
+ logger.error("getUsedBytes: Failed to get used bytes for pool [{}]", storagePool.getId(), e);
+ throw e;
+ } catch (Exception e) {
+ logger.error("getUsedBytes: Failed to get used bytes for pool [{}]", storagePool.getId(), e);
+ throw new CloudRuntimeException(
+ String.format("Could not read used space for pool [%s]: %s", storagePool.getId(), e.getMessage()), e);
+ }
}
+ /**
+ * Returns min IOPS reserved on the pool, including volumes still being created.
+ * Destroyed and expunged volumes are omitted by the DAO query.
+ */
@Override
public long getUsedIops(StoragePool storagePool) {
- return 0;
+ return getAllocatedMinIops(storagePool, null);
+ }
+
+ private long getAllocatedMinIops(StoragePool storagePool, Long excludeVolumeId) {
+ long usedIops = 0;
+
+ List volumes = volumeDao.findNonDestroyedVolumesByPoolId(storagePool.getId(), null);
+ if (volumes != null) {
+ for (VolumeVO volume : volumes) {
+ if (excludeVolumeId != null && excludeVolumeId.equals(volume.getId())) {
+ continue;
+ }
+ if (volume.getMinIops() != null) {
+ usedIops += volume.getMinIops();
+ }
+ }
+ }
+
+ return usedIops;
}
/**
@@ -749,9 +1843,23 @@ public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback snapshotDetails = new LinkedHashMap<>();
+ snapshotDetails.put(OntapStorageConstants.SRC_CS_VOLUME_ID, String.valueOf(volumeInfo.getId()));
+ snapshotDetails.put(OntapStorageConstants.BASE_ONTAP_FV_ID, flexVolUuid);
+ snapshotDetails.put(OntapStorageConstants.ONTAP_SNAP_ID, ontapSnapshotUuid);
+ snapshotDetails.put(OntapStorageConstants.ONTAP_SNAP_NAME, snapshotName);
+ snapshotDetails.put(OntapStorageConstants.VOLUME_PATH, volumePath);
+ snapshotDetails.put(OntapStorageConstants.PRIMARY_POOL_ID, String.valueOf(volumeVO.getPoolId()));
+ snapshotDetails.put(OntapStorageConstants.PROTOCOL, protocol);
+ // iSCSI only — needed for LUN restore / identity; null (skipped) for NFS.
+ snapshotDetails.put(OntapStorageConstants.LUN_DOT_UUID, lunUuid);
+ // Source-disk IOPS at snapshot time. Create-volume-from-snapshot applies the new volume's
+ // min/max (these values, or a root disk offering) rather than reading this detail back.
+ putPositiveIopsDetail(snapshotDetails, OntapStorageConstants.MIN_IOPS, volumeVO.getMinIops());
+ putPositiveIopsDetail(snapshotDetails, OntapStorageConstants.MAX_IOPS, volumeVO.getMaxIops());
+ updateSnapshotDetails(snapshot.getId(), snapshotDetails);
CreateObjectAnswer createObjectAnswer = new CreateObjectAnswer(snapshotObjectTo);
result = new CreateCmdResult(null, createObjectAnswer);
@@ -989,6 +2097,250 @@ private CloudStackVolume createDeleteCloudStackVolumeRequest(StoragePool storage
}
+ private boolean isIscsi(Map details) {
+ return ProtocolType.ISCSI.name().equalsIgnoreCase(details.get(OntapStorageConstants.PROTOCOL));
+ }
+
+ /**
+ * Resize request. Size is passed separately to {@code resizeCloudStackVolume}.
+ * When QoS changes, iSCSI carries the LUN uuid and policy, and NFS carries the FlexVol uuid and file policy.
+ */
+ private CloudStackVolume resizeCloudStackVolumeRequest(Map details, VolumeInfo volumeInfo,
+ VolumeQosPolicy qosPolicy) {
+ CloudStackVolume resizeRequest = new CloudStackVolume();
+ resizeRequest.setVolumeInfo(volumeInfo);
+ if (qosPolicy == null) {
+ return resizeRequest;
+ }
+ VolumeQosPolicy qosPolicyReference = new VolumeQosPolicy();
+ qosPolicyReference.setName(qosPolicy.getName());
+ qosPolicyReference.setUuid(qosPolicy.getUuid());
+
+ String protocol = details.get(OntapStorageConstants.PROTOCOL);
+ ProtocolType protocolType = ProtocolType.valueOf(protocol);
+ switch (protocolType) {
+ case NFS3:
+ FileInfo fileInfo = new FileInfo();
+ fileInfo.setQosPolicy(qosPolicyReference);
+ resizeRequest.setFile(fileInfo);
+ resizeRequest.setFlexVolumeUuid(details.get(OntapStorageConstants.VOLUME_UUID));
+ return resizeRequest;
+ case ISCSI:
+ VolumeDetailVO lunUuid = volumeDetailsDao.findDetail(volumeInfo.getId(), OntapStorageConstants.LUN_DOT_UUID);
+ if (lunUuid == null || lunUuid.getValue() == null) {
+ throw new CloudRuntimeException("LUN UUID is missing for volume " + volumeInfo.getId());
+ }
+ Lun lun = new Lun();
+ lun.setUuid(lunUuid.getValue());
+ lun.setQosPolicy(qosPolicyReference);
+ resizeRequest.setLun(lun);
+ return resizeRequest;
+ default:
+ throw new CloudRuntimeException("Unsupported protocol " + protocol);
+ }
+ }
+
+ /**
+ * Builds the request that creates or updates a volume (LUN for iSCSI, qcow2 file for NFS),
+ * attaching a QoS policy reference when one is provided.
+ */
+ private CloudStackVolume createCloudStackVolumeRequestByProtocol(StoragePoolVO storagePool, Map details,
+ DataObject volumeObject, VolumeQosPolicy qosPolicy) {
+ VolumeQosPolicy qosPolicyReference = null;
+ if (qosPolicy != null) {
+ qosPolicyReference = new VolumeQosPolicy();
+ qosPolicyReference.setName(qosPolicy.getName());
+ qosPolicyReference.setUuid(qosPolicy.getUuid());
+ }
+
+ String protocol = details.get(OntapStorageConstants.PROTOCOL);
+ ProtocolType protocolType = ProtocolType.valueOf(protocol);
+ switch (protocolType) {
+ case NFS3:
+ CloudStackVolume nfsRequest = new CloudStackVolume();
+ nfsRequest.setDatastoreId(String.valueOf(storagePool.getId()));
+ nfsRequest.setFlexVolumeUuid(details.get(OntapStorageConstants.VOLUME_UUID));
+ nfsRequest.setVolumeInfo(volumeObject);
+ if (qosPolicyReference != null) {
+ FileInfo fileInfo = new FileInfo();
+ fileInfo.setQosPolicy(qosPolicyReference);
+ nfsRequest.setFile(fileInfo);
+ }
+ return nfsRequest;
+ case ISCSI:
+ Svm svm = new Svm();
+ svm.setName(details.get(OntapStorageConstants.SVM_NAME));
+ CloudStackVolume iscsiRequest = new CloudStackVolume();
+ Lun lunRequest = new Lun();
+ lunRequest.setSvm(svm);
+
+ LunSpace lunSpace = new LunSpace();
+ lunSpace.setSize(volumeObject.getSize());
+ lunRequest.setSpace(lunSpace);
+ String lunName = volumeObject.getName().replace(OntapStorageConstants.HYPHEN, OntapStorageConstants.UNDERSCORE);
+ if (!OntapStorageUtils.isValidName(lunName)) {
+ throw new InvalidParameterValueException("Invalid dataObject name [" + lunName
+ + "]. It must start with a letter and can only contain letters, digits, and underscores, and be up to 200 characters long.");
+ }
+ lunRequest.setName(OntapStorageUtils.getLunName(storagePool.getName(), lunName));
+ lunRequest.setOsType(Lun.OsTypeEnum.valueOf(
+ OntapStorageUtils.getOSTypeFromHypervisor(storagePool.getHypervisor().name())));
+ lunRequest.setQosPolicy(qosPolicyReference);
+ iscsiRequest.setLun(lunRequest);
+ return iscsiRequest;
+ default:
+ throw new CloudRuntimeException("Unsupported protocol " + protocol);
+ }
+ }
+
+ /**
+ * LUN path used to cache a template on this pool: {@code /vol//cs_tmpl_}.
+ */
+ private String getTemplateLunName(StoragePoolVO storagePool, long templateId) {
+ return OntapStorageUtils.getLunName(storagePool.getName(), OntapStorageConstants.TEMPLATE_LUN_PREFIX + templateId);
+ }
+
+ /**
+ * Builds the request that clones the cached template LUN into a new volume LUN.
+ *
+ * Source identity mirrors the NFS file-clone path workflow: {@code clone.source.name} is
+ * the same deterministic ONTAP path used at template create
+ * ({@code /vol//cs_tmpl_}). {@code local_download_path} (LUN uuid) is
+ * still sent as a secondary identity.
+ *
+ * Size is omitted: ONTAP rejects a size on a clone create, and the clone inherits the
+ * source size. Growing to the requested volume size is a separate PATCH.
+ */
+ private CloudStackVolume createCloneLunRequest(StoragePoolVO storagePool, Map details,
+ VolumeInfo volumeObject, VMTemplateStoragePoolVO templatePoolRef,
+ long templateId, VolumeQosPolicy qosPolicy) {
+ String sourceLunUuid = templatePoolRef.getLocalDownloadPath();
+ if (sourceLunUuid == null || sourceLunUuid.isEmpty()) {
+ throw new CloudRuntimeException("Template [" + templateId + "] has no cached LUN on pool ["
+ + storagePool.getId() + "]; cannot clone volume [" + volumeObject.getId() + "]");
+ }
+
+ Svm svm = new Svm();
+ svm.setName(details.get(OntapStorageConstants.SVM_NAME));
+
+ String lunName = volumeObject.getName().replace(OntapStorageConstants.HYPHEN, OntapStorageConstants.UNDERSCORE);
+ if (!OntapStorageUtils.isValidName(lunName)) {
+ throw new InvalidParameterValueException("Invalid dataObject name [" + lunName
+ + "]. It must start with a letter and can only contain letters, digits, and underscores, and be up to 200 characters long.");
+ }
+
+ Lun.Source source = new Lun.Source();
+ source.setName(getTemplateLunName(storagePool, templateId));
+ source.setUuid(sourceLunUuid);
+ Lun.Clone clone = new Lun.Clone();
+ clone.setSource(source);
+
+ Lun lunRequest = new Lun();
+ lunRequest.setSvm(svm);
+ lunRequest.setName(OntapStorageUtils.getLunName(storagePool.getName(), lunName));
+ lunRequest.setClone(clone);
+ if (qosPolicy != null) {
+ VolumeQosPolicy qosPolicyReference = new VolumeQosPolicy();
+ qosPolicyReference.setName(qosPolicy.getName());
+ qosPolicyReference.setUuid(qosPolicy.getUuid());
+ lunRequest.setQosPolicy(qosPolicyReference);
+ }
+
+ CloudStackVolume request = new CloudStackVolume();
+ request.setLun(lunRequest);
+ request.setVolumeInfo(volumeObject);
+ return request;
+ }
+
+ /**
+ * Builds the request that clones the cached qcow2 ({@code install_path}) into a new file
+ * named after the volume uuid, inside the same FlexVolume.
+ */
+ private CloudStackVolume createCloneFileRequest(StoragePoolVO storagePool, VolumeInfo volumeInfo,
+ VMTemplateStoragePoolVO templatePoolRef, long templateId) {
+ String sourcePath = templatePoolRef.getInstallPath();
+ if (sourcePath == null || sourcePath.isEmpty()) {
+ throw new CloudRuntimeException("Template [" + templateId + "] has no cached file on pool ["
+ + storagePool.getId() + "]; cannot clone volume [" + volumeInfo.getId() + "]");
+ }
+
+ FileInfo file = new FileInfo();
+ file.setPath(sourcePath);
+
+ CloudStackVolume request = new CloudStackVolume();
+ request.setDatastoreId(String.valueOf(storagePool.getId()));
+ request.setVolumeInfo(volumeInfo);
+ request.setFile(file);
+ request.setDestinationPath(volumeInfo.getUuid());
+ return request;
+ }
+
+ /**
+ * Builds the request that clones a LUN out of a FlexVolume snapshot into a new volume LUN.
+ *
+ * {@code clone.source.name} is {@code /vol//.snapshot//}; ONTAP cannot
+ * resolve a snapshot-resident LUN by uuid, so no uuid is sent.
+ */
+ private CloudStackVolume createCloneLunFromSnapshotRequest(StoragePoolVO storagePool, Map details,
+ VolumeInfo volumeInfo, String sourceVolumePath,
+ String snapshotName, VolumeQosPolicy qosPolicy) {
+ String lunName = volumeInfo.getName().replace(OntapStorageConstants.HYPHEN, OntapStorageConstants.UNDERSCORE);
+ if (!OntapStorageUtils.isValidName(lunName)) {
+ throw new CloudRuntimeException("Invalid dataObject name [" + lunName
+ + "]. It must start with a letter and can only contain letters, digits, and underscores, and be up to 200 characters long.");
+ }
+
+ String flexVolName = details.get(OntapStorageConstants.VOLUME_NAME);
+ if (flexVolName == null || flexVolName.isEmpty()) {
+ flexVolName = storagePool.getName();
+ }
+
+ Svm svm = new Svm();
+ svm.setName(details.get(OntapStorageConstants.SVM_NAME));
+
+ Lun.Source source = new Lun.Source();
+ source.setName(OntapStorageUtils.toLunCloneSourcePathInSnapshot(sourceVolumePath, flexVolName, snapshotName));
+ Lun.Clone clone = new Lun.Clone();
+ clone.setSource(source);
+
+ Lun lunRequest = new Lun();
+ lunRequest.setSvm(svm);
+ lunRequest.setName(OntapStorageUtils.getLunName(storagePool.getName(), lunName));
+ lunRequest.setClone(clone);
+ if (qosPolicy != null) {
+ VolumeQosPolicy qosPolicyReference = new VolumeQosPolicy();
+ qosPolicyReference.setName(qosPolicy.getName());
+ qosPolicyReference.setUuid(qosPolicy.getUuid());
+ lunRequest.setQosPolicy(qosPolicyReference);
+ }
+
+ CloudStackVolume request = new CloudStackVolume();
+ request.setLun(lunRequest);
+ request.setVolumeInfo(volumeInfo);
+ return request;
+ }
+
+ /**
+ * Builds the request that clones a file out of a FlexVolume snapshot into a new file named after
+ * the volume uuid, inside the same FlexVolume.
+ */
+ private CloudStackVolume createCloneFileFromSnapshotRequest(StoragePoolVO storagePool, Map details,
+ VolumeInfo volumeInfo, String sourceVolumePath,
+ String snapshotName) {
+ String flexVolName = details.get(OntapStorageConstants.VOLUME_NAME);
+
+ FileInfo file = new FileInfo();
+ file.setPath(OntapStorageUtils.toFlexVolRelativePath(sourceVolumePath, flexVolName));
+
+ CloudStackVolume request = new CloudStackVolume();
+ request.setDatastoreId(String.valueOf(storagePool.getId()));
+ request.setVolumeInfo(volumeInfo);
+ request.setFile(file);
+ request.setDestinationPath(OntapStorageUtils.toFlexVolRelativePath(volumeInfo.getUuid(), flexVolName));
+ request.setSnapshotName(snapshotName);
+ return request;
+ }
+
// ──────────────────────────────────────────────────────────────────────────
// Snapshot Helper Methods
// ──────────────────────────────────────────────────────────────────────────
@@ -1000,6 +2352,19 @@ private String buildSnapshotName(String cloudStackSnapshotName, long snapshotId)
return OntapStorageUtils.buildOntapSnapshotName(cloudStackSnapshotName, OntapStorageConstants.CS + snapshotId);
}
+ /**
+ * Only ISCSI and NFS3 pools can be provisioned; any other protocol would fall through
+ * createAsync without producing a result, leaving the caller with a null callback value.
+ */
+ private void validateProtocol(Map details, DataStore dataStore) {
+ String protocol = details == null ? null : details.get(OntapStorageConstants.PROTOCOL);
+ boolean supported = protocol != null && Arrays.stream(ProtocolType.values())
+ .anyMatch(type -> type.name().equalsIgnoreCase(protocol));
+ if (!supported) {
+ throw new CloudRuntimeException("Unsupported protocol [" + protocol + "] on storage pool ["
+ + dataStore.getName() + "]; supported protocols are " + Arrays.toString(ProtocolType.values()));
+ }
+ }
private Storage.ImageFormat getImageFormat(StoragePoolVO storagePool) {
HypervisorType hypervisorType = storagePool.getHypervisor();
@@ -1016,81 +2381,45 @@ private Storage.ImageFormat getImageFormat(StoragePoolVO storagePool) {
throw new CloudRuntimeException("Unsupported pool type [" + spType + "] for ONTAP image format resolution");
}
}
+
/**
- * Only ISCSI and NFS3 pools can be provisioned; any other protocol would fall through
- * createAsync without producing a result, leaving the caller with a null callback value.
- */
- private void validateProtocol(Map details, DataStore dataStore) {
- String protocol = details == null ? null : details.get(OntapStorageConstants.PROTOCOL);
- boolean supported = protocol != null && Arrays.stream(ProtocolType.values())
- .anyMatch(type -> type.name().equalsIgnoreCase(protocol));
- if (!supported) {
- throw new CloudRuntimeException("Unsupported protocol [" + protocol + "] on storage pool ["
- + dataStore.getName() + "]; supported protocols are " + Arrays.toString(ProtocolType.values()));
- }
- }
- /**
- * Persists snapshot metadata in snapshot_details table.
- *
- * Persists ONTAP snapshot metadata in {@code snapshot_details} for revert and delete.
+ * Persists ONTAP snapshot metadata in {@code snapshot_details} for revert, delete, and
+ * create-volume-from-snapshot.
*
* Volume-snapshot delete reads {@code base_ontap_fv_id} and {@code ontap_snap_id} here
* during {@link #deleteCloudStackVolumeSnapshot}; missing rows prevent ONTAP cleanup.
*
- * @param csSnapshotId CloudStack snapshot ID
- * @param csVolumeId Source CloudStack volume ID
- * @param flexVolUuid ONTAP FlexVolume UUID
- * @param ontapSnapshotUuid ONTAP FlexVolume snapshot UUID
- * @param snapshotName ONTAP snapshot name
- * @param volumePath Path of the volume file/LUN within the FlexVolume (for restore)
- * @param storagePoolId Primary storage pool ID
- * @param protocol Storage protocol (NFS3 or ISCSI)
- * @param lunUuid LUN UUID (only for iSCSI, null for NFS)
+ * All rows go through {@link #persistSnapshotDetail} so DAO writes stay consistent;
+ * optional fields (LUN uuid, IOPS) are skipped when unset.
+ *
+ * @param csSnapshotId CloudStack snapshot ID
+ * @param details {@code snapshot_details} name to value, keyed by {@link OntapStorageConstants};
+ * entries with null or blank values are skipped
*/
- private void updateSnapshotDetails(long csSnapshotId, long csVolumeId, String flexVolUuid,
- String ontapSnapshotUuid, String snapshotName,
- String volumePath, long storagePoolId, String protocol,
- String lunUuid) {
- SnapshotDetailsVO snapshotDetail = new SnapshotDetailsVO(csSnapshotId,
- OntapStorageConstants.SRC_CS_VOLUME_ID, String.valueOf(csVolumeId), false);
- snapshotDetailsDao.persist(snapshotDetail);
-
- snapshotDetail = new SnapshotDetailsVO(csSnapshotId,
- OntapStorageConstants.BASE_ONTAP_FV_ID, flexVolUuid, false);
- snapshotDetailsDao.persist(snapshotDetail);
-
- snapshotDetail = new SnapshotDetailsVO(csSnapshotId,
- OntapStorageConstants.ONTAP_SNAP_ID, ontapSnapshotUuid, false);
- snapshotDetailsDao.persist(snapshotDetail);
-
- snapshotDetail = new SnapshotDetailsVO(csSnapshotId,
- OntapStorageConstants.ONTAP_SNAP_NAME, snapshotName, false);
- snapshotDetailsDao.persist(snapshotDetail);
-
- snapshotDetail = new SnapshotDetailsVO(csSnapshotId,
- OntapStorageConstants.VOLUME_PATH, volumePath, false);
- snapshotDetailsDao.persist(snapshotDetail);
-
- snapshotDetail = new SnapshotDetailsVO(csSnapshotId,
- OntapStorageConstants.PRIMARY_POOL_ID, String.valueOf(storagePoolId), false);
- snapshotDetailsDao.persist(snapshotDetail);
-
- snapshotDetail = new SnapshotDetailsVO(csSnapshotId,
- OntapStorageConstants.PROTOCOL, protocol, false);
- snapshotDetailsDao.persist(snapshotDetail);
+ private void updateSnapshotDetails(long csSnapshotId, Map details) {
+ for (Map.Entry detail : details.entrySet()) {
+ persistSnapshotDetail(csSnapshotId, detail.getKey(), detail.getValue());
+ }
+ }
- // Store LUN UUID for iSCSI volumes (required for LUN restore API)
- if (lunUuid != null && !lunUuid.isEmpty()) {
- snapshotDetail = new SnapshotDetailsVO(csSnapshotId,
- OntapStorageConstants.LUN_DOT_UUID, lunUuid, false);
- snapshotDetailsDao.persist(snapshotDetail);
+ /**
+ * Adds an IOPS entry to {@code details} only when {@code iops} is non-null and positive.
+ */
+ private static void putPositiveIopsDetail(Map details, String detailName, Long iops) {
+ if (iops != null && iops > 0) {
+ details.put(detailName, String.valueOf(iops));
}
}
+
/**
- * Builds the volume path the KVM agent expects for managed iSCSI: {@code //}.
+ * Persists one {@code snapshot_details} row. No-op when {@code value} is null or blank so
+ * optional keys (e.g. LUN uuid on NFS) share the same DAO path as required keys.
*/
- private String buildIscsiPath(StoragePoolVO storagePool, String lunWwid) {
- return OntapStorageConstants.SLASH + storagePool.getPath() + OntapStorageConstants.SLASH + lunWwid;
+ private void persistSnapshotDetail(long csSnapshotId, String detailName, String value) {
+ if (value == null || value.isEmpty()) {
+ return;
+ }
+ snapshotDetailsDao.persist(new SnapshotDetailsVO(csSnapshotId, detailName, value, false));
}
/**
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/ClusterFeignClient.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/ClusterFeignClient.java
index 582fb58e6f3b..3127e4a63335 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/ClusterFeignClient.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/ClusterFeignClient.java
@@ -19,9 +19,15 @@
package org.apache.cloudstack.storage.feign.client;
+import java.util.Map;
+
import org.apache.cloudstack.storage.feign.model.Cluster;
+import org.apache.cloudstack.storage.feign.model.ClusterNode;
+import org.apache.cloudstack.storage.feign.model.response.OntapResponse;
+
import feign.Headers;
import feign.Param;
+import feign.QueryMap;
import feign.RequestLine;
public interface ClusterFeignClient {
@@ -29,4 +35,9 @@ public interface ClusterFeignClient {
@RequestLine("GET /api/cluster")
@Headers({"Authorization: {authHeader}", "return_records: {returnRecords}"})
Cluster getCluster(@Param("authHeader") String authHeader, @Param("returnRecords") boolean returnRecords);
+
+ @RequestLine("GET /api/cluster/nodes")
+ @Headers({"Authorization: {authHeader}"})
+ OntapResponse getClusterNodes(@Param("authHeader") String authHeader,
+ @QueryMap Map queryMap);
}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/NASFeignClient.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/NASFeignClient.java
index 8cf21b94b2f1..ba38f57ef1c7 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/NASFeignClient.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/NASFeignClient.java
@@ -21,7 +21,9 @@
import feign.QueryMap;
import org.apache.cloudstack.storage.feign.model.ExportPolicy;
+import org.apache.cloudstack.storage.feign.model.FileCloneRequest;
import org.apache.cloudstack.storage.feign.model.FileInfo;
+import org.apache.cloudstack.storage.feign.model.response.JobResponse;
import org.apache.cloudstack.storage.feign.model.response.OntapResponse;
import feign.Headers;
import feign.Param;
@@ -58,6 +60,15 @@ void createFile(@Param("authHeader") String authHeader,
@Param("path") String filePath,
FileInfo file);
+ /**
+ * Creates a space-efficient clone of a file within a FlexVolume.
+ *
+ * ONTAP REST: {@code POST /api/storage/file/clone}
+ */
+ @RequestLine("POST /api/storage/file/clone")
+ @Headers({"Authorization: {authHeader}", "Content-Type: application/json"})
+ JobResponse cloneFile(@Param("authHeader") String authHeader, FileCloneRequest request);
+
// Export Policy Operations
@RequestLine("POST /api/protocols/nfs/export-policies")
@Headers({"Authorization: {authHeader}"})
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/QosFeignClient.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/QosFeignClient.java
new file mode 100644
index 000000000000..669ea935124d
--- /dev/null
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/QosFeignClient.java
@@ -0,0 +1,51 @@
+/*
+ * 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.feign.client;
+
+import java.util.Map;
+
+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 feign.Headers;
+import feign.Param;
+import feign.QueryMap;
+import feign.RequestLine;
+
+public interface QosFeignClient {
+
+ @RequestLine("POST /api/storage/qos/policies")
+ @Headers({"Authorization: {authHeader}"})
+ JobResponse createPolicy(@Param("authHeader") String authHeader, VolumeQosPolicy policy);
+
+ @RequestLine("GET /api/storage/qos/policies")
+ @Headers({"Authorization: {authHeader}"})
+ OntapResponse getPolicies(@Param("authHeader") String authHeader,
+ @QueryMap Map queryParams);
+
+ @RequestLine("GET /api/storage/qos/policies/{uuid}")
+ @Headers({"Authorization: {authHeader}"})
+ VolumeQosPolicy getPolicy(@Param("authHeader") String authHeader, @Param("uuid") String uuid,
+ @QueryMap Map queryParams);
+
+ @RequestLine("DELETE /api/storage/qos/policies/{uuid}")
+ @Headers({"Authorization: {authHeader}"})
+ JobResponse deletePolicy(@Param("authHeader") String authHeader, @Param("uuid") String uuid);
+}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/SANFeignClient.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/SANFeignClient.java
index 7281dc2ecbeb..8a60a9a3e2bb 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/SANFeignClient.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/SANFeignClient.java
@@ -50,13 +50,13 @@ public interface SANFeignClient {
@Headers({"Authorization: {authHeader}"})
Lun getLunByUUID(@Param("authHeader") String authHeader, @Param("uuid") String uuid);
- @RequestLine("PATCH /{uuid}")
- @Headers({"Authorization: {authHeader}"})
- void updateLun(@Param("authHeader") String authHeader, @Param("uuid") String uuid, Lun lun);
+ @RequestLine("PATCH /api/storage/luns/{uuid}")
+ @Headers({"Authorization: {authHeader}", "Content-Type: application/json"})
+ JobResponse updateLun(@Param("authHeader") String authHeader, @Param("uuid") String uuid, Lun lun);
@RequestLine("DELETE /api/storage/luns/{uuid}")
@Headers({"Authorization: {authHeader}"})
- void deleteLun(@Param("authHeader") String authHeader, @Param("uuid") String uuid, @QueryMap Map queryMap);
+ JobResponse deleteLun(@Param("authHeader") String authHeader, @Param("uuid") String uuid, @QueryMap Map queryMap);
// iGroup Operation APIs
@RequestLine("POST /api/protocols/san/igroups?return_records={returnRecords}")
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/VolumeFeignClient.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/VolumeFeignClient.java
index 6384566487d4..67cddceff8ca 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/VolumeFeignClient.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/client/VolumeFeignClient.java
@@ -44,7 +44,7 @@ public interface VolumeFeignClient {
@RequestLine("GET /api/storage/volumes/{uuid}")
@Headers({"Authorization: {authHeader}"})
- Volume getVolumeByUUID(@Param("authHeader") String authHeader, @Param("uuid") String uuid);
+ Volume getVolumeByUUID(@Param("authHeader") String authHeader, @Param("uuid") String uuid, @QueryMap Map queryParams);
@RequestLine("GET /api/storage/volumes")
@Headers({"Authorization: {authHeader}"})
@@ -53,4 +53,8 @@ public interface VolumeFeignClient {
@RequestLine("PATCH /api/storage/volumes/{uuid}")
@Headers({ "Authorization: {authHeader}"})
JobResponse updateVolumeRebalancing(@Param("authHeader") String authHeader, @Param("uuid") String uuid, Volume volumeRequest);
+
+ @RequestLine("PATCH /api/storage/volumes/{uuid}")
+ @Headers({ "Authorization: {authHeader}"})
+ JobResponse updateVolume(@Param("authHeader") String authHeader, @Param("uuid") String uuid, Volume volumeRequest);
}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/Cluster.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/Cluster.java
index 061372756175..861430ecf3c8 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/Cluster.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/Cluster.java
@@ -19,6 +19,7 @@
package org.apache.cloudstack.storage.feign.model;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -48,6 +49,11 @@ public class Cluster {
@JsonProperty("disaggregated")
private Boolean disaggregated = null;
+ @JsonIgnore
+ private String model;
+
+ @JsonIgnore
+ private String platformType;
public String getHealth() {
return health;
@@ -104,6 +110,22 @@ public void setDisaggregated(Boolean disaggregated) {
this.disaggregated = disaggregated;
}
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+
+ public String getPlatformType() {
+ return platformType;
+ }
+
+ public void setPlatformType(String platformType) {
+ this.platformType = platformType;
+ }
+
@Override
public int hashCode() {
return Objects.hash(getName(), getUuid());
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/ClusterNode.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/ClusterNode.java
new file mode 100644
index 000000000000..8d067c05790c
--- /dev/null
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/ClusterNode.java
@@ -0,0 +1,76 @@
+/*
+ * 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.feign.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Subset of {@code GET /api/cluster/nodes} used for ASUP
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class ClusterNode {
+
+ @JsonProperty("model")
+ private String model;
+
+ @JsonProperty("is_all_flash_optimized")
+ private Boolean allFlashOptimized;
+
+ @JsonProperty("is_perf_optimized")
+ private Boolean performanceOptimized;
+
+ @JsonProperty("is_capacity_optimized")
+ private Boolean capacityOptimized;
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+
+ public Boolean getAllFlashOptimized() {
+ return allFlashOptimized;
+ }
+
+ public void setAllFlashOptimized(Boolean allFlashOptimized) {
+ this.allFlashOptimized = allFlashOptimized;
+ }
+
+ public Boolean getPerformanceOptimized() {
+ return performanceOptimized;
+ }
+
+ public void setPerformanceOptimized(Boolean performanceOptimized) {
+ this.performanceOptimized = performanceOptimized;
+ }
+
+ public Boolean getCapacityOptimized() {
+ return capacityOptimized;
+ }
+
+ public void setCapacityOptimized(Boolean capacityOptimized) {
+ this.capacityOptimized = capacityOptimized;
+ }
+}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/FileCloneRequest.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/FileCloneRequest.java
new file mode 100644
index 000000000000..cefff9fd282f
--- /dev/null
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/FileCloneRequest.java
@@ -0,0 +1,183 @@
+/*
+ * 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.feign.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Request body for the ONTAP file clone API.
+ *
+ * ONTAP REST endpoint: {@code POST /api/storage/file/clone}
+ *
+ * Creates a space-efficient copy of a file. Source and destination paths are relative to the
+ * root of {@code volume}, and both must live in that same FlexVolume.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class FileCloneRequest {
+
+ @JsonProperty("volume")
+ private VolumeRef volume;
+
+ @JsonProperty("source_path")
+ private String sourcePath;
+
+ @JsonProperty("destination_path")
+ private String destinationPath;
+
+ @JsonProperty("overwrite_destination")
+ private Boolean overwriteDestination;
+
+ /**
+ * Optional FlexVolume snapshot to clone from. When set, ONTAP clones {@code source_path}
+ * as it existed in that snapshot rather than from the live file/LUN.
+ *
+ * Used by create-volume-from-snapshot (same FlexVol). Omitted for live template-cache clones.
+ */
+ @JsonProperty("snapshot")
+ private SnapshotRef snapshot;
+
+ public FileCloneRequest() {
+ }
+
+ public FileCloneRequest(String flexVolUuid, String flexVolName, String sourcePath, String destinationPath) {
+ this.volume = new VolumeRef(flexVolUuid, flexVolName);
+ this.sourcePath = sourcePath;
+ this.destinationPath = destinationPath;
+ }
+
+ public FileCloneRequest(String flexVolUuid, String flexVolName, String sourcePath, String destinationPath,
+ String snapshotName) {
+ this(flexVolUuid, flexVolName, sourcePath, destinationPath);
+ if (snapshotName != null && !snapshotName.isEmpty()) {
+ this.snapshot = new SnapshotRef(snapshotName);
+ }
+ }
+
+ public VolumeRef getVolume() {
+ return volume;
+ }
+
+ public void setVolume(VolumeRef volume) {
+ this.volume = volume;
+ }
+
+ public String getSourcePath() {
+ return sourcePath;
+ }
+
+ public void setSourcePath(String sourcePath) {
+ this.sourcePath = sourcePath;
+ }
+
+ public String getDestinationPath() {
+ return destinationPath;
+ }
+
+ public void setDestinationPath(String destinationPath) {
+ this.destinationPath = destinationPath;
+ }
+
+ public Boolean getOverwriteDestination() {
+ return overwriteDestination;
+ }
+
+ public void setOverwriteDestination(Boolean overwriteDestination) {
+ this.overwriteDestination = overwriteDestination;
+ }
+
+ public SnapshotRef getSnapshot() {
+ return snapshot;
+ }
+
+ public void setSnapshot(SnapshotRef snapshot) {
+ this.snapshot = snapshot;
+ }
+
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ public static class VolumeRef {
+
+ @JsonProperty("uuid")
+ private String uuid;
+
+ @JsonProperty("name")
+ private String name;
+
+ public VolumeRef() {
+ }
+
+ public VolumeRef(String uuid, String name) {
+ this.uuid = uuid;
+ this.name = name;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+ }
+
+ /**
+ * Snapshot identity for {@code POST /api/storage/file/clone} when cloning from a FlexVol snapshot.
+ */
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ public static class SnapshotRef {
+
+ @JsonProperty("name")
+ private String name;
+
+ public SnapshotRef() {
+ }
+
+ public SnapshotRef(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "FileCloneRequest{volume=" + (volume != null ? volume.getUuid() : null)
+ + ", sourcePath=" + sourcePath
+ + ", destinationPath=" + destinationPath
+ + ", snapshot=" + (snapshot != null ? snapshot.getName() : null) + "}";
+ }
+}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/FileInfo.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/FileInfo.java
index a5dd24a3a286..71bf4c980bd4 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/FileInfo.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/FileInfo.java
@@ -49,6 +49,8 @@ public class FileInfo {
private Boolean overwriteEnabled = null;
@JsonProperty("path")
private String path = null;
+ @JsonProperty("qos_policy")
+ private VolumeQosPolicy qosPolicy = null;
@JsonProperty("size")
private Long size = null;
@JsonProperty("target")
@@ -178,6 +180,15 @@ public String getPath() {
public void setPath(String path) {
this.path = path;
}
+
+ public VolumeQosPolicy getQosPolicy() {
+ return qosPolicy;
+ }
+
+ public void setQosPolicy(VolumeQosPolicy qosPolicy) {
+ this.qosPolicy = qosPolicy;
+ }
+
public Long getSize() {
return size;
}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/Lun.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/Lun.java
index 364790958c8a..0b2e09dbec45 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/Lun.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/Lun.java
@@ -83,6 +83,9 @@ public static PropertyClassEnum fromValue(String value) {
@JsonProperty("name")
private String name = null;
+ @JsonProperty("qos_policy")
+ private VolumeQosPolicy qosPolicy = null;
+
@JsonProperty("clone")
private Clone clone = null;
@@ -202,6 +205,14 @@ public void setName(String name) {
this.name = name;
}
+ public VolumeQosPolicy getQosPolicy() {
+ return qosPolicy;
+ }
+
+ public void setQosPolicy(VolumeQosPolicy qosPolicy) {
+ this.qosPolicy = qosPolicy;
+ }
+
public Lun osType(OsTypeEnum osType) {
this.osType = osType;
return this;
@@ -308,6 +319,7 @@ private String toIndentedString(Object o) {
}
+ @JsonInclude(JsonInclude.Include.NON_NULL)
public static class Clone {
@JsonProperty("source")
private Source source = null;
@@ -319,6 +331,7 @@ public void setSource(Source source) {
}
}
+ @JsonInclude(JsonInclude.Include.NON_NULL)
public static class Source {
@JsonProperty("name")
private String name = null;
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/VolumeQosPolicy.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/VolumeQosPolicy.java
index 7a9a4307ab1a..2e6ce1b6fa3c 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/VolumeQosPolicy.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/feign/model/VolumeQosPolicy.java
@@ -26,43 +26,23 @@
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class VolumeQosPolicy {
- @JsonProperty("max_throughput_iops")
- private Integer maxThroughputIops = null;
-
- @JsonProperty("max_throughput_mbps")
- private Integer maxThroughputMbps = null;
-
- @JsonProperty("min_throughput_iops")
- private Integer minThroughputIops = null;
-
+ @JsonProperty("fixed")
+ private Fixed fixed;
@JsonProperty("name")
private String name = null;
-
@JsonProperty("uuid")
private String uuid = null;
+ @JsonProperty("svm")
+ private Svm svm;
+ @JsonProperty("object_count")
+ private Integer objectCount;
- public Integer getMaxThroughputIops() {
- return maxThroughputIops;
- }
-
- public void setMaxThroughputIops(Integer maxThroughputIops) {
- this.maxThroughputIops = maxThroughputIops;
- }
-
- public Integer getMaxThroughputMbps() {
- return maxThroughputMbps;
+ public Fixed getFixed() {
+ return fixed;
}
- public void setMaxThroughputMbps(Integer maxThroughputMbps) {
- this.maxThroughputMbps = maxThroughputMbps;
- }
-
- public Integer getMinThroughputIops() {
- return minThroughputIops;
- }
-
- public void setMinThroughputIops(Integer minThroughputIops) {
- this.minThroughputIops = minThroughputIops;
+ public void setFixed(Fixed fixed) {
+ this.fixed = fixed;
}
public String getName() {
@@ -80,4 +60,57 @@ public String getUuid() {
public void setUuid(String uuid) {
this.uuid = uuid;
}
+
+ public Svm getSvm() {
+ return svm;
+ }
+
+ public void setSvm(Svm svm) {
+ this.svm = svm;
+ }
+
+ public Integer getObjectCount() {
+ return objectCount;
+ }
+
+ public void setObjectCount(Integer objectCount) {
+ this.objectCount = objectCount;
+ }
+
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ public static class Fixed {
+ @JsonProperty("capacity_shared")
+ private Boolean capacityShared;
+
+ @JsonProperty("min_throughput_iops")
+ private Long minThroughputIops;
+
+ @JsonProperty("max_throughput_iops")
+ private Long maxThroughputIops;
+
+ public Boolean getCapacityShared() {
+ return capacityShared;
+ }
+
+ public void setCapacityShared(Boolean capacityShared) {
+ this.capacityShared = capacityShared;
+ }
+
+ public Long getMinThroughputIops() {
+ return minThroughputIops;
+ }
+
+ public void setMinThroughputIops(Long minThroughputIops) {
+ this.minThroughputIops = minThroughputIops;
+ }
+
+ public Long getMaxThroughputIops() {
+ return maxThroughputIops;
+ }
+
+ public void setMaxThroughputIops(Long maxThroughputIops) {
+ this.maxThroughputIops = maxThroughputIops;
+ }
+ }
}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/lifecycle/OntapPrimaryDatastoreLifecycle.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/lifecycle/OntapPrimaryDatastoreLifecycle.java
index e67bf4ba1dde..55fb7c868c49 100755
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/lifecycle/OntapPrimaryDatastoreLifecycle.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/lifecycle/OntapPrimaryDatastoreLifecycle.java
@@ -57,6 +57,7 @@
import com.cloud.agent.api.StoragePoolInfo;
import com.cloud.alert.AlertManager;
+import com.cloud.capacity.CapacityManager;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.exception.InvalidParameterValueException;
@@ -81,6 +82,7 @@ public class OntapPrimaryDatastoreLifecycle extends BasePrimaryDataStoreLifeCycl
@Inject private PrimaryDataStoreDao storagePoolDao;
@Inject private StoragePoolDetailsDao storagePoolDetailsDao;
@Inject private AlertManager _alertMgr;
+ @Inject private CapacityManager _capacityMgr;
private static final Logger logger = LogManager.getLogger(OntapPrimaryDatastoreLifecycle.class);
private static final long ONTAP_MIN_VOLUME_SIZE_IN_BYTES = 20971520L;
@@ -101,6 +103,7 @@ public DataStore initialize(Map dsInfos) {
String storagePoolName = (String) dsInfos.get("name");
String providerName = (String) dsInfos.get("providerName");
Long capacityBytes = (Long) dsInfos.get("capacityBytes");
+ Long capacityIops = (Long) dsInfos.get("capacityIops");
boolean managed = (boolean) dsInfos.get("managed");
String tags = (String) dsInfos.get("tags");
Boolean isTagARule = (Boolean) dsInfos.get("isTagARule");
@@ -113,7 +116,7 @@ public DataStore initialize(Map dsInfos) {
@SuppressWarnings("unchecked")
Map details = (Map) dsInfos.get("details");
- validateInitializeInputs(capacityBytes, podId, clusterId, zoneId, storagePoolName, providerName, managed, details);
+ validateInitializeInputs(capacityBytes, capacityIops, podId, clusterId, zoneId, storagePoolName, providerName, managed, details);
PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters();
if (clusterId != null) {
@@ -140,6 +143,7 @@ public DataStore initialize(Map dsInfos) {
StorageStrategy storageStrategy = StorageProviderFactory.getStrategy(ontapStorage);
boolean isValid = storageStrategy.connect();
if (isValid) {
+ details.put(OntapStorageConstants.IS_AFF, Boolean.toString(storageStrategy.isAff()));
if (storageStrategy.getResolvedSvmUuid() != null && !storageStrategy.getResolvedSvmUuid().isEmpty()) {
details.put(OntapStorageConstants.SVM_UUID, storageStrategy.getResolvedSvmUuid());
}
@@ -207,12 +211,13 @@ public DataStore initialize(Map dsInfos) {
parameters.setProviderName(providerName);
parameters.setManaged(managed);
parameters.setCapacityBytes(capacityBytes);
+ parameters.setCapacityIops(capacityIops);
parameters.setUsedBytes(0);
return _dataStoreHelper.createPrimaryDataStore(parameters);
}
- private void validateInitializeInputs(Long capacityBytes, Long podId, Long clusterId, Long zoneId,
+ private void validateInitializeInputs(Long capacityBytes, Long capacityIops, Long podId, Long clusterId, Long zoneId,
String storagePoolName, String providerName, boolean managed, Map details) {
if (capacityBytes == null || capacityBytes <= 0) {
@@ -223,6 +228,10 @@ private void validateInitializeInputs(Long capacityBytes, Long podId, Long clust
throw new InvalidParameterValueException("Storage pool capacity " + capacityBytes + " bytes is below the ONTAP minimum volume size of "
+ ONTAP_MIN_VOLUME_SIZE_IN_BYTES + " bytes (20 MB)");
}
+ // IOPS capacity is optional; when left blank no pool-level IOPS ceiling is enforced.
+ if (capacityIops != null && capacityIops <= 0) {
+ throw new InvalidParameterValueException("Storage pool IOPS capacity must be greater than 0");
+ }
// Validate scope
if (podId == null ^ clusterId == null) {
@@ -551,7 +560,62 @@ public boolean migrateToObjectStore(DataStore store) {
@Override
public void updateStoragePool(StoragePool storagePool, Map details) {
+ String newCapacityIopsStr = details.get(PrimaryDataStoreLifeCycle.CAPACITY_IOPS);
+ if (newCapacityIopsStr != null) {
+ validateUpdatedCapacityIops(storagePool, newCapacityIopsStr);
+ }
+
+ String newCapacityStr = details.get(PrimaryDataStoreLifeCycle.CAPACITY_BYTES);
+ if (newCapacityStr == null) {
+ logger.debug("No capacity change requested for pool: {}, skipping FlexVolume resize", storagePool.getName());
+ return;
+ }
+ long currentCapacityBytes = storagePool.getCapacityBytes();
+ long newCapacityBytes = Long.parseLong(newCapacityStr);
+ StorageStrategy storageStrategy = OntapStorageUtils.getStrategyByStoragePoolDetails(details);
+
+ String volumeUuid = details.get(OntapStorageConstants.VOLUME_UUID);
+ if (volumeUuid == null || volumeUuid.isEmpty()) {
+ logger.error("Volume UUID or name not found in details for pool: {}, cannot resize", storagePool.getName());
+ throw new CloudRuntimeException("Volume UUID or name not found in details, cannot resize ONTAP FlexVolume");
+ }
+
+ Volume volume = new Volume();
+ volume.setUuid(volumeUuid);
+ volume.setName(details.get(OntapStorageConstants.VOLUME_NAME));
+ volume.setSize(newCapacityBytes);
+ try {
+ storageStrategy.updateStorageVolume(volume);
+ logger.info("Successfully resized ONTAP FlexVolume '{}' (UUID: {}) for pool '{}' from {} bytes to {} bytes",
+ volume.getName(), volume.getUuid(), storagePool.getName(), currentCapacityBytes, newCapacityBytes);
+ } catch (Exception e) {
+ logger.error("Exception while resizing FlexVolume for pool: {}. Error: {}", storagePool.getName(), e.getMessage(), e);
+ throw new CloudRuntimeException("Failed to resize ONTAP FlexVolume for pool: " + storagePool.getName() + ". " + e.getMessage(), e);
+ }
+ }
+
+ private void validateUpdatedCapacityIops(StoragePool storagePool, String newCapacityIopsStr) {
+ long newCapacityIops;
+ try {
+ newCapacityIops = Long.parseLong(newCapacityIopsStr);
+ } catch (NumberFormatException e) {
+ throw new InvalidParameterValueException("Invalid storage pool IOPS capacity: " + newCapacityIopsStr);
+ }
+ if (newCapacityIops <= 0) {
+ throw new InvalidParameterValueException("Storage pool IOPS capacity must be greater than 0");
+ }
+
+ StoragePoolVO storagePoolVO = storagePoolDao.findById(storagePool.getId());
+ if (storagePoolVO == null) {
+ throw new InvalidParameterValueException("Storage pool not found for id: " + storagePool.getId());
+ }
+ long allocatedIops = _capacityMgr.getUsedIops(storagePoolVO);
+ if (newCapacityIops < allocatedIops) {
+ throw new InvalidParameterValueException(String.format(
+ "Cannot set IOPS capacity of storage pool %s to %d IOPS because %d IOPS are already allocated",
+ storagePool.getName(), newCapacityIops, allocatedIops));
+ }
}
@Override
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/StorageStrategy.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/StorageStrategy.java
index b385269d5f2a..47df8e008c8c 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/StorageStrategy.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/StorageStrategy.java
@@ -19,29 +19,38 @@
package org.apache.cloudstack.storage.service;
-import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.feign.FeignClientFactory;
import org.apache.cloudstack.storage.feign.client.AggregateFeignClient;
+import org.apache.cloudstack.storage.feign.client.ClusterFeignClient;
import org.apache.cloudstack.storage.feign.client.JobFeignClient;
import org.apache.cloudstack.storage.feign.client.NASFeignClient;
import org.apache.cloudstack.storage.feign.client.NetworkFeignClient;
+import org.apache.cloudstack.storage.feign.client.QosFeignClient;
import org.apache.cloudstack.storage.feign.client.SANFeignClient;
import org.apache.cloudstack.storage.feign.client.SnapshotFeignClient;
import org.apache.cloudstack.storage.feign.client.SvmFeignClient;
import org.apache.cloudstack.storage.feign.client.VolumeFeignClient;
import org.apache.cloudstack.storage.feign.model.Aggregate;
+import org.apache.cloudstack.storage.feign.model.Cluster;
+import org.apache.cloudstack.storage.feign.model.ClusterNode;
import org.apache.cloudstack.storage.feign.model.IpInterface;
import org.apache.cloudstack.storage.feign.model.IscsiService;
import org.apache.cloudstack.storage.feign.model.Job;
import org.apache.cloudstack.storage.feign.model.Nas;
import org.apache.cloudstack.storage.feign.model.OntapStorage;
import org.apache.cloudstack.storage.feign.model.Svm;
+import org.apache.cloudstack.storage.feign.model.Version;
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;
import org.apache.cloudstack.storage.service.model.AccessGroup;
@@ -49,6 +58,7 @@
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.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -72,9 +82,11 @@ public abstract class StorageStrategy {
protected SvmFeignClient svmFeignClient;
protected JobFeignClient jobFeignClient;
protected NetworkFeignClient networkFeignClient;
+ protected QosFeignClient qosFeignClient;
protected SANFeignClient sanFeignClient;
protected NASFeignClient nasFeignClient;
protected SnapshotFeignClient snapshotFeignClient;
+ protected ClusterFeignClient clusterFeignClient;
protected OntapStorage storage;
@@ -103,9 +115,140 @@ public StorageStrategy(OntapStorage ontapStorage) {
this.svmFeignClient = feignClientFactory.createClient(SvmFeignClient.class, baseURL);
this.jobFeignClient = feignClientFactory.createClient(JobFeignClient.class, baseURL);
this.networkFeignClient = feignClientFactory.createClient(NetworkFeignClient.class, baseURL);
+ this.qosFeignClient = feignClientFactory.createClient(QosFeignClient.class, baseURL);
this.sanFeignClient = feignClientFactory.createClient(SANFeignClient.class, baseURL);
this.nasFeignClient = feignClientFactory.createClient(NASFeignClient.class, baseURL);
this.snapshotFeignClient = feignClientFactory.createClient(SnapshotFeignClient.class, baseURL);
+ this.clusterFeignClient = feignClientFactory.createClient(ClusterFeignClient.class, baseURL);
+ }
+
+ /**
+ * Fetches the ONTAP {@link Cluster} (name, uuid, version) and, for ASUP, the rolled-up node
+ * {@code model} and {@code platformType} from {@code GET /api/cluster/nodes}. Best-effort:
+ * returns {@code null} if the cluster GET fails. Node fields are left unset if the nodes GET
+ * fails. Callers must never fail a storage operation because of this.
+ *
+ * @return the ONTAP {@link Cluster}, or {@code null} if it cannot be resolved
+ */
+ public Cluster getClusterInfo() {
+ try {
+ String authHeader = OntapStorageUtils.generateAuthHeader(storage.getUsername(), storage.getPassword());
+ Cluster cluster = clusterFeignClient.getCluster(authHeader, true);
+ if (cluster != null) {
+ populateNodeAsupFields(cluster, authHeader);
+ }
+ return cluster;
+ } catch (Exception e) {
+ logger.warn("getClusterInfo: failed to fetch ONTAP cluster info for storage IP {}: {}",
+ storage.getStorageIP(), e.getMessage());
+ return null;
+ }
+ }
+
+ /**
+ * Sets {@link Cluster#setModel(String)} and {@link Cluster#setPlatformType(String)} from one
+ * {@code GET /api/cluster/nodes}. Distinct models are joined with a comma. Platform type is
+ * {@code performance}, {@code capacity}, {@code fas}, or {@code composite} when personalities mix.
+ */
+ private void populateNodeAsupFields(Cluster cluster, String authHeader) {
+ try {
+ Map query = new HashMap<>();
+ query.put(OntapStorageConstants.FIELDS, OntapStorageConstants.CLUSTER_NODE_ASUP_FIELDS);
+ OntapResponse response = clusterFeignClient.getClusterNodes(authHeader, query);
+ if (response == null || response.getRecords() == null || response.getRecords().isEmpty()) {
+ return;
+ }
+ LinkedHashSet models = new LinkedHashSet<>();
+ LinkedHashSet platformTypes = new LinkedHashSet<>();
+ for (ClusterNode node : response.getRecords()) {
+ if (node == null) {
+ continue;
+ }
+ if (node.getModel() != null && !node.getModel().isBlank()) {
+ models.add(node.getModel().trim());
+ }
+ platformTypes.add(classifyNodePlatformType(node));
+ }
+ if (!models.isEmpty()) {
+ cluster.setModel(String.join(OntapStorageConstants.COMMA, models));
+ }
+ cluster.setPlatformType(rollupPlatformType(platformTypes));
+ } catch (Exception e) {
+ logger.warn("getClusterInfo: failed to fetch ONTAP node hardware for storage IP {}: {}",
+ storage.getStorageIP(), e.getMessage());
+ }
+ }
+
+ /**
+ * Extracts a clean, parser-friendly ONTAP version string from a {@link Cluster}.
+ *
+ * Prefers the compact "generation.major.minor" numeric form (e.g. "9.17.1"), which avoids
+ * the colon/date noise in {@code version.full}. Falls back to the verbose {@code version.full}
+ * banner only when the numeric fields are unavailable.
+ *
+ * @param cluster the cluster (may be {@code null})
+ * @return the ONTAP version string, or {@code null} if it cannot be resolved
+ */
+ public String getClusterVersion(Cluster cluster) {
+ if (cluster == null || cluster.getVersion() == null) {
+ return null;
+ }
+ Version version = cluster.getVersion();
+ if (version.getGeneration() != null && version.getMajor() != null && version.getMinor() != null) {
+ return version.getGeneration() + OntapStorageConstants.DOT + version.getMajor()
+ + OntapStorageConstants.DOT + version.getMinor();
+ }
+ if (version.getFull() != null && !version.getFull().isEmpty()) {
+ return version.getFull();
+ }
+ return null;
+ }
+
+ /**
+ * Classifies one node: not all-flash → {@code fas}; all-flash + capacity → {@code capacity};
+ * otherwise all-flash (including performance-optimized or classic AFF) → {@code performance}.
+ */
+ private static String classifyNodePlatformType(ClusterNode node) {
+ boolean allFlash = Boolean.TRUE.equals(node.getAllFlashOptimized());
+ boolean capacity = Boolean.TRUE.equals(node.getCapacityOptimized());
+ if (!allFlash) {
+ return OntapStorageConstants.ASUP_PLATFORM_TYPE_FAS;
+ }
+ if (capacity) {
+ return OntapStorageConstants.ASUP_PLATFORM_TYPE_CAPACITY;
+ }
+ return OntapStorageConstants.ASUP_PLATFORM_TYPE_PERFORMANCE;
+ }
+
+ private static String rollupPlatformType(LinkedHashSet platformTypes) {
+ if (platformTypes == null || platformTypes.isEmpty()) {
+ return null;
+ }
+ if (platformTypes.size() == 1) {
+ return platformTypes.iterator().next();
+ }
+ return OntapStorageConstants.ASUP_PLATFORM_TYPE_COMPOSITE;
+ }
+
+ /**
+ * True when every cluster node reports {@code is_all_flash_optimized} (AFF, including C-series).
+ * A FAS node, or a node that omits the flag, makes this false. Used for min-throughput QoS support.
+ */
+ public boolean isAff() {
+ Map query = new HashMap<>();
+ query.put(OntapStorageConstants.FIELDS, OntapStorageConstants.CLUSTER_NODE_ASUP_FIELDS);
+ OntapResponse response = clusterFeignClient.getClusterNodes(getAuthHeader(), query);
+ if (response == null || response.getRecords() == null
+ || response.getRecords().stream().allMatch(node -> node == null)) {
+ throw new CloudRuntimeException(
+ "Unable to determine whether the ONTAP cluster is AFF or FAS");
+ }
+ for (ClusterNode node : response.getRecords()) {
+ if (node == null || !Boolean.TRUE.equals(node.getAllFlashOptimized())) {
+ return false;
+ }
+ }
+ return true;
}
/**
@@ -191,7 +334,6 @@ private void validateAndSelectAggregatesForVolumeCreation(String authHeader, Str
logger.error("No aggregates are assigned to SVM " + svmName);
throw new CloudRuntimeException("No aggregates are assigned to SVM " + svmName);
}
- List eligibleAggregates = new ArrayList<>();
for (Aggregate aggr : aggrs) {
logger.debug("Found aggregate: " + aggr.getName() + " with UUID: " + aggr.getUuid());
Aggregate aggrResp = aggregateFeignClient.getAggregateByUUID(authHeader, aggr.getUuid(),
@@ -211,13 +353,12 @@ private void validateAndSelectAggregatesForVolumeCreation(String authHeader, Str
continue;
}
logger.info("Selected aggregate: " + aggr.getName() + " for volume operations.");
- eligibleAggregates.add(aggrResp);
+ this.aggregates = List.of(aggr);
}
- if (eligibleAggregates.isEmpty()) {
+ if (this.aggregates == null || this.aggregates.isEmpty()) {
logger.error("No suitable aggregates found on SVM " + svmName + " for volume creation.");
throw new CloudRuntimeException("No suitable aggregates found on SVM " + svmName + " for volume creation.");
}
- this.aggregates = eligibleAggregates;
}
// Common methods like create/delete etc., should be here
@@ -387,7 +528,25 @@ public Volume createStorageVolume(String volumeName, Long size) {
* @return the updated Volume object
*/
public Volume updateStorageVolume(Volume volume) {
- return null;
+ logger.info("Resizing ONTAP FlexVolume '{}' (UUID: {}) to {} bytes", volume.getName(), volume.getUuid(), volume.getSize());
+ String authHeader = OntapStorageUtils.generateAuthHeader(storage.getUsername(), storage.getPassword());
+ try {
+ Volume resizeRequest = new Volume();
+ resizeRequest.setSize(volume.getSize());
+ JobResponse jobResponse = volumeFeignClient.updateVolume(authHeader, volume.getUuid(), resizeRequest);
+ pollJobIfPresent(jobResponse, "resize FlexVolume [" + volume.getUuid() + "]",
+ OntapStorageConstants.ONTAP_VOLUME_JOB_MAX_RETRIES, OntapStorageConstants.ONTAP_VOLUME_JOB_POLL_INTERVAL_MS);
+ logger.info("FlexVolume '{}' (UUID: {}) resized successfully to {} bytes", volume.getName(), volume.getUuid(), volume.getSize());
+ } catch (FeignException e) {
+ if (OntapStorageUtils.isOntapObjectNotFoundError(e)) {
+ String msg = String.format("Cannot resize FlexVolume '%s' (UUID: %s): volume not found on ONTAP (404). ", volume.getName(), volume.getUuid());
+ logger.error(msg);
+ throw new CloudRuntimeException(msg, e);
+ }
+ logger.error("Exception while resizing FlexVolume '{}' (UUID: {}): {}", volume.getName(), volume.getUuid(), e.getMessage(), e);
+ throw new CloudRuntimeException("Failed to resize ONTAP FlexVolume: " + e.getMessage(), e);
+ }
+ return volume;
}
/**
@@ -420,15 +579,38 @@ public void deleteStorageVolume(Volume volume) {
}
/**
- * Gets ONTAP Flex-Volume
- * Eligible only for Unified ONTAP storage
- * throw exception in case of disaggregated ONTAP storage
+ * Gets an ONTAP FlexVolume by UUID.
+ * Eligible only for Unified ONTAP storage.
+ * Throws exception in case of disaggregated ONTAP storage.
+ *
+ * Callers pass ONTAP query parameters when they need a partial record. For example,
+ * {@code fields=space.used} returns only used space instead of the full volume.
+ * A null or empty map returns the default volume representation.
*
- * @param volume the volume to retrieve
- * @return the retrieved Volume object
+ * @param uuid the UUID of the volume to retrieve
+ * @param queryParams ONTAP query parameters applied to {@code GET /storage/volumes/{uuid}};
+ * may be null
+ * @return the retrieved Volume object, or null if not found
*/
- public Volume getStorageVolume(Volume volume) {
- return null;
+ public Volume getStorageVolume(String uuid, Map queryParams) {
+ if (StringUtils.isBlank(uuid)) {
+ throw new CloudRuntimeException("Cannot fetch ONTAP volume: UUID is null or empty");
+ }
+ Map params = queryParams != null ? queryParams : Collections.emptyMap();
+ logger.info("getStorageVolume: Fetching ONTAP volume [{}] with query params {}", uuid, params);
+ String authHeader = OntapStorageUtils.generateAuthHeader(storage.getUsername(), storage.getPassword());
+ try {
+ Volume fetchedVolume = volumeFeignClient.getVolumeByUUID(authHeader, uuid, params);
+ logger.info("getStorageVolume: Volume [{}] fetched successfully", uuid);
+ return fetchedVolume;
+ } catch (FeignException e) {
+ if (OntapStorageUtils.isOntapObjectNotFoundError(e)) {
+ logger.warn("getStorageVolume: Volume [{}] not found in ONTAP", uuid);
+ return null;
+ }
+ logger.error("getStorageVolume: Exception while fetching volume [{}]: ", uuid, e);
+ throw new CloudRuntimeException("Failed to fetch volume: " + e.getMessage());
+ }
}
/**
@@ -531,10 +713,7 @@ public Pair getNetworkInterface() {
IpInterface fallbackInterface = null;
for (IpInterface iface : response.getRecords()) {
- if (iface == null || !Boolean.TRUE.equals(iface.getEnabled()) || !OntapStorageConstants.LIF_STATE_UP.equals(iface.getState())) {
- continue;
- }
- if (iface.getIp() == null || iface.getIp().getAddress() == null) {
+ if (!Boolean.TRUE.equals(iface.getEnabled()) || !OntapStorageConstants.LIF_STATE_UP.equals(iface.getState())) {
continue;
}
if (!isIPv4Address(iface.getIp().getAddress())) {
@@ -612,6 +791,27 @@ private boolean isIPv4Address(String address) {
*/
abstract public CloudStackVolume createCloudStackVolume(CloudStackVolume cloudstackVolume);
+ /**
+ * Creates the protocol-specific backend object that caches a template on this pool.
+ *
+ * iSCSI creates an empty LUN ({@code /vol/<flexVol>/cs_tmpl_<id>}) sized to
+ * {@code sizeInBytes}. NFS is a no-op on the array: the KVM agent later writes the qcow2
+ * into the mounted FlexVolume.
+ *
+ * Returns a {@link CloudStackVolume} so the driver can map it to {@code CreateCmdResult}
+ * and update {@code template_spool_ref}. SAN populates {@code lun}; NAS returns an empty
+ * volume (no LUN / file yet).
+ *
+ * @param storagePool CloudStack primary storage pool (one FlexVolume)
+ * @param templateInfo template being cached
+ * @param details pool details (SVM, protocol, etc.)
+ * @param sizeInBytes virtual size for the cache object (required for SAN; ignored for NAS)
+ * @return created cache identity, or an empty {@link CloudStackVolume} when nothing is
+ * pre-created on the array
+ */
+ abstract public CloudStackVolume createTemplateCache(StoragePoolVO storagePool, TemplateInfo templateInfo,
+ Map details, long sizeInBytes);
+
/**
* Method encapsulates the behavior based on the opted protocol in subclasses.
* it is going to mimic
@@ -622,7 +822,7 @@ private boolean isIPv4Address(String address) {
* @param cloudstackVolume the CloudStack volume to update
* @return the updated CloudStackVolume object
*/
- abstract CloudStackVolume updateCloudStackVolume(CloudStackVolume cloudstackVolume);
+ public abstract CloudStackVolume updateCloudStackVolume(CloudStackVolume cloudstackVolume);
/**
* Method encapsulates the behavior based on the opted protocol in subclasses.
@@ -636,14 +836,41 @@ private boolean isIPv4Address(String address) {
abstract public void deleteCloudStackVolume(CloudStackVolume cloudstackVolume);
/**
- * Method encapsulates the behavior based on the opted protocol in subclasses.
+ * Creates a space-efficient clone of an existing object inside the same FlexVolume.
* it is going to mimic
* cloneLun for iSCSI, FC protocols
* cloneFile for NFS3.0 and NFS4.1 protocols
* cloneNameSpace for Nvme/TCP and Nvme/FC protocol
- * @param cloudstackVolume the CloudStack volume to copy
+ *
+ * ONTAP requires the source and the destination to live in the same FlexVolume, which
+ * holds because a CloudStack primary storage pool maps one-to-one onto a FlexVolume.
+ *
+ * The source may be an active object or one inside a FlexVolume snapshot:
+ *
+ * - SAN — {@code lun.clone.source.name} set to
+ * {@code /vol/<fv>/.snapshot/<snap>/<lun>}
+ * - NAS — {@link CloudStackVolume#getSnapshotName()} set; it is sent as
+ * {@code snapshot.name} on {@code POST /api/storage/file/clone}
+ *
+ *
+ * @param cloudstackVolume describes the clone to create; the source is carried in the
+ * protocol-specific clone reference (for SAN, {@code lun.clone.source})
+ * @return the created CloudStackVolume, populated with the backend identity of the clone
*/
- abstract public void copyCloudStackVolume(CloudStackVolume cloudstackVolume);
+ abstract public CloudStackVolume cloneCloudStackVolume(CloudStackVolume cloudstackVolume);
+
+ /**
+ * Grows an existing backend object to {@code sizeInBytes}.
+ *
+ * Needed after cloning a cached template, because a clone inherits the size of its source
+ * while the service offering may ask for a larger disk.
+ *
+ * When the request already carries a QoS policy on the LUN or file, that policy is applied
+ * as part of this resize. iSCSI sends one LUN update with the new size and the policy.
+ * NFS grows the file on the host, then updates the file policy. A request with no policy
+ * changes size only.
+ */
+ abstract public void resizeCloudStackVolume(CloudStackVolume cloudstackVolume, long sizeInBytes);
/**
* Method encapsulates the behavior based on the opted protocol in subclasses.
@@ -765,6 +992,112 @@ public String getAuthHeader() {
return OntapStorageUtils.generateAuthHeader(storage.getUsername(), storage.getPassword());
}
+ public VolumeQosPolicy createVolumeQosPolicy(String policyName, Long minIops, Long maxIops) {
+ VolumeQosPolicy policy = buildVolumeQosPolicy(policyName, minIops, maxIops);
+ Svm svm = new Svm();
+ svm.setName(storage.getSvmName());
+ policy.setSvm(svm);
+ try {
+ JobResponse response = qosFeignClient.createPolicy(getAuthHeader(), policy);
+ pollJobIfPresent(response, "create QoS policy [" + policyName + "]");
+ } catch (FeignException e) {
+ if (e.status() != 409) {
+ throw new CloudRuntimeException("Failed to create ONTAP QoS policy [" + policyName + "]: "
+ + e.getMessage(), e);
+ }
+ logger.info("QoS policy [{}] already exists; using the existing policy", policyName);
+ }
+
+ VolumeQosPolicy createdPolicy = getVolumeQosPolicy(policyName);
+ return createdPolicy;
+ }
+
+ public void deleteVolumeQosPolicy(String policyUuid) {
+ if (policyUuid == null || policyUuid.isEmpty()) {
+ return;
+ }
+ VolumeQosPolicy policy = getVolumeQosPolicyByUuid(policyUuid);
+ if (policy == null) {
+ logger.info("QoS policy [{}] not found on ONTAP; skipping delete", policyUuid);
+ return;
+ }
+ if (policy.getObjectCount() != null && policy.getObjectCount() > 0) {
+ logger.info("QoS policy [{}] still has object_count={}; skipping delete",
+ policyUuid, policy.getObjectCount());
+ return;
+ }
+ try {
+ JobResponse response = qosFeignClient.deletePolicy(getAuthHeader(), policyUuid);
+ pollJobIfPresent(response, "delete QoS policy [" + policyUuid + "]");
+ } catch (Exception e) {
+ if ((e instanceof FeignException && ((FeignException) e).status() == 409)
+ || OntapStorageUtils.isOntapObjectNotFoundError(e)) {
+ logger.info("QoS policy [{}] was not deleted on ONTAP (already absent or conflict): {}",
+ policyUuid, e.getMessage());
+ return;
+ }
+ throw new CloudRuntimeException("Failed to delete ONTAP QoS policy [" + policyUuid + "]: "
+ + e.getMessage(), e);
+ }
+ }
+
+ private VolumeQosPolicy getVolumeQosPolicyByUuid(String policyUuid) {
+ Map queryParams = new HashMap<>();
+ queryParams.put(OntapStorageConstants.FIELDS, OntapStorageConstants.QOS_POLICY_OBJECT_COUNT_FIELDS);
+ try {
+ VolumeQosPolicy policy = qosFeignClient.getPolicy(getAuthHeader(), policyUuid, queryParams);
+ if (policy == null || StringUtils.isEmpty(policy.getUuid())) {
+ throw new CloudRuntimeException("Failed to fetch ONTAP QoS policy [" + policyUuid
+ + "]: empty response");
+ }
+ return policy;
+ } catch (FeignException e) {
+ if (OntapStorageUtils.isOntapObjectNotFoundError(e)) {
+ return null;
+ }
+ throw new CloudRuntimeException("Failed to fetch ONTAP QoS policy [" + policyUuid + "]: "
+ + e.getMessage(), e);
+ }
+ }
+
+ private VolumeQosPolicy getVolumeQosPolicy(String policyName) {
+ Map queryParams = new HashMap<>();
+ queryParams.put(OntapStorageConstants.NAME, policyName);
+ queryParams.put(OntapStorageConstants.SVM_DOT_NAME, storage.getSvmName());
+ try {
+ OntapResponse response = qosFeignClient.getPolicies(getAuthHeader(), queryParams);
+ if (response == null || response.getRecords() == null || response.getRecords().size() <= 0) {
+ throw new CloudRuntimeException("Unable to get ONTAP QoS policy [" + policyName + "] after creation");
+ }
+ VolumeQosPolicy policy = response.getRecords().get(0);
+ if (policy == null || StringUtils.isEmpty(policy.getUuid())) {
+ throw new CloudRuntimeException("Failed to fetch ONTAP QoS policy [" + policyName
+ + "]: empty response");
+ }
+ return policy;
+ } catch (FeignException e) {
+ throw new CloudRuntimeException("Failed to fetch ONTAP QoS policy [" + policyName + "]: "
+ + e.getMessage(), e);
+ }
+ }
+
+ private VolumeQosPolicy buildVolumeQosPolicy(String policyName, Long minIops, Long maxIops) {
+ VolumeQosPolicy.Fixed fixed = new VolumeQosPolicy.Fixed();
+ fixed.setCapacityShared(false);
+ // ONTAP rejects a policy whose throughput limit is zero, so only unlimited-side values are omitted.
+ if (minIops != null && minIops > 0) {
+ fixed.setMinThroughputIops(minIops);
+ }
+ if (maxIops != null && maxIops > 0) {
+ fixed.setMaxThroughputIops(maxIops);
+ }
+
+ VolumeQosPolicy policy = new VolumeQosPolicy();
+ policy.setName(policyName);
+ policy.setFixed(fixed);
+ return policy;
+ }
+
/**
* Polls an ONTAP async job for successful completion.
*
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/UnifiedNASStrategy.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/UnifiedNASStrategy.java
index 39e947b17b51..41f48541f1f0 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/UnifiedNASStrategy.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/UnifiedNASStrategy.java
@@ -19,6 +19,16 @@
package org.apache.cloudstack.storage.service;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.storage.ResizeVolumeCommand;
+import com.cloud.agent.api.to.StorageFilerTO;
+import com.cloud.host.HostVO;
+import com.cloud.storage.ResizeVolumePayload;
+import com.cloud.storage.Storage;
+import com.cloud.storage.VolumeVO;
+import com.cloud.storage.dao.VolumeDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+import feign.FeignException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
@@ -30,18 +40,23 @@
import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.storage.command.CreateObjectCommand;
import org.apache.cloudstack.storage.command.DeleteCommand;
+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.feign.model.CliSnapshotRestoreRequest;
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.Nas;
import org.apache.cloudstack.storage.feign.model.OntapStorage;
import org.apache.cloudstack.storage.feign.model.Svm;
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;
import org.apache.cloudstack.storage.service.model.AccessGroup;
@@ -54,20 +69,12 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
-import com.cloud.agent.api.Answer;
-import com.cloud.host.HostVO;
-import com.cloud.storage.Storage;
-import com.cloud.storage.VolumeVO;
-import com.cloud.storage.dao.VolumeDao;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-import feign.FeignException;
-
public class UnifiedNASStrategy extends NASStrategy {
private static final Logger logger = LogManager.getLogger(UnifiedNASStrategy.class);
@Inject private VolumeDao volumeDao;
@Inject private EndPointSelector epSelector;
@Inject private StoragePoolDetailsDao storagePoolDetailsDao;
+ @Inject private PrimaryDataStoreDao primaryDataStoreDao;
public UnifiedNASStrategy(OntapStorage ontapStorage) {
super(ontapStorage);
@@ -90,18 +97,71 @@ public CloudStackVolume createCloudStackVolume(CloudStackVolume cloudstackVolume
logger.error("createCloudStackVolume: " + errMsg);
throw new CloudRuntimeException(errMsg);
}
+ if (cloudstackVolume.getFile() != null && cloudstackVolume.getFile().getQosPolicy() != null) {
+ try {
+ updateCloudStackVolume(cloudstackVolume);
+ } catch (RuntimeException qosError) {
+ logger.error("createCloudStackVolume: QoS attach failed; deleting leftover NFS volume file", qosError);
+ try {
+ Answer cleanup = deleteVolumeOnKVMHost(cloudstackVolume.getVolumeInfo());
+ if (cleanup == null || !cleanup.getResult()) {
+ logger.error("createCloudStackVolume: leftover NFS file may remain after QoS attach failure: {}",
+ cleanup != null ? cleanup.getDetails() : "null answer");
+ }
+ } catch (Exception cleanupError) {
+ logger.error("createCloudStackVolume: failed to delete leftover NFS volume file after QoS attach failure",
+ cleanupError);
+ }
+ throw qosError;
+ }
+ }
return cloudstackVolume;
- }catch (Exception e) {
+ } catch (CloudRuntimeException e) {
+ throw e;
+ } catch (Exception e) {
logger.error("createCloudStackVolume: error occured " + e);
throw new CloudRuntimeException(e);
}
}
+ /**
+ * NFS template cache: nothing is pre-created on the array. The KVM agent writes the qcow2
+ * into the mounted FlexVolume; the framework records {@code install_path} afterward.
+ *
+ * @return {@code null}. The driver records the template uuid as the create path.
+ */
@Override
- CloudStackVolume updateCloudStackVolume(CloudStackVolume cloudstackVolume) {
+ public CloudStackVolume createTemplateCache(StoragePoolVO storagePool, TemplateInfo templateInfo,
+ Map details, long sizeInBytes) {
+ logger.info("createTemplateCache: NFS pool [{}], template [{}] will be written directly to the mounted FlexVolume",
+ storagePool.getId(), templateInfo.getId());
return null;
}
+ @Override
+ public CloudStackVolume updateCloudStackVolume(CloudStackVolume cloudstackVolume) {
+ if (cloudstackVolume == null || cloudstackVolume.getVolumeInfo() == null
+ || cloudstackVolume.getFlexVolumeUuid() == null || cloudstackVolume.getFile() == null) {
+ throw new CloudRuntimeException("Invalid NFS volume request");
+ }
+ VolumeQosPolicy qosPolicy = cloudstackVolume.getFile().getQosPolicy();
+ if (qosPolicy == null) {
+ return cloudstackVolume;
+ }
+ FileInfo fileInfo = new FileInfo();
+ fileInfo.setQosPolicy(qosPolicy);
+ String filePath = cloudstackVolume.getVolumeInfo().getUuid();
+ try {
+ nasFeignClient.updateFile(getAuthHeader(), cloudstackVolume.getFlexVolumeUuid(), filePath, fileInfo);
+ } catch (FeignException e) {
+ throw new CloudRuntimeException("Failed to update NFS volume file: " + e.getMessage(), e);
+ } catch (Exception e) {
+ throw new CloudRuntimeException("Failed to update NFS volume file: " + e.getMessage(), e);
+ }
+ logger.info("Updated NFS volume file [{}] with QoS policy [{}]", filePath, qosPolicy.getName());
+ return cloudstackVolume;
+ }
+
@Override
public void deleteCloudStackVolume(CloudStackVolume cloudstackVolume) {
logger.info("deleteCloudStackVolume: Delete cloudstack volume " + cloudstackVolume);
@@ -119,9 +179,121 @@ public void deleteCloudStackVolume(CloudStackVolume cloudstackVolume) {
}
}
+ /**
+ * Clones a file inside the FlexVolume using ONTAP's file clone API.
+ *
+ * The source is taken from {@code file.path} and the destination from
+ * {@code destinationPath}, both relative to the root of the FlexVolume backing the pool.
+ * When {@code snapshotName} is set, the source is read from that FlexVolume snapshot.
+ */
+ @Override
+ public CloudStackVolume cloneCloudStackVolume(CloudStackVolume cloudstackVolume) {
+ if (cloudstackVolume == null || cloudstackVolume.getFile() == null
+ || cloudstackVolume.getFile().getPath() == null || cloudstackVolume.getDestinationPath() == null) {
+ logger.error("cloneCloudStackVolume: File clone failed. Invalid request: {}", cloudstackVolume);
+ throw new CloudRuntimeException("Failed to clone file, invalid request");
+ }
+ if (cloudstackVolume.getDatastoreId() == null) {
+ throw new CloudRuntimeException("Failed to clone file, no datastore id in the request");
+ }
+ if (cloudstackVolume.getVolumeInfo() == null) {
+ throw new CloudRuntimeException("Failed to clone file, volume info is missing from the request");
+ }
+ final long poolId = parseDatastoreId(cloudstackVolume.getDatastoreId());
+
+ Map details = storagePoolDetailsDao.listDetailsKeyPairs(poolId);
+ String flexVolUuid = details.get(OntapStorageConstants.VOLUME_UUID);
+ String flexVolName = details.get(OntapStorageConstants.VOLUME_NAME);
+ if (flexVolUuid == null || flexVolUuid.isEmpty()) {
+ throw new CloudRuntimeException("Failed to clone file, FlexVolume uuid is missing from pool details");
+ }
+ String sourcePath = cloudstackVolume.getFile().getPath();
+ String destinationPath = cloudstackVolume.getDestinationPath();
+ String snapshotName = cloudstackVolume.getSnapshotName();
+
+ logger.info("cloneCloudStackVolume: Cloning file [{}] to [{}] in FlexVol [{}] from snapshot [{}]",
+ sourcePath, destinationPath, flexVolName, snapshotName);
+ try {
+ FileCloneRequest request = new FileCloneRequest(flexVolUuid, flexVolName, sourcePath, destinationPath, snapshotName);
+ JobResponse jobResponse = nasFeignClient.cloneFile(getAuthHeader(), request);
+ pollJobIfPresent(jobResponse, "clone file [" + sourcePath + "] to [" + destinationPath + "]");
+
+ updateCloudStackVolumeMetadata(cloudstackVolume.getDatastoreId(), cloudstackVolume.getVolumeInfo());
+
+ FileInfo clonedFile = new FileInfo();
+ clonedFile.setPath(destinationPath);
+
+ CloudStackVolume clonedCloudStackVolume = new CloudStackVolume();
+ clonedCloudStackVolume.setFile(clonedFile);
+ clonedCloudStackVolume.setDatastoreId(cloudstackVolume.getDatastoreId());
+ clonedCloudStackVolume.setVolumeInfo(cloudstackVolume.getVolumeInfo());
+ clonedCloudStackVolume.setSnapshotName(snapshotName);
+ return clonedCloudStackVolume;
+ } catch (FeignException e) {
+ logger.error("FeignException occurred while cloning file [{}], Status: {}, Exception: {}",
+ sourcePath, e.status(), e.getMessage());
+ throw new CloudRuntimeException("Failed to clone file: " + e.getMessage());
+ } catch (Exception e) {
+ logger.error("Exception occurred while cloning file [{}], Exception: {}", sourcePath, e.getMessage());
+ throw new CloudRuntimeException("Failed to clone file: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Grows the cloned qcow2 to the requested size via a host-side {@code qemu-img resize}.
+ */
@Override
- public void copyCloudStackVolume(CloudStackVolume cloudstackVolume) {
+ public void resizeCloudStackVolume(CloudStackVolume cloudstackVolume, long sizeInBytes) {
+ if (cloudstackVolume == null || cloudstackVolume.getVolumeInfo() == null) {
+ logger.error("resizeCloudStackVolume: Resize failed. Invalid request: {}", cloudstackVolume);
+ throw new CloudRuntimeException("Failed to resize file, invalid request");
+ }
+ if (sizeInBytes <= 0) {
+ throw new CloudRuntimeException("Failed to resize file, invalid size " + sizeInBytes);
+ }
+
+ DataObject volumeInfo = cloudstackVolume.getVolumeInfo();
+ Answer answer = resizeVolumeOnKVMHost(volumeInfo, sizeInBytes);
+ if (answer == null || !answer.getResult()) {
+ String errMsg = answer != null ? answer.getDetails() : "Failed to resize qcow2 on KVM host";
+ logger.error("resizeCloudStackVolume: " + errMsg);
+ throw new CloudRuntimeException(errMsg);
+ }
+ if (cloudstackVolume.getFile() != null && cloudstackVolume.getFile().getQosPolicy() != null) {
+ updateCloudStackVolume(cloudstackVolume);
+ }
+ logger.info("resizeCloudStackVolume: Resized volume [{}] to {} bytes", volumeInfo.getUuid(), sizeInBytes);
+ }
+ private Answer resizeVolumeOnKVMHost(DataObject volumeInfo, long sizeInBytes) {
+ VolumeObject volumeObject = (VolumeObject) volumeInfo;
+ VolumeVO volume = volumeDao.findById(volumeObject.getId());
+ if (volume == null) {
+ throw new CloudRuntimeException("Volume not found with id: " + volumeObject.getId());
+ }
+
+ StoragePoolVO storagePool = primaryDataStoreDao.findById(volume.getPoolId());
+ if (storagePool == null) {
+ throw new CloudRuntimeException("Storage Pool not found for id: " + volume.getPoolId());
+ }
+
+ // instanceName is set by VolumeApiServiceImpl.orchestrateResizeVolume() before calling the
+ // driver — it is the VM instance name when attached, or "none" when the volume is detached.
+ ResizeVolumePayload resizePayload = volumeObject.getpayload() instanceof ResizeVolumePayload
+ ? (ResizeVolumePayload) volumeObject.getpayload()
+ : null;
+ String instanceName = resizePayload != null ? resizePayload.instanceName : "none";
+ ResizeVolumeCommand cmd = new ResizeVolumeCommand(volume.getPath(), new StorageFilerTO(storagePool),
+ volume.getSize(), sizeInBytes, false, instanceName);
+
+ EndPoint ep = epSelector.select(volumeInfo);
+ if (ep == null) {
+ String errMsg = "No remote endpoint to send ResizeVolumeCommand, check if host is up";
+ logger.error(errMsg);
+ return new Answer(cmd, false, errMsg);
+ }
+ logger.info("resizeVolumeOnKVMHost: Sending command to endpoint: {}", ep.getHostAddr());
+ return ep.sendMessage(cmd);
}
@Override
@@ -393,7 +565,7 @@ private void assignExportPolicyToVolume(String volumeUuid, String policyName) {
volumeUpdate.setNas(nas);
try {
- JobResponse jobResponse = volumeFeignClient.updateVolumeRebalancing(authHeader, volumeUuid, volumeUpdate);
+ JobResponse jobResponse = volumeFeignClient.updateVolume(authHeader, volumeUuid, volumeUpdate);
if (jobResponse == null || jobResponse.getJob() == null) {
throw new CloudRuntimeException("Failed to attach policy " + policyName + "to volume " + volumeUuid);
}
@@ -473,8 +645,23 @@ private ExportPolicy createExportPolicyRequest(AccessGroup accessGroup,String sv
return exportPolicy;
}
+ /**
+ * Parses the pool id carried on a file-clone request. A non-numeric value fails before any
+ * ONTAP call, with the stored value in the error.
+ */
+ private long parseDatastoreId(String datastoreId) {
+ try {
+ return Long.parseLong(datastoreId);
+ } catch (NumberFormatException e) {
+ throw new CloudRuntimeException("Failed to clone file, datastore id [" + datastoreId + "] is not a number", e);
+ }
+ }
+
private String updateCloudStackVolumeMetadata(String dataStoreId, DataObject volumeInfo) {
logger.info("updateCloudStackVolumeMetadata called with datastoreID: {} volumeInfo: {} ", dataStoreId, volumeInfo );
+ if (volumeInfo == null) {
+ throw new CloudRuntimeException("Failed to update volume metadata, volume info is missing");
+ }
try {
VolumeObject volumeObject = (VolumeObject) volumeInfo;
long volumeId = volumeObject.getId();
@@ -550,6 +737,28 @@ private Answer deleteVolumeOnKVMHost(DataObject volumeInfo) {
}
}
+ /**
+ * Deletes a file from a FlexVolume, treating an already-absent file as success.
+ */
+ public void deleteFileByPath(String flexVolUuid, String filePath) {
+ logger.info("deleteFileByPath: Deleting file [{}] from FlexVol [{}]", filePath, flexVolUuid);
+ try {
+ nasFeignClient.deleteFile(getAuthHeader(), flexVolUuid, filePath);
+ logger.debug("deleteFileByPath: Deleted file [{}]", filePath);
+ } catch (FeignException e) {
+ if (e.status() == 404) {
+ logger.warn("deleteFileByPath: File [{}] does not exist (status 404), skipping deletion", filePath);
+ return;
+ }
+ logger.error("FeignException occurred while deleting file [{}], Status: {}, Exception: {}",
+ filePath, e.status(), e.getMessage());
+ throw new CloudRuntimeException("Failed to delete file: " + e.getMessage());
+ } catch (Exception e) {
+ logger.error("Exception occurred while deleting file [{}], Exception: {}", filePath, e.getMessage());
+ throw new CloudRuntimeException("Failed to delete file: " + e.getMessage());
+ }
+ }
+
private FileInfo getFile(String volumeUuid, String filePath) {
logger.info("Get File: {} for volume: {}", filePath, volumeUuid);
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/UnifiedSANStrategy.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/UnifiedSANStrategy.java
index 31d4523c6290..f78fcbaca9f4 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/UnifiedSANStrategy.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/UnifiedSANStrategy.java
@@ -19,17 +19,24 @@
package org.apache.cloudstack.storage.service;
-import com.cloud.host.HostVO;
-import com.cloud.utils.exception.CloudRuntimeException;
-import feign.FeignException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+import org.apache.cloudstack.storage.feign.model.CliSnapshotRestoreRequest;
import org.apache.cloudstack.storage.feign.model.Igroup;
import org.apache.cloudstack.storage.feign.model.Initiator;
-import org.apache.cloudstack.storage.feign.model.Svm;
-import org.apache.cloudstack.storage.feign.model.OntapStorage;
import org.apache.cloudstack.storage.feign.model.Lun;
import org.apache.cloudstack.storage.feign.model.LunMap;
-import org.apache.cloudstack.storage.feign.model.CliSnapshotRestoreRequest;
+import org.apache.cloudstack.storage.feign.model.LunSpace;
+import org.apache.cloudstack.storage.feign.model.OntapStorage;
+import org.apache.cloudstack.storage.feign.model.Svm;
+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;
@@ -38,18 +45,24 @@
import org.apache.cloudstack.storage.utils.OntapStorageConstants;
import org.apache.cloudstack.storage.utils.OntapStorageUtils;
import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
-import javax.inject.Inject;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
+
+import com.cloud.host.HostVO;
+import com.cloud.storage.VolumeDetailVO;
+import com.cloud.storage.dao.VolumeDetailsDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+import feign.FeignException;
public class UnifiedSANStrategy extends SANStrategy {
private static final Logger logger = LogManager.getLogger(UnifiedSANStrategy.class);
@Inject
private StoragePoolDetailsDao storagePoolDetailsDao;
+ @Inject
+ private VolumeDetailsDao volumeDetailsDao;
public UnifiedSANStrategy(OntapStorage ontapStorage) {
super(ontapStorage);
@@ -78,6 +91,7 @@ public CloudStackVolume createCloudStackVolume(CloudStackVolume cloudstackVolume
throw new CloudRuntimeException("Failed to create Lun: " + cloudstackVolume.getLun().getName());
}
Lun lun = createdLun.getRecords().get(0);
+ validateCreatedLun(lun, cloudstackVolume.getLun().getName(), "createCloudStackVolume");
logger.debug("createCloudStackVolume: LUN created successfully. Lun: {}", lun);
CloudStackVolume createdCloudStackVolume = new CloudStackVolume();
@@ -86,16 +100,129 @@ public CloudStackVolume createCloudStackVolume(CloudStackVolume cloudstackVolume
} catch (FeignException e) {
logger.error("FeignException occurred while creating LUN: {}, Status: {}, Exception: {}",
cloudstackVolume.getLun().getName(), e.status(), e.getMessage());
- throw new CloudRuntimeException("Failed to create Lun: " + e.getMessage());
+ throw new CloudRuntimeException("Failed to create Lun: " + e.getMessage(), e);
+ } catch (CloudRuntimeException e) {
+ throw e;
} catch (Exception e) {
logger.error("Exception occurred while creating LUN: {}, Exception: {}", cloudstackVolume.getLun().getName(), e.getMessage());
- throw new CloudRuntimeException("Failed to create Lun: " + e.getMessage());
+ throw new CloudRuntimeException("Failed to create Lun: " + e.getMessage(), e);
}
}
+ /**
+ * Creates an empty LUN that caches a template on this pool's FlexVolume.
+ *
+ * Sized to the template virtual disk size (what KVM writes after {@code qemu-img convert}
+ * to RAW). On create failure, best-effort deletes any leftover LUN before rethrowing.
+ */
@Override
- CloudStackVolume updateCloudStackVolume(CloudStackVolume cloudstackVolume) {
- return null;
+ public CloudStackVolume createTemplateCache(StoragePoolVO storagePool, TemplateInfo templateInfo,
+ Map details, long sizeInBytes) {
+ if (sizeInBytes <= 0) {
+ throw new CloudRuntimeException("Unknown virtual size for template [" + templateInfo.getId()
+ + "]; cannot size the template LUN on pool [" + storagePool.getId() + "]. The template size in vm_template"
+ + " is unset; verify the template was registered/seeded with its virtual size (virtualsize in"
+ + " template.properties on secondary storage).");
+ }
+
+ CloudStackVolume request = buildTemplateLunRequest(storagePool, details, templateInfo.getId(), sizeInBytes);
+ String lunName = request.getLun().getName();
+ CloudStackVolume created = null;
+ try {
+ created = createCloudStackVolume(request);
+ Lun lun = created.getLun();
+ logger.info("createTemplateCache: Created template cache LUN [{}] (uuid [{}], {} bytes) on pool [{}] for template [{}]",
+ lun.getName(), lun.getUuid(), sizeInBytes, storagePool.getId(), templateInfo.getId());
+ return created;
+ } catch (Exception e) {
+ bestEffortDeleteTemplateCacheLun(details.get(OntapStorageConstants.SVM_NAME), lunName,
+ created != null && created.getLun() != null ? created.getLun().getUuid() : null);
+ if (e instanceof CloudRuntimeException) {
+ throw (CloudRuntimeException) e;
+ }
+ throw new CloudRuntimeException("Failed to create template cache LUN for template [" + templateInfo.getId()
+ + "]: " + e.getMessage(), e);
+ }
+ }
+
+ private CloudStackVolume buildTemplateLunRequest(StoragePoolVO storagePool, Map details,
+ long templateId, long sizeInBytes) {
+ Svm svm = new Svm();
+ svm.setName(details.get(OntapStorageConstants.SVM_NAME));
+
+ Lun lunRequest = new Lun();
+ lunRequest.setSvm(svm);
+ lunRequest.setName(OntapStorageUtils.getLunName(storagePool.getName(),
+ OntapStorageConstants.TEMPLATE_LUN_PREFIX + templateId));
+ lunRequest.setOsType(Lun.OsTypeEnum.valueOf(
+ OntapStorageUtils.getOSTypeFromHypervisor(storagePool.getHypervisor().name())));
+ LunSpace lunSpace = new LunSpace();
+ lunSpace.setSize(sizeInBytes);
+ lunRequest.setSpace(lunSpace);
+
+ CloudStackVolume request = new CloudStackVolume();
+ request.setLun(lunRequest);
+ return request;
+ }
+
+ private void bestEffortDeleteTemplateCacheLun(String svmName, String lunName, String lunUuid) {
+ try {
+ String uuid = lunUuid;
+ if (uuid == null || uuid.isEmpty()) {
+ if (svmName == null || svmName.trim().isEmpty() || lunName == null || lunName.trim().isEmpty()) {
+ logger.warn("bestEffortDeleteTemplateCacheLun: Cannot look up leftover template cache LUN; "
+ + "svm [{}] or lun name [{}] is missing", svmName, lunName);
+ return;
+ }
+ Map lookup = Map.of(
+ OntapStorageConstants.NAME, lunName,
+ OntapStorageConstants.SVM_DOT_NAME, svmName);
+ CloudStackVolume existing = getCloudStackVolume(lookup);
+ if (existing == null || existing.getLun() == null || existing.getLun().getUuid() == null) {
+ logger.warn("bestEffortDeleteTemplateCacheLun: LUN [{}] not found on SVM [{}]; nothing to delete",
+ lunName, svmName);
+ return;
+ }
+ uuid = existing.getLun().getUuid();
+ }
+ Lun lun = new Lun();
+ lun.setUuid(uuid);
+ lun.setName(lunName);
+ CloudStackVolume deleteRequest = new CloudStackVolume();
+ deleteRequest.setLun(lun);
+ deleteCloudStackVolume(deleteRequest);
+ logger.info("bestEffortDeleteTemplateCacheLun: Removed leftover template cache LUN [{}] on SVM [{}]",
+ lunName, svmName);
+ } catch (Exception cleanupEx) {
+ logger.warn("bestEffortDeleteTemplateCacheLun: Failed to remove leftover template cache LUN [{}] on SVM [{}]: {}",
+ lunName, svmName, cleanupEx.getMessage());
+ }
+ }
+
+ @Override
+ public CloudStackVolume updateCloudStackVolume(CloudStackVolume cloudstackVolume) {
+ if (cloudstackVolume == null || cloudstackVolume.getLun() == null
+ || cloudstackVolume.getLun().getUuid() == null) {
+ throw new CloudRuntimeException("Invalid iSCSI volume request");
+ }
+ VolumeQosPolicy qosPolicy = cloudstackVolume.getLun().getQosPolicy();
+ if (qosPolicy == null) {
+ return cloudstackVolume;
+ }
+ Lun lunUpdate = new Lun();
+ lunUpdate.setQosPolicy(qosPolicy);
+ try {
+ JobResponse response = sanFeignClient.updateLun(
+ getAuthHeader(), cloudstackVolume.getLun().getUuid(), lunUpdate);
+ pollJobIfPresent(response, "update LUN [" + cloudstackVolume.getLun().getUuid() + "]");
+ } catch (FeignException e) {
+ throw new CloudRuntimeException("Failed to update LUN: " + e.getMessage(), e);
+ } catch (Exception e) {
+ throw new CloudRuntimeException("Failed to update LUN: " + e.getMessage(), e);
+ }
+ logger.info("Updated LUN [{}] with QoS policy [{}]",
+ cloudstackVolume.getLun().getUuid(), qosPolicy.getName());
+ return cloudstackVolume;
}
@Override
@@ -109,7 +236,8 @@ public void deleteCloudStackVolume(CloudStackVolume cloudstackVolume) {
String authHeader = OntapStorageUtils.generateAuthHeader(storage.getUsername(), storage.getPassword());
Map queryParams = Map.of("allow_delete_while_mapped", "true");
try {
- sanFeignClient.deleteLun(authHeader, cloudstackVolume.getLun().getUuid(), queryParams);
+ JobResponse response = sanFeignClient.deleteLun(authHeader, cloudstackVolume.getLun().getUuid(), queryParams);
+ pollJobIfPresent(response, "delete Lun [" + cloudstackVolume.getLun().getName() + "]");
} catch (FeignException feignEx) {
if (feignEx.status() == 404) {
logger.warn("deleteCloudStackVolume: Lun {} does not exist (status 404), skipping deletion", cloudstackVolume.getLun().getName());
@@ -124,8 +252,128 @@ public void deleteCloudStackVolume(CloudStackVolume cloudstackVolume) {
}
}
+ /**
+ * Clones a LUN inside the FlexVolume using ONTAP's {@code clone.source} form of LUN create.
+ *
+ * The resulting LUN shares blocks with its source and is created in constant time.
+ * It is a sis-clone, so it stays readable after the source LUN is deleted.
+ */
@Override
- public void copyCloudStackVolume(CloudStackVolume cloudstackVolume) {}
+ public CloudStackVolume cloneCloudStackVolume(CloudStackVolume cloudstackVolume) {
+ if (cloudstackVolume == null || cloudstackVolume.getLun() == null) {
+ logger.error("cloneCloudStackVolume: LUN clone failed. Invalid request: {}", cloudstackVolume);
+ throw new CloudRuntimeException("Failed to clone Lun, invalid request");
+ }
+ Lun lunRequest = cloudstackVolume.getLun();
+ if (lunRequest.getClone() == null || lunRequest.getClone().getSource() == null) {
+ logger.error("cloneCloudStackVolume: LUN clone failed. No clone source in request for Lun {}", lunRequest.getName());
+ throw new CloudRuntimeException("Failed to clone Lun, no clone source provided");
+ }
+ logger.trace("cloneCloudStackVolume: Cloning Lun {} from source name={} uuid={}",
+ lunRequest.getName(),
+ lunRequest.getClone().getSource().getName(),
+ lunRequest.getClone().getSource().getUuid());
+ try {
+ String authHeader = OntapStorageUtils.generateAuthHeader(storage.getUsername(), storage.getPassword());
+ OntapResponse clonedLun = sanFeignClient.createLun(authHeader, true, lunRequest);
+ if (clonedLun == null || CollectionUtils.isEmpty(clonedLun.getRecords())) {
+ logger.error("cloneCloudStackVolume: LUN clone returned no records for Lun {}", lunRequest.getName());
+ throw new CloudRuntimeException("Failed to clone Lun: " + lunRequest.getName());
+ }
+ Lun lun = clonedLun.getRecords().get(0);
+ validateCreatedLun(lun, lunRequest.getName(), "cloneCloudStackVolume");
+ logger.debug("cloneCloudStackVolume: LUN cloned successfully. Lun: {}", lun);
+
+ CloudStackVolume clonedCloudStackVolume = new CloudStackVolume();
+ clonedCloudStackVolume.setLun(lun);
+ clonedCloudStackVolume.setVolumeInfo(cloudstackVolume.getVolumeInfo());
+ return clonedCloudStackVolume;
+ } catch (FeignException e) {
+ logger.error("FeignException occurred while cloning LUN: {}, Status: {}, Exception: {}",
+ lunRequest.getName(), e.status(), e.getMessage());
+ throw new CloudRuntimeException("Failed to clone Lun: " + e.getMessage());
+ } catch (CloudRuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ logger.error("Exception occurred while cloning LUN: {}, Exception: {}", lunRequest.getName(), e.getMessage());
+ throw new CloudRuntimeException("Failed to clone Lun: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Ensures ONTAP returned a usable LUN identity from create/clone. Callers in the datastore
+ * driver rely on non-null name and uuid, so reject incomplete records at the Feign boundary.
+ */
+ private void validateCreatedLun(Lun lun, String requestName, String operation) {
+ if (lun == null || lun.getName() == null || lun.getUuid() == null) {
+ logger.error("{}: ONTAP returned incomplete LUN for {}", operation, requestName);
+ throw new CloudRuntimeException("ONTAP returned incomplete LUN for: " + requestName);
+ }
+ }
+
+ /**
+ * Grows an existing LUN to {@code sizeInBytes}.
+ *
+ * Needed after cloning a cached template, because a clone inherits the size of its source
+ * while the service offering may ask for a larger disk.
+ */
+ @Override
+ public void resizeCloudStackVolume(CloudStackVolume cloudstackVolume, long sizeInBytes) {
+ if (cloudstackVolume == null || cloudstackVolume.getVolumeInfo() == null) {
+ logger.error("resizeCloudStackVolume: Lun resize failed. Invalid request: {}", cloudstackVolume);
+ throw new CloudRuntimeException("Failed to resize Lun, invalid request");
+ }
+ if (sizeInBytes <= 0) {
+ throw new CloudRuntimeException("Failed to resize Lun, invalid size " + sizeInBytes);
+ }
+
+ // Resolve LUN UUID from volume details when not pre-populated on the cloudstackVolume
+ // Keep a QoS policy already set on the request so size and QoS go out in one LUN update.
+ VolumeQosPolicy qosPolicy = cloudstackVolume.getLun() != null ? cloudstackVolume.getLun().getQosPolicy() : null;
+ if (cloudstackVolume.getLun() == null || cloudstackVolume.getLun().getUuid() == null) {
+ logger.debug("LUN details not present on cloudstackVolume, resolving UUID from volume details");
+ long volumeId = cloudstackVolume.getVolumeInfo().getId();
+ VolumeDetailVO lunUuidDetail = volumeDetailsDao.findDetail(volumeId, OntapStorageConstants.LUN_DOT_UUID);
+ if (lunUuidDetail == null || StringUtils.isBlank(lunUuidDetail.getValue())) {
+ throw new CloudRuntimeException("LUN UUID not found in volume details for volume " + volumeId);
+ }
+ Lun resolvedLun = new Lun();
+ resolvedLun.setUuid(lunUuidDetail.getValue());
+ cloudstackVolume.setLun(resolvedLun);
+ } else {
+ logger.debug("resizeCloudStackVolume: LUN UUID [{}] already present on cloudstackVolume, skipping volume details lookup", cloudstackVolume.getLun().getUuid());
+ }
+
+ String lunUuid = cloudstackVolume.getLun().getUuid();
+ logger.trace("resizeCloudStackVolume: Resizing Lun {} to {} bytes", lunUuid, sizeInBytes);
+ try {
+ String authHeader = OntapStorageUtils.generateAuthHeader(storage.getUsername(), storage.getPassword());
+ LunSpace lunSpace = new LunSpace();
+ lunSpace.setSize(sizeInBytes);
+ Lun lunPatch = new Lun();
+ lunPatch.setSpace(lunSpace);
+ if (qosPolicy != null) {
+ lunPatch.setQosPolicy(qosPolicy);
+ }
+ JobResponse response = sanFeignClient.updateLun(authHeader, lunUuid, lunPatch);
+ pollJobIfPresent(response, "resize Lun [" + lunUuid + "]");
+ logger.debug("resizeCloudStackVolume: Lun {} resized to {} bytes", lunUuid, sizeInBytes);
+ } catch (FeignException e) {
+ logger.error("FeignException occurred while resizing LUN [{}], Status: {}, Exception: {}",
+ lunUuid, e.status(), e.getMessage());
+ if (OntapStorageUtils.isOntapObjectNotFoundError(e)) {
+ throw new CloudRuntimeException(String.format(
+ "LUN [%s] no longer exists on ONTAP; it may have been deleted externally. " +
+ "Verify the LUN is present before retrying the resize.", lunUuid));
+ }
+ throw new CloudRuntimeException(String.format(
+ "Failed to resize LUN [%s]: %s",lunUuid, e.getMessage()));
+ } catch (Exception e) {
+ logger.error("Exception occurred while resizing LUN [{}]: {}", lunUuid, e.getMessage());
+ throw new CloudRuntimeException(String.format(
+ "Unexpected error while resizing LUN [%s]: %s", lunUuid, e.getMessage()));
+ }
+ }
@Override
public CloudStackVolume getCloudStackVolume(Map values) {
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/model/CloudStackVolume.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/model/CloudStackVolume.java
index ab38e3045f51..5147e9ff7ac2 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/model/CloudStackVolume.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/service/model/CloudStackVolume.java
@@ -51,6 +51,12 @@ public class CloudStackVolume {
*/
private String destinationPath;
+ /**
+ * ONTAP FlexVolume snapshot name when cloning a new file/LUN from a snapshot
+ * (create-volume-from-snapshot). Null for live clones (e.g. template cache).
+ */
+ private String snapshotName;
+
private DataObject volumeInfo; // This is needed as we need DataObject to be passed to agent to create volume
public FileInfo getFile() {
@@ -101,4 +107,12 @@ public void setDestinationPath(String destinationPath) {
this.destinationPath = destinationPath;
}
+ public String getSnapshotName() {
+ return snapshotName;
+ }
+
+ public void setSnapshotName(String snapshotName) {
+ this.snapshotName = snapshotName;
+ }
+
}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/utils/OntapStorageConstants.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/utils/OntapStorageConstants.java
index 3a0a5b64eb7a..4e45f2cc6a7c 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/utils/OntapStorageConstants.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/utils/OntapStorageConstants.java
@@ -59,14 +59,20 @@ public class OntapStorageConstants {
public static final String JOB_SUCCESS = "success";
public static final String TRUE = "true";
- public static final String FALSE = "false";
// Query params
public static final String NAME = "name";
public static final String FIELDS = "fields";
+ /** ONTAP volume field: bytes consumed, {@code space.used}. */
+ public static final String SPACE_USED = "space.used";
public static final String INITIATORS = "initiators";
public static final String AGGREGATES = "aggregates";
public static final String STATE = "state";
+ public static final String CLUSTER_NODE_ASUP_FIELDS = "model,is_all_flash_optimized,is_capacity_optimized,is_perf_optimized";
+ public static final String ASUP_PLATFORM_TYPE_PERFORMANCE = "performance";
+ public static final String ASUP_PLATFORM_TYPE_CAPACITY = "capacity";
+ public static final String ASUP_PLATFORM_TYPE_FAS = "fas";
+ public static final String ASUP_PLATFORM_TYPE_COMPOSITE = "composite";
public static final String AGGREGATE_NODE = "node";
public static final String AGGREGATE_SPACE = "space";
public static final String DATA_NFS = "data_nfs";
@@ -89,10 +95,17 @@ public class OntapStorageConstants {
public static final String EQUALS = "=";
public static final String SEMICOLON = ";";
public static final String COMMA = ",";
+ public static final String DOT = ".";
public static final String HYPHEN = "-";
public static final String VOLUME_PATH_PREFIX = "/vol/";
+ /**
+ * Path segment inserted after the FlexVol name when identifying a LUN inside a FlexVol snapshot
+ * for {@code POST /api/storage/luns} clone ({@code /vol/<fv>/.snapshot/<snap>/<lun>}).
+ */
+ public static final String SNAPSHOT_PATH_SEGMENT = "/.snapshot/";
+
public static final String ONTAP_NAME_REGEX = "^[a-zA-Z][a-zA-Z0-9_]*$";
public static final String KVM = "KVM";
@@ -102,6 +115,15 @@ public class OntapStorageConstants {
public static final String IQN = "iqn";
public static final String LUN_DOT_UUID = "lun.uuid";
public static final String LUN_DOT_SERIAL_NUMBER = "lun.serial_number";
+ public static final String QOS_POLICY_UUID = "qosPolicyUuid";
+ public static final String IS_AFF = "isAFF";
+ public static final String MIN_IOPS_NOT_SUPPORTED_ON_FAS = "Minimum IOPS must be 0 for FAS. Only a Maximum IOPS limit is supported";
+ public static final String QOS_POLICY_NONE = "none";
+ public static final String QOS_POLICY_NAME_PREFIX = "cs_";
+ public static final String QOS_POLICY_NAME_TO = "to_";
+ public static final String QOS_POLICY_NAME_IOPS = "iops_";
+ public static final String UUID = "uuid";
+ public static final String QOS_POLICY_OBJECT_COUNT_FIELDS = "uuid,name,object_count";
public static final String LOGICAL_UNIT_NUMBER = "logical_unit_number";
public static final String IGROUP_DOT_NAME = "igroup.name";
public static final String IGROUP_DOT_UUID = "igroup.uuid";
@@ -115,6 +137,13 @@ public class OntapStorageConstants {
public static final String VOLUME_PATH = "volume_path";
public static final String PRIMARY_POOL_ID = "primary_pool_id";
public static final String ONTAP_SNAP_SIZE = "ontap_snap_size";
+ /**
+ * Optional {@code snapshot_details} keys: min/max IOPS from the source volume at take-snapshot
+ * time. Persisted only when the volume has configured values; applied to volumes created from
+ * the snapshot in a later change (see TODO on create-from-snapshot).
+ */
+ public static final String MIN_IOPS = "min_iops";
+ public static final String MAX_IOPS = "max_iops";
public static final String FILE_PATH = "file_path";
public static final int MAX_SNAPSHOT_NAME_LENGTH = 255;
public static final String ONTAP_TEMP_CG_PREFIX = "cs-temp-cg-";
@@ -128,6 +157,9 @@ public class OntapStorageConstants {
public static final int ONTAP_SFSR_JOB_POLL_INTERVAL_MS = 2000;
public static final int ONTAP_SNAPSHOT_DELETE_JOB_MAX_RETRIES = 30;
public static final int ONTAP_SNAPSHOT_DELETE_JOB_POLL_INTERVAL_MS = 2000;
+ /** Retry settings for FlexVolume create/resize/delete job polling. */
+ public static final int ONTAP_VOLUME_JOB_MAX_RETRIES = 10;
+ public static final int ONTAP_VOLUME_JOB_POLL_INTERVAL_MS = 1000;
public static final int ONTAP_FLEXVOL_JOB_POLL_INTERVAL_MS = 2000;
public static final int ONTAP_FLEXVOL_RESOLVE_MAX_RETRIES = 30;
@@ -151,4 +183,35 @@ public class OntapStorageConstants {
* bytes of the LUN serial, hex-encoded), yielding 32 hex chars / 128 bits.
*/
public static final String NETAPP_NAA_PREFIX = NAA_IEEE_REG_EXT + NETAPP_OUI + "0";
+
+ /** Name prefix of the LUN that caches a template on the FlexVol, suffixed with the template id. */
+ public static final String TEMPLATE_LUN_PREFIX = "cs_tmpl_";
+
+ /**
+ * Key of the {@code volume_details} row that {@code StorageSystemDataMotionStrategy} writes
+ * immediately before {@code createAsync} when a volume is to be cloned from a template already
+ * cached on this pool. The value is the CloudStack template id. The literal must stay in sync
+ * with the string used by the orchestrator.
+ */
+ public static final String CLONE_OF_TEMPLATE = "cloneOfTemplate";
+
+ /**
+ * Key of the {@code volume_details} row that {@code StorageSystemDataMotionStrategy} writes
+ * immediately before {@code createAsync} when a volume is to be created from a CloudStack
+ * snapshot already present on this pool. The value is the CloudStack snapshot id. The literal
+ * must stay in sync with the string used by the orchestrator.
+ */
+ public static final String CLONE_OF_SNAPSHOT = "cloneOfSnapshot";
+
+ /**
+ * Driver capability read by {@code StorageSystemDataMotionStrategy} when copying a snapshot to
+ * secondary storage. The literal must stay in sync with the string used by the orchestrator.
+ */
+ public static final String CAN_DIRECT_ATTACH_SNAPSHOT = "CAN_DIRECT_ATTACH_SNAPSHOT";
+
+ /**
+ * Name prefix of the temporary volume a snapshot is cloned into for createTemplate(snapshotid),
+ * suffixed with the CloudStack snapshot id and volume id.
+ */
+ public static final String TEMP_SNAPSHOT_COPY_NAME_PREFIX = "cs_tmp_snap_";
}
diff --git a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/utils/OntapStorageUtils.java b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/utils/OntapStorageUtils.java
index 7f09b5584b40..0e19d767c4a0 100644
--- a/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/utils/OntapStorageUtils.java
+++ b/plugins/storage/volume/ontap/src/main/java/org/apache/cloudstack/storage/utils/OntapStorageUtils.java
@@ -19,28 +19,23 @@
package org.apache.cloudstack.storage.utils;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.utils.StringUtils;
+import com.cloud.utils.exception.CloudRuntimeException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import feign.FeignException;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
-import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.feign.model.Lun;
-import org.apache.cloudstack.storage.feign.model.LunSpace;
import org.apache.cloudstack.storage.feign.model.OntapStorage;
-import org.apache.cloudstack.storage.feign.model.Svm;
import org.apache.cloudstack.storage.provider.StorageProviderFactory;
import org.apache.cloudstack.storage.service.StorageStrategy;
-import org.apache.cloudstack.storage.service.model.CloudStackVolume;
import org.apache.cloudstack.storage.service.model.ProtocolType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.Base64Utils;
import com.cloud.alert.AlertManager;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.utils.StringUtils;
-import com.cloud.utils.exception.CloudRuntimeException;
public class OntapStorageUtils {
@@ -60,48 +55,6 @@ public static String generateAuthHeader (String username, String password) {
return BASIC + StringUtils.SPACE + new String(encodedBytes);
}
- public static CloudStackVolume createCloudStackVolumeRequestByProtocol(StoragePoolVO storagePool, Map details, DataObject volumeObject) {
- CloudStackVolume cloudStackVolumeRequest = null;
-
- String protocol = details.get(OntapStorageConstants.PROTOCOL);
- ProtocolType protocolType = ProtocolType.valueOf(protocol);
- switch (protocolType) {
- case NFS3:
- cloudStackVolumeRequest = new CloudStackVolume();
- cloudStackVolumeRequest.setDatastoreId(String.valueOf(storagePool.getId()));
- cloudStackVolumeRequest.setVolumeInfo(volumeObject);
- break;
- case ISCSI:
- Svm svm = new Svm();
- svm.setName(details.get(OntapStorageConstants.SVM_NAME));
- cloudStackVolumeRequest = new CloudStackVolume();
- Lun lunRequest = new Lun();
- lunRequest.setSvm(svm);
-
- LunSpace lunSpace = new LunSpace();
- lunSpace.setSize(volumeObject.getSize());
- lunRequest.setSpace(lunSpace);
- //Lun name is full path like in unified "/vol/VolumeName/LunName"
- String lunName = volumeObject.getName().replace(OntapStorageConstants.HYPHEN, OntapStorageConstants.UNDERSCORE);
- if(!isValidName(lunName)) {
- String errMsg = "createAsync: Invalid dataObject name [" + lunName + "]. It must start with a letter and can only contain letters, digits, and underscores, and be up to 200 characters long.";
- throw new InvalidParameterValueException(errMsg);
- }
- String lunFullName = getLunName(storagePool.getName(), lunName);
- lunRequest.setName(lunFullName);
-
- String osType = getOSTypeFromHypervisor(storagePool.getHypervisor().name());
- lunRequest.setOsType(Lun.OsTypeEnum.valueOf(osType));
-
- cloudStackVolumeRequest.setLun(lunRequest);
- break;
- default:
- throw new CloudRuntimeException("Unsupported protocol " + protocol);
-
- }
- return cloudStackVolumeRequest;
- }
-
public static boolean isValidName(String name) {
// Check for null and length constraint first
if (name == null || name.length() > 200) {
@@ -177,6 +130,49 @@ public static String getLunName(String volName, String lunName) {
return OntapStorageConstants.VOLUME_PATH_PREFIX + volName + OntapStorageConstants.SLASH + lunName;
}
+ /**
+ * Converts a path stored in CloudStack (absolute LUN {@code /vol/<flexVol>/...} or already
+ * relative NFS file path) into the FlexVol-relative path expected by
+ * {@code POST /api/storage/file/clone}.
+ */
+ public static String toFlexVolRelativePath(String path, String flexVolName) {
+ if (path == null || path.isEmpty()) {
+ return path;
+ }
+ if (flexVolName != null && !flexVolName.isEmpty()) {
+ String prefix = OntapStorageConstants.VOLUME_PATH_PREFIX + flexVolName + OntapStorageConstants.SLASH;
+ if (path.startsWith(prefix)) {
+ return path.substring(prefix.length());
+ }
+ }
+ // Already relative (typical NFS uuid path) or unexpected absolute form — strip a leading slash.
+ return path.startsWith(OntapStorageConstants.SLASH) ? path.substring(1) : path;
+ }
+
+ /**
+ * Builds the ONTAP LUN clone source name that points at a LUN inside a FlexVol snapshot.
+ *
+ * Format required by {@code POST /api/storage/luns} when cloning from a snapshot:
+ * {@code /vol/<flexVol>/.snapshot/<snapshotName>/<relativeLunPath>}.
+ *
+ * {@code clone.source.uuid} cannot identify a snapshot-resident LUN; name must be used.
+ */
+ public static String toLunCloneSourcePathInSnapshot(String lunPath, String flexVolName, String snapshotName) {
+ if (flexVolName == null || flexVolName.isEmpty()) {
+ throw new InvalidParameterValueException("FlexVolume name is required to build a snapshot LUN path");
+ }
+ if (snapshotName == null || snapshotName.isEmpty()) {
+ throw new InvalidParameterValueException("Snapshot name is required to build a snapshot LUN path");
+ }
+ String relativeLunPath = toFlexVolRelativePath(lunPath, flexVolName);
+ if (relativeLunPath == null || relativeLunPath.isEmpty()) {
+ throw new InvalidParameterValueException("LUN path is required to build a snapshot LUN path");
+ }
+ return OntapStorageConstants.VOLUME_PATH_PREFIX + flexVolName
+ + OntapStorageConstants.SNAPSHOT_PATH_SEGMENT + snapshotName
+ + OntapStorageConstants.SLASH + relativeLunPath;
+ }
+
/**
* Builds an ONTAP-safe name token from user-provided snapshot text.
*/
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 e23171e8acdf..a7a86133cd4c 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
@@ -22,23 +22,43 @@
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.hypervisor.Hypervisor;
+import com.cloud.storage.DataStoreRole;
+import com.cloud.storage.ResizeVolumePayload;
import com.cloud.storage.ScopeType;
import com.cloud.storage.Storage;
+import com.cloud.storage.SnapshotVO;
+import com.cloud.storage.VMTemplateStoragePoolVO;
+import com.cloud.storage.Volume;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.VolumeDetailVO;
+import com.cloud.storage.dao.SnapshotDao;
+import com.cloud.storage.dao.SnapshotDetailsDao;
+import com.cloud.storage.dao.SnapshotDetailsVO;
+import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.dao.VolumeDetailsDao;
import com.cloud.utils.exception.CloudRuntimeException;
+import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult;
import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+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.SnapshotInfo;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
import org.apache.cloudstack.storage.command.CommandResult;
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.feign.model.FileInfo;
import org.apache.cloudstack.storage.feign.model.Igroup;
import org.apache.cloudstack.storage.feign.model.Lun;
+import org.apache.cloudstack.storage.feign.model.VolumeSpace;
+import org.apache.cloudstack.storage.feign.model.Svm;
+import org.apache.cloudstack.storage.feign.model.VolumeQosPolicy;
+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.AccessGroup;
@@ -56,23 +76,34 @@
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
+import static com.cloud.agent.api.to.DataObjectType.SNAPSHOT;
+import static com.cloud.agent.api.to.DataObjectType.TEMPLATE;
import static com.cloud.agent.api.to.DataObjectType.VOLUME;
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;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doNothing;
+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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -100,12 +131,27 @@ class OntapPrimaryDatastoreDriverTest {
@Mock
private VolumeDetailsDao volumeDetailsDao;
+ @Mock
+ private SnapshotDetailsDao snapshotDetailsDao;
+
+ @Mock
+ private SnapshotDao snapshotDao;
+
+ @Mock
+ private VMTemplatePoolDao vmTemplatePoolDao;
+
+ @Mock
+ private VMTemplateStoragePoolVO templatePoolRef;
+
@Mock
private DataStore dataStore;
@Mock
private VolumeInfo volumeInfo;
+ @Mock
+ private TemplateInfo templateInfo;
+
@Mock
private StoragePoolVO storagePool;
@@ -137,6 +183,11 @@ void setUp() {
storagePoolDetails = new HashMap<>();
storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.ISCSI.name());
storagePoolDetails.put(OntapStorageConstants.SVM_NAME, "svm1");
+ storagePoolDetails.put(OntapStorageConstants.IS_AFF, "true");
+ lenient().when(volumeInfo.getName()).thenReturn("test-volume");
+ lenient().when(volumeInfo.getSize()).thenReturn(1073741824L);
+ lenient().when(storagePool.getName()).thenReturn("vol1");
+ lenient().when(storagePool.getHypervisor()).thenReturn(Hypervisor.HypervisorType.KVM);
}
@Test
@@ -149,6 +200,9 @@ void testGetCapabilities() {
assertEquals(Boolean.TRUE.toString(), capabilities.get("STORAGE_SYSTEM_SNAPSHOT"));
assertEquals(Boolean.TRUE.toString(), capabilities.get("CAN_CREATE_VOLUME_FROM_SNAPSHOT"));
assertEquals(Boolean.TRUE.toString(), capabilities.get("CAN_REVERT_VOLUME_TO_SNAPSHOT"));
+ assertEquals(Boolean.TRUE.toString(), capabilities.get("CAN_CREATE_VOLUME_FROM_VOLUME"));
+ assertEquals(Boolean.TRUE.toString(), capabilities.get("CAN_CREATE_TEMPLATE_FROM_SNAPSHOT"));
+ assertEquals(Boolean.FALSE.toString(), capabilities.get("CAN_DIRECT_ATTACH_SNAPSHOT"));
}
@Test
@@ -179,7 +233,9 @@ void testCreateAsync_VolumeWithISCSI_Success() {
when(volumeInfo.getName()).thenReturn("test-volume");
when(storagePoolDao.findById(1L)).thenReturn(storagePool);
- when(storagePool.getId()).thenReturn(1L);
+ lenient().when(storagePool.getId()).thenReturn(1L);
+ lenient().when(storagePool.getName()).thenReturn("vol1");
+
when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.OntapiSCSI);
when(storagePool.getHypervisor()).thenReturn(Hypervisor.HypervisorType.KVM);
@@ -190,18 +246,12 @@ void testCreateAsync_VolumeWithISCSI_Success() {
Lun mockLun = new Lun();
mockLun.setName("/vol/vol1/lun1");
mockLun.setUuid("lun-uuid-123");
- // Create request volume (returned by Utility.createCloudStackVolumeRequestByProtocol)
- CloudStackVolume requestVolume = new CloudStackVolume();
- requestVolume.setLun(mockLun);
- // Create response volume (returned by sanStrategy.createCloudStackVolume)
CloudStackVolume responseVolume = new CloudStackVolume();
responseVolume.setLun(mockLun);
- try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) {
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any()))
.thenReturn(sanStrategy);
- utilityMock.when(() -> OntapStorageUtils.createCloudStackVolumeRequestByProtocol(
- any(), any(), any())).thenReturn(requestVolume);
when(sanStrategy.createCloudStackVolume(any())).thenReturn(responseVolume);
// Execute
@@ -243,11 +293,9 @@ void testCreateAsync_VolumeWithNFS_Success() {
CloudStackVolume mockCloudStackVolume = new CloudStackVolume();
- try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) {
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails))
.thenReturn(nasStrategy);
- utilityMock.when(() -> OntapStorageUtils.createCloudStackVolumeRequestByProtocol(
- any(), any(), any())).thenReturn(mockCloudStackVolume);
when(nasStrategy.createCloudStackVolume(any())).thenReturn(mockCloudStackVolume);
@@ -268,7 +316,9 @@ void testCreateAsync_VolumeWithNFS_Success() {
@Test
void testCreateAsync_UnsupportedHypervisor_FailsWithError() {
- storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.ISCSI.name());
+ // Use NFS so LUN OS-type resolution does not fail earlier in getOSTypeFromHypervisor;
+ // the failure under test is image-format resolution for non-KVM hypervisors.
+ storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name());
when(dataStore.getId()).thenReturn(1L);
when(dataStore.getName()).thenReturn("ontap-pool");
@@ -278,12 +328,16 @@ void testCreateAsync_UnsupportedHypervisor_FailsWithError() {
when(storagePoolDao.findById(1L)).thenReturn(storagePool);
when(storagePool.getId()).thenReturn(1L);
+ when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem);
when(storagePool.getHypervisor()).thenReturn(Hypervisor.HypervisorType.VMware);
when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
when(volumeDao.findById(100L)).thenReturn(volumeVO);
- try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) {
- utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ CloudStackVolume mockCloudStackVolume = new CloudStackVolume();
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(nasStrategy);
+ when(nasStrategy.createCloudStackVolume(any())).thenReturn(mockCloudStackVolume);
driver.createAsync(dataStore, volumeInfo, createCallback);
@@ -341,8 +395,9 @@ void testDeleteAsync_ISCSIVolume_Success() {
when(volumeDetailsDao.findDetail(100L, OntapStorageConstants.LUN_DOT_NAME)).thenReturn(lunNameDetail);
when(volumeDetailsDao.findDetail(100L, OntapStorageConstants.LUN_DOT_UUID)).thenReturn(lunUuidDetail);
+ when(volumeDetailsDao.findDetail(100L, OntapStorageConstants.QOS_POLICY_UUID)).thenReturn(null);
- try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) {
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails))
.thenReturn(sanStrategy);
@@ -359,6 +414,8 @@ void testDeleteAsync_ISCSIVolume_Success() {
assertNotNull(result);
assertTrue(result.isSuccess());
verify(sanStrategy).deleteCloudStackVolume(any(CloudStackVolume.class));
+ verify(volumeDao, never()).remove(anyLong());
+ verify(volumeDetailsDao, never()).removeDetails(anyLong());
}
}
@@ -385,6 +442,93 @@ void testDeleteAsync_NFSVolume_Success() {
// NFS deletion doesn't fail, handled by hypervisor
}
+ @Test
+ void testDeleteAsync_Template_DeletesCacheLun() {
+ when(dataStore.getId()).thenReturn(1L);
+ when(templateInfo.getType()).thenReturn(TEMPLATE);
+ when(templateInfo.getId()).thenReturn(50L);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePool.getId()).thenReturn(1L);
+ when(storagePool.getName()).thenReturn("vol1");
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getLocalDownloadPath()).thenReturn("template-lun-uuid");
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails)).thenReturn(sanStrategy);
+
+ driver.deleteAsync(dataStore, templateInfo, commandCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CommandResult.class);
+ verify(commandCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(sanStrategy).deleteCloudStackVolume(requestCaptor.capture());
+ assertEquals("template-lun-uuid", requestCaptor.getValue().getLun().getUuid());
+ }
+ }
+
+
+ @Test
+ void testDeleteAsync_Template_ResolvesLunByNameWhenUuidMissing() {
+ when(dataStore.getId()).thenReturn(1L);
+ when(templateInfo.getType()).thenReturn(TEMPLATE);
+ when(templateInfo.getId()).thenReturn(50L);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePool.getId()).thenReturn(1L);
+ when(storagePool.getName()).thenReturn("vol1");
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getLocalDownloadPath()).thenReturn(null);
+
+ Lun templateLun = new Lun();
+ templateLun.setName("/vol/vol1/cs_tmpl_50");
+ templateLun.setUuid("resolved-lun-uuid");
+ CloudStackVolume existing = new CloudStackVolume();
+ existing.setLun(templateLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails)).thenReturn(sanStrategy);
+ when(sanStrategy.getCloudStackVolume(argThat(map ->
+ map != null && "/vol/vol1/cs_tmpl_50".equals(map.get("name")))))
+ .thenReturn(existing);
+ doNothing().when(sanStrategy).deleteCloudStackVolume(any());
+
+ driver.deleteAsync(dataStore, templateInfo, commandCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CommandResult.class);
+ verify(commandCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+
+ ArgumentCaptor deleteCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(sanStrategy).deleteCloudStackVolume(deleteCaptor.capture());
+ assertEquals("resolved-lun-uuid", deleteCaptor.getValue().getLun().getUuid());
+ assertEquals("/vol/vol1/cs_tmpl_50", deleteCaptor.getValue().getLun().getName());
+ }
+ }
+
+ @Test
+ void testDeleteAsync_Template_NoCachedLun_SucceedsWithoutCallingOntap() {
+ when(dataStore.getId()).thenReturn(1L);
+ when(templateInfo.getType()).thenReturn(TEMPLATE);
+ when(templateInfo.getId()).thenReturn(50L);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePool.getId()).thenReturn(1L);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(null);
+
+ driver.deleteAsync(dataStore, templateInfo, commandCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CommandResult.class);
+ verify(commandCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+ verify(sanStrategy, never()).deleteCloudStackVolume(any());
+ }
+
@Test
void testGrantAccess_NullParameters_ThrowsException() {
assertThrows(CloudRuntimeException.class,
@@ -426,7 +570,7 @@ void testGrantAccess_ClusterScope_Success() {
existingIgroup.setName("igroup1");
existingAccessGroup.setIgroup(existingIgroup);
- try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) {
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails))
.thenReturn(sanStrategy);
utilityMock.when(() -> OntapStorageUtils.getIgroupName(anyString(), anyString()))
@@ -445,6 +589,7 @@ void testGrantAccess_ClusterScope_Success() {
verify(sanStrategy).getAccessGroup(any());
verify(sanStrategy).ensureLunMapped(anyString(), anyString(), anyString());
verify(sanStrategy, never()).validateInitiatorInAccessGroup(anyString(), anyString(), any(Igroup.class));
+ verify(volumeInfo, never()).getVolume();
}
}
@@ -478,7 +623,7 @@ void testGrantAccess_IgroupNotFound_CreatesNewIgroup() {
createdIgroup.setName("igroup1");
createdAccessGroup.setIgroup(createdIgroup);
- try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) {
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails))
.thenReturn(sanStrategy);
utilityMock.when(() -> OntapStorageUtils.getIgroupName(anyString(), anyString()))
@@ -504,12 +649,12 @@ void testGrantAccess_IgroupNotFound_CreatesNewIgroup() {
@Test
void testRevokeAccess_NFSVolume_SkipsRevoke() {
// Setup - NFS volumes have no LUN mapping, so revokeAccess is a no-op
+ storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name());
when(dataStore.getId()).thenReturn(1L);
when(volumeInfo.getType()).thenReturn(VOLUME);
when(volumeInfo.getId()).thenReturn(100L);
when(volumeDao.findById(100L)).thenReturn(volumeVO);
- when(volumeVO.getId()).thenReturn(100L);
when(volumeVO.getName()).thenReturn("test-volume");
when(storagePoolDao.findById(1L)).thenReturn(storagePool);
@@ -518,7 +663,7 @@ void testRevokeAccess_NFSVolume_SkipsRevoke() {
when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
when(host.getName()).thenReturn("host1");
- try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) {
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails))
.thenReturn(sanStrategy);
@@ -565,7 +710,7 @@ void testRevokeAccess_ISCSIVolume_Success() {
AccessGroup mockAccessGroup = new AccessGroup();
mockAccessGroup.setIgroup(mockIgroup);
- try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class)) {
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails))
.thenReturn(sanStrategy);
utilityMock.when(() -> OntapStorageUtils.getIgroupName(anyString(), anyString()))
@@ -608,32 +753,3007 @@ void testRevokeAccess_ISCSIVolume_Success() {
}
@Test
- void testCanHostAccessStoragePool_ReturnsTrue() {
- assertTrue(driver.canHostAccessStoragePool(host, storagePool));
+ void testGetDataObjectSizeIncludingHypervisorSnapshotReserve_NoReserveAdded() {
+ when(templateInfo.getSize()).thenReturn(5368709120L);
+
+ assertEquals(5368709120L, driver.getDataObjectSizeIncludingHypervisorSnapshotReserve(templateInfo, storagePool));
}
@Test
- void testIsVmInfoNeeded_ReturnsTrue() {
- assertTrue(driver.isVmInfoNeeded());
+ void testGetBytesRequiredForTemplate_AlreadyCached_ReturnsZero() {
+ when(storagePool.getId()).thenReturn(1L);
+ when(templateInfo.getId()).thenReturn(50L);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getState()).thenReturn(ObjectInDataStoreStateMachine.State.Ready);
+ when(templatePoolRef.getLocalDownloadPath()).thenReturn("template-lun-uuid");
+
+ assertEquals(0L, driver.getBytesRequiredForTemplate(templateInfo, storagePool));
}
@Test
- void testIsStorageSupportHA_ReturnsTrue() {
- assertTrue(driver.isStorageSupportHA(Storage.StoragePoolType.NetworkFilesystem));
+ void testGetBytesRequiredForTemplate_NotCached_ReturnsVirtualSize() {
+ when(storagePool.getId()).thenReturn(1L);
+ when(templateInfo.getId()).thenReturn(50L);
+ when(templateInfo.getSize()).thenReturn(5368709120L);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(null);
+
+ assertEquals(5368709120L, driver.getBytesRequiredForTemplate(templateInfo, storagePool));
}
@Test
- void testGetChapInfo_ReturnsNull() {
- assertNull(driver.getChapInfo(volumeInfo));
+ void testGetBytesRequiredForTemplate_SpoolRefNotReady_ReturnsVirtualSize() {
+ when(storagePool.getId()).thenReturn(1L);
+ when(templateInfo.getId()).thenReturn(50L);
+ when(templateInfo.getSize()).thenReturn(5368709120L);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getState()).thenReturn(ObjectInDataStoreStateMachine.State.Allocated);
+
+ assertEquals(5368709120L, driver.getBytesRequiredForTemplate(templateInfo, storagePool));
}
@Test
- void testCanProvideStorageStats_ReturnsFalse() {
- assertFalse(driver.canProvideStorageStats());
+ void testGetBytesRequiredForTemplate_ReadyWithoutBackendIdentity_ReturnsVirtualSize() {
+ when(storagePool.getId()).thenReturn(1L);
+ when(templateInfo.getId()).thenReturn(50L);
+ when(templateInfo.getSize()).thenReturn(5368709120L);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getState()).thenReturn(ObjectInDataStoreStateMachine.State.Ready);
+ when(templatePoolRef.getLocalDownloadPath()).thenReturn(null);
+
+ assertEquals(5368709120L, driver.getBytesRequiredForTemplate(templateInfo, storagePool));
}
@Test
- void testCanProvideVolumeStats_ReturnsFalse() {
- assertFalse(driver.canProvideVolumeStats());
+ void testGetBytesRequiredForTemplate_NfsCached_ReturnsZero() {
+ storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name());
+ when(storagePool.getId()).thenReturn(1L);
+ when(templateInfo.getId()).thenReturn(50L);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getState()).thenReturn(ObjectInDataStoreStateMachine.State.Ready);
+ when(templatePoolRef.getInstallPath()).thenReturn("/mnt/pool/template-uuid");
+
+ assertEquals(0L, driver.getBytesRequiredForTemplate(templateInfo, storagePool));
+ }
+
+ @Test
+ void testCreateAsync_TemplateWithISCSI_CreatesLunAndRecordsCloneSource() {
+ when(dataStore.getId()).thenReturn(1L);
+ when(dataStore.getName()).thenReturn("ontap-pool");
+ when(templateInfo.getType()).thenReturn(TEMPLATE);
+ when(templateInfo.getId()).thenReturn(50L);
+ when(templateInfo.getSize()).thenReturn(5368709120L);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePool.getId()).thenReturn(1L);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getId()).thenReturn(7L);
+
+ Lun templateLun = new Lun();
+ templateLun.setName("/vol/vol1/cs_tmpl_50");
+ templateLun.setUuid("template-lun-uuid");
+ CloudStackVolume created = new CloudStackVolume();
+ created.setLun(templateLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.createTemplateCache(any(), any(), any(), anyLong())).thenReturn(created);
+
+ driver.createAsync(dataStore, templateInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+
+ // local_download_path carries the clone source; install_path is left for grantAccess
+ verify(templatePoolRef).setLocalDownloadPath("template-lun-uuid");
+ verify(templatePoolRef).setTemplateSize(5368709120L);
+ verify(templatePoolRef, never()).setInstallPath(any());
+ verify(vmTemplatePoolDao).update(eq(7L), any(VMTemplateStoragePoolVO.class));
+ }
+ }
+
+
+ @Test
+ void testCreateAsync_TemplateWithISCSI_RollsBackLunWhenDbUpdateFails() {
+ when(dataStore.getId()).thenReturn(1L);
+ when(dataStore.getName()).thenReturn("ontap-pool");
+ when(templateInfo.getType()).thenReturn(TEMPLATE);
+ when(templateInfo.getId()).thenReturn(50L);
+ when(templateInfo.getSize()).thenReturn(5368709120L);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePool.getId()).thenReturn(1L);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getId()).thenReturn(7L);
+ doThrow(new RuntimeException("db update failed")).when(vmTemplatePoolDao)
+ .update(eq(7L), any(VMTemplateStoragePoolVO.class));
+
+ Lun templateLun = new Lun();
+ templateLun.setName("/vol/vol1/cs_tmpl_50");
+ templateLun.setUuid("template-lun-uuid");
+ CloudStackVolume created = new CloudStackVolume();
+ created.setLun(templateLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.createTemplateCache(any(), any(), any(), anyLong())).thenReturn(created);
+ doNothing().when(sanStrategy).deleteCloudStackVolume(any());
+
+ driver.createAsync(dataStore, templateInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+
+ ArgumentCaptor deleteCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(sanStrategy).deleteCloudStackVolume(deleteCaptor.capture());
+ assertEquals("template-lun-uuid", deleteCaptor.getValue().getLun().getUuid());
+ assertEquals("/vol/vol1/cs_tmpl_50", deleteCaptor.getValue().getLun().getName());
+ }
+ }
+
+ @Test
+ void testCreateAsync_TemplateWithISCSI_UnknownSize_Fails() {
+ when(dataStore.getId()).thenReturn(1L);
+ when(dataStore.getName()).thenReturn("ontap-pool");
+ when(templateInfo.getType()).thenReturn(TEMPLATE);
+ when(templateInfo.getSize()).thenReturn(0L);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.createTemplateCache(any(), any(), any(), anyLong()))
+ .thenThrow(new CloudRuntimeException("Unknown virtual size for template [50]"));
+
+ driver.createAsync(dataStore, templateInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+ }
+ }
+
+ @Test
+ void testCreateAsync_TemplateWithNFS_IsMetadataOnly() {
+ storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name());
+
+ when(dataStore.getId()).thenReturn(1L);
+ when(dataStore.getName()).thenReturn("ontap-pool");
+ when(templateInfo.getType()).thenReturn(TEMPLATE);
+ when(templateInfo.getUuid()).thenReturn("template-uuid");
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(nasStrategy);
+ when(nasStrategy.createTemplateCache(any(), any(), any(), anyLong())).thenReturn(null);
+
+ driver.createAsync(dataStore, templateInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+ verify(vmTemplatePoolDao, never()).update(any(Long.class), any(VMTemplateStoragePoolVO.class));
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromTemplate_ClonesWithoutGrowing() {
+ stubVolumeCloneFromTemplate(5368709120L, 5368709120L);
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(sanStrategy).cloneCloudStackVolume(requestCaptor.capture());
+ assertEquals("/vol/vol1/cs_tmpl_50", requestCaptor.getValue().getLun().getClone().getSource().getName());
+ assertEquals("template-lun-uuid", requestCaptor.getValue().getLun().getClone().getSource().getUuid());
+ assertSame(volumeInfo, requestCaptor.getValue().getVolumeInfo());
+ verify(sanStrategy, never()).createCloudStackVolume(any());
+ verify(sanStrategy, never()).resizeCloudStackVolume(any(), anyLong());
+ verify(sanStrategy, never()).updateCloudStackVolume(any());
+ verify(volumeDetailsDao).addDetail(eq(100L), eq(OntapStorageConstants.LUN_DOT_UUID), eq("cloned-lun-uuid"), eq(false));
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromTemplate_GrowsWhenOfferingIsLarger() {
+ stubVolumeCloneFromTemplate(5368709120L, 21474836480L);
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ verify(sanStrategy).resizeCloudStackVolume(eq(cloned), eq(21474836480L));
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_IscsiSuccessWithoutGrow() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("snap-cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any()))
+ .thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(sanStrategy).cloneCloudStackVolume(requestCaptor.capture());
+ Lun lunRequest = requestCaptor.getValue().getLun();
+ assertEquals("/vol/vol1/.snapshot/snap_cs200/source_lun", lunRequest.getClone().getSource().getName());
+ assertNull(lunRequest.getClone().getSource().getUuid());
+ assertEquals("/vol/vol1/test_volume", lunRequest.getName());
+ assertEquals("svm1", lunRequest.getSvm().getName());
+ assertSame(volumeInfo, requestCaptor.getValue().getVolumeInfo());
+ verify(sanStrategy, never()).createCloudStackVolume(any());
+ verify(sanStrategy, never()).resizeCloudStackVolume(any(), anyLong());
+ verify(volumeDetailsDao).addDetail(eq(100L), eq(OntapStorageConstants.LUN_DOT_UUID), eq("snap-cloned-lun-uuid"), eq(false));
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_IscsiWithIops_SetsQosOnLunCreate() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+ when(volumeInfo.getVolumeType()).thenReturn(Volume.Type.DATADISK);
+ when(volumeInfo.getMinIops()).thenReturn(100L);
+ when(volumeInfo.getMaxIops()).thenReturn(200L);
+ lenient().when(storagePool.getCapacityIops()).thenReturn(null);
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("snap-cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+ VolumeQosPolicy qosPolicy = qosPolicy("qos-snap-uuid", "cs_100_to_200_iops_svm1");
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ stubQosCreateMocks(utilityMock, sanStrategy, cloned, qosPolicy);
+ when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+ verify(sanStrategy).createVolumeQosPolicy(eq("cs_100_to_200_iops_svm1"), eq(100L), eq(200L));
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(sanStrategy).cloneCloudStackVolume(requestCaptor.capture());
+ assertTrue(isQosPolicyReference(requestCaptor.getValue().getLun().getQosPolicy(),
+ "qos-snap-uuid", "cs_100_to_200_iops_svm1"));
+ verify(sanStrategy, never()).updateCloudStackVolume(any());
+ verify(volumeDetailsDao).addDetail(eq(100L), eq(OntapStorageConstants.QOS_POLICY_UUID),
+ eq("qos-snap-uuid"), eq(false));
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_NfsWithIops_AttachesQosAfterClone() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.NFS3.name());
+ storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name());
+ storagePoolDetails.put(OntapStorageConstants.VOLUME_UUID, "flex-uuid");
+ when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem);
+ when(volumeInfo.getUuid()).thenReturn("new-volume-uuid");
+ when(volumeInfo.getVolumeType()).thenReturn(Volume.Type.DATADISK);
+ when(volumeInfo.getMinIops()).thenReturn(100L);
+ when(volumeInfo.getMaxIops()).thenReturn(200L);
+ lenient().when(storagePool.getCapacityIops()).thenReturn(null);
+
+ CloudStackVolume cloned = new CloudStackVolume();
+ VolumeQosPolicy qosPolicy = lookedUpQosPolicy("qos-nfs-snap-uuid", "cs_100_to_200_iops_svm1");
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ stubQosCreateMocks(utilityMock, nasStrategy, cloned, qosPolicy);
+ when(nasStrategy.cloneCloudStackVolume(any())).thenReturn(cloned);
+ when(nasStrategy.updateCloudStackVolume(any())).thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+ verify(nasStrategy).createVolumeQosPolicy(eq("cs_100_to_200_iops_svm1"), eq(100L), eq(200L));
+ ArgumentCaptor cloneCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(nasStrategy).cloneCloudStackVolume(cloneCaptor.capture());
+ assertNull(cloneCaptor.getValue().getFile().getQosPolicy());
+ verify(nasStrategy).updateCloudStackVolume(argThat(request ->
+ "1".equals(request.getDatastoreId())
+ && "flex-uuid".equals(request.getFlexVolumeUuid())
+ && request.getVolumeInfo() == volumeInfo
+ && request.getFile() != null
+ && isQosPolicyReference(request.getFile().getQosPolicy(),
+ "qos-nfs-snap-uuid", "cs_100_to_200_iops_svm1")));
+ verify(volumeDetailsDao).addDetail(eq(100L), eq(OntapStorageConstants.QOS_POLICY_UUID),
+ eq("qos-nfs-snap-uuid"), eq(false));
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_NoIops_DoesNotCreatePolicy() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+ when(volumeInfo.getVolumeType()).thenReturn(Volume.Type.DATADISK);
+ when(volumeInfo.getMinIops()).thenReturn(null);
+ when(volumeInfo.getMaxIops()).thenReturn(null);
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("snap-cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ verify(sanStrategy, never()).createVolumeQosPolicy(nullable(String.class), nullable(Long.class), nullable(Long.class));
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(sanStrategy).cloneCloudStackVolume(requestCaptor.capture());
+ assertNull(requestCaptor.getValue().getLun().getQosPolicy());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_CloneFails_DeletesNewPolicy() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+ when(volumeInfo.getVolumeType()).thenReturn(Volume.Type.ROOT);
+ when(volumeInfo.getMinIops()).thenReturn(100L);
+ when(volumeInfo.getMaxIops()).thenReturn(200L);
+ lenient().when(storagePool.getCapacityIops()).thenReturn(null);
+
+ VolumeQosPolicy qosPolicy = qosPolicy("qos-snap-uuid", "cs_100_to_200_iops_svm1");
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ stubQosCreateMocks(utilityMock, sanStrategy, new CloudStackVolume(), qosPolicy);
+ when(sanStrategy.cloneCloudStackVolume(any()))
+ .thenThrow(new CloudRuntimeException("clone failed"));
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+ verify(sanStrategy).deleteVolumeQosPolicy("qos-snap-uuid");
+ verify(volumeDetailsDao, never()).addDetail(eq(100L), eq(OntapStorageConstants.QOS_POLICY_UUID),
+ anyString(), eq(false));
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_GrowsWhenOfferingIsLarger() {
+ stubVolumeCloneFromSnapshot(5368709120L, 21474836480L, ProtocolType.ISCSI.name());
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("snap-cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any()))
+ .thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ verify(sanStrategy).resizeCloudStackVolume(eq(cloned), eq(21474836480L));
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_ResizeFails_DeletesOrphanedClone() {
+ stubVolumeCloneFromSnapshot(5368709120L, 21474836480L, ProtocolType.ISCSI.name());
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("snap-cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any())).thenReturn(cloned);
+ doThrow(new CloudRuntimeException("resize failed"))
+ .when(sanStrategy).resizeCloudStackVolume(eq(cloned), eq(21474836480L));
+ doNothing().when(sanStrategy).deleteCloudStackVolume(eq(cloned));
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+ verify(sanStrategy).deleteCloudStackVolume(eq(cloned));
+ verify(volumeDetailsDao, never()).addDetail(eq(100L), eq(OntapStorageConstants.LUN_DOT_UUID), anyString(), anyBoolean());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_NfsSuccess() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.NFS3.name());
+ storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name());
+ when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem);
+ when(volumeInfo.getUuid()).thenReturn("new-volume-uuid");
+
+ CloudStackVolume cloned = new CloudStackVolume();
+ FileInfo file = new FileInfo();
+ file.setPath("new-volume-uuid");
+ cloned.setFile(file);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(nasStrategy);
+ when(nasStrategy.cloneCloudStackVolume(any()))
+ .thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(nasStrategy).cloneCloudStackVolume(requestCaptor.capture());
+ CloudStackVolume request = requestCaptor.getValue();
+ assertEquals("source-file-uuid", request.getFile().getPath());
+ assertEquals("new-volume-uuid", request.getDestinationPath());
+ assertEquals("snap_cs200", request.getSnapshotName());
+ assertEquals("1", request.getDatastoreId());
+ verify(nasStrategy, never()).createCloudStackVolume(any());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_PoolMismatch_Fails() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+ when(snapshotDetailsDao.findDetail(200L, OntapStorageConstants.PRIMARY_POOL_ID))
+ .thenReturn(new SnapshotDetailsVO(200L, OntapStorageConstants.PRIMARY_POOL_ID, "999", false));
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+ verify(sanStrategy, never()).cloneCloudStackVolume(any());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_MissingDetail_Fails() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+ when(snapshotDetailsDao.findDetail(200L, OntapStorageConstants.ONTAP_SNAP_NAME)).thenReturn(null);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+ verify(sanStrategy, never()).cloneCloudStackVolume(any());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_ProtocolMismatch_Fails() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+ // Pool is iSCSI (default stub details) but snapshot was taken on NFS.
+ when(snapshotDetailsDao.findDetail(200L, OntapStorageConstants.PROTOCOL))
+ .thenReturn(new SnapshotDetailsVO(200L, OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name(), false));
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+ verify(sanStrategy, never()).cloneCloudStackVolume(any());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_NullStrategyResult_Fails() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any()))
+ .thenReturn(null);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_StrategyThrows_Fails() {
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any()))
+ .thenThrow(new CloudRuntimeException("ONTAP clone failed"));
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertFalse(resultCaptor.getValue().isSuccess());
+ verify(sanStrategy, never()).resizeCloudStackVolume(any(), anyLong());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_PrefersSnapshotOverTemplate() {
+ // Corner: when both details are present, the snapshot clone wins over the template clone.
+ stubVolumeCloneFromSnapshot(5368709120L, 5368709120L, ProtocolType.ISCSI.name());
+ when(volumeDetailsDao.findDetail(100L, OntapStorageConstants.CLONE_OF_TEMPLATE))
+ .thenReturn(new VolumeDetailVO(100L, OntapStorageConstants.CLONE_OF_TEMPLATE, "50", false));
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("snap-cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any()))
+ .thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(CloudStackVolume.class);
+ verify(sanStrategy).cloneCloudStackVolume(requestCaptor.capture());
+ assertEquals("/vol/vol1/.snapshot/snap_cs200/source_lun",
+ requestCaptor.getValue().getLun().getClone().getSource().getName());
+ verify(vmTemplatePoolDao, never()).findByPoolTemplate(anyLong(), anyLong(), any());
+ verify(sanStrategy, never()).createCloudStackVolume(any());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_NfsGrowsWhenOfferingIsLarger() {
+ stubVolumeCloneFromSnapshot(5368709120L, 21474836480L, ProtocolType.NFS3.name());
+ storagePoolDetails.put(OntapStorageConstants.PROTOCOL, ProtocolType.NFS3.name());
+ when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem);
+ when(volumeInfo.getUuid()).thenReturn("new-volume-uuid");
+
+ CloudStackVolume cloned = new CloudStackVolume();
+ FileInfo file = new FileInfo();
+ file.setPath("new-volume-uuid");
+ cloned.setFile(file);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(nasStrategy);
+ when(nasStrategy.cloneCloudStackVolume(any()))
+ .thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ verify(nasStrategy).resizeCloudStackVolume(eq(cloned), eq(21474836480L));
+ verify(sanStrategy, never()).cloneCloudStackVolume(any());
+ }
+ }
+
+ @Test
+ void testCreateAsync_VolumeClonedFromSnapshot_SkipsGrowWhenSnapshotSizeUnknown() {
+ stubVolumeCloneFromSnapshot(0L, 21474836480L, ProtocolType.ISCSI.name());
+
+ Lun clonedLun = new Lun();
+ clonedLun.setName("/vol/vol1/test_volume");
+ clonedLun.setUuid("snap-cloned-lun-uuid");
+ CloudStackVolume cloned = new CloudStackVolume();
+ cloned.setLun(clonedLun);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(any())).thenReturn(sanStrategy);
+ when(sanStrategy.cloneCloudStackVolume(any()))
+ .thenReturn(cloned);
+
+ driver.createAsync(dataStore, volumeInfo, createCallback);
+
+ verify(sanStrategy, never()).resizeCloudStackVolume(any(), anyLong());
+ ArgumentCaptor resultCaptor = ArgumentCaptor.forClass(CreateCmdResult.class);
+ verify(createCallback).complete(resultCaptor.capture());
+ assertTrue(resultCaptor.getValue().isSuccess());
+ }
+ }
+
+ /**
+ * Sets up a volume create that the orchestrator has marked as a clone of a CloudStack snapshot.
+ */
+ private void stubVolumeCloneFromSnapshot(long snapshotSize, long volumeSize, String protocol) {
+ when(dataStore.getId()).thenReturn(1L);
+ when(dataStore.getName()).thenReturn("ontap-pool");
+ when(volumeInfo.getType()).thenReturn(VOLUME);
+ when(volumeInfo.getId()).thenReturn(100L);
+ when(volumeInfo.getName()).thenReturn("test-volume");
+ lenient().when(volumeInfo.getSize()).thenReturn(volumeSize);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ // getId is only used after snapshot_details validation succeeds; lenient for early-fail tests.
+ lenient().when(storagePool.getId()).thenReturn(1L);
+ lenient().when(storagePool.getName()).thenReturn("vol1");
+ lenient().when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.OntapiSCSI);
+ lenient().when(storagePool.getHypervisor()).thenReturn(Hypervisor.HypervisorType.KVM);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+
+ when(volumeDao.findById(100L)).thenReturn(volumeVO);
+ lenient().when(volumeVO.getId()).thenReturn(100L);
+ when(volumeDetailsDao.findDetail(100L, OntapStorageConstants.CLONE_OF_SNAPSHOT))
+ .thenReturn(new VolumeDetailVO(100L, OntapStorageConstants.CLONE_OF_SNAPSHOT, "200", false));
+
+ String volumePath = ProtocolType.NFS3.name().equalsIgnoreCase(protocol)
+ ? "source-file-uuid"
+ : "/vol/vol1/source_lun";
+ if (!ProtocolType.NFS3.name().equalsIgnoreCase(protocol)) {
+ storagePoolDetails.put(OntapStorageConstants.VOLUME_NAME, "vol1");
+ }
+ // Lenient so early-fail tests can override/null individual keys without STRICT_STUBS noise.
+ lenient().when(snapshotDetailsDao.findDetail(200L, OntapStorageConstants.ONTAP_SNAP_NAME))
+ .thenReturn(new SnapshotDetailsVO(200L, OntapStorageConstants.ONTAP_SNAP_NAME, "snap_cs200", false));
+ lenient().when(snapshotDetailsDao.findDetail(200L, OntapStorageConstants.VOLUME_PATH))
+ .thenReturn(new SnapshotDetailsVO(200L, OntapStorageConstants.VOLUME_PATH, volumePath, false));
+ lenient().when(snapshotDetailsDao.findDetail(200L, OntapStorageConstants.PRIMARY_POOL_ID))
+ .thenReturn(new SnapshotDetailsVO(200L, OntapStorageConstants.PRIMARY_POOL_ID, "1", false));
+ lenient().when(snapshotDetailsDao.findDetail(200L, OntapStorageConstants.PROTOCOL))
+ .thenReturn(new SnapshotDetailsVO(200L, OntapStorageConstants.PROTOCOL, protocol, false));
+
+ SnapshotVO snapshotVO = mock(SnapshotVO.class);
+ lenient().when(snapshotDao.findById(200L)).thenReturn(snapshotVO);
+ lenient().when(snapshotVO.getSize()).thenReturn(snapshotSize);
+ }
+
+ /**
+ * Sets up a volume create that the orchestrator has marked as a clone of a cached template.
+ */
+ private void stubVolumeCloneFromTemplate(long templateSize, long volumeSize) {
+ when(dataStore.getId()).thenReturn(1L);
+ when(dataStore.getName()).thenReturn("ontap-pool");
+ when(volumeInfo.getType()).thenReturn(VOLUME);
+ when(volumeInfo.getId()).thenReturn(100L);
+ when(volumeInfo.getName()).thenReturn("test-volume");
+ lenient().when(volumeInfo.getSize()).thenReturn(volumeSize);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePool.getId()).thenReturn(1L);
+ lenient().when(storagePool.getName()).thenReturn("vol1");
+ lenient().when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.OntapiSCSI);
+ lenient().when(storagePool.getHypervisor()).thenReturn(Hypervisor.HypervisorType.KVM);
+ lenient().when(storagePool.getCapacityIops()).thenReturn(null);
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+
+ when(volumeDao.findById(100L)).thenReturn(volumeVO);
+ lenient().when(volumeVO.getId()).thenReturn(100L);
+ // createAsync checks cloneOfSnapshot before cloneOfTemplate; under STRICT_STUBS an
+ // unstubbed alternate key on the same method is treated as an argument mismatch.
+ lenient().when(volumeDetailsDao.findDetail(100L, OntapStorageConstants.CLONE_OF_SNAPSHOT)).thenReturn(null);
+ when(volumeDetailsDao.findDetail(100L, OntapStorageConstants.CLONE_OF_TEMPLATE))
+ .thenReturn(new VolumeDetailVO(100L, OntapStorageConstants.CLONE_OF_TEMPLATE, "50", false));
+
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ lenient().when(templatePoolRef.getLocalDownloadPath()).thenReturn("template-lun-uuid");
+ lenient().when(templatePoolRef.getTemplateSize()).thenReturn(templateSize);
+ }
+
+ @Test
+ void testGrantAccess_Template_WritesInstallPathAndRefreshesStoreTarget() {
+ PrimaryDataStore primaryDataStore = mock(PrimaryDataStore.class);
+ Map dataStoreDetails = new HashMap<>();
+ dataStoreDetails.put(PrimaryDataStore.MANAGED_STORE_TARGET, "stale-value");
+
+ when(primaryDataStore.getId()).thenReturn(1L);
+ when(primaryDataStore.getDetails()).thenReturn(dataStoreDetails);
+ when(templateInfo.getType()).thenReturn(TEMPLATE);
+ when(templateInfo.getId()).thenReturn(50L);
+
+ when(storagePoolDao.findById(1L)).thenReturn(storagePool);
+ when(storagePool.getId()).thenReturn(1L);
+ when(storagePool.getName()).thenReturn("vol1");
+ when(storagePool.getScope()).thenReturn(ScopeType.CLUSTER);
+ when(storagePool.getPath()).thenReturn("iqn.1992-08.com.netapp:sn.123456");
+ when(storagePoolDetailsDao.listDetailsKeyPairs(1L)).thenReturn(storagePoolDetails);
+ when(vmTemplatePoolDao.findByPoolTemplate(1L, 50L, null)).thenReturn(templatePoolRef);
+ when(templatePoolRef.getId()).thenReturn(7L);
+
+ when(host.getName()).thenReturn("host1");
+ when(host.getUuid()).thenReturn("host-uuid-1");
+
+ AccessGroup existingAccessGroup = new AccessGroup();
+ Igroup existingIgroup = new Igroup();
+ existingIgroup.setName("igroup1");
+ existingAccessGroup.setIgroup(existingIgroup);
+
+ try (MockedStatic utilityMock = mockStatic(OntapStorageUtils.class, CALLS_REAL_METHODS)) {
+ utilityMock.when(() -> OntapStorageUtils.getStrategyByStoragePoolDetails(storagePoolDetails)).thenReturn(sanStrategy);
+ utilityMock.when(() -> OntapStorageUtils.getIgroupName(anyString(), anyString())).thenReturn("igroup1");
+
+ when(sanStrategy.getAccessGroup(any())).thenReturn(existingAccessGroup);
+ when(sanStrategy.ensureLunMapped(eq("svm1"), eq("/vol/vol1/cs_tmpl_50"), eq("igroup1"))).thenReturn("3");
+
+ assertTrue(driver.grantAccess(templateInfo, host, primaryDataStore));
+
+ String expectedPath = "/iqn.1992-08.com.netapp:sn.123456/3";
+ verify(templatePoolRef).setInstallPath(expectedPath);
+ verify(vmTemplatePoolDao).update(eq(7L), any(VMTemplateStoragePoolVO.class));
+
+ ArgumentCaptor