diff --git a/include/OpenNebulaTemplate.h b/include/OpenNebulaTemplate.h index 5d061feac6..0092b23bf2 100644 --- a/include/OpenNebulaTemplate.h +++ b/include/OpenNebulaTemplate.h @@ -112,6 +112,7 @@ private: const std::string& clone_target, const std::string& shared, const std::string& ds_migrate, + const std::string& ds_migrate_snap, const std::string& driver); /** diff --git a/include/VirtualMachine.h b/include/VirtualMachine.h index d693acfe5d..03d63d8d96 100644 --- a/include/VirtualMachine.h +++ b/include/VirtualMachine.h @@ -1661,6 +1661,14 @@ public: // ------------------------------------------------------------------------ // Disk Snapshot related functions // ------------------------------------------------------------------------ + /** + * @return true if the VM has disk with snapshots + */ + bool has_disk_snapshots() + { + return disks.has_snapshots(); + } + /** * Return the snapshot list for the disk * @param disk_id of the disk diff --git a/include/VirtualMachineDisk.h b/include/VirtualMachineDisk.h index 584392c605..622709647d 100644 --- a/include/VirtualMachineDisk.h +++ b/include/VirtualMachineDisk.h @@ -735,6 +735,11 @@ public: get_attribute("DISK_SNAPSHOT_ACTIVE")); } + /** + * @return true if any of the disks has snapshots + */ + bool has_snapshots(); + /** * Set the snapshots for a disk * @param id of disk diff --git a/include/VirtualMachineManagerDriver.h b/include/VirtualMachineManagerDriver.h index 763f01454a..bff54701e2 100644 --- a/include/VirtualMachineManagerDriver.h +++ b/include/VirtualMachineManagerDriver.h @@ -88,14 +88,6 @@ public: return keep_snapshots; } - /** - * @return true if datastore live migration - */ - bool is_ds_live_migration() const - { - return ds_live_migration; - } - /** * @return true if cold nic attach */ @@ -265,11 +257,6 @@ private: */ bool keep_snapshots; - /** - * Set to true if live migration between datastores is allowed. - */ - bool ds_live_migration; - /** * Set to true if cold nic attach/detach calls (pre, post, clean scripts) */ diff --git a/share/doc/xsd/opennebula_configuration.xsd b/share/doc/xsd/opennebula_configuration.xsd index 5301b20ee7..dc5d533450 100644 --- a/share/doc/xsd/opennebula_configuration.xsd +++ b/share/doc/xsd/opennebula_configuration.xsd @@ -375,14 +375,6 @@ - - - - - - - - diff --git a/src/cli/onevm b/src/cli/onevm index ddcb082b04..949c8ce5a7 100755 --- a/src/cli/onevm +++ b/src/cli/onevm @@ -656,8 +656,7 @@ CommandParser::CmdParser.new(ARGV) do migrate_desc = <<-EOT.unindent Migrates the given running VM to another Host. If used with --live - parameter the migration is done without downtime. Datastore migration is - not supported for --live flag. + parameter the migration is done without downtime. States: RUNNING EOT diff --git a/src/datastore/Datastore.cc b/src/datastore/Datastore.cc index 6efaae95a7..e7201240cb 100644 --- a/src/datastore/Datastore.cc +++ b/src/datastore/Datastore.cc @@ -406,33 +406,24 @@ int Datastore::set_tm_mad(const string &tm_mad, string &error_str) bool shared_type; bool ds_migrate; + bool ds_migrate_snap = false; + if (vatt->vector_value("SHARED", shared_type) == -1) { goto error; } - if (shared_type) - { - replace_template_attribute("SHARED", "YES"); - } - else - { - replace_template_attribute("SHARED", "NO"); - } + replace_template_attribute("SHARED", shared_type); if (vatt->vector_value("DS_MIGRATE", ds_migrate) == -1) { ds_migrate = true; } - if (ds_migrate) - { - replace_template_attribute("DS_MIGRATE", "YES"); - } - else - { - replace_template_attribute("DS_MIGRATE", "NO"); - } + vatt->vector_value("DS_MIGRATE_SNAP", ds_migrate_snap); + + replace_template_attribute("DS_MIGRATE", ds_migrate); + replace_template_attribute("DS_MIGRATE_SNAP", ds_migrate_snap); remove_template_attribute("LN_TARGET"); remove_template_attribute("CLONE_TARGET"); diff --git a/src/rm/api/VirtualMachineAPI.cc b/src/rm/api/VirtualMachineAPI.cc index 6e81a1b6b9..f5f617a205 100644 --- a/src/rm/api/VirtualMachineAPI.cc +++ b/src/rm/api/VirtualMachineAPI.cc @@ -399,9 +399,9 @@ Request::ErrorCode VirtualMachineAPI::deploy(int vid, else //Get information from user selected system DS { set ds_cluster_ids; - bool ds_migr; + bool ds_migr, ds_migr_snap; - ec = get_ds_information(ds_id, ds_cluster_ids, tm_mad, att, ds_migr); + ec = get_ds_information(ds_id, ds_cluster_ids, tm_mad, att, ds_migr, ds_migr_snap); if (ec != Request::SUCCESS) { @@ -813,7 +813,7 @@ Request::ErrorCode VirtualMachineAPI::migrate(int vid, set cluster_ids; string error_str; - bool ds_migr; + bool ds_migr, ds_migr_snap; auto ec = get_host_information(hid, hostname, @@ -914,6 +914,13 @@ Request::ErrorCode VirtualMachineAPI::migrate(int vid, return Request::ACTION; } + if (live && c_hid != hid && ds_id != -1 && ds_id != c_ds_id) + { + att.resp_msg = "Cannot live migrate host and datastore at the same time."; + + return Request::ACTION; + } + // Check the host has enough capacity if (check_host(hid, enforce, vm.get(), att.resp_msg) == false) { @@ -986,15 +993,7 @@ Request::ErrorCode VirtualMachineAPI::migrate(int vid, return Request::ACTION; } - if (live && !vmmd->is_ds_live_migration()) - { - att.resp_msg = "A migration to a different system datastore " - "cannot be performed live."; - - return Request::ACTION; - } - - ec = get_ds_information(ds_id, ds_cluster_ids, tm_mad, att, ds_migr); + ec = get_ds_information(ds_id, ds_cluster_ids, tm_mad, att, ds_migr, ds_migr_snap); if (ec != Request::SUCCESS) { @@ -1008,6 +1007,13 @@ Request::ErrorCode VirtualMachineAPI::migrate(int vid, return Request::ACTION; } + if (!ds_migr_snap && vm->has_disk_snapshots()) + { + att.resp_msg = "System datastore migration with disk snapshots not supported by driver"; + + return Request::ACTION; + } + if (c_tm_mad != tm_mad) { att.resp_msg = "Cannot migrate to a system datastore with a different driver"; @@ -1019,7 +1025,7 @@ Request::ErrorCode VirtualMachineAPI::migrate(int vid, { ds_id = c_ds_id; - ec = get_ds_information(ds_id, ds_cluster_ids, tm_mad, att, ds_migr); + ec = get_ds_information(ds_id, ds_cluster_ids, tm_mad, att, ds_migr, ds_migr_snap); if (ec != Request::SUCCESS) { @@ -3983,7 +3989,8 @@ Request::ErrorCode VirtualMachineAPI::get_ds_information(int ds_id, set& ds_cluster_ids, string& tm_mad, RequestAttributes& att, - bool& ds_migr) + bool& ds_migr, + bool& ds_migr_snap) { auto ds = Nebula::instance().get_dspool()->get_ro(ds_id); @@ -4016,6 +4023,8 @@ Request::ErrorCode VirtualMachineAPI::get_ds_information(int ds_id, ds->get_template_attribute("DS_MIGRATE", ds_migr); + ds->get_template_attribute("DS_MIGRATE_SNAP", ds_migr_snap); + return Request::SUCCESS; } @@ -4029,7 +4038,7 @@ Request::ErrorCode VirtualMachineAPI::get_default_ds_information(int cluster_id, { ClusterPool* clpool = Nebula::instance().get_clpool(); - bool ds_migr; + bool ds_migr, ds_migr_snap; set ds_ids; @@ -4065,7 +4074,7 @@ Request::ErrorCode VirtualMachineAPI::get_default_ds_information(int cluster_id, set ds_cluster_ids; - return get_ds_information(ds_id, ds_cluster_ids, tm_mad, att, ds_migr); + return get_ds_information(ds_id, ds_cluster_ids, tm_mad, att, ds_migr, ds_migr_snap); } /* -------------------------------------------------------------------------- */ diff --git a/src/rm/api/VirtualMachineAPI.h b/src/rm/api/VirtualMachineAPI.h index 7fea183a75..23c7279f57 100644 --- a/src/rm/api/VirtualMachineAPI.h +++ b/src/rm/api/VirtualMachineAPI.h @@ -262,7 +262,8 @@ protected: std::set& ds_cluster_ids, std::string& tm_mad, RequestAttributes& att, - bool& ds_migr); + bool& ds_migr, + bool& ds_migr_snap); Request::ErrorCode get_default_ds_information( int cluster_id, diff --git a/src/template/OpenNebulaTemplate.cc b/src/template/OpenNebulaTemplate.cc index 678b25a78d..a6dee57eaa 100644 --- a/src/template/OpenNebulaTemplate.cc +++ b/src/template/OpenNebulaTemplate.cc @@ -70,22 +70,23 @@ void OpenNebulaTemplate::set_multiple_conf_default() # vmfs # ceph # dev - #******************************************************************************* + # name, ln_target, clone_target, shared, ds_migrate, ds_migrate_snap, driver + # ******************************************************************************* */ - set_conf_tm("dummy", "NONE", "SYSTEM", "YES", "YES", ""); + set_conf_tm("dummy", "NONE", "SYSTEM", "YES", "YES", "YES", ""); - set_conf_tm("lvm", "NONE", "SELF", "YES", "NO", ""); - set_conf_tm("fs_lvm", "SYSTEM", "SYSTEM", "YES", "NO", "raw"); - set_conf_tm("fs_lvm_ssh", "SYSTEM", "SYSTEM", "YES", "NO", "raw"); + set_conf_tm("lvm", "NONE", "SELF", "YES", "YES", "NO", ""); + set_conf_tm("fs_lvm", "SYSTEM", "SYSTEM", "YES", "YES", "NO", "raw"); + set_conf_tm("fs_lvm_ssh", "SYSTEM", "SYSTEM", "YES", "YES", "NO", "raw"); - set_conf_tm("shared", "NONE", "SYSTEM", "YES", "YES", ""); - set_conf_tm("qcow2", "NONE", "SYSTEM", "YES", "NO", "qcow2"); + set_conf_tm("shared", "NONE", "SYSTEM", "YES", "YES", "YES", ""); + set_conf_tm("qcow2", "NONE", "SYSTEM", "YES", "YES", "YES", "qcow2"); - set_conf_tm("ssh", "SYSTEM", "SYSTEM", "NO", "YES", ""); - set_conf_tm("local", "SYSTEM", "SYSTEM", "NO", "YES", ""); + set_conf_tm("ssh", "SYSTEM", "SYSTEM", "NO", "YES", "YES", ""); + set_conf_tm("local", "SYSTEM", "SYSTEM", "NO", "YES", "YES", ""); - set_conf_tm("ceph", "NONE", "SELF", "YES", "NO", "raw"); - set_conf_tm("dev", "NONE", "NONE", "YES", "NO", ""); + set_conf_tm("ceph", "NONE", "SELF", "YES", "NO", "NO", "raw"); + set_conf_tm("dev", "NONE", "NONE", "YES", "NO", "NO", ""); register_multiple_conf_default("TM_MAD_CONF"); @@ -273,6 +274,7 @@ void OpenNebulaTemplate::set_conf_tm(const std::string& name, const std::string& clone_target, const std::string& shared, const std::string& ds_migrate, + const std::string& ds_migrate_snap, const std::string& driver) { VectorAttribute * vattribute; @@ -283,6 +285,7 @@ void OpenNebulaTemplate::set_conf_tm(const std::string& name, vvalue.insert(make_pair("CLONE_TARGET", clone_target)); vvalue.insert(make_pair("SHARED", shared)); vvalue.insert(make_pair("DS_MIGRATE", ds_migrate)); + vvalue.insert(make_pair("DS_MIGRATE_SNAP", ds_migrate_snap)); vvalue.insert(make_pair("DRIVER", driver)); vattribute = new VectorAttribute("TM_MAD_CONF", vvalue); diff --git a/src/tm_mad/common/prepostmigrate b/src/tm_mad/common/prepostmigrate deleted file mode 100755 index 3f709081d1..0000000000 --- a/src/tm_mad/common/prepostmigrate +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/bash - -# -------------------------------------------------------------------------- # -# Copyright 2002-2025, OpenNebula Project, OpenNebula Systems # -# # -# Licensed 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. # -#--------------------------------------------------------------------------- # -# PREMIGRATE SOURCE DST remote_system_dir vmid dsid template system_ds_mad -# POSTMIGRATE SOURCE DST remote_system_dir vmid dsid template system_ds_mad -# - SOURCE is the host where the VM is running -# - DST is the host where the VM is to be migrated -# - remote_system_dir is the path for the VM home in the system datastore -# - vmid is the id of the VM -# - dsid is the target datastore -# - template is the template of the VM in XML and base64 encoded -# - system_ds_mad flag if called by other SYSTEM_DS TM_MAD - -SRC_HOST="$1" -DST_HOST="$2" -DST_PATH="$3" -VM_ID="$4" -DS_ID="$5" -TEMPLATE_64=$(cat) - -#-------------------------------------------------------------------------------- - -if [ -z "${ONE_LOCATION}" ]; then - TMCOMMON=/var/lib/one/remotes/tm/tm_common.sh -else - TMCOMMON=$ONE_LOCATION/var/remotes/tm/tm_common.sh -fi - -source $TMCOMMON - -#-------------------------------------------------------------------------------- - -if [ "$SRC_HOST" == "$DST_HOST" ]; then - log "Not moving $SRC_HOST to $DST_HOST, they are the same host" - exit 0 -fi - -#-------------------------------------------------------------------------------- - -migrate_other "$@" diff --git a/src/tm_mad/fs_lvm_ssh/postmigrate b/src/tm_mad/fs_lvm_ssh/postmigrate index 5962555d2f..5cbc846965 100755 --- a/src/tm_mad/fs_lvm_ssh/postmigrate +++ b/src/tm_mad/fs_lvm_ssh/postmigrate @@ -45,33 +45,82 @@ fi POOL_NAME="lv-one-$VMID-pool" VG_NAME="vg-one-$DSID" -CMD=$(cat <[:] # ---------------------------------------------------------------------- @@ -117,7 +115,7 @@ module TransferManager raise NotALocation, 'Invalid location format' end - # # FIXME: convert ^ to pattern matching once we've dropped Ruby<2.7: + # FIXME: convert ^ to pattern matching once we've dropped Ruby<2.7: # case location # in [path] # @host = nil @@ -405,6 +403,10 @@ module TransferManager @vm['/VM/HISTORY_RECORDS/HISTORY[last()]/VM_MAD'] end + def sys_dsid + @vm['/VM/HISTORY_RECORDS/HISTORY[last()]/DS_ID'] + end + def kvm? 'kvm'.casecmp(vm_mad) == 0 end diff --git a/src/tm_mad/local/postmigrate b/src/tm_mad/local/postmigrate index e2e66a5846..16eab340cb 100755 --- a/src/tm_mad/local/postmigrate +++ b/src/tm_mad/local/postmigrate @@ -18,10 +18,9 @@ # limitations under the License. # # ---------------------------------------------------------------------------- # -# postmigrate: It is executed after a livemigration operation. Note that only the postmigrate script -# from the system datastore will be used. Any customization must be done for the postmigrate script -# of the system datastore, although you will probably add operations for other backends than that -# used by the system datastore. +# postmigrate: It is executed after a livemigration operation. Only postmigrate +# from the system datastore will be used. +# # ARGUMENTS: source_host dst_host remote_system_dir vmid dsid # - src_host is the host the VM is in. # - dst_host is the target host to migrate the VM to @@ -34,27 +33,34 @@ arg_srchost = ARGV[0] arg_dsthost = ARGV[1] arg_dstpath = ARGV[2] arg_vmid = ARGV[3] -_arg_dsid = ARGV[4] +arg_dsid = ARGV[4] template64 = STDIN.read postmg = TransferManager::Action.new(:vm_id => arg_vmid, :action_name => 'premigrate') - -dst = TransferManager::Action::Location.new([arg_dsthost, arg_dstpath]) +dst = TransferManager::Action::Location.new([arg_dsthost, arg_dstpath]) #-------------------------------------------------------------------------------- -if arg_srchost == dst.host +# Obtain original system directory (srcpath) for system DS migrations +orig_dsid = postmg.vm['/VM/HISTORY_RECORDS/HISTORY[last()-1]/DS_ID'] +srcpath = "#{arg_dstpath}/../../#{orig_dsid}/#{arg_vmid}" + +#-------------------------------------------------------------------------------- + +if orig_dsid == arg_dsid && arg_srchost == dst.host OpenNebula::DriverLogger.log_info <<~EOF Not moving #{arg_srchost} to #{dst.host}, they are the same host EOF + exit 0 end postmg.migrate_other(template64) -rc = postmg.ssh(:host => arg_srchost, - :cmds => "rm -rf '#{dst.path}'", +rc = postmg.ssh(:host => arg_srchost, + :cmds => "rm -rf '#{srcpath}'", :nostdout => false, :nostderr => false) + exit(rc.code) if rc.code != 0 diff --git a/src/tm_mad/qcow2/postmigrate b/src/tm_mad/qcow2/postmigrate deleted file mode 120000 index ae93fad874..0000000000 --- a/src/tm_mad/qcow2/postmigrate +++ /dev/null @@ -1 +0,0 @@ -../common/prepostmigrate \ No newline at end of file diff --git a/src/tm_mad/qcow2/postmigrate b/src/tm_mad/qcow2/postmigrate new file mode 100755 index 0000000000..a3cde5f746 --- /dev/null +++ b/src/tm_mad/qcow2/postmigrate @@ -0,0 +1,75 @@ +#!/bin/bash + +# -------------------------------------------------------------------------- # +# Copyright 2002-2025, OpenNebula Project, OpenNebula Systems # +# # +# Licensed 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. # +#--------------------------------------------------------------------------- # +# PREMIGRATE SOURCE DST remote_system_dir vmid dsid template system_ds_mad +# POSTMIGRATE SOURCE DST remote_system_dir vmid dsid template system_ds_mad +# - SOURCE is the host where the VM is running +# - DST is the host where the VM is to be migrated +# - remote_system_dir is the path for the VM home in the system datastore +# - vmid is the id of the VM +# - dsid is the target datastore +# - template is the template of the VM in XML and base64 encoded +# - system_ds_mad flag if called by other SYSTEM_DS TM_MAD + +SRC_HOST="$1" +DST_HOST="$2" +DST_PATH="$3" +VM_ID="$4" +DS_ID="$5" +TEMPLATE_64=$(cat) + +#-------------------------------------------------------------------------------- + +if [ -z "${ONE_LOCATION}" ]; then + TMCOMMON=/var/lib/one/remotes/tm/tm_common.sh +else + TMCOMMON=$ONE_LOCATION/var/remotes/tm/tm_common.sh +fi + +source $TMCOMMON + +# Obtain original system directory (srcpath) for system DS migrations +DRIVER_PATH=$(dirname $0) +XPATH="${DRIVER_PATH}/../../datastore/xpath.rb --stdin" +unset i j XPATH_ELEMENTS +while IFS= read -r -d '' element; do + XPATH_ELEMENTS[i++]="$element" +done < <(onevm show -x $VM_ID | $XPATH \ + /VM/HISTORY_RECORDS/HISTORY[last\(\)-1]/DS_ID) + +ORIG_DS_ID="${XPATH_ELEMENTS[j++]}" + +if [ "$ORIG_DS_ID" != "$DS_ID" ]; then + SRC_PATH="${DST_PATH}/../../${ORIG_DS_ID}/${VM_ID}" + + CMD=$(cat <rename_snapshot(snap_id, new_name, error_str); } + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +bool VirtualMachineDisks::has_snapshots() +{ + for (const auto disk : *this) + { + if (disk->has_snapshots()) + { + return true; + } + } + + return false; +} + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ diff --git a/src/vmm/VirtualMachineManagerDriver.cc b/src/vmm/VirtualMachineManagerDriver.cc index 5e76cf0b2c..6009a872ca 100644 --- a/src/vmm/VirtualMachineManagerDriver.cc +++ b/src/vmm/VirtualMachineManagerDriver.cc @@ -31,7 +31,6 @@ VirtualMachineManagerDriver::VirtualMachineManagerDriver( Driver(), driver_conf(true), keep_snapshots(false), - ds_live_migration(false), cold_nic_attach(false), live_resize(false), support_shareable_(false) @@ -92,11 +91,6 @@ VirtualMachineManagerDriver::VirtualMachineManagerDriver( // ------------------------------------------------------------------------- driver_conf.get("KEEP_SNAPSHOTS", keep_snapshots); - // ------------------------------------------------------------------------- - // Parse DS_LIVE_MIGRATION - // ------------------------------------------------------------------------- - driver_conf.get("DS_LIVE_MIGRATION", ds_live_migration); - // ------------------------------------------------------------------------- // Parse COLD_NIC_ATTACH // ------------------------------------------------------------------------- diff --git a/src/vmm_mad/remotes/kvm/migrate b/src/vmm_mad/remotes/kvm/migrate index dbdb5cae87..8036f54cdc 100755 --- a/src/vmm_mad/remotes/kvm/migrate +++ b/src/vmm_mad/remotes/kvm/migrate @@ -15,26 +15,11 @@ # See the License for the specific language governing permissions and # # limitations under the License. # #--------------------------------------------------------------------------- # -ONE_LOCATION = ENV['ONE_LOCATION'] - -if !ONE_LOCATION - RUBY_LIB_LOCATION = '/usr/lib/one/ruby' - GEMS_LOCATION = '/usr/share/one/gems' - VMDIR = '/var/lib/one' - CONFIG_FILE = '/var/lib/one/config' -else - RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby' - GEMS_LOCATION = ONE_LOCATION + '/share/gems' - VMDIR = ONE_LOCATION + '/var' - CONFIG_FILE = ONE_LOCATION + '/var/config' -end # %%RUBYGEMS_SETUP_BEGIN%% require 'load_opennebula_paths' # %%RUBYGEMS_SETUP_END%% -$LOAD_PATH << RUBY_LIB_LOCATION - require 'pathname' require_relative 'opennebula_vm' @@ -51,20 +36,21 @@ load_remote_env # Note input parameters are defined as instance variables # - @deploy_id # - @dst_host -# - @vm_dir +# - @src_vm_dir +# - @dst_vm_dir # - @shared # ------------------------------------------------------------------------------ -# sync paths to the destination VM folder -# -# @param paths [Array/String] Array of paths to sync +# Synchronizes a list of files and directories to the destination host using rsync. # +# @param paths [Array/String] A list of paths to synchronize. +# @param raise_error [Boolean] If true, raises an exception if rsync fails. def rsync_paths(paths, raise_error = true) return if paths.empty? opts = '-az' paths = paths.join(' ') if paths.class == Array - dpath = "#{@dst_host}:#{@vm_dir}/" + dpath = "#{@dst_host}:#{@dst_vm_dir}/" tini = Time.now @@ -75,30 +61,39 @@ def rsync_paths(paths, raise_error = true) raise StandardError, "Cannot rsync files: #{e}" if rc != 0 && raise_error end -# In case of error this function is used to remove migration leftovers. For non -# shared storage configuration it will remove the destination VM folder +# Cleans up migration artifacts on failure. +# For non-shared storage, it removes the destination VM directory. +# For host migrations, it destroys and undefines the transient VM on the destination. # -# @param kvm_vm [KvmDomain] libvirt domain class -# @param error[String] message for the StandardError raised by the function -# -def cleanup_host(kvm_vm, error) - kvm_vm.destroy @dst_host - - kvm_vm.undefine @dst_host +# @param kvm_vm [KvmDomain] The libvirt domain object. +# @param error [String] The error message to raise. +# @param type [Symbol] The type of migration that failed (:host, :ds). +def cleanup_host(kvm_vm, error, type) + if type == :host + kvm_vm.destroy @dst_host + kvm_vm.undefine @dst_host + end if !@shared - Command.ssh(:host => @dst_host, :cmds => "rm -rf #{@vm_dir}") + Command.ssh(:host => @dst_host, :cmds => "rm -rf #{@dst_vm_dir}") end raise StandardError, error end -# Migrate VMs running on local storage, using the copy-storage feature of libvirt +# Analyzes the VM's disks and prepares them for migration. +# +# It creates placeholder disks on the destination for local storage migrations +# and determines which files need to be synchronized before and after the migration. +# # Disks are scanned and classified as: -# - Regular disks are copied during migration (devs array). A place holder needs +# - Regular disks are copied during migration (disks array). A place holder needs # to be created in the destination host # -# - Readonly disks are copied before starting the migration (pre_sync array) +# - Readonly disks are copied before starting the migration (pre_sync array). +# Read-only files can't be `blockcopy`ed by libvirt. These files are rsync'ed +# them and then do a `virsh change-media` to update its path on the +# VM's definition. # # - Snapshots and other ancialliary files are also copied in the pre_sync phase # @@ -109,18 +104,21 @@ end # # To allow this post sync phase the VM is paused after migration (--suspend) # -# @param kvm_vm [KvmDomain] libvirt domain class -def local_migration(kvm_vm) - devs = [] - - pre_sync = ["#{@vm_dir}/*.xml"] +# @param kvm_vm [KvmDomain] The libvirt domain object. +# @param type [Symbol] The type of migration being performed. +# @return [Array] An array containing [disks_to_migrate, pre_sync_paths, post_sync_paths, rodisks]. +def prepare_disks(kvm_vm, type) + disks = [] + rodisks = [] + pre_sync = ["#{@src_vm_dir}/*.xml"] post_sync = [] - kvm_vm.disks.each do |disk| - dev = disk[0] + symlink_cmds = ["set -e; mkdir -p #{@dst_vm_dir}; cd #{@dst_vm_dir};"] + + kvm_vm.disks.each_with_index do |disk, disk_id| path = disk[1] - if !File.symlink? path # qcow2 & raw disks, regular files + if !path.symlink? # qcow2 & raw disks, regular files qimg = QemuImg.new path format = qimg['format'] @@ -129,90 +127,195 @@ def local_migration(kvm_vm) if format == 'raw' && kvm_vm.readonly?(path) pre_sync << path + rodisks << disk else - devs << dev + disks << disk post_sync << path if format == 'qcow2' && snaps - cmds =<<~EOS - mkdir -p #{File.dirname(path)} - qemu-img create -f #{format} #{path} #{size} - EOS + create_params = { + :host => @dst_host, + :cmds => <<~EOS, + mkdir -p #{path.dirname} + qemu-img create -f #{format} #{path} #{size} + EOS + :emsg => 'Cannot create disk' + } - Command.ssh(:host => @dst_host, :cmds => cmds, - :emsg => 'Cannot create disk') + Command.ssh(create_params) if type == :host end - elsif path.match(%r{disk.[0-9]*.snap/}) # qcow2-symlink, replica - devs << dev + elsif path.to_s.match(%r{disk.[0-9]*.snap/}) # qcow2-symlink + disks << disk + elsif path.readlink.to_s.match(%r{^/dev/vg-one}) # LVM disk + disks << disk # else - # network-disk, symlinks are assumed to be network disks + # network-disk, other symlinks are assumed to be network disks end - # Add disk snapshots dir to the list of paths to sync - if File.directory? "#{path}.snap" + # Add disk snapshots dir to the list of paths to sync. + if (m = path.to_s.match(%r{(disk.[0-9]*.snap)/})) + if type == :host + pre_sync << Pathname.new("#{@src_vm_dir}/#{m[1]}").cleanpath + else # :ds + pre_sync << Pathname.new(path.dirname).cleanpath + end + elsif File.directory?("#{path}.snap") # raw disks with snapshots pre_sync << Pathname.new("#{path}.snap").cleanpath - elsif (m = path.match(%r{(disk.[0-9]*.snap)/})) # replica - pre_sync << Pathname.new("#{@vm_dir}/#{m[1]}").cleanpath end - # recreate disk symlinks - if File.symlink? path - target = File.readlink(path) + # Recreate disk symlinks + if path.symlink? + target = path.readlink lname = path - elsif (m = path.match(%r{(disk.([0-9]*).snap/.*)})) + + if target.to_s.match(%r{^/dev/vg-one}) + # LVM disks + target = "/dev/vg-one-#{@dst_vm_dir.dirname.basename}/#{target.basename}" + lname = @dst_vm_dir + lname.relative_path_from(@src_vm_dir) + + symlink_cmds << <<~EOS.chomp + rm #{lname} + EOS + end + elsif (m = path.to_s.match(%r{(/([0-9a-z]*).snap/.*)})) + # Persistent disks @ shared DS pointing to image datastore + target = path + lname = "disk.#{disk_id}" + elsif (m = path.to_s.match(%r{(disk.([0-9]*).snap/.*)})) + # Disk snapshots target = m[1] lname = "disk.#{m[2]}" else next end - cmds =<<~EOS - cd #{@vm_dir} + symlink_cmds << <<~EOS.chomp [ -L "#{lname}" ] || ln -s "#{target}" "#{lname}" EOS - - Command.ssh(:host => @dst_host, :cmds => cmds, - :emsg => 'Cannot symlink disk') end - rsync_paths(pre_sync) + Command.ssh(:host => @dst_host, :cmds => symlink_cmds.join("\n"), + :emsg => 'Cannot symlink disks') - rc, _out, err = kvm_vm.live_migrate_disks(@dst_host, devs) + [disks, pre_sync, post_sync, rodisks] +end - cleanup_host(err) if rc != 0 +# Creates placeholder disk images on the destination datastore. +# +# For storage-only migrations, this function creates empty disk images or +# qcow2 images linked to their backing files on the destination datastore. +# +# This allows to control the backing file paths during the migration (--shallow + --reuse-external). +# If not, blockcopy will create the images with backing files pointing to absolute paths. +# +# @param disks [Array] An array of disk information, each element being [dev, path]. +def disk_placeholders(disks) + disks.each do |(_dev, path)| + next if File.symlink? path - rsync_paths(post_sync) + qimg = QemuImg.new(path.to_s) - kvm_vm.resume(@dst_host) + format = qimg['format'] + size = qimg['virtual-size'] + + dest_path = (@dst_vm_dir + path.relative_path_from(@src_vm_dir)).cleanpath + + cmds = [ + 'set -e', + "mkdir -p #{dest_path.dirname}", + "rm -f #{dest_path}" + ] + + backing = qimg['backing-filename'] + + if format == 'qcow2' && backing && !backing.empty? + backing_fmt = qimg['backing-filename-format'] + backing_target = + if backing.start_with?(@src_vm_dir.to_s) + backing.sub(@src_vm_dir.to_s, @dst_vm_dir.to_s) + else + backing + end + + create_cmd = "qemu-img create -f #{format}" + create_cmd << " -F #{backing_fmt}" if backing_fmt && !backing_fmt.empty? + create_cmd << " -b #{backing_target} #{dest_path}" + else + create_cmd = "qemu-img create -f #{format} #{dest_path} #{size}" + end + + cmds << create_cmd + + Command.ssh(:host => @src_host, + :cmds => cmds.join("\n"), + :emsg => 'Cannot create destination disk') + end end # ------------------------------------------------------------------------------ +# Main execution logic # ------------------------------------------------------------------------------ begin @deploy_id = ARGV[0] @dst_host = ARGV[1] + @src_host = ARGV[2] + vmid = ARGV[3] - action_xml = XMLElement.new_s(STDIN.read) + action_xml = XMLElement.new_s(STDIN.read) - @vm_dir = Pathname.new(action_xml['/VMM_DRIVER_ACTION_DATA/DISK_TARGET_PATH']).cleanpath - @shared = action_xml['/VMM_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/SHARED'].casecmp('YES') == 0 + @src_vm_dir = Pathname.new(action_xml['/VMM_DRIVER_ACTION_DATA/DATASTORE/BASE_PATH']) + .cleanpath + vmid + @dst_vm_dir = Pathname.new(action_xml['/VMM_DRIVER_ACTION_DATA/DISK_TARGET_PATH']).cleanpath + @shared = action_xml['/VMM_DRIVER_ACTION_DATA/DATASTORE/TEMPLATE/SHARED'] + .casecmp('YES') == 0 - kvm_vm = KvmDomain.new(@deploy_id) + src_path = @src_vm_dir.parent.basename.to_s + dst_path = @dst_vm_dir.parent.basename.to_s + + kvm_vm = KvmDomain.new(@deploy_id) # Migration can't be done with domain snapshots, drop them first kvm_vm.snapshots_delete - # Migrate VMs using shared/local storage - if @shared - rc, _out, err = kvm_vm.live_migrate(@dst_host) + if @src_host != @dst_host + if @shared + rc, _out, err = kvm_vm.live_migrate(@dst_host) - cleanup_host(kvm_vm, err) if rc != 0 + cleanup_host(kvm_vm, err, :host) if rc != 0 + else + disks, pre_sync, post_sync, _rodisks = prepare_disks(kvm_vm, :host) + + rsync_paths(pre_sync) + + rc, _out, err = kvm_vm.live_migrate_disks(@dst_host, disks.map {|(dev, _path)| dev }) + + cleanup_host(kvm_vm, err, :host) if rc != 0 + + rsync_paths(post_sync) + + kvm_vm.resume(@dst_host) + end + elsif src_path != dst_path + disks, pre_sync, post_sync, rodisks = prepare_disks(kvm_vm, :ds) + + rsync_paths(pre_sync) + + disk_placeholders(disks) + + rc, _out, err = kvm_vm.live_blockcopy_disks(disks, rodisks, @src_vm_dir, @dst_vm_dir) + + cleanup_host(kvm_vm, err, :ds) if rc != 0 + + rsync_paths(post_sync) else - local_migration(kvm_vm) + STDERR.puts 'Unsupported migration type' + exit(1) end # Redefine system snapshots on the destination libvirtd - kvm_vm.snapshots_redefine(@dst_host, @vm_dir) + kvm_vm.snapshots_redefine(@dst_host, @dst_vm_dir) + + exit(0) if src_path != dst_path # Sync guest time if ENV['SYNC_TIME'].to_s.upcase == 'YES' @@ -241,7 +344,7 @@ begin end # rubocop:enable Layout/LineLength rescue StandardError => e - STDERR.puts "Error mirgating VM #{@deploy_id} to host #{@dst_host}: #{e.message}" + STDERR.puts "Error migrating VM #{@deploy_id}: #{e.message}" STDERR.puts e.backtrace.to_s exit(1) end diff --git a/src/vmm_mad/remotes/lib/command.rb b/src/vmm_mad/remotes/lib/command.rb index 09306b6c99..1cc0366d27 100644 --- a/src/vmm_mad/remotes/lib/command.rb +++ b/src/vmm_mad/remotes/lib/command.rb @@ -107,6 +107,8 @@ module Command :emsg => '' }.merge!(options) + emsg = opt[:emsg] + script = <<~EOS export LANG=C export LC_ALL=C diff --git a/src/vmm_mad/remotes/lib/kvm/opennebula_vm.rb b/src/vmm_mad/remotes/lib/kvm/opennebula_vm.rb index 1ed91ce350..0fb5e04514 100644 --- a/src/vmm_mad/remotes/lib/kvm/opennebula_vm.rb +++ b/src/vmm_mad/remotes/lib/kvm/opennebula_vm.rb @@ -18,6 +18,7 @@ require_relative '../lib/command' require_relative '../lib/opennebula_vm' require 'json' +require 'tempfile' # rubocop:disable Style/ClassAndModuleChildren # rubocop:disable Style/ClassVars @@ -168,6 +169,8 @@ module VirtualMachineManagerKVM # class KvmDomain + attr_reader :domain + def initialize(domain) @domain = domain @xml = nil @@ -272,8 +275,13 @@ module VirtualMachineManagerKVM raise StandardError, "Error getting domain snapshots #{e}" end - @disks = o.lines[2..o.lines.length].map {|l| l.split } - @disks.reject! {|s| s.empty? } + @disks = + o.lines[2..o.lines.length] + .reject {|l| l.chomp.empty? } + .map do |l| + (dev, path) = l.split + [dev, Pathname.new(path)] + end end @disks @@ -311,6 +319,65 @@ module VirtualMachineManagerKVM virsh_retry(cmd, 'active block job', virsh_tries) end + # Live migrate the given disks between the given VM directories. + # This only works within the same host. + # + # @param disks[Array] disks (as (dev,path) tuples) to be moved + # Example: [['vda', '/var/lib/one/datastores/0/12/disk.0']] + # @param rodisks[Array] read-only disks (as (dev,path) tuples) to be redefined + # Example: [['hda', '/var/lib/one/datastores/0/12/disk.1']] + # @param src_dir[Pathname] source VM dir + # Example: /var/lib/one/datastores/0/12 + # @param dst_dir[Pathname] destination VM dir + # Example: /var/lib/one/datastores/100/12 + def live_blockcopy_disks(disks, rodisks, src_dir, dst_dir) + disks.each do |(dev, path)| + new_path = dst_dir + path.relative_path_from(src_dir) + + `mkdir -p #{new_path.dirname}; touch #{new_path}` + + qimg = QemuImg.new(path.to_s) + has_backing = qimg['backing-filename'] && !qimg['backing-filename'].empty? + + # --pivot: Pivot the VM to use the new disk after copy. + # --reuse-external: Reuse existing backing files on the destination. + # --shallow: Only copy the top layer of a disk with backing files. + # --blockdev: Destination file is a block device (e.g., LV) + cmd = "blockcopy #{@domain} #{dev} #{new_path} " \ + '--wait --verbose --pivot --reuse-external' + cmd << ' --shallow' if has_backing + cmd << ' --blockdev' if path.symlink? && path.readlink.blockdev? + + rc, out, err = virsh_retry(cmd, 'active block job', virsh_tries) + return [rc, out, err] if rc != 0 + end + + rodisks.each do |(dev, path)| + new_path = dst_dir + path.relative_path_from(src_dir) + cmd = "change-media #{@domain} #{dev} #{new_path} --update" + + rc, out, err = virsh_retry(cmd, 'active block job', virsh_tries) + return [rc, out, err] if rc != 0 + end + + # Update one:system_datastore metadata tag in running VM + tmpf = Tempfile.new([@domain, '.xml']) + + virsh_retry("dumpxml #{@domain} > '#{tmpf.path}'", 'active block job', virsh_tries) + + `sed -i '/one:system_datastore/s:CDATA\\[[^]]*\\]:CDATA[#{dst_dir}]:' '#{tmpf.path}'` + + virsh_retry("define '#{tmpf.path}'", 'active block job', virsh_tries) + + tmpf.unlink + + # `define` makes the VM persistent. We immediately `undefine` it to + # keep it transient. + undefine + + [0, nil, nil] + end + # Basic domain operations (does not require additional parameters) VIRSH_COMMANDS = [ 'resume',