Copilot commented on code in PR #14426:
URL: https://github.com/apache/cloudstack/pull/14426#discussion_r4676779728
##########
engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java:
##########
@@ -2378,6 +2401,21 @@ protected MigrateCommand.MigrateDiskInfo
configureMigrateDiskInfo(VolumeInfo src
MigrateCommand.MigrateDiskInfo.Source.DEV, destPath,
backingPath);
}
+ /**
+ * Configures a {@link MigrateDiskInfo} for a destination volume on a Ceph
RBD pool: a network disk of the raw format
+ * that is addressed as "pool/image". The monitors and the authentication
of the destination pool are handed over as
+ * the host the Instance runs on may not know that pool, which can belong
to another cluster.
+ */
+ protected MigrateCommand.MigrateDiskInfo
configureMigrateDiskInfoForRbd(VolumeInfo srcVolumeInfo, String destPath,
StoragePoolVO destStoragePool) {
+ MigrateCommand.MigrateDiskInfo migrateDiskInfo = new
MigrateCommand.MigrateDiskInfo(srcVolumeInfo.getPath(),
+ MigrateCommand.MigrateDiskInfo.DiskType.NETWORK,
+ MigrateCommand.MigrateDiskInfo.DriverType.RAW,
+ MigrateCommand.MigrateDiskInfo.Source.NETWORK, destPath);
+ migrateDiskInfo.setDestPoolInformation(new
StoragePoolInformation(destStoragePool.getUuid(),
destStoragePool.getHostAddress(), destStoragePool.getPort(),
+ destStoragePool.getPath(),
StringUtils.substringBefore(destStoragePool.getUserInfo(), ":"),
StoragePoolType.RBD, null, true));
Review Comment:
The RBD destination handoff does not include the Ceph pool's libvirt secret
UUID. If the destination pool belongs to another cluster and is unknown on the
source host (the case this `StoragePoolInformation` handoff is intended to
support), `KVMStoragePoolManager` reconstructs the pool from this object but
leaves `LibvirtStoragePool.authSecretUUID` unset. `replaceDiskSourceWithRbd`
then emits an RBD `<auth>` node with a null/empty secret UUID, so the
destination host cannot authenticate the disk. Carry the pool secret UUID
through the handoff and set it when reconstructing the fallback pool.
##########
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java:
##########
@@ -807,6 +808,11 @@ protected String replaceStorage(String xmlDesc,
Map<String, MigrateCommand.Migra
diskNodeAttribute.setTextContent(migrateDiskInfo.getDiskType().toString());
+ boolean networkDestination =
MigrateCommand.MigrateDiskInfo.DiskType.NETWORK.equals(migrateDiskInfo.getDiskType());
+ if (networkDestination) {
+ replaceDiskSourceWithRbd(doc, diskNode,
migrateDiskInfo);
+ }
Review Comment:
`networkDestination` routes through `replaceDiskSourceWithRbd`, but that
helper only replaces the source, auth, and backing-store nodes. The existing
`<encryption>` node is left untouched, so an encrypted NFS → RBD migration
keeps `format="luks"` without `engine="librbd"`, while an RBD → file migration
keeps `format="luks2" engine="librbd"`. The destination disk is then opened
with the source pool's encryption description and can fail to start; rewrite
the encryption format/engine and destination secret for the destination pool
type as well.
##########
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java:
##########
@@ -864,6 +870,48 @@ protected String replaceStorage(String xmlDesc,
Map<String, MigrateCommand.Migra
return LibvirtXMLParser.getXml(doc);
}
+ /**
+ * Points the disk at an image on a Ceph RBD pool: the source is
"pool/image" with the monitors of the destination pool,
+ * and the Ceph authentication of the source pool is replaced by the one
of the destination pool (the secret is
+ * defined on the destination host, which is where the Instance will open
the image).
+ */
+ protected void replaceDiskSourceWithRbd(Document doc, Node diskNode,
MigrateCommand.MigrateDiskInfo migrateDiskInfo) {
+ List<Node> toRemove = new ArrayList<>();
+ NodeList diskChildNodes = diskNode.getChildNodes();
+ for (int i = 0; i < diskChildNodes.getLength(); i++) {
+ Node child = diskChildNodes.item(i);
+ // a backing chain of the source (a qcow2 volume cloned from a
template) is flattened into the raw image
+ if ("source".equals(child.getNodeName()) ||
"auth".equals(child.getNodeName()) ||
"backingStore".equals(child.getNodeName())) {
+ toRemove.add(child);
+ }
+ }
+ toRemove.forEach(diskNode::removeChild);
+
+ StoragePoolInformation destPool =
migrateDiskInfo.getDestPoolInformation();
+ Element sourceNode = doc.createElement("source");
+ sourceNode.setAttribute("protocol", "rbd");
+ sourceNode.setAttribute("name", migrateDiskInfo.getSourceText());
+ for (String monitorHost : StringUtils.split(destPool.getHost(), ',')) {
+ Element hostNode = doc.createElement("host");
+ hostNode.setAttribute("name", monitorHost.trim());
+ if (destPool.getPort() > 0) {
+ hostNode.setAttribute("port",
String.valueOf(destPool.getPort()));
+ }
Review Comment:
The VM-with-volumes migration path has the same endpoint bug as the
live-volume path: an explicitly ported monitor is copied into the XML `name`
attribute and then the pool port is appended to every host. For example,
`mon1:6789,mon2` with pool port 3300 becomes `name="mon1:6789" port="3300"`, so
the destination disk cannot connect to the intended monitor. Normalize each
monitor and preserve its own port (including IPv6 handling) before constructing
these `<host>` elements.
##########
test/integration/smoke/test_volume_migration_rbd_nfs.py:
##########
@@ -0,0 +1,667 @@
+# 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.
+""" BVT tests for volume migration between RBD (Ceph) and NFS primary
+storage pools on KVM.
+
+Every combination below is covered, for plain volumes
+(TestVolumeMigrationRbdNfs) as well as for encrypted volumes
+(TestEncryptedVolumeMigrationRbdNfs):
+
+* source and destination pool: RBD -> NFS, NFS -> RBD, NFS -> NFS and
+ RBD -> RBD
+* online (the Instance keeps running, migrateVolume with livemigrate) and
+ offline (the Instance is stopped, or the volume is not attached)
+* ROOT and DATA volumes
+* volumes with and without a backing chain: every test deploys its own
+ Instance on its source pool, so the first migration moves a ROOT volume
+ cloned from the template (a qcow2 backing file on NFS, an RBD clone on
+ Ceph); the DATA volume, and the ROOT volume once it was migrated, have no
+ chain.
+
+Besides the volume being on the expected pool, the data of each volume is
+verified on the host after every migration, as the Instance sees it (that is,
+decrypted): a pattern written to the DATA volume, and a checksum of the boot
+area of the ROOT volume. For encrypted volumes the encryption the destination
+pool requires is verified too: native librbd LUKS2 on RBD, qemu LUKS on NFS.
+
+Requirements: KVM, an RBD pool and the "nfs" primary storage of the test
+data. The NFS -> NFS migrations also need the "nfs2" primary storage and the
+RBD -> RBD migrations a second RBD pool; those are skipped otherwise. The
+encrypted volume tests need a host with RBD volume encryption support.
+"""
+
+import base64
+import hashlib
+import re
+import xml.etree.ElementTree as ET
+
+from marvin.cloudstackAPI import (deleteStoragePool,
+ detachVolume,
+ enableStorageMaintenance)
+from marvin.cloudstackTestCase import cloudstackTestCase
+from marvin.lib.base import (Account,
+ DiskOffering,
+ Host,
+ ServiceOffering,
+ StoragePool,
+ Template,
+ VirtualMachine,
+ Volume)
+from marvin.lib.common import (get_domain,
+ get_pod,
+ get_zone,
+ list_clusters,
+ list_hosts,
+ list_storage_pools)
+from marvin.lib.utils import random_gen
+from marvin.sshClient import SshClient
+
+from nose.plugins.attrib import attr
+
+_multiprocess_shared_ = False
+
+# KVM copies a volume in place only between two RBD pools, or between an RBD
pool and a file based
+# one (Storage.isMigrationBetweenRbdOrRbdAndFileBased). A migration between
two file based pools is
+# refused, with this message for a live one and the next for an encrypted
volume, so the tests which
+# ask for one assert the refusal instead of the move.
+LIVE_MIGRATION_REFUSED = "KVM does not support volume live migration"
+ENCRYPTED_MIGRATION_REFUSED = "Migration of encrypted volumes is unsupported"
+
+# Runs on the host of an Instance to access one of its disks as the Instance
sees it, i.e. decrypted:
+# disk-io.sh <domain> <disk alias> write|read "<qemu-io command>"
+# A write goes through the HMP qemu-io command of the disk device. A read goes
through a read-only NBD
+# export of the node of the disk, as the output of HMP qemu-io ends up
(buffered) in the log of qemu.
+DISK_IO_SCRIPT = r'''
+dom=$1; dev=$2; mode=$3; cmd=$4
+qmp() { virsh qemu-monitor-command "$dom" "$1"; }
+read qdev node <<<$(qmp '{"execute":"query-block"}' | python3 -c '
+import json, sys
+for b in json.load(sys.stdin)["return"]:
+ q = b.get("qdev", "")
+ if sys.argv[1] in (q, b.get("device", "")) or
q.startswith("/machine/peripheral/%s/" % sys.argv[1]):
+ print(q or b["device"], b["inserted"]["node-name"])
+ break' "$dev")
+[ -z "$node" ] && { echo "no block node found for disk $dev"; exit 1; }
+if [ "$mode" = write ]; then
+ virsh qemu-monitor-command "$dom" --hmp "qemu-io -d $qdev \"$cmd\""
+ exit $?
+fi
+sock=$(ls -d /var/lib/libvirt/qemu/domain-*-$dom | head
-1)/volume-migration-test.sock
+qmp
"{\"execute\":\"nbd-server-start\",\"arguments\":{\"addr\":{\"type\":\"unix\",\"data\":{\"path\":\"$sock\"}}}}"
>/dev/null
+qmp
"{\"execute\":\"block-export-add\",\"arguments\":{\"type\":\"nbd\",\"id\":\"volmig\",\"node-name\":\"$node\",\"writable\":false}}"
>/dev/null
+qemu-io -r -f raw "nbd+unix:///$node?socket=$sock" -c "$cmd"
+rc=$?
+qmp '{"execute":"block-export-del","arguments":{"id":"volmig"}}' >/dev/null
+sleep 1
+qmp '{"execute":"nbd-server-stop"}' >/dev/null
+exit $rc
+'''
+DISK_IO_SCRIPT_PATH = "/tmp/cs-volume-migration-test-disk-io.sh"
+
+DATA_PATTERN = "0xa5"
+DATA_PATTERN_OFFSET = "1M"
+DATA_PATTERN_LENGTH = "4M"
+DATA_PATTERN_BYTES = 4 * 1024 * 1024
+# The start of a ROOT volume that the guest does not write to: the MBR and the
gap in front of the first
+# partition (which traditionally starts at sector 63) that holds the boot
loader. Further on, the guest
+# updates its file systems (e.g. the mount time in the superblock of /boot)
while it runs.
+ROOT_CHECKSUM_LENGTH = "31k"
+
+
+class VolumeMigrationRbdNfsBase(cloudstackTestCase):
+ """Set up and helpers of the volume migration tests between RBD and NFS
pools on KVM"""
+
+ # whether the ROOT and DATA volumes of the Instances are encrypted
+ encrypted = False
+
+ @classmethod
+ def setUpClass(cls):
+ testClient = super(VolumeMigrationRbdNfsBase, cls).getClsTestClient()
+ cls.apiclient = testClient.getApiClient()
+ cls.dbclient = testClient.getDbConnection()
+ cls.services = testClient.getParsedTestDataConfig()
+ cls._cleanup = []
+ cls.created_pools = []
+ cls.saved_pool_tags = {}
+ cls.unsupported_reason = None
+
+ cls.domain = get_domain(cls.apiclient)
+ cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
+ cls.pod = get_pod(cls.apiclient, cls.zone.id)
+ cls.services['mode'] = cls.zone.networktype
+ cls.hypervisor = testClient.getHypervisorInfo()
+
+ if cls.hypervisor.lower() != 'kvm':
+ cls.unsupported_reason = "requires KVM"
+ return
+
+ rbd_pools = [pool for pool in list_storage_pools(cls.apiclient,
zoneid=cls.zone.id) or []
+ if pool.type == 'RBD' and pool.state == 'Up']
+ if not rbd_pools:
+ cls.unsupported_reason = "requires an RBD storage pool"
+ return
+ cls.rbd_pool = rbd_pools[0]
+ cls.rbd_pool2 = rbd_pools[1] if len(rbd_pools) > 1 else None
+
+ cls.cluster = None
+ for cluster in list_clusters(cls.apiclient, zoneid=cls.zone.id) or []:
+ if list_hosts(cls.apiclient, clusterid=cluster.id):
+ cls.cluster = cluster
+ break
+ if cls.cluster is None:
+ cls.unsupported_reason = "requires a cluster with hosts"
+ return
+
+ cls.host_config =
cls.config.__dict__["zones"][0].__dict__["pods"][0].__dict__["clusters"][0].__dict__["hosts"][0].__dict__
+
+ if cls.encrypted and not cls.host_with_rbd_encryption_support_exists():
+ cls.unsupported_reason = "requires a host with RBD volume
encryption support"
+ return
+
+ cls.template = Template.register(
+ cls.apiclient,
+ cls.services["test_templates_cloud_init"][cls.hypervisor.lower()],
+ zoneid=cls.zone.id,
+ hypervisor=cls.hypervisor,
+ )
+ cls.template.download(cls.apiclient)
+
+ cls.services["domainid"] = cls.domain.id
+ cls.services["zoneid"] = cls.zone.id
+ cls.services["template"] = cls.template.id
+
+ cls.account = Account.create(
+ cls.apiclient,
+ cls.services["account"],
+ domainid=cls.domain.id
+ )
+ cls._cleanup.append(cls.account)
+
+ # The offerings carry a storage tag of their own, which is put on the
pool an Instance has to be
+ # deployed on, and on all the pools the volumes are migrated between.
+ cls.pool_tag = "volmig-" + random_gen(size=6).lower()
+ encryption_args = {"encryptroot": True} if cls.encrypted else {}
+ cls.service_offering = ServiceOffering.create(
+ cls.apiclient,
+ cls.services["service_offerings"]["tiny"],
+ tags=cls.pool_tag,
+ **encryption_args
+ )
+ cls._cleanup.append(cls.service_offering)
+
+ encryption_args = {"encrypt": True} if cls.encrypted else {}
+ cls.disk_offering = DiskOffering.create(
+ cls.apiclient,
+ cls.services["disk_offering"],
+ tags=cls.pool_tag,
+ **encryption_args
+ )
+ cls._cleanup.append(cls.disk_offering)
+
+ cls.nfs_pool = cls.create_nfs_pool(cls.services["nfs"])
+ cls.nfs_pool2 = cls.create_nfs_pool(cls.services["nfs2"]) if "nfs2" in
cls.services else None
+
+ cls.pools = [pool for pool in (cls.rbd_pool, cls.rbd_pool2,
cls.nfs_pool, cls.nfs_pool2) if pool is not None]
+ for pool in cls.pools:
+ cls.saved_pool_tags[pool.id] = getattr(pool, 'tags', "") or ""
+
+ @classmethod
+ def create_nfs_pool(cls, services):
+ pool = StoragePool.create(
+ cls.apiclient,
+ services,
+ clusterid=cls.cluster.id,
+ zoneid=cls.zone.id,
+ podid=cls.pod.id
+ )
+ cls.created_pools.append(pool)
+ return pool
+
+ @classmethod
+ def host_with_rbd_encryption_support_exists(cls):
+ # librbd encryption support is only tracked in host_details, it is not
part of the API response
+ hosts = Host.list(cls.apiclient, zoneid=cls.zone.id, type='Routing',
hypervisor='KVM', state='Up') or []
+ for host in hosts:
+ supported = cls.dbclient.execute(
+ "select hd.value from host_details hd join host h on
h.id=hd.host_id "
+ "where h.uuid='%s' and hd.name='host.volume.encryption.rbd'" %
host.id
+ )
+ if supported and supported[0][0].lower() == 'true':
+ return True
+ return False
+
+ @classmethod
+ def tag_pools(cls, pools):
+ """Put the storage tag of the offerings on the given pools (on top of
their own tags) and remove it
+ from the other ones"""
+ for pool in cls.pools:
+ tags = [tag for tag in cls.saved_pool_tags[pool.id].split(",") if
tag]
+ if pool in pools:
+ tags.append(cls.pool_tag)
+ StoragePool.update(cls.apiclient, id=pool.id, tags=",".join(tags))
+
+ @classmethod
+ def tearDownClass(cls):
+ try:
+ super(VolumeMigrationRbdNfsBase, cls).tearDownClass()
+ finally:
+ for pool in getattr(cls, 'pools', []):
+ try:
+ StoragePool.update(cls.apiclient, id=pool.id,
tags=cls.saved_pool_tags[pool.id])
+ except Exception as e:
+ cls.debug("Warning: failed to restore the tags of storage
pool %s: %s" % (pool.id, e))
+ for pool in cls.created_pools:
+ cls.delete_storage_pool(pool)
+
+ @classmethod
+ def delete_storage_pool(cls, pool):
+ """Put the pool in maintenance and force delete it, so a volume left
+ behind by a failed test does not leak the pool into the next run."""
+ try:
+ cmd = enableStorageMaintenance.enableStorageMaintenanceCmd()
+ cmd.id = pool.id
+ cls.apiclient.enableStorageMaintenance(cmd)
+ cmd = deleteStoragePool.deleteStoragePoolCmd()
+ cmd.id = pool.id
+ cmd.forced = True
+ cls.apiclient.deleteStoragePool(cmd)
+ except Exception as e:
+ cls.debug("Warning: failed to delete storage pool %s: %s" %
(pool.id, e))
+
+ def setUp(self):
+ self.apiclient = self.testClient.getApiClient()
+ self.cleanup = []
+ if self.unsupported_reason:
+ self.skipTest("Skipping test: %s" % self.unsupported_reason)
+
+ def tearDown(self):
+ super(VolumeMigrationRbdNfsBase, self).tearDown()
+
+ def require_pools(self, *pools):
+ if None in pools:
+ self.skipTest("Skipping test: requires a second NFS (\"nfs2\" in
the test data) or RBD storage pool")
+
+ def require_rbd_encrypted_hotplug(self):
+ """libvirt < 10.1.0 cannot hot-plug or live migrate an encrypted RBD
volume of a running Instance
+ (the agent refuses it), so the tests that do so are skipped on such
hosts"""
+ hosts = Host.list(self.apiclient, zoneid=self.zone.id, type='Routing',
hypervisor='KVM', state='Up') or []
+ for host in hosts:
+ ssh = SshClient(host=host.ipaddress, port=22,
user=self.host_config['username'],
+ passwd=self.host_config['password'])
+ out = ssh.execute("virsh version | awk '/Using library/{print
$NF}'")
+ version = [int(v) for v in re.findall(r'\d+', (out[-1] if out else
"0.0.0"))[:3]]
+ if version < [10, 1, 0]:
+ self.skipTest("Skipping test: libvirt %s on host %s cannot
attach or live migrate an encrypted "
+ "RBD volume of a running Instance (libvirt
10.1.0 is required)"
+ % (".".join(map(str, version)), host.name))
+
+ # Instances and volumes
+
+ def deploy_instance(self, pool):
+ """Deploy an Instance with a DATA volume, both volumes allocated on
the given pool. The ROOT volume
+ is cloned from the template, so it has a backing chain (a qcow2
backing file or an RBD parent)."""
+ self.tag_pools([pool])
+ try:
+ instance = VirtualMachine.create(
+ self.apiclient,
+ self.services,
+ accountid=self.account.name,
+ domainid=self.account.domainid,
+ serviceofferingid=self.service_offering.id,
+ mode=self.services["mode"]
+ )
+ self.cleanup.append(instance)
+ data_volume = Volume.create(
+ self.apiclient,
+ self.services,
+ account=self.account.name,
+ domainid=self.account.domainid,
+ diskofferingid=self.disk_offering.id
+ )
+ self.cleanup.append(data_volume)
+ instance.attach_volume(self.apiclient, data_volume)
+ finally:
+ self.tag_pools(self.pools)
+
+ root_volume = Volume.list(self.apiclient,
virtualmachineid=instance.id, type='ROOT', listall=True)[0]
+ for volume in (root_volume, data_volume):
+ self.assert_volume_on_pool(volume, pool)
+ # Destroying the Instance does not remove its DATA volume, which is to
be detached first
+ self.cleanup.remove(data_volume)
+ self.cleanup.insert(0, _DetachedVolume(self.apiclient, data_volume))
+ return instance, root_volume, data_volume
+
+ def migrate_online(self, instance, volumes, pool):
+ for volume in volumes:
+ Volume.migrate(self.apiclient, volumeid=volume.id,
storageid=pool.id, livemigrate=True)
Review Comment:
Please add the Marvin smoke-suite run result for
`test_volume_migration_rbd_nfs.py` to the PR description, including the outcome
of its KVM migration cases; the description states that this test has not been
run from this branch.
##########
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapper.java:
##########
@@ -374,4 +392,408 @@ protected MigrateVolumeAnswer migrateRegularVolume(final
MigrateVolumeCommand co
return new MigrateVolumeAnswer(command, true, null, destPath);
}
+
+
+ protected MigrateVolumeAnswer migrateRBDVolume(final MigrateVolumeCommand
command, final LibvirtComputingResource libvirtComputingResource) {
+ final String vmName = command.getAttachedVmName();
+
+ VolumeObjectTO srcVolumeObjectTO =
(VolumeObjectTO)command.getSrcData();
+ PrimaryDataStoreTO sourcePool =
(PrimaryDataStoreTO)srcVolumeObjectTO.getDataStore();
+
+ VolumeObjectTO destVolumeObjectTO =
(VolumeObjectTO)command.getDestData();
+ PrimaryDataStoreTO destPool =
(PrimaryDataStoreTO)destVolumeObjectTO.getDataStore();
+
+ String destDiskLabel = null;
+
+ VolumeMigrationCancelHook cancelHook = null;
+
+ final KVMStoragePoolManager storagePoolMgr =
libvirtComputingResource.getStoragePoolMgr();
+
+ Domain dm = null;
+ MigrateVolumeAnswer answer = null;
+ boolean destVolumeCreated = false;
+ // whether the block copy has been pivoted: the Instance then uses the
destination volume, so nothing
+ // that follows may turn the migration into a failure
+ boolean pivoted = false;
+ KVMStoragePool destKvmPool = null;
+ try {
+ // libvirt < 10.1.0 cannot add the LUKS secret of an encrypted RBD
image to a running domain before the
+ // image itself (see
KVMStorageProcessor.MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG), so the
block copy
+ // into it fails. Refuse before anything is created on the
destination pool.
+ if (Objects.equals(Storage.StoragePoolType.RBD,
destPool.getPoolType()) &&
ArrayUtils.isNotEmpty(destVolumeObjectTO.getPassphrase())
+ && libvirtComputingResource.getHypervisorLibvirtVersion()
< KVMStorageProcessor.MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG) {
+ return new MigrateVolumeAnswer(command, false,
String.format("Libvirt version %s required to live migrate a volume to an
encrypted RBD volume, but version %s detected."
+ + " Stop the Instance to migrate the volume, or
upgrade libvirt.",
+
LibvirtComputingResource.prettyVersion(KVMStorageProcessor.MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG),
+
LibvirtComputingResource.prettyVersion(libvirtComputingResource.getHypervisorLibvirtVersion())),
null);
+ }
+
+ final LibvirtUtilitiesHelper libvirtUtilitiesHelper =
libvirtComputingResource.getLibvirtUtilitiesHelper();
+ Connect conn = libvirtUtilitiesHelper.getConnection();
+ dm = libvirtComputingResource.getDomain(conn, vmName);
+ if (dm == null) {
+ return new MigrateVolumeAnswer(command, false, "Migrate volume
failed due to can not find vm: " + vmName, null);
+ }
+
+ DomainInfo.DomainState domainState = dm.getInfo().state ;
+ if (domainState != DomainInfo.DomainState.VIR_DOMAIN_RUNNING) {
+ return new MigrateVolumeAnswer(command, false, "Migrate volume
failed due to VM is not running: " + vmName + " with domainState = " +
domainState, null);
+ }
+
+ KVMStoragePool pool =
storagePoolMgr.getStoragePool(destPool.getPoolType(), destPool.getUuid());
+ destKvmPool = pool;
+ pool.connectPhysicalDisk(destVolumeObjectTO.getPath(), null);
+
+ KVMStoragePool srcKvmPool =
storagePoolMgr.getStoragePool(sourcePool.getPoolType(), sourcePool.getUuid());
+ final String sourceFilePath = generateVolumePathOnHost(srcKvmPool,
sourcePool, srcVolumeObjectTO);
+ final String destFilePath = generateVolumePathOnHost(pool,
destPool, destVolumeObjectTO);
+
+ String srcSecretUUID = null;
+ String destSecretUUID = null;
+ if (ArrayUtils.isNotEmpty(destVolumeObjectTO.getPassphrase())) {
+ srcSecretUUID =
libvirtComputingResource.createLibvirtVolumeSecret(conn,
srcVolumeObjectTO.getPath(), srcVolumeObjectTO.getPassphrase());
+ destSecretUUID =
libvirtComputingResource.createLibvirtVolumeSecret(conn,
destVolumeObjectTO.getPath(), destVolumeObjectTO.getPassphrase());
+ if (Objects.equals(srcSecretUUID, destSecretUUID)) {
+ // the secret is named after the volume path and is shared
by both disks: keep it for the Instance
+ srcSecretUUID = null;
+ }
+ }
+
+ // A block copy between two RBD pools only has to copy the active
layer, as the destination image is
+ // already provisioned. When NFS is involved the backing chain of
the source differs from what the
+ // destination can reference, so the whole chain is flattened into
the destination instead.
+ boolean srcAndDestOnRbd =
Objects.equals(Storage.StoragePoolType.RBD, sourcePool.getPoolType())
+ && Objects.equals(Storage.StoragePoolType.RBD,
destPool.getPoolType());
+
+ String diskdef = generateDestinationDiskXMLForRBD(dm,
sourceFilePath, destFilePath, destSecretUUID, pool, destPool.getPoolType(),
+ srcAndDestOnRbd);
+ if (diskdef == null) {
+ return new MigrateVolumeAnswer(command, false,
+ String.format("Migrate volume failed as the disk with
path %s was not found in the XML domain of vm %s", sourceFilePath, vmName),
null);
+ }
+ destDiskLabel = generateDestinationDiskLabel(diskdef);
+
+ TypedUlongParameter parameter = new
TypedUlongParameter("bandwidth", 0);
+ TypedParameter[] parameters = new TypedParameter[1];
+ parameters[0] = parameter;
+
+ int blockCopyFlags = srcAndDestOnRbd ?
Domain.BlockCopyFlags.SHALLOW : 0;
+ if (ArrayUtils.isNotEmpty(destVolumeObjectTO.getPassphrase())) {
+ // libvirt can not create (and format) an encrypted mirror
itself, so the destination volume is
+ // created with its encryption header up front and the block
copy writes into it.
+ KVMPhysicalDisk srcDisk =
srcKvmPool.getPhysicalDisk(srcVolumeObjectTO.getPath());
+ long guestSize = srcDisk.getVirtualSize();
+ if (Objects.equals(Storage.StoragePoolType.RBD,
sourcePool.getPoolType())) {
+ guestSize -=
LibvirtStorageAdaptor.LUKS2_HEADER_RESERVE_BYTES;
+ }
+ createEncryptedDestinationVolume(pool, destPool,
destVolumeObjectTO, guestSize);
+ destVolumeCreated = true;
+ blockCopyFlags |= Domain.BlockCopyFlags.REUSE_EXT;
+ }
+
+ cancelHook = new VolumeMigrationCancelHook(dm, destDiskLabel);
+ libvirtComputingResource.addDisconnectHook(cancelHook);
+
+ libvirtComputingResource.createOrUpdateLogFileForCommand(command,
Command.State.PROCESSING_IN_BACKEND);
+
+ dm.blockCopy(destDiskLabel, diskdef, parameters, blockCopyFlags);
+ logger.info(String.format("Block copy has started for the volume
%s : %s to %s", destDiskLabel, sourceFilePath, destFilePath));
+
+ answer = checkBlockJobStatus(command, dm, destDiskLabel,
sourceFilePath, destFilePath, libvirtComputingResource, conn, srcSecretUUID);
+ if (answer != null && answer.getResult()) {
+ // the block copy was pivoted: from here on the migration is
done, and what follows only logs a failure
+ pivoted = true;
+ answer = new MigrateVolumeAnswer(command, true, null,
destVolumeObjectTO.getPath());
+ try {
+
libvirtComputingResource.createOrUpdateLogFileForCommand(command,
Command.State.COMPLETED);
+ } catch (Exception e) {
+ logger.warn(String.format("Failed to finish the migration
of the volume %s to the pool %s after the block copy was pivoted: %s",
+ destVolumeObjectTO.getPath(), destPool.getUuid(),
e.getMessage()), e);
+ }
+ } else if (answer != null) {
+
libvirtComputingResource.createOrUpdateLogFileForCommand(command,
Command.State.FAILED);
+ }
+ return answer;
+ } catch (Exception e) {
+ if (pivoted) {
+ // the Instance already uses the destination volume: report
the migration as done, as it is
+ logger.warn(String.format("Ignoring %s after the block copy of
the volume %s was pivoted", e.toString(), destVolumeObjectTO.getPath()), e);
+ return answer;
+ }
+ String msg = "Migrate volume failed due to " + e.toString();
+ logger.warn(msg, e);
+ if (destDiskLabel != null) {
+ try {
+ dm.blockJobAbort(destDiskLabel,
Domain.BlockJobAbortFlags.ASYNC);
+ } catch (LibvirtException ex) {
+ logger.error("Migrate volume failed while aborting the
block job due to " + ex.getMessage());
+ }
+ }
+ libvirtComputingResource.createOrUpdateLogFileForCommand(command,
Command.State.FAILED);
+ answer = new MigrateVolumeAnswer(command, false, msg, null);
+ return answer;
+ } finally {
+ if (cancelHook != null) {
+ libvirtComputingResource.removeDisconnectHook(cancelHook);
+ }
+ if (destVolumeCreated && (answer == null || !answer.getResult())) {
+ deleteDestinationVolume(destKvmPool, destPool,
destVolumeObjectTO.getPath());
+ }
+ if (pivoted) {
+ // Remove old volume after successful migration. The Instance
uses the destination volume already, so a
+ // failure to remove the source one is only logged: it must
not turn the migration into a failure.
+ try {
+ KVMStoragePool libvirtSourcePool =
storagePoolMgr.getStoragePool(sourcePool.getPoolType(), sourcePool.getUuid());
+ Storage.ImageFormat srcFormat =
Objects.equals(Storage.StoragePoolType.RBD, sourcePool.getPoolType())
+ ? Storage.ImageFormat.RAW :
Storage.ImageFormat.QCOW2;
+
libvirtSourcePool.deletePhysicalDisk(srcVolumeObjectTO.getPath(), srcFormat);
+ } catch (Exception e) {
+ logger.warn(String.format("Failed to remove the source
volume %s from the pool %s after it was migrated: %s. It has to be removed
manually",
+ srcVolumeObjectTO.getPath(), sourcePool.getUuid(),
e.getMessage()), e);
+ }
+ }
+ if (dm != null) {
+ try {
+ dm.free();
+ } catch (LibvirtException l) {
+ logger.trace("Ignoring libvirt error.", l);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Creates the (empty) destination volume of a live migration of an
encrypted volume, with its encryption
+ * header, so that the block copy can write into it. An RBD volume gets a
native librbd LUKS2 header, a volume
+ * on a file based pool is a qemu LUKS encrypted QCOW2 file.
+ *
+ * @param guestSize size of the disk as seen by the Instance
+ */
+ protected void createEncryptedDestinationVolume(KVMStoragePool pool,
PrimaryDataStoreTO destPool, VolumeObjectTO destVolumeObjectTO, long guestSize)
{
+ String path = destVolumeObjectTO.getPath();
+ // a previous failed attempt may have left the volume behind
+ deleteDestinationVolume(pool, destPool, path);
+ if (Objects.equals(Storage.StoragePoolType.RBD,
destPool.getPoolType())) {
+ // the LUKS2 header is carved out of the image, so it has to be
added to what the Instance can use
+ pool.createPhysicalDisk(path, PhysicalDiskFormat.RAW,
Storage.ProvisioningType.THIN,
+ guestSize +
LibvirtStorageAdaptor.LUKS2_HEADER_RESERVE_BYTES,
destVolumeObjectTO.getPassphrase());
+ } else {
+ pool.createPhysicalDisk(path, PhysicalDiskFormat.QCOW2,
Storage.ProvisioningType.THIN, guestSize, destVolumeObjectTO.getPassphrase());
+ }
+ }
+
+ protected void deleteDestinationVolume(KVMStoragePool pool,
PrimaryDataStoreTO destPool, String path) {
+ if (pool == null) {
+ return;
+ }
+ try {
+ pool.deletePhysicalDisk(path,
Objects.equals(Storage.StoragePoolType.RBD, destPool.getPoolType())
+ ? Storage.ImageFormat.RAW : Storage.ImageFormat.QCOW2);
+ } catch (Exception e) {
+ logger.debug("Could not remove the destination volume {} (it may
not exist): {}", path, e.getMessage());
+ }
+ }
+
+ /**
+ * Returns the path of the volume as it is referenced in the XML domain of
the Instance on this host. RBD volumes
+ * are addressed as "<pool>/<image>", while file based volumes (e.g. NFS)
are addressed by their path on the
+ * local mount point of the pool.
+ */
+ protected String generateVolumePathOnHost(KVMStoragePool kvmStoragePool,
PrimaryDataStoreTO dataStore, VolumeObjectTO volumeObjectTO) {
+ if (Objects.equals(Storage.StoragePoolType.RBD,
dataStore.getPoolType())) {
+ return String.format("%s/%s", dataStore.getPath(),
volumeObjectTO.getPath());
+ }
+ return String.format("%s/%s", kvmStoragePool.getLocalPath(),
volumeObjectTO.getPath());
+ }
+
+ /**
+ * Generates the XML of the destination disk used by the libvirt block
copy. The source disk is located in the XML
+ * domain of the Instance by its current path, and is then rewritten to
point at the destination pool. Both an RBD
+ * (network) and an NFS (file) destination are supported, independently of
the type of the source disk.
+ */
+ /**
+ * Build the mirror disk XML handed to {@code blockCopy} from the disk the
volume currently uses.
+ *
+ * @param shallowBlockCopy whether the copy will run with {@code
VIR_DOMAIN_BLOCK_COPY_SHALLOW}, which decides
+ * whether the source's backing chain may be
carried over to the mirror.
+ */
+ protected String generateDestinationDiskXMLForRBD(Domain dm, String
srcVolumePath, String diskFilePath, String destSecretUUID, KVMStoragePool pool,
+ Storage.StoragePoolType destPoolType, boolean shallowBlockCopy)
+ throws LibvirtException, ParserConfigurationException,
IOException, TransformerException, SAXException {
+ final String domXml = dm.getXMLDesc(0);
+
+ DocumentBuilderFactory dbFactory =
ParserUtils.getSaferDocumentBuilderFactory();
+ DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
+ Document doc = dBuilder.parse(new
ByteArrayInputStream(domXml.getBytes("UTF-8")));
+ doc.getDocumentElement().normalize();
+
+ NodeList disks = doc.getElementsByTagName("disk");
+
+ for (int i = 0; i < disks.getLength(); i++) {
+ Node diskNode = disks.item(i);
+ if (!isDiskNodeOfVolume(diskNode, srcVolumePath)) {
+ continue;
+ }
+
+ logger.debug(String.format("Found disk node with source volume
path %s, generating destination disk XML for %s on %s", srcVolumePath,
diskFilePath,
+ destPoolType));
+ updateDiskNodeForDestinationPool(doc, diskNode, diskFilePath,
destSecretUUID, pool, destPoolType, shallowBlockCopy);
+
+ StringWriter diskSection = new StringWriter();
+ Transformer xformer =
TransformerFactory.newInstance().newTransformer();
+ xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ xformer.transform(new DOMSource(diskNode), new
StreamResult(diskSection));
+
+ return diskSection.toString();
+ }
+ return null;
+ }
+
+ /**
+ * True if the disk node is the one backing the volume with the given
path, be it an RBD (network) or a file disk.
+ */
+ protected boolean isDiskNodeOfVolume(Node diskNode, String srcVolumePath) {
+ Node diskTypeAttribute = diskNode.getAttributes().getNamedItem("type");
+ if (diskTypeAttribute == null) {
+ return false;
+ }
+ String diskType = diskTypeAttribute.getNodeValue();
+ boolean networkDisk =
LibvirtVMDef.DiskDef.DiskType.NETWORK.toString().equalsIgnoreCase(diskType);
+ boolean fileDisk =
LibvirtVMDef.DiskDef.DiskType.FILE.toString().equalsIgnoreCase(diskType);
+ if (!networkDisk && !fileDisk) {
+ return false;
+ }
+
+ Node sourceNode = getChildNode(diskNode, "source");
+ if (sourceNode == null) {
+ return false;
+ }
+ NamedNodeMap sourceAttributes = sourceNode.getAttributes();
+
+ if (networkDisk) {
+ Node protocolAttribute = sourceAttributes.getNamedItem("protocol");
+ if (protocolAttribute == null ||
!protocolAttribute.getNodeValue().equalsIgnoreCase(LibvirtVMDef.DiskDef.DiskProtocol.RBD.toString()))
{
+ logger.debug("Skipped disk node with protocol: " +
protocolAttribute);
+ return false;
+ }
+ Node nameAttribute = sourceAttributes.getNamedItem("name");
+ return nameAttribute != null &&
nameAttribute.getNodeValue().contains(srcVolumePath);
+ }
+
+ Node fileAttribute = sourceAttributes.getNamedItem("file");
+ return fileAttribute != null &&
fileAttribute.getNodeValue().contains(srcVolumePath);
+ }
+
+ /**
+ * Rewrites the disk node so that it refers to the volume on the
destination pool. The disk type, the source, the
+ * driver type and the Ceph authentication are all adjusted to what the
destination pool requires.
+ */
+ protected void updateDiskNodeForDestinationPool(Document doc, Node
diskNode, String diskFilePath, String destSecretUUID, KVMStoragePool pool,
+ Storage.StoragePoolType destPoolType, boolean shallowBlockCopy) {
+ boolean destinationOnRbd = Objects.equals(Storage.StoragePoolType.RBD,
destPoolType);
+
+ Element diskElement = (Element)diskNode;
+ diskElement.setAttribute("type", destinationOnRbd ?
LibvirtVMDef.DiskDef.DiskType.NETWORK.toString().toLowerCase()
+ : LibvirtVMDef.DiskDef.DiskType.FILE.toString().toLowerCase());
+
+ Node sourceNode = getChildNode(diskNode, "source");
+ if (sourceNode != null) {
+ diskNode.removeChild(sourceNode);
+ }
+ diskNode.appendChild(destinationOnRbd ? createRbdSourceNode(doc,
diskFilePath, pool) : createFileSourceNode(doc, diskFilePath));
+
+ // A disk cloned from a template keeps that template as its backing
file, and libvirt reports the whole
+ // chain in the live domain XML. Only a shallow copy may carry that
chain into the mirror: a full copy
+ // flattens every layer into the destination, so a <backingStore>
there describes a chain the destination
+ // does not have. libvirt refuses that combination outright with
"backingStore of mirror without
+ // VIR_DOMAIN_BLOCK_COPY_SHALLOW doesn't make sense", which is why the
element is dropped here.
+ if (!shallowBlockCopy) {
+ Node backingStoreNode = getChildNode(diskNode, "backingStore");
+ if (backingStoreNode != null) {
+ diskNode.removeChild(backingStoreNode);
+ }
+ }
+
+ Node driverNode = getChildNode(diskNode, "driver");
+ if (driverNode instanceof Element) {
+ // RBD volumes are raw, whereas volumes on a file based pool are
qcow2
+ ((Element)driverNode).setAttribute("type", destinationOnRbd ?
"raw" : "qcow2");
+ }
+
+ // The Ceph authentication of the source pool does not apply to the
destination pool, so it is always replaced
+ Node authNode = getChildNode(diskNode, "auth");
+ if (authNode != null) {
+ diskNode.removeChild(authNode);
+ }
+ if (destinationOnRbd &&
StringUtils.isNotBlank(pool.getAuthUserName())) {
+ diskNode.appendChild(createAuthNode(doc, pool));
+ }
+
+ if (StringUtils.isNotBlank(destSecretUUID)) {
+ Node encryptionNode = getChildNode(diskNode, "encryption");
+ if (encryptionNode instanceof Element) {
+ // librbd encrypts an RBD image natively (LUKS2), a file is
encrypted by qemu (LUKS)
+ Element encryptionElement = (Element)encryptionNode;
+ if (destinationOnRbd) {
+ encryptionElement.setAttribute("format", "luks2");
+ encryptionElement.setAttribute("engine", "librbd");
+ } else {
+ encryptionElement.setAttribute("format", "luks");
+ encryptionElement.removeAttribute("engine");
+ }
+ }
+ if (encryptionNode != null) {
+ Node secretNode = getChildNode(encryptionNode, "secret");
+ if (secretNode != null) {
+ Node uuidAttribute =
secretNode.getAttributes().getNamedItem("uuid");
+ if (uuidAttribute != null) {
+ uuidAttribute.setTextContent(destSecretUUID);
+ }
+ }
+ }
+ }
+ }
+
+ protected Element createRbdSourceNode(Document doc, String diskFilePath,
KVMStoragePool pool) {
+ Element sourceNode = doc.createElement("source");
+ sourceNode.setAttribute("protocol",
LibvirtVMDef.DiskDef.DiskProtocol.RBD.toString().toLowerCase());
+ sourceNode.setAttribute("name", diskFilePath);
+ for (String sourceHost : pool.getSourceHost().split(",")) {
+ Element hostNode = doc.createElement("host");
+ hostNode.setAttribute("name", sourceHost);
+ if (pool.getSourcePort() != 0) {
+ hostNode.setAttribute("port",
String.valueOf(pool.getSourcePort()));
Review Comment:
This new XML builder bypasses the monitor normalization used by `RbdUtils`.
When a pool host contains an explicitly ported monitor such as `mon1:6789,mon2`
(or entries with whitespace), this emits `host name="mon1:6789" port="3300"`,
so libvirt is given the wrong endpoint; the same path also does not handle the
pool's IPv6/individual-port forms consistently. Parse the monitor list with the
same per-monitor-port rules as the other RBD consumers and emit the host name
and port separately.
--
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]