Damans227 commented on code in PR #12086:
URL: https://github.com/apache/cloudstack/pull/12086#discussion_r4175385076


##########
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateSnapshotsBetweenSecondaryStoragesCommandWrapper.java:
##########
@@ -0,0 +1,193 @@
+//
+// 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 com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.MigrateSnapshotsBetweenSecondaryStoragesCommand;
+import com.cloud.agent.api.MigrateBetweenSecondaryStoragesCommandAnswer;
+import com.cloud.agent.api.to.DataStoreTO;
+import com.cloud.agent.api.to.DataTO;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+import com.cloud.utils.Pair;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.Script;
+import org.apache.cloudstack.utils.qemu.QemuImageOptions;
+import org.apache.cloudstack.utils.qemu.QemuImg;
+import org.apache.cloudstack.utils.qemu.QemuImgException;
+import org.apache.cloudstack.utils.qemu.QemuImgFile;
+import org.libvirt.LibvirtException;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+@ResourceWrapper(handles = 
MigrateSnapshotsBetweenSecondaryStoragesCommand.class)
+public class LibvirtMigrateSnapshotsBetweenSecondaryStoragesCommandWrapper 
extends CommandWrapper<MigrateSnapshotsBetweenSecondaryStoragesCommand, Answer, 
LibvirtComputingResource> {
+
+    protected Set<String> filesToRemove;
+    protected List<Pair<Long, String>> resourcesToUpdate;
+    protected int wait;
+
+    @Override
+    public Answer execute(MigrateSnapshotsBetweenSecondaryStoragesCommand 
command, LibvirtComputingResource serverResource) {
+        filesToRemove = new HashSet<>();
+        resourcesToUpdate = new ArrayList<>();
+        wait = command.getWait() * 1000;
+
+        DataStoreTO srcDataStore = command.getSrcDataStore();
+        DataStoreTO destDataStore = command.getDestDataStore();
+        KVMStoragePoolManager storagePoolManager = 
serverResource.getStoragePoolMgr();
+
+        Set<KVMStoragePool> imagePools = new HashSet<>();
+        KVMStoragePool destImagePool = 
storagePoolManager.getStoragePoolByURI(destDataStore.getUrl());
+        imagePools.add(destImagePool);
+
+        String imagePoolUrl;
+        KVMStoragePool imagePool = null;
+
+        String parentSnapshotPath = null;
+        boolean parentSnapshotWasMigrated = false;
+        Set<Long> snapshotIdsToMigrate = command.getSnapshotIdsToMigrate();
+
+        DataTO currentSnapshot = null;
+
+        try {
+            for (DataTO snapshot : command.getSnapshotChain()) {
+                currentSnapshot = snapshot;
+                imagePoolUrl = snapshot.getDataStore().getUrl();
+                imagePool = 
storagePoolManager.getStoragePoolByURI(imagePoolUrl);
+                imagePools.add(imagePool);
+
+                String resourceCurrentPath = 
imagePool.getLocalPathFor(snapshot.getPath());
+
+                if (imagePoolUrl.equals(srcDataStore.getUrl()) && 
snapshotIdsToMigrate.contains(snapshot.getId())) {
+                    logger.debug("Migrating snapshot [{}] to destination 
storage pool [{}].", snapshot.getId(), destImagePool.getUuid());
+                    parentSnapshotPath = copyResourceToDestDataStore(snapshot, 
resourceCurrentPath, destImagePool, parentSnapshotPath);
+                    parentSnapshotWasMigrated = 
!parentSnapshotPath.equals(resourceCurrentPath);
+                    logger.debug("Snapshot [{}] migrated successfully. New 
path: [{}].", snapshot.getId(), parentSnapshotPath);
+                } else {
+                    if (parentSnapshotWasMigrated) {
+                        logger.debug("Rebasing snapshot [{}] to new parent 
path: [{}].", snapshot.getId(), parentSnapshotPath);
+                        parentSnapshotPath = 
rebaseResourceToNewParentPath(resourceCurrentPath, parentSnapshotPath);
+                    } else {
+                        logger.debug("Skipping migration/rebase for snapshot 
[{}]. Keeping current path.", snapshot.getId());
+                        parentSnapshotPath = resourceCurrentPath;
+                    }
+                    parentSnapshotWasMigrated = false;
+                }
+            }
+            logger.info("Successfully completed migrating snapshot chain 
[{}].", command.getSnapshotChain());
+        }  catch (LibvirtException | QemuImgException e) {
+            logger.error("Exception while migrating snapshots [{}] to 
secondary storage [{}] due to: [{}].", command.getSnapshotChain(), imagePool, 
e.getMessage(), e);
+            return new MigrateBetweenSecondaryStoragesCommandAnswer(command, 
false, String.format("Unable to migrate snapshot with ID [%s].", 
currentSnapshot.getId()), resourcesToUpdate);
+        } finally {
+            for (String file : filesToRemove) {

Review Comment:
   if a rebase fails partway through, does this still delete the old copy of 
the parent? the child that wasnt rebased yet would then point at a file thats 
gone



##########
engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/StorageOrchestrator.java:
##########
@@ -352,39 +374,130 @@ protected Pair<String, Boolean> migrateCompleted(Long 
destDatastoreId, DataStore
     protected Map<Long, Pair<Long, Long>> migrateAway(
             DataObject chosenFileForMigration,
             Map<Long, Pair<Long, Long>> storageCapacities,
-            Map<DataObject,
-            Pair<List<SnapshotInfo>, Long>> snapshotChains,
+            Map<DataObject, Pair<List<SnapshotInfo>, Long>> snapshotChains,
             Map<DataObject, Pair<List<TemplateInfo>, Long>> templateChains,
+            Set<Long> snapshotIdsToMigrate,
             DataStore srcDatastore,
             Long destDatastoreId,
             List<Future<DataObjectResult>> futures) {
 
         Long fileSize = migrationHelper.getFileSize(chosenFileForMigration, 
snapshotChains, templateChains);
         storageCapacities = assumeMigrate(storageCapacities, 
srcDatastore.getId(), destDatastoreId, fileSize);
 
-        MigrateDataTask task = new MigrateDataTask(chosenFileForMigration, 
srcDatastore, dataStoreManager.getDataStore(destDatastoreId, 
DataStoreRole.Image));
-        if (chosenFileForMigration instanceof SnapshotInfo ) {
+        DataStore destDataStore = 
dataStoreManager.getDataStore(destDatastoreId, DataStoreRole.Image);
+
+        boolean isKvmIncrementalSnapshot = chosenFileForMigration instanceof 
SnapshotInfo && ((SnapshotInfo) 
chosenFileForMigration).isKvmIncrementalSnapshot() && 
snapshotChains.containsKey(chosenFileForMigration);
+
+        if (isKvmIncrementalSnapshot) {
+            MigrateKvmIncrementalSnapshotTask task = new 
MigrateKvmIncrementalSnapshotTask(chosenFileForMigration, snapshotChains, 
srcDatastore, destDataStore, snapshotIdsToMigrate);
+            
futures.add(submitMigrationOnKvmAgent(srcDatastore.getScope().getScopeId(), 
task));
+            logger.debug("Incremental snapshot migration {} submitted to KVM 
Agent pool.", chosenFileForMigration.getUuid());
+        } else {
+            createMigrateDataTask(chosenFileForMigration, snapshotChains, 
templateChains, srcDatastore, destDataStore, futures);
+        }
+
+        return storageCapacities;
+    }
+
+    private void migrateKvmIncrementalSnapshotChain(DataObject 
chosenFileForMigration, Map<DataObject, Pair<List<SnapshotInfo>, Long>> 
snapshotChains, DataStore srcDatastore, DataStore destDataStore, Set<Long> 
snapshotIdsToMigrate) {
+        
Transaction.execute((TransactionCallback<AsyncCallFuture<DataObjectResult>>) 
status -> {
+            MigrateBetweenSecondaryStoragesCommandAnswer answer = null;
+            AsyncCallFuture<DataObjectResult> future = new AsyncCallFuture<>();
+            DataObjectResult result = new 
DataObjectResult(chosenFileForMigration);
+
+            try {
+                List<SnapshotInfo> snapshotChain = 
snapshotChains.get(chosenFileForMigration).first();
+                MigrateSnapshotsBetweenSecondaryStoragesCommand 
migrateBetweenSecondaryStoragesCmd = new 
MigrateSnapshotsBetweenSecondaryStoragesCommand(snapshotChain.stream().map(DataObject::getTO).collect(Collectors.toList()),
 srcDatastore.getTO(), destDataStore.getTO(), snapshotIdsToMigrate);
+
+                HostVO host = getAvailableHost(((SnapshotInfo) 
chosenFileForMigration).getDataCenterId());
+                if (host == null) {
+                    throw new CloudRuntimeException("No suitable hosts found 
to send migrate command.");
+                }
+
+                
migrateBetweenSecondaryStoragesCmd.setWait(StorageManager.AgentMaxDataMigrationWaitTime.valueIn(host.getClusterId()));
+                answer = (MigrateBetweenSecondaryStoragesCommandAnswer) 
agentManager.send(host.getId(), migrateBetweenSecondaryStoragesCmd);
+                if (answer == null || !answer.getResult()) {
+                    if (answer != null) {
+                        logger.warn(answer.getDetails());
+                    }
+                    throw new CloudRuntimeException("Unable to migrate KVM 
incremental snapshots to another secondary storage.");
+                }
+            } catch (final OperationTimedoutException | 
AgentUnavailableException e) {
+                throw new CloudRuntimeException("Error while migrating KVM 
incremental snapshot chain. Check the logs for more information.", e);
+            } finally {
+                if (answer != null) {
+                    updateSnapshotsReference(destDataStore, answer);
+                }
+            }
+            result.setSuccess(true);
+            future.complete(result);
+            return future;
+        });
+    }
+
+    private void updateSnapshotsReference(DataStore destDataStore, 
MigrateBetweenSecondaryStoragesCommandAnswer answer) {
+        for (Pair<Long, String> snapshotIdAndUpdatedCheckpointPath : 
answer.getMigratedResources()) {
+            Long snapshotId = snapshotIdAndUpdatedCheckpointPath.first();
+            String newCheckpointPath = 
snapshotIdAndUpdatedCheckpointPath.second();
+
+            SnapshotDataStoreVO snapshotDataStore = 
snapshotDataStoreDao.findOneBySnapshotAndDatastoreRole(snapshotId, 
DataStoreRole.Image);

Review Comment:
   what happens if the snapshot is on more than one secondary storage, like 
after a copy to another zone? this lookup doesnt filter by the source store so 
it could move the wrong record



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to