]> git.proxmox.com Git - pve-container.git/blobdiff - src/PVE/API2/LXC.pm
fix #1532: add target-storage support to migration
[pve-container.git] / src / PVE / API2 / LXC.pm
index 4dd692dcbd89e8794ff2123382b41149b47a05f3..61eaaf7c24df37d6650989549924fed69a89efee 100644 (file)
@@ -36,6 +36,18 @@ BEGIN {
     }
 }
 
+my $check_storage_access_migrate = sub {
+    my ($rpcenv, $authuser, $storecfg, $storage, $node) = @_;
+
+    PVE::Storage::storage_check_enabled($storecfg, $storage, $node);
+
+    $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace']);
+
+    my $scfg = PVE::Storage::storage_config($storecfg, $storage);
+    die "storage '$storage' does not support CT rootdirs\n"
+       if !$scfg->{content}->{rootdir};
+};
+
 __PACKAGE__->register_method ({
     subclass => "PVE::API2::LXC::Config",
     path => '{vmid}/config',
@@ -247,6 +259,13 @@ __PACKAGE__->register_method({
            # we don't want to restore a container-provided FW conf in this case
            # since the user is lacking permission to configure the container's FW
            $skip_fw_config_restore = 1;
+
+           # error out if a user tries to change from unprivileged to privileged
+           # explicit change is checked here, implicit is checked down below or happening in root-only paths
+           my $conf = PVE::LXC::Config->load_config($vmid);
+           if ($conf->{unprivileged} && defined($unprivileged) && !$unprivileged) {
+               raise_perm_exc("cannot change from unprivileged to privileged without VM.Allocate");
+           }
        } else {
            raise_perm_exc();
        }
@@ -254,7 +273,7 @@ __PACKAGE__->register_method({
        my $ostemplate = extract_param($param, 'ostemplate');
        my $storage = extract_param($param, 'storage') // 'local';
 
-       PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, $pool, $param, []);
+       PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, $pool, undef, $param, [], $unprivileged);
 
        my $storage_cfg = cfs_read_file("storage.cfg");
 
@@ -275,7 +294,7 @@ __PACKAGE__->register_method({
        my $check_and_activate_storage = sub {
            my ($sid) = @_;
 
-           my $scfg = PVE::Storage::storage_check_node($storage_cfg, $sid, $node);
+           my $scfg = PVE::Storage::storage_check_enabled($storage_cfg, $sid, $node);
 
            raise_param_exc({ storage => "storage '$sid' does not support container directories"})
                if !$scfg->{content}->{rootdir};
@@ -343,11 +362,12 @@ __PACKAGE__->register_method({
        eval { PVE::LXC::Config->create_and_lock_config($vmid, $force) };
        die "$emsg $@" if $@;
 
+       my $remove_lock = 1;
+
        my $code = sub {
            my $old_conf = PVE::LXC::Config->load_config($vmid);
            my $was_template;
 
-           my $vollist = [];
            eval {
                my $orig_mp_param; # only used if $restore
                if ($restore) {
@@ -367,6 +387,11 @@ __PACKAGE__->register_method({
 
                        $conf->{unprivileged} = $orig_conf->{unprivileged}
                            if !defined($unprivileged) && defined($orig_conf->{unprivileged});
+
+                       # implicit privileged change is checked here
+                       if ($old_conf->{unprivileged} && !$conf->{unprivileged}) {
+                           $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Allocate']);
+                       }
                    }
                }
                if ($storage_only_mode) {
@@ -409,7 +434,14 @@ __PACKAGE__->register_method({
                        $mp_param->{rootfs} = "$storage:4"; # defaults to 4GB
                    }
                }
+           };
+           die "$emsg $@" if $@;
 
+           # up until here we did not modify the container, besides the lock
+           $remove_lock = 0;
+
+           my $vollist = [];
+           eval {
                $vollist = PVE::LXC::create_disks($storage_cfg, $vmid, $mp_param, $conf);
 
                # we always have the 'create' lock so check for more than 1 entry
@@ -468,7 +500,18 @@ __PACKAGE__->register_method({
        };
 
        my $workername = $restore ? 'vzrestore' : 'vzcreate';
-       my $realcmd = sub { PVE::LXC::Config->lock_config($vmid, $code); };
+       my $realcmd = sub {
+           eval {
+               PVE::LXC::Config->lock_config($vmid, $code);
+           };
+           if (my $err = $@) {
+               # if we aborted before changing the container, we must remove the create lock
+               if ($remove_lock) {
+                   PVE::LXC::Config->remove_lock($vmid, 'create');
+               }
+               die $err;
+           }
+       };
 
        return $rpcenv->fork_worker($workername, $vmid, $authuser, $realcmd);
     }});
@@ -1060,6 +1103,7 @@ __PACKAGE__->register_method({
                description => "Target node.",
                completion => \&PVE::Cluster::complete_migration_target,
            }),
+           'target-storage' => get_standard_option('pve-targetstorage'),
            online => {
                type => 'boolean',
                description => "Use online/live migration.",
@@ -1118,6 +1162,25 @@ __PACKAGE__->register_method({
                if !$param->{online} && !$param->{restart};
        }
 
+       if (my $targetstorage = delete $param->{'target-storage'}) {
+           my $storecfg = PVE::Storage::config();
+           my $storagemap = eval { PVE::JSONSchema::parse_idmap($targetstorage, 'pve-storage-id') };
+           raise_param_exc({ targetstorage => "failed to parse storage map: $@" })
+               if $@;
+
+           $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk'])
+               if !defined($storagemap->{identity});
+
+           foreach my $target_sid (values %{$storagemap->{entries}}) {
+               $check_storage_access_migrate->($rpcenv, $authuser, $storecfg, $target_sid, $target);
+           }
+
+           $check_storage_access_migrate->($rpcenv, $authuser, $storecfg, $storagemap->{default}, $target)
+               if $storagemap->{default};
+
+           $param->{storagemap} = $storagemap;
+       }
+
        if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
 
            my $hacmd = sub {
@@ -1378,7 +1441,7 @@ __PACKAGE__->register_method({
            PVE::Storage::storage_check_enabled($storecfg, $storage);
            if ($target) {
                # check if storage is available on target node
-               PVE::Storage::storage_check_node($storecfg, $storage, $target);
+               PVE::Storage::storage_check_enabled($storecfg, $storage, $target);
                # clone only works if target storage is shared
                my $scfg = PVE::Storage::storage_config($storecfg, $storage);
                die "can't clone to non-shared storage '$storage'\n" if !$scfg->{shared};
@@ -1387,7 +1450,6 @@ __PACKAGE__->register_method({
 
        PVE::Cluster::check_cfs_quorum();
 
-       my $conffile;
        my $newconf = {};
        my $mountpoints = {};
        my $fullclone = {};
@@ -1395,120 +1457,125 @@ __PACKAGE__->register_method({
        my $running;
 
        PVE::LXC::Config->create_and_lock_config($newid, 0);
-       $conffile = PVE::LXC::Config->config_file($newid);
+       PVE::Firewall::clone_vmfw_conf($vmid, $newid);
 
-       PVE::LXC::Config->lock_config($vmid, sub {
-           my $src_conf = PVE::LXC::Config->set_lock($vmid, 'disk');
+       my $lock_and_reload = sub {
+           my ($vmid, $code) = @_;
+           return PVE::LXC::Config->lock_config($vmid, sub {
+               my $conf = PVE::LXC::Config->load_config($vmid);
+               die "Lost 'create' config lock, aborting.\n"
+                   if !PVE::LXC::Config->has_lock($conf, 'create');
 
-           $running = PVE::LXC::check_running($vmid) || 0;
+               return $code->($conf);
+           });
+       };
 
-           my $full = extract_param($param, 'full');
-           if (!defined($full)) {
-               $full = !PVE::LXC::Config->is_template($src_conf);
-           }
-           die "parameter 'storage' not allowed for linked clones\n" if defined($storage) && !$full;
+       my $src_conf = PVE::LXC::Config->set_lock($vmid, 'disk');
 
-           eval {
-               die "snapshot '$snapname' does not exist\n"
-                   if $snapname && !defined($src_conf->{snapshots}->{$snapname});
+       $running = PVE::LXC::check_running($vmid) || 0;
 
-               my $src_conf = $snapname ? $src_conf->{snapshots}->{$snapname} : $src_conf;
+       my $full = extract_param($param, 'full');
+       if (!defined($full)) {
+           $full = !PVE::LXC::Config->is_template($src_conf);
+       }
 
-               my $sharedvm = 1;
-               for my $opt (sort keys %$src_conf) {
-                   next if $opt =~ m/^unused\d+$/;
+       eval {
+           die "parameter 'storage' not allowed for linked clones\n"
+               if defined($storage) && !$full;
 
-                   my $value = $src_conf->{$opt};
+           die "snapshot '$snapname' does not exist\n"
+               if $snapname && !defined($src_conf->{snapshots}->{$snapname});
 
-                   if (($opt eq 'rootfs') || ($opt =~ m/^mp\d+$/)) {
-                       my $mp = PVE::LXC::Config->parse_volume($opt, $value);
+           my $src_conf = $snapname ? $src_conf->{snapshots}->{$snapname} : $src_conf;
 
-                       if ($mp->{type} eq 'volume') {
-                           my $volid = $mp->{volume};
+           my $sharedvm = 1;
+           for my $opt (sort keys %$src_conf) {
+               next if $opt =~ m/^unused\d+$/;
 
-                           my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
-                           $sid = $storage if defined($storage);
-                           my $scfg = PVE::Storage::storage_config($storecfg, $sid);
-                           if (!$scfg->{shared}) {
-                               $sharedvm = 0;
-                               warn "found non-shared volume: $volid\n" if $target;
-                           }
+               my $value = $src_conf->{$opt};
 
-                           $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
+               if (($opt eq 'rootfs') || ($opt =~ m/^mp\d+$/)) {
+                   my $mp = PVE::LXC::Config->parse_volume($opt, $value);
 
-                           if ($full) {
-                               die "Cannot do full clones on a running container without snapshots\n"
-                                   if $running && !defined($snapname);
-                               $fullclone->{$opt} = 1;
-                           } else {
-                               # not full means clone instead of copy
-                               die "Linked clone feature for '$volid' is not available\n"
-                                   if !PVE::Storage::volume_has_feature($storecfg, 'clone', $volid, $snapname, $running, {'valid_target_formats' => ['raw', 'subvol']});
-                           }
+                   if ($mp->{type} eq 'volume') {
+                       my $volid = $mp->{volume};
+
+                       my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
+                       $sid = $storage if defined($storage);
+                       my $scfg = PVE::Storage::storage_config($storecfg, $sid);
+                       if (!$scfg->{shared}) {
+                           $sharedvm = 0;
+                           warn "found non-shared volume: $volid\n" if $target;
+                       }
 
-                           $mountpoints->{$opt} = $mp;
-                           push @$vollist, $volid;
+                       $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
 
+                       if ($full) {
+                           die "Cannot do full clones on a running container without snapshots\n"
+                               if $running && !defined($snapname);
+                           $fullclone->{$opt} = 1;
                        } else {
-                           # TODO: allow bind mounts?
-                           die "unable to clone mountpoint '$opt' (type $mp->{type})\n";
+                           # not full means clone instead of copy
+                           die "Linked clone feature for '$volid' is not available\n"
+                               if !PVE::Storage::volume_has_feature($storecfg, 'clone', $volid, $snapname, $running, {'valid_target_formats' => ['raw', 'subvol']});
                        }
-                   } elsif ($opt =~ m/^net(\d+)$/) {
-                       # always change MAC! address
-                       my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
-                       my $net = PVE::LXC::Config->parse_lxc_network($value);
-                       $net->{hwaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
-                       $newconf->{$opt} = PVE::LXC::Config->print_lxc_network($net);
+
+                       $mountpoints->{$opt} = $mp;
+                       push @$vollist, $volid;
+
                    } else {
-                       # copy everything else
-                       $newconf->{$opt} = $value;
+                       # TODO: allow bind mounts?
+                       die "unable to clone mountpoint '$opt' (type $mp->{type})\n";
                    }
+               } elsif ($opt =~ m/^net(\d+)$/) {
+                   # always change MAC! address
+                   my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
+                   my $net = PVE::LXC::Config->parse_lxc_network($value);
+                   $net->{hwaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
+                   $newconf->{$opt} = PVE::LXC::Config->print_lxc_network($net);
+               } else {
+                   # copy everything else
+                   $newconf->{$opt} = $value;
                }
-               die "can't clone CT to node '$target' (CT uses local storage)\n"
-                   if $target && !$sharedvm;
+           }
+           die "can't clone CT to node '$target' (CT uses local storage)\n"
+               if $target && !$sharedvm;
 
-               # Replace the 'disk' lock with a 'create' lock.
-               $newconf->{lock} = 'create';
+           # Replace the 'disk' lock with a 'create' lock.
+           $newconf->{lock} = 'create';
 
-               delete $newconf->{snapshots};
-               delete $newconf->{pending};
-               delete $newconf->{template};
-               if ($param->{hostname}) {
-                   $newconf->{hostname} = $param->{hostname};
-               }
+           # delete all snapshot related config options
+           delete $newconf->@{qw(snapshots parent snaptime snapstate)};
 
-               if ($param->{description}) {
-                   $newconf->{description} = $param->{description};
-               }
+           delete $newconf->{pending};
+           delete $newconf->{template};
+
+           $newconf->{hostname} = $param->{hostname} if $param->{hostname};
+           $newconf->{description} = $param->{description} if $param->{description};
+
+           $lock_and_reload->($newid, sub {
+               PVE::LXC::Config->write_config($newid, $newconf);
+           });
+       };
+       if (my $err = $@) {
+           eval { PVE::LXC::Config->remove_lock($vmid, 'disk') };
+           warn "Failed to remove source CT config lock - $@\n" if $@;
 
-               PVE::LXC::Config->lock_config($newid, sub {
-                   # read empty config, lock needs to be still here
-                   my $conf = PVE::LXC::Config->load_config($newid);
-                   die "Lost 'create' config lock, aborting.\n"
-                       if !PVE::LXC::Config->has_lock($conf, 'create');
-                   # write the actual new config now to disk
-                   PVE::LXC::Config->write_config($newid, $newconf);
+           eval {
+               $lock_and_reload->($newid, sub {
+                   PVE::LXC::Config->destroy_config($newid);
+                   PVE::Firewall::remove_vmfw_conf($newid);
                });
            };
-           if (my $err = $@) {
-               eval { PVE::LXC::Config->remove_lock($vmid, 'disk') };
-               PVE::LXC::Config->lock_config($newid, sub {
-                   my $conf = PVE::LXC::Config->load_config($newid);
-                   die "Lost 'create' config lock, aborting.\n"
-                       if !PVE::LXC::Config->has_lock($conf, 'create');
-                   unlink($conffile);
-               });
-               warn $@ if $@;
-               die $err;
-           }
-       });
+           warn "Failed to remove target CT config - $@\n" if $@;
+
+           die $err;
+       }
 
        my $update_conf = sub {
            my ($key, $value) = @_;
-           return PVE::LXC::Config->lock_config($newid, sub {
-               my $conf = PVE::LXC::Config->load_config($newid);
-               die "Lost 'create' config lock, aborting.\n"
-                   if !PVE::LXC::Config->has_lock($conf, 'create');
+           return $lock_and_reload->($newid, sub {
+               my $conf = shift;
                $conf->{$key} = $value;
                PVE::LXC::Config->write_config($newid, $conf);
            });
@@ -1555,25 +1622,20 @@ __PACKAGE__->register_method({
 
                PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
 
-               $newconf = PVE::LXC::Config->load_config($newid);
-               die "Lost 'create' config lock, aborting.\n"
-                   if !PVE::LXC::Config->has_lock($newconf, 'create');
-               my $rootdir = PVE::LXC::mount_all($newid, $storecfg, $newconf, 1);
-               my $lxc_setup = PVE::LXC::Setup->new($newconf, $rootdir);
-               $lxc_setup->post_clone_hook($newconf);
-               PVE::LXC::umount_all($newid, $storecfg, $newconf, 1);
-
-               PVE::LXC::Config->remove_lock($newid, 'create');
-
-               PVE::LXC::Config->lock_config($newid, sub {
-                   if ($target) {
-                       # always deactivate volumes - avoid lvm LVs to be active on several nodes
-                       PVE::Storage::deactivate_volumes($storecfg, $vollist, $snapname) if !$running;
-                       PVE::Storage::deactivate_volumes($storecfg, $newvollist);
-
-                       my $newconffile = PVE::LXC::Config->config_file($newid, $target);
-                       die "Failed to move config to node '$target' - rename failed: $!\n"
-                           if !rename($conffile, $newconffile);
+               $lock_and_reload->($newid, sub {
+                   my $conf = shift;
+                   my $rootdir = PVE::LXC::mount_all($newid, $storecfg, $conf, 1);
+                   eval {
+                       my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
+                       $lxc_setup->post_clone_hook($conf);
+                   };
+                   my $err = $@;
+                   eval { PVE::LXC::umount_all($newid, $storecfg, $conf, 1); };
+                   if ($err) {
+                       warn "$@\n" if $@;
+                       die $err;
+                   } else {
+                       die $@ if $@;
                    }
                });
            };
@@ -1584,18 +1646,36 @@ __PACKAGE__->register_method({
 
            if ($err) {
                # Now cleanup the config & disks:
-               unlink $conffile;
-
                sleep 1; # some storages like rbd need to wait before release volume - really?
 
                foreach my $volid (@$newvollist) {
                    eval { PVE::Storage::vdisk_free($storecfg, $volid); };
                    warn $@ if $@;
                }
+
+               eval {
+                   $lock_and_reload->($newid, sub {
+                       PVE::LXC::Config->destroy_config($newid);
+                       PVE::Firewall::remove_vmfw_conf($newid);
+                   });
+               };
+               warn "Failed to remove target CT config - $@\n" if $@;
+
                die "clone failed: $err";
            }
 
-           PVE::Firewall::clone_vmfw_conf($vmid, $newid);
+           $lock_and_reload->($newid, sub {
+               PVE::LXC::Config->remove_lock($newid, 'create');
+
+               if ($target) {
+                   # always deactivate volumes - avoid lvm LVs to be active on several nodes
+                   PVE::Storage::deactivate_volumes($storecfg, $vollist, $snapname) if !$running;
+                   PVE::Storage::deactivate_volumes($storecfg, $newvollist);
+
+                   PVE::LXC::Config->move_config_to_node($newid, $target);
+               }
+           });
+
            return;
        };
 
@@ -1660,8 +1740,6 @@ __PACKAGE__->register_method({
 
        die "no options specified\n" if !scalar(keys %$param);
 
-       PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, $param, []);
-
        my $storage_cfg = cfs_read_file("storage.cfg");
 
        my $code = sub {
@@ -1669,6 +1747,8 @@ __PACKAGE__->register_method({
            my $conf = PVE::LXC::Config->load_config($vmid);
            PVE::LXC::Config->check_lock($conf);
 
+           PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, $conf, $param, [], $conf->{unprivileged});
+
            PVE::Tools::assert_if_modified($digest, $conf->{digest});
 
            my $running = PVE::LXC::check_running($vmid);
@@ -1765,39 +1845,45 @@ __PACKAGE__->register_method({
     method => 'POST',
     protected => 1,
     proxyto => 'node',
-    description => "Move a rootfs-/mp-volume to a different storage",
+    description => "Move a rootfs-/mp-volume to a different storage or to a different container.",
     permissions => {
        description => "You need 'VM.Config.Disk' permissions on /vms/{vmid}, " .
-           "and 'Datastore.AllocateSpace' permissions on the storage.",
-       check =>
-       [ 'and',
-         ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
-         ['perm', '/storage/{storage}', [ 'Datastore.AllocateSpace' ]],
-       ],
+           "and 'Datastore.AllocateSpace' permissions on the storage. To move ".
+           "a volume to another container, you need the permissions on the ".
+           "target container as well.",
+       check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
     },
     parameters => {
        additionalProperties => 0,
        properties => {
            node => get_standard_option('pve-node'),
            vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
+           'target-vmid' => get_standard_option('pve-vmid', {
+               completion => \&PVE::LXC::complete_ctid,
+               optional => 1,
+           }),
            volume => {
                type => 'string',
-               enum => [ PVE::LXC::Config->valid_volume_keys() ],
+               #TODO: check how to handle unused mount points as the mp parameter is not configured
+               enum => [ PVE::LXC::Config->valid_volume_keys_with_unused() ],
                description => "Volume which will be moved.",
            },
            storage => get_standard_option('pve-storage-id', {
                description => "Target Storage.",
                completion => \&PVE::Storage::complete_storage_enabled,
+               optional => 1,
            }),
            delete => {
                type => 'boolean',
-               description => "Delete the original volume after successful copy. By default the original is kept as an unused volume entry.",
+               description => "Delete the original volume after successful copy. By default the " .
+                   "original is kept as an unused volume entry.",
                optional => 1,
                default => 0,
            },
            digest => {
                type => 'string',
-               description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
+               description => 'Prevent changes if current configuration file has different SHA1 " .
+                   "digest. This can be used to prevent concurrent modifications.',
                maxLength => 40,
                optional => 1,
            },
@@ -1808,6 +1894,21 @@ __PACKAGE__->register_method({
                minimum => '0',
                default => 'clone limit from datacenter or storage config',
            },
+           'target-volume' => {
+               type => 'string',
+               description => "The config key the volume will be moved to. Default is the " .
+                   "source volume key.",
+               enum => [PVE::LXC::Config->valid_volume_keys_with_unused()],
+               optional => 1,
+           },
+           'target-digest' => {
+               type => 'string',
+               description => 'Prevent changes if current configuration file of the target " .
+                   "container has a different SHA1 digest. This can be used to prevent " .
+                   "concurrent modifications.',
+               maxLength => 40,
+               optional => 1,
+           },
        },
     },
     returns => {
@@ -1822,34 +1923,59 @@ __PACKAGE__->register_method({
 
        my $vmid = extract_param($param, 'vmid');
 
+       my $target_vmid = extract_param($param, 'target-vmid');
+
        my $storage = extract_param($param, 'storage');
 
        my $mpkey = extract_param($param, 'volume');
 
+       my $target_mpkey = extract_param($param, 'target-volume') // $mpkey;
+
+       my $digest = extract_param($param, 'digest');
+
+       my $target_digest = extract_param($param, 'target-digest');
+
        my $lockname = 'disk';
 
        my ($mpdata, $old_volid);
 
-       PVE::LXC::Config->lock_config($vmid, sub {
-           my $conf = PVE::LXC::Config->load_config($vmid);
-           PVE::LXC::Config->check_lock($conf);
+       die "either set storage or target-vmid, but not both\n"
+           if $storage && $target_vmid;
 
-           die "cannot move volumes of a running container\n" if PVE::LXC::check_running($vmid);
+       my $storecfg = PVE::Storage::config();
 
-           $mpdata = PVE::LXC::Config->parse_volume($mpkey, $conf->{$mpkey});
-           $old_volid = $mpdata->{volume};
+       my $move_to_storage_checks = sub {
+           PVE::LXC::Config->lock_config($vmid, sub {
+               my $conf = PVE::LXC::Config->load_config($vmid);
+               PVE::LXC::Config->check_lock($conf);
 
-           die "you can't move a volume with snapshots and delete the source\n"
-               if $param->{delete} && PVE::LXC::Config->is_volume_in_use_by_snapshots($conf, $old_volid);
+               die "cannot move volumes of a running container\n"
+                   if PVE::LXC::check_running($vmid);
 
-           PVE::Tools::assert_if_modified($param->{digest}, $conf->{digest});
+               if ($mpkey =~ m/^unused\d+$/) {
+                   die "cannot move volume '$mpkey', only configured volumes can be moved to ".
+                       "another storage\n";
+               }
 
-           PVE::LXC::Config->set_lock($vmid, $lockname);
-       });
+               $mpdata = PVE::LXC::Config->parse_volume($mpkey, $conf->{$mpkey});
+               $old_volid = $mpdata->{volume};
 
-       my $realcmd = sub {
+               die "you can't move a volume with snapshots and delete the source\n"
+                   if $param->{delete} && PVE::LXC::Config->is_volume_in_use_by_snapshots($conf, $old_volid);
+
+               PVE::Tools::assert_if_modified($digest, $conf->{digest});
+
+               PVE::LXC::Config->set_lock($vmid, $lockname);
+           });
+       };
+
+       my $storage_realcmd = sub {
            eval {
-               PVE::Cluster::log_msg('info', $authuser, "move volume CT $vmid: move --volume $mpkey --storage $storage");
+               PVE::Cluster::log_msg(
+                   'info',
+                   $authuser,
+                   "move volume CT $vmid: move --volume $mpkey --storage $storage"
+               );
 
                my $conf = PVE::LXC::Config->load_config($vmid);
                my $storage_cfg = PVE::Storage::config();
@@ -1860,8 +1986,20 @@ __PACKAGE__->register_method({
                    PVE::Storage::activate_volumes($storage_cfg, [ $old_volid ]);
                    my $bwlimit = extract_param($param, 'bwlimit');
                    my $source_storage = PVE::Storage::parse_volume_id($old_volid);
-                   my $movelimit = PVE::Storage::get_bandwidth_limit('move', [$source_storage, $storage], $bwlimit);
-                   $new_volid = PVE::LXC::copy_volume($mpdata, $vmid, $storage, $storage_cfg, $conf, undef, $movelimit);
+                   my $movelimit = PVE::Storage::get_bandwidth_limit(
+                       'move',
+                       [$source_storage, $storage],
+                       $bwlimit
+                   );
+                   $new_volid = PVE::LXC::copy_volume(
+                       $mpdata,
+                       $vmid,
+                       $storage,
+                       $storage_cfg,
+                       $conf,
+                       undef,
+                       $movelimit
+                   );
                    if (PVE::LXC::Config->is_template($conf)) {
                        PVE::Storage::activate_volumes($storage_cfg, [ $new_volid ]);
                        my $template_volid = PVE::Storage::vdisk_create_base($storage_cfg, $new_volid);
@@ -1875,7 +2013,10 @@ __PACKAGE__->register_method({
                        $conf = PVE::LXC::Config->load_config($vmid);
                        PVE::Tools::assert_if_modified($digest, $conf->{digest});
 
-                       $conf->{$mpkey} = PVE::LXC::Config->print_ct_mountpoint($mpdata, $mpkey eq 'rootfs');
+                       $conf->{$mpkey} = PVE::LXC::Config->print_ct_mountpoint(
+                           $mpdata,
+                           $mpkey eq 'rootfs'
+                       );
 
                        PVE::LXC::Config->add_unused_volume($conf, $old_volid) if !$param->{delete};
 
@@ -1917,15 +2058,199 @@ __PACKAGE__->register_method({
            warn $@ if $@;
            die $err if $err;
        };
-       my $task = eval {
-           $rpcenv->fork_worker('move_volume', $vmid, $authuser, $realcmd);
+
+       my $load_and_check_reassign_configs = sub {
+           my $vmlist = PVE::Cluster::get_vmlist()->{ids};
+
+           die "Cannot move to/from 'rootfs'\n" if $mpkey eq "rootfs" || $target_mpkey eq "rootfs";
+
+           if ($mpkey =~ m/^unused\d+$/ && $target_mpkey !~ m/^unused\d+$/) {
+               die "Moving an unused volume to a used one is not possible\n";
+           }
+           die "could not find CT ${vmid}\n" if !exists($vmlist->{$vmid});
+           die "could not find CT ${target_vmid}\n" if !exists($vmlist->{$target_vmid});
+
+           my $source_node = $vmlist->{$vmid}->{node};
+           my $target_node = $vmlist->{$target_vmid}->{node};
+
+           die "Both containers need to be on the same node ($source_node != $target_node)\n"
+               if $source_node ne $target_node;
+
+           my $source_conf = PVE::LXC::Config->load_config($vmid);
+           PVE::LXC::Config->check_lock($source_conf);
+           my $target_conf = PVE::LXC::Config->load_config($target_vmid);
+           PVE::LXC::Config->check_lock($target_conf);
+
+           die "Can't move volumes from or to template CT\n"
+               if ($source_conf->{template} || $target_conf->{template});
+
+           if ($digest) {
+               eval { PVE::Tools::assert_if_modified($digest, $source_conf->{digest}) };
+               die "Container ${vmid}: $@" if $@;
+           }
+
+           if ($target_digest) {
+               eval { PVE::Tools::assert_if_modified($target_digest, $target_conf->{digest}) };
+               die "Container ${target_vmid}: $@" if $@;
+           }
+
+           die "volume '${mpkey}' for container '$vmid' does not exist\n"
+               if !defined($source_conf->{$mpkey});
+
+           die "Target volume key '${target_mpkey}' is already in use for container '$target_vmid'\n"
+               if exists $target_conf->{$target_mpkey};
+
+           my $drive = PVE::LXC::Config->parse_volume(
+               $mpkey,
+               $source_conf->{$mpkey},
+           );
+
+           my $source_volid = $drive->{volume};
+
+           die "Volume '${mpkey}' has no associated image\n"
+               if !$source_volid;
+           die "Cannot move volume used by a snapshot to another container\n"
+               if PVE::LXC::Config->is_volume_in_use_by_snapshots($source_conf, $source_volid);
+           die "Storage does not support moving of this disk to another container\n"
+               if !PVE::Storage::volume_has_feature($storecfg, 'rename', $source_volid);
+           die "Cannot move a bindmount or device mount to another container\n"
+               if $drive->{type} ne "volume";
+           die "Cannot move volume to another container while the source is running - detach first\n"
+               if PVE::LXC::check_running($vmid) && $mpkey !~ m/^unused\d+$/;
+
+           my $repl_conf = PVE::ReplicationConfig->new();
+           if ($repl_conf->check_for_existing_jobs($target_vmid, 1)) {
+               my ($storeid, undef) = PVE::Storage::parse_volume_id($source_volid);
+               my $format = (PVE::Storage::parse_volname($storecfg, $source_volid))[6];
+
+               die "Cannot move volume on storage '$storeid' to a replicated container - missing replication support\n"
+                   if !PVE::Storage::storage_can_replicate($storecfg, $storeid, $format);
+           }
+
+           return ($source_conf, $target_conf, $drive);
        };
-       if (my $err = $@) {
-           eval { PVE::LXC::Config->remove_lock($vmid, $lockname) };
-           warn $@ if $@;
-           die $err;
+
+       my $logfunc = sub {
+           my ($msg) = @_;
+           print STDERR "$msg\n";
+       };
+
+       my $volume_reassignfn = sub {
+           return PVE::LXC::Config->lock_config($vmid, sub {
+               return PVE::LXC::Config->lock_config($target_vmid, sub {
+                   my ($source_conf, $target_conf, $drive) = &$load_and_check_reassign_configs();
+                   my $source_volid = $drive->{volume};
+
+                   my $target_unused = $target_mpkey =~ m/^unused\d+$/;
+
+                   print "moving volume '$mpkey' from container '$vmid' to '$target_vmid'\n";
+
+                   my ($storage, $source_volname) = PVE::Storage::parse_volume_id($source_volid);
+
+                   my $fmt = (PVE::Storage::parse_volname($storecfg, $source_volid))[6];
+
+                   my $new_volid = PVE::Storage::rename_volume(
+                       $storecfg,
+                       $source_volid,
+                       $target_vmid,
+                   );
+
+                   $drive->{volume} = $new_volid;
+
+                   delete $source_conf->{$mpkey};
+                   print "removing volume '${mpkey}' from container '${vmid}' config\n";
+                   PVE::LXC::Config->write_config($vmid, $source_conf);
+
+                   my $drive_string;
+
+                   if ($target_unused) {
+                       $drive_string = $new_volid;
+                   } else {
+                       $drive_string = PVE::LXC::Config->print_volume($target_mpkey, $drive);
+                   }
+
+                   if ($target_unused) {
+                       $target_conf->{$target_mpkey} = $drive_string;
+                   } else {
+                       my $running = PVE::LXC::check_running($target_vmid);
+                       my $param = { $target_mpkey => $drive_string };
+                       my $errors = PVE::LXC::Config->update_pct_config(
+                           $target_vmid,
+                           $target_conf,
+                           $running,
+                           $param
+                       );
+
+                       foreach my $key (keys %$errors) {
+                           $rpcenv->warn($errors->{$key});
+                       }
+                   }
+
+                   PVE::LXC::Config->write_config($target_vmid, $target_conf);
+                   $target_conf = PVE::LXC::Config->load_config($target_vmid);
+
+                   PVE::LXC::update_lxc_config($target_vmid, $target_conf) if !$target_unused;
+                   print "target container '$target_vmid' updated with '$target_mpkey'\n";
+
+                   # remove possible replication snapshots
+                   if (PVE::Storage::volume_has_feature($storecfg,'replicate', $source_volid)) {
+                       eval {
+                           PVE::Replication::prepare(
+                               $storecfg,
+                               [$new_volid],
+                               undef,
+                               1,
+                               undef,
+                               $logfunc,
+                           )
+                       };
+                       if (my $err = $@) {
+                           $rpcenv->warn("Failed to remove replication snapshots on volume ".
+                               "'${target_mpkey}'. Manual cleanup could be necessary. " .
+                               "Error: ${err}\n");
+                       }
+                   }
+               });
+           });
+       };
+
+       if ($target_vmid && $storage) {
+           my $msg = "either set 'storage' or 'target-vmid', but not both";
+           raise_param_exc({ 'target-vmid' => $msg, 'storage' => $msg });
+       } elsif ($target_vmid) {
+           $rpcenv->check_vm_perm($authuser, $target_vmid, undef, ['VM.Config.Disk'])
+               if $authuser ne 'root@pam';
+
+           if ($vmid eq $target_vmid) {
+               my $msg = "must be different than source VMID to move disk to another container";
+               raise_param_exc({ 'target-vmid' => $msg });
+           }
+
+           my (undef, undef, $drive) = &$load_and_check_reassign_configs();
+           my $storeid = PVE::Storage::parse_volume_id($drive->{volume});
+           $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
+           return $rpcenv->fork_worker(
+               'move_volume',
+               "${vmid}-${mpkey}>${target_vmid}-${target_mpkey}",
+               $authuser,
+               $volume_reassignfn
+           );
+       } elsif ($storage) {
+           $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace']);
+           &$move_to_storage_checks();
+           my $task = eval {
+               $rpcenv->fork_worker('move_volume', $vmid, $authuser, $storage_realcmd);
+           };
+           if (my $err = $@) {
+               eval { PVE::LXC::Config->remove_lock($vmid, $lockname) };
+               warn $@ if $@;
+               die $err;
+           }
+           return $task;
+       } else {
+           my $msg = "both 'storage' and 'target-vmid' missing, either needs to be set";
+           raise_param_exc({ 'target-vmid' => $msg, 'storage' => $msg });
        }
-       return $task;
   }});
 
 __PACKAGE__->register_method({