]> git.proxmox.com Git - pve-container.git/blobdiff - src/PVE/API2/LXC.pm
prefer storage_check_enabled over storage_check_node
[pve-container.git] / src / PVE / API2 / LXC.pm
index 47dcb08acee40debd69403208bc841a905944a6b..b929481e3a0847b46d045388fc43142fa4896c9e 100644 (file)
@@ -5,17 +5,22 @@ use warnings;
 
 use PVE::SafeSyslog;
 use PVE::Tools qw(extract_param run_command);
-use PVE::Exception qw(raise raise_param_exc);
+use PVE::Exception qw(raise raise_param_exc raise_perm_exc);
 use PVE::INotify;
 use PVE::Cluster qw(cfs_read_file);
+use PVE::RRD;
+use PVE::DataCenterConfig;
 use PVE::AccessControl;
 use PVE::Firewall;
 use PVE::Storage;
 use PVE::RESTHandler;
 use PVE::RPCEnvironment;
+use PVE::ReplicationConfig;
 use PVE::LXC;
 use PVE::LXC::Create;
 use PVE::LXC::Migrate;
+use PVE::GuestHelpers;
+use PVE::VZDump::Plugin;
 use PVE::API2::LXC::Config;
 use PVE::API2::LXC::Status;
 use PVE::API2::LXC::Snapshot;
@@ -33,7 +38,7 @@ BEGIN {
 
 __PACKAGE__->register_method ({
     subclass => "PVE::API2::LXC::Config",
-    path => '{vmid}/config',                         
+    path => '{vmid}/config',
 });
 
 __PACKAGE__->register_method ({
@@ -72,7 +77,7 @@ __PACKAGE__->register_method({
        type => 'array',
        items => {
            type => "object",
-           properties => {},
+           properties => $PVE::LXC::vmstatus_return_properties,
        },
        links => [ { rel => 'child', href => "{vmid}" } ],
     },
@@ -89,7 +94,6 @@ __PACKAGE__->register_method({
            next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
 
            my $data = $vmstatus->{$vmid};
-           $data->{vmid} = $vmid;
            push @$res, $data;
        }
 
@@ -143,6 +147,12 @@ __PACKAGE__->register_method({
                type => 'boolean',
                description => "Mark this as restore task.",
            },
+           unique => {
+               optional => 1,
+               type => 'boolean',
+               description => "Assign a unique random ethernet address.",
+               requires => 'restore',
+           },
            pool => {
                optional => 1,
                type => 'string', format => 'pve-poolid',
@@ -159,6 +169,19 @@ __PACKAGE__->register_method({
                description => "Setup public SSH keys (one key per line, " .
                                "OpenSSH format).",
            },
+           bwlimit => {
+               description => "Override I/O bandwidth limit (in KiB/s).",
+               optional => 1,
+               type => 'number',
+               minimum => '0',
+               default => 'restore limit from datacenter or storage config',
+           },
+           start => {
+               optional => 1,
+               type => 'boolean',
+               default => 0,
+               description => "Start the CT after its creation finished successfully.",
+           },
        }),
     },
     returns => {
@@ -167,46 +190,47 @@ __PACKAGE__->register_method({
     code => sub {
        my ($param) = @_;
 
-       my $rpcenv = PVE::RPCEnvironment::get();
+       PVE::Cluster::check_cfs_quorum();
 
+       my $rpcenv = PVE::RPCEnvironment::get();
        my $authuser = $rpcenv->get_user();
 
        my $node = extract_param($param, 'node');
-
        my $vmid = extract_param($param, 'vmid');
-
        my $ignore_unpack_errors = extract_param($param, 'ignore-unpack-errors');
+       my $bwlimit = extract_param($param, 'bwlimit');
+       my $start_after_create = extract_param($param, 'start');
 
        my $basecfg_fn = PVE::LXC::Config->config_file($vmid);
-
        my $same_container_exists = -f $basecfg_fn;
 
        # 'unprivileged' is read-only, so we can't pass it to update_pct_config
        my $unprivileged = extract_param($param, 'unprivileged');
-
        my $restore = extract_param($param, 'restore');
+       my $unique = extract_param($param, 'unique');
+
+       # used to skip firewall config restore if user lacks permission
+       my $skip_fw_config_restore = 0;
 
        if ($restore) {
            # fixme: limit allowed parameters
-
        }
-       
+
        my $force = extract_param($param, 'force');
 
        if (!($same_container_exists && $restore && $force)) {
            PVE::Cluster::check_vmid_unused($vmid);
        } else {
+           die "can't overwrite running container\n" if PVE::LXC::check_running($vmid);
            my $conf = PVE::LXC::Config->load_config($vmid);
            PVE::LXC::Config->check_protection($conf, "unable to restore CT $vmid");
        }
 
        my $password = extract_param($param, 'password');
-
        my $ssh_keys = extract_param($param, 'ssh-public-keys');
        PVE::Tools::validate_ssh_public_keys($ssh_keys) if defined($ssh_keys);
 
        my $pool = extract_param($param, 'pool');
-
        if (defined($pool)) {
            $rpcenv->check_pool_exist($pool);
            $rpcenv->check_perm_modify($authuser, "/pool/$pool");
@@ -219,6 +243,10 @@ __PACKAGE__->register_method({
        } elsif ($restore && $force && $same_container_exists &&
                 $rpcenv->check($authuser, "/vms/$vmid", ['VM.Backup'], 1)) {
            # OK: user has VM.Backup permissions, and want to restore an existing VM
+
+           # 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;
        } else {
            raise_perm_exc();
        }
@@ -230,25 +258,24 @@ __PACKAGE__->register_method({
 
        my $storage_cfg = cfs_read_file("storage.cfg");
 
-
        my $archive;
-
        if ($ostemplate eq '-') {
-           die "pipe requires cli environment\n" 
-               if $rpcenv->{type} ne 'cli'; 
-           die "pipe can only be used with restore tasks\n" 
+           die "pipe requires cli environment\n"
+               if $rpcenv->{type} ne 'cli';
+           die "pipe can only be used with restore tasks\n"
                if !$restore;
            $archive = '-';
            die "restore from pipe requires rootfs parameter\n" if !defined($param->{rootfs});
        } else {
            PVE::Storage::check_volume_access($rpcenv, $authuser, $storage_cfg, $vmid, $ostemplate);
-           $archive = PVE::Storage::abs_filesystem_path($storage_cfg, $ostemplate);
+           $archive = $ostemplate;
        }
 
+       my %used_storages;
        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};
@@ -256,10 +283,13 @@ __PACKAGE__->register_method({
            $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
 
            PVE::Storage::activate_storage($storage_cfg, $sid);
+           $used_storages{$sid} = 1;
        };
 
        my $conf = {};
 
+       my $is_root = $authuser eq 'root@pam';
+
        my $no_disk_param = {};
        my $mp_param = {};
        my $storage_only_mode = 1;
@@ -286,7 +316,7 @@ __PACKAGE__->register_method({
 
        # check storage access, activate storage
        my $delayed_mp_param = {};
-       PVE::LXC::Config->foreach_mountpoint($mp_param, sub {
+       PVE::LXC::Config->foreach_volume($mp_param, sub {
            my ($ms, $mountpoint) = @_;
 
            my $volid = $mountpoint->{volume};
@@ -294,7 +324,7 @@ __PACKAGE__->register_method({
 
            if ($mountpoint->{type} ne 'volume') { # bind or device
                die "Only root can pass arbitrary filesystem paths.\n"
-                   if $authuser ne 'root@pam';
+                   if !$is_root;
            } else {
                my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
                &$check_and_activate_storage($sid);
@@ -308,43 +338,47 @@ __PACKAGE__->register_method({
 
        $conf->{unprivileged} = 1 if $unprivileged;
 
-       my $check_vmid_usage = sub {
-           if ($force) {
-               die "can't overwrite running container\n"
-                   if PVE::LXC::check_running($vmid);
-           } else {
-               PVE::Cluster::check_vmid_unused($vmid);
-           }
-       };
-
-       my $code = sub {
-           &$check_vmid_usage(); # final check after locking
-           my $old_conf;
+       my $emsg = $restore ? "unable to restore CT $vmid -" : "unable to create CT $vmid -";
 
-           my $config_fn = PVE::LXC::Config->config_file($vmid);
-           if (-f $config_fn) {
-               die "container exists" if !$restore; # just to be sure
-               $old_conf = PVE::LXC::Config->load_config($vmid);
-           } else {
-               eval {
-                   # try to create empty config on local node, we have an flock
-                   PVE::LXC::Config->write_config($vmid, {});
-               };
+       eval { PVE::LXC::Config->create_and_lock_config($vmid, $force) };
+       die "$emsg $@" if $@;
 
-               # another node was faster, abort
-               die "Could not reserve ID $vmid, already taken\n" if $@;
-           }
+       my $code = sub {
+           my $old_conf = PVE::LXC::Config->load_config($vmid);
+           my $was_template;
 
-           PVE::Cluster::check_cfs_quorum();
            my $vollist = [];
-
            eval {
+               my $orig_mp_param; # only used if $restore
+               if ($restore) {
+                   die "can't overwrite running container\n" if PVE::LXC::check_running($vmid);
+                   if ($archive ne '-') {
+                       my $orig_conf;
+                       print "recovering backed-up configuration from '$archive'\n";
+                       ($orig_conf, $orig_mp_param) = PVE::LXC::Create::recover_config($storage_cfg, $archive, $vmid);
+
+                       $was_template = delete $orig_conf->{template};
+
+                       # When we're root call 'restore_configuration' with restricted=0,
+                       # causing it to restore the raw lxc entries, among which there may be
+                       # 'lxc.idmap' entries. We need to make sure that the extracted contents
+                       # of the container match up with the restored configuration afterwards:
+                       $conf->{lxc} = $orig_conf->{lxc} if $is_root;
+
+                       $conf->{unprivileged} = $orig_conf->{unprivileged}
+                           if !defined($unprivileged) && defined($orig_conf->{unprivileged});
+                   }
+               }
                if ($storage_only_mode) {
                    if ($restore) {
-                       (undef, $mp_param) = PVE::LXC::Create::recover_config($archive);
+                       if (!defined($orig_mp_param)) {
+                           print "recovering backed-up configuration from '$archive'\n";
+                           (undef, $orig_mp_param) = PVE::LXC::Create::recover_config($storage_cfg, $archive, $vmid);
+                       }
+                       $mp_param = $orig_mp_param;
                        die "rootfs configuration could not be recovered, please check and specify manually!\n"
                            if !defined($mp_param->{rootfs});
-                       PVE::LXC::Config->foreach_mountpoint($mp_param, sub {
+                       PVE::LXC::Config->foreach_volume($mp_param, sub {
                            my ($ms, $mountpoint) = @_;
                            my $type = $mountpoint->{type};
                            if ($type eq 'volume') {
@@ -359,7 +393,7 @@ __PACKAGE__->register_method({
                                die "restoring rootfs to $type mount is only possible by specifying -rootfs manually!\n"
                                    if ($ms eq 'rootfs');
                                die "restoring '$ms' to $type mount is only possible for root\n"
-                                   if $authuser ne 'root@pam';
+                                   if !$is_root;
 
                                if ($mountpoint->{backup}) {
                                    warn "WARNING - unsupported configuration!\n";
@@ -378,17 +412,24 @@ __PACKAGE__->register_method({
 
                $vollist = PVE::LXC::create_disks($storage_cfg, $vmid, $mp_param, $conf);
 
-               if (defined($old_conf)) {
+               # we always have the 'create' lock so check for more than 1 entry
+               if (scalar(keys %$old_conf) > 1) {
                    # destroy old container volumes
-                   PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $old_conf, {});
+                   PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $old_conf, { lock => 'create' });
                }
 
                eval {
                    my $rootdir = PVE::LXC::mount_all($vmid, $storage_cfg, $conf, 1);
-                   PVE::LXC::Create::restore_archive($archive, $rootdir, $conf, $ignore_unpack_errors);
+                   $bwlimit = PVE::Storage::get_bandwidth_limit('restore', [keys %used_storages], $bwlimit);
+                   print "restoring '$archive' now..\n"
+                       if $restore && $archive ne '-';
+                   PVE::LXC::Create::restore_archive($storage_cfg, $archive, $rootdir, $conf, $ignore_unpack_errors, $bwlimit);
 
                    if ($restore) {
-                       PVE::LXC::Create::restore_configuration($vmid, $rootdir, $conf, $authuser ne 'root@pam');
+                       print "merging backed-up and given configuration..\n";
+                       PVE::LXC::Create::restore_configuration($vmid, $storage_cfg, $archive, $rootdir, $conf, !$is_root, $unique, $skip_fw_config_restore);
+                       my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
+                       $lxc_setup->template_fixup($conf);
                    } else {
                        my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir); # detect OS
                        PVE::LXC::Config->write_config($vmid, $conf); # safe config (after OS detection)
@@ -406,23 +447,30 @@ __PACKAGE__->register_method({
                foreach my $mp (keys %$delayed_mp_param) {
                    $conf->{$mp} = $delayed_mp_param->{$mp};
                }
+               # If the template flag was set, we try to convert again to template after restore
+               if ($was_template) {
+                   print STDERR "Convert restored container to template...\n";
+                   PVE::LXC::template_create($vmid, $conf);
+                   $conf->{template} = 1;
+               }
                PVE::LXC::Config->write_config($vmid, $conf);
            };
            if (my $err = $@) {
                PVE::LXC::destroy_disks($storage_cfg, $vollist);
-               PVE::LXC::destroy_config($vmid);
-               die $err;
+               eval { PVE::LXC::Config->destroy_config($vmid) };
+               warn $@ if $@;
+               die "$emsg $err";
            }
            PVE::AccessControl::add_vm_to_pool($vmid, $pool) if $pool;
+
+           PVE::API2::LXC::Status->vm_start({ vmid => $vmid, node => $node })
+               if $start_after_create;
        };
 
+       my $workername = $restore ? 'vzrestore' : 'vzcreate';
        my $realcmd = sub { PVE::LXC::Config->lock_config($vmid, $code); };
 
-       &$check_vmid_usage(); # first check before locking
-
-       return $rpcenv->fork_worker($restore ? 'vzrestore' : 'vzcreate',
-                                   $vmid, $authuser, $realcmd);
-
+       return $rpcenv->fork_worker($workername, $vmid, $authuser, $realcmd);
     }});
 
 __PACKAGE__->register_method({
@@ -459,8 +507,10 @@ __PACKAGE__->register_method({
 
        my $res = [
            { subdir => 'config' },
+           { subdir => 'pending' },
            { subdir => 'status' },
            { subdir => 'vncproxy' },
+           { subdir => 'termproxy' },
            { subdir => 'vncwebsocket' },
            { subdir => 'spiceproxy' },
            { subdir => 'migrate' },
@@ -517,7 +567,7 @@ __PACKAGE__->register_method({
     code => sub {
        my ($param) = @_;
 
-       return PVE::Cluster::create_rrd_graph(
+       return PVE::RRD::create_rrd_graph(
            "pve2-vm/$param->{vmid}", $param->{timeframe},
            $param->{ds}, $param->{cf});
 
@@ -560,7 +610,7 @@ __PACKAGE__->register_method({
     code => sub {
        my ($param) = @_;
 
-       return PVE::Cluster::create_rrd_data(
+       return PVE::RRD::create_rrd_data(
            "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
     }});
 
@@ -579,6 +629,26 @@ __PACKAGE__->register_method({
        properties => {
            node => get_standard_option('pve-node'),
            vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
+           force => {
+               type => 'boolean',
+               description => "Force destroy, even if running.",
+               default => 0,
+               optional => 1,
+           },
+           purge => {
+               type => 'boolean',
+               description => "Remove container from all related configurations."
+                   ." For example, backup jobs, replication jobs or HA."
+                   ." Related ACLs and Firewall entries will *always* be removed.",
+               default => 0,
+               optional => 1,
+           },
+           'destroy-unreferenced-disks' => {
+               type => 'boolean',
+               description => "If set, destroy additionally all disks with the VMID from all"
+                   ." enabled storages which are not referenced in the config.",
+               optional => 1,
+           },
        },
     },
     returns => {
@@ -588,39 +658,79 @@ __PACKAGE__->register_method({
        my ($param) = @_;
 
        my $rpcenv = PVE::RPCEnvironment::get();
-
        my $authuser = $rpcenv->get_user();
-
        my $vmid = $param->{vmid};
 
        # test if container exists
+
        my $conf = PVE::LXC::Config->load_config($vmid);
+       my $early_checks = sub {
+           my ($conf) = @_;
+           PVE::LXC::Config->check_protection($conf, "can't remove CT $vmid");
+           PVE::LXC::Config->check_lock($conf);
 
-       my $storage_cfg = cfs_read_file("storage.cfg");
+           my $ha_managed = PVE::HA::Config::service_is_configured("ct:$vmid");
 
-       PVE::LXC::Config->check_protection($conf, "can't remove CT $vmid");
+           if (!$param->{purge}) {
+               die "unable to remove CT $vmid - used in HA resources and purge parameter not set.\n"
+                   if $ha_managed;
 
-       die "unable to remove CT $vmid - used in HA resources\n"
-           if PVE::HA::Config::vm_is_ha_managed($vmid);
+               # do not allow destroy if there are replication jobs without purge
+               my $repl_conf = PVE::ReplicationConfig->new();
+               $repl_conf->check_for_existing_jobs($vmid);
+           }
 
-       my $running_error_msg = "unable to destroy CT $vmid - container is running\n";
+           return $ha_managed;
+       };
 
-       die $running_error_msg if PVE::LXC::check_running($vmid); # check early
+       $early_checks->($conf);
+
+       my $running_error_msg = "unable to destroy CT $vmid - container is running\n";
+       die $running_error_msg if !$param->{force} && PVE::LXC::check_running($vmid); # check early
 
        my $code = sub {
            # reload config after lock
            $conf = PVE::LXC::Config->load_config($vmid);
-           PVE::LXC::Config->check_lock($conf);
+           my $ha_managed = $early_checks->($conf);
+
+           if (PVE::LXC::check_running($vmid)) {
+               die $running_error_msg if !$param->{force};
+               warn "forced to stop CT $vmid before destroying!\n";
+               if (!$ha_managed) {
+                   PVE::LXC::vm_stop($vmid, 1);
+               } else {
+                   run_command(['ha-manager', 'crm-command', 'stop',  "ct:$vmid", '120']);
+               }
+           }
 
-           die $running_error_msg if PVE::LXC::check_running($vmid);
+           my $storage_cfg = cfs_read_file("storage.cfg");
+           PVE::LXC::destroy_lxc_container(
+               $storage_cfg,
+               $vmid,
+               $conf,
+               { lock => 'destroyed' },
+               $param->{'destroy-unreferenced-disks'},
+           );
 
-           PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $conf);
            PVE::AccessControl::remove_vm_access($vmid);
            PVE::Firewall::remove_vmfw_conf($vmid);
+           if ($param->{purge}) {
+               print "purging CT $vmid from related configurations..\n";
+               PVE::ReplicationConfig::remove_vmid_jobs($vmid);
+               PVE::VZDump::Plugin::remove_vmid_from_backup_jobs($vmid);
+
+               if ($ha_managed) {
+                   PVE::HA::Config::delete_service_from_config("ct:$vmid");
+                   print "NOTE: removed CT $vmid from HA resource configuration.\n";
+               }
+           }
+
+           # only now remove the zombie config, else we can have reuse race
+           PVE::LXC::Config->destroy_config($vmid);
        };
 
        my $realcmd = sub { PVE::LXC::Config->lock_config($vmid, $code); };
-       
+
        return $rpcenv->fork_worker('vzdestroy', $vmid, $authuser, $realcmd);
     }});
 
@@ -645,6 +755,20 @@ __PACKAGE__->register_method ({
                type => 'boolean',
                description => "use websocket instead of standard VNC.",
            },
+           width => {
+               optional => 1,
+               description => "sets the width of the console in pixels.",
+               type => 'integer',
+               minimum => 16,
+               maximum => 4096,
+           },
+           height => {
+               optional => 1,
+               description => "sets the height of the console in pixels.",
+               type => 'integer',
+               minimum => 16,
+               maximum => 2160,
+           },
        },
     },
     returns => {
@@ -687,10 +811,10 @@ __PACKAGE__->register_method ({
        # NOTE: vncterm VNC traffic is already TLS encrypted,
        # so we select the fastest chipher here (or 'none'?)
        my $remcmd = $remip ?
-           ['/usr/bin/ssh', '-t', $remip] : [];
+           ['/usr/bin/ssh', '-e', 'none', '-t', $remip] : [];
 
        my $conf = PVE::LXC::Config->load_config($vmid, $node);
-       my $concmd = PVE::LXC::get_console_command($vmid, $conf);
+       my $concmd = PVE::LXC::get_console_command($vmid, $conf, -1);
 
        my $shcmd = [ '/usr/bin/dtach', '-A',
                      "/var/run/dtach/vzctlconsole$vmid",
@@ -707,6 +831,14 @@ __PACKAGE__->register_method ({
                       '-timeout', $timeout, '-authpath', $authpath,
                       '-perm', 'VM.Console'];
 
+           if ($param->{width}) {
+               push @$cmd, '-width', $param->{width};
+           }
+
+           if ($param->{height}) {
+               push @$cmd, '-height', $param->{height};
+           }
+
            if ($param->{websocket}) {
                $ENV{PVE_VNC_TICKET} = $ticket; # pass ticket to vncterm
                push @$cmd, '-notls', '-listen', 'localhost';
@@ -732,6 +864,89 @@ __PACKAGE__->register_method ({
        };
     }});
 
+__PACKAGE__->register_method ({
+    name => 'termproxy',
+    path => '{vmid}/termproxy',
+    method => 'POST',
+    protected => 1,
+    permissions => {
+       check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
+    },
+    description => "Creates a TCP proxy connection.",
+    parameters => {
+       additionalProperties => 0,
+       properties => {
+           node => get_standard_option('pve-node'),
+           vmid => get_standard_option('pve-vmid'),
+       },
+    },
+    returns => {
+       additionalProperties => 0,
+       properties => {
+           user => { type => 'string' },
+           ticket => { type => 'string' },
+           port => { type => 'integer' },
+           upid => { type => 'string' },
+       },
+    },
+    code => sub {
+       my ($param) = @_;
+
+       my $rpcenv = PVE::RPCEnvironment::get();
+
+       my $authuser = $rpcenv->get_user();
+
+       my $vmid = $param->{vmid};
+       my $node = $param->{node};
+
+       my $authpath = "/vms/$vmid";
+
+       my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
+
+       my ($remip, $family);
+
+       if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
+           ($remip, $family) = PVE::Cluster::remote_node_ip($node);
+       } else {
+           $family = PVE::Tools::get_host_address_family($node);
+       }
+
+       my $port = PVE::Tools::next_vnc_port($family);
+
+       my $remcmd = $remip ?
+           ['/usr/bin/ssh', '-e', 'none', '-t', $remip, '--'] : [];
+
+       my $conf = PVE::LXC::Config->load_config($vmid, $node);
+       my $concmd = PVE::LXC::get_console_command($vmid, $conf, -1);
+
+       my $shcmd = [ '/usr/bin/dtach', '-A',
+                     "/var/run/dtach/vzctlconsole$vmid",
+                     '-r', 'winch', '-z', @$concmd];
+
+       my $realcmd = sub {
+           my $upid = shift;
+
+           syslog ('info', "starting lxc termproxy $upid\n");
+
+           my $cmd = ['/usr/bin/termproxy', $port, '--path', $authpath,
+                      '--perm', 'VM.Console', '--'];
+           push @$cmd, @$remcmd, @$shcmd;
+
+           PVE::Tools::run_command($cmd);
+       };
+
+       my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd, 1);
+
+       PVE::Tools::wait_for_vnc_port($port);
+
+       return {
+           user => $authuser,
+           ticket => $ticket,
+           port => $port,
+           upid => $upid,
+       };
+    }});
+
 __PACKAGE__->register_method({
     name => 'vncwebsocket',
     path => '{vmid}/vncwebsocket',
@@ -861,11 +1076,12 @@ __PACKAGE__->register_method({
                optional => 1,
                default => 180,
            },
-           force => {
-               type => 'boolean',
-               description => "Force migration despite local bind / device" .
-                   " mounts. NOTE: deprecated, use 'shared' property of mount point instead.",
+           bwlimit => {
+               description => "Override I/O bandwidth limit (in KiB/s).",
                optional => 1,
+               type => 'number',
+               minimum => '0',
+               default => 'migrate limit from datacenter or storage config',
            },
        },
     },
@@ -911,7 +1127,7 @@ __PACKAGE__->register_method({
 
                my $cmd = ['ha-manager', 'migrate', $service, $target];
 
-               print "Executing HA migrate for CT $vmid to node $target\n";
+               print "Requesting HA migration for CT $vmid to node $target\n";
 
                PVE::Tools::run_command($cmd);
 
@@ -923,14 +1139,14 @@ __PACKAGE__->register_method({
        } else {
 
            my $realcmd = sub {
-               my $upid = shift;
-
                PVE::LXC::Migrate->migrate($target, $targetip, $vmid, $param);
+           };
 
-               return;
+           my $worker = sub {
+               return PVE::GuestHelpers::guest_migration_lock($vmid, 10, $realcmd);
            };
 
-           return $rpcenv->fork_worker('vzmigrate', $vmid, $authuser, $realcmd);
+           return $rpcenv->fork_worker('vzmigrate', $vmid, $authuser, $worker);
        }
     }});
 
@@ -952,9 +1168,9 @@ __PACKAGE__->register_method({
             feature => {
                 description => "Feature to check.",
                 type => 'string',
-                enum => [ 'snapshot' ],
+                enum => [ 'snapshot', 'clone', 'copy' ],
             },
-            snapname => get_standard_option('pve-lxc-snapshot-name', {
+            snapname => get_standard_option('pve-snapshot-name', {
                 optional => 1,
             }),
        },
@@ -1014,12 +1230,6 @@ __PACKAGE__->register_method({
        properties => {
            node => get_standard_option('pve-node'),
            vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
-           experimental => {
-               type => 'boolean',
-               description => "The template feature is experimental, set this " .
-                   "flag if you know what you are doing.",
-               default => 0,
-           },
        },
     },
     returns => { type => 'null'},
@@ -1050,13 +1260,13 @@ __PACKAGE__->register_method({
 
            my $realcmd = sub {
                PVE::LXC::template_create($vmid, $conf);
-           };
 
-           $conf->{template} = 1;
+               $conf->{template} = 1;
 
-           PVE::LXC::Config->write_config($vmid, $conf);
-           # and remove lxc config
-           PVE::LXC::update_lxc_config($vmid, $conf);
+               PVE::LXC::Config->write_config($vmid, $conf);
+               # and remove lxc config
+               PVE::LXC::update_lxc_config($vmid, $conf);
+           };
 
            return $rpcenv->fork_worker('vztemplate', $vmid, $authuser, $realcmd);
        };
@@ -1110,31 +1320,30 @@ __PACKAGE__->register_method({
                type => 'string', format => 'pve-poolid',
                description => "Add the new CT to the specified pool.",
            },
-           snapname => get_standard_option('pve-lxc-snapshot-name', {
+           snapname => get_standard_option('pve-snapshot-name', {
                optional => 1,
             }),
            storage => get_standard_option('pve-storage-id', {
                description => "Target storage for full clone.",
-               requires => 'full',
                optional => 1,
            }),
            full => {
                optional => 1,
                type => 'boolean',
-               description => "Create a full copy of all disk. This is always done when " .
+               description => "Create a full copy of all disks. This is always done when " .
                    "you clone a normal CT. For CT templates, we try to create a linked clone by default.",
-               default => 0,
            },
-           experimental => {
-               type => 'boolean',
-               description => "The clone feature is experimental, set this " .
-                   "flag if you know what you are doing.",
-               default => 0,
+           target => get_standard_option('pve-node', {
+               description => "Target node. Only allowed if the original VM is on shared storage.",
+               optional => 1,
+           }),
+           bwlimit => {
+               description => "Override I/O bandwidth limit (in KiB/s).",
+               optional => 1,
+               type => 'number',
+               minimum => '0',
+               default => 'clone limit from datacenter or storage config',
            },
-#          target => get_standard_option('pve-node', {
-#              description => "Target node. Only allowed if the original VM is on shared storage.",
-#              optional => 1,
-#          }),
         },
     },
     returns => {
@@ -1144,87 +1353,108 @@ __PACKAGE__->register_method({
        my ($param) = @_;
 
        my $rpcenv = PVE::RPCEnvironment::get();
-
-        my $authuser = $rpcenv->get_user();
+       my $authuser = $rpcenv->get_user();
 
        my $node = extract_param($param, 'node');
-
        my $vmid = extract_param($param, 'vmid');
-
        my $newid = extract_param($param, 'newid');
-
        my $pool = extract_param($param, 'pool');
-
        if (defined($pool)) {
            $rpcenv->check_pool_exist($pool);
        }
-
        my $snapname = extract_param($param, 'snapname');
-
        my $storage = extract_param($param, 'storage');
-
+       my $target = extract_param($param, 'target');
         my $localnode = PVE::INotify::nodename();
 
+       undef $target if $target && ($target eq $localnode || $target eq 'localhost');
+
+       PVE::Cluster::check_node_exists($target) if $target;
+
        my $storecfg = PVE::Storage::config();
 
        if ($storage) {
            # check if storage is enabled on local node
            PVE::Storage::storage_check_enabled($storecfg, $storage);
+           if ($target) {
+               # check if storage is available on target node
+               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};
+           }
        }
 
        PVE::Cluster::check_cfs_quorum();
 
-       my $running = PVE::LXC::check_running($vmid) || 0;
-
-       my $clonefn = sub {
+       my $newconf = {};
+       my $mountpoints = {};
+       my $fullclone = {};
+       my $vollist = [];
+       my $running;
 
-           # do all tests after lock
-           # we also try to do all tests before we fork the worker
-           my $conf = PVE::LXC::Config->load_config($vmid);
+       PVE::LXC::Config->create_and_lock_config($newid, 0);
+       PVE::Firewall::clone_vmfw_conf($vmid, $newid);
 
-           PVE::LXC::Config->check_lock($conf);
+       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');
 
-           my $verify_running = PVE::LXC::check_running($vmid) || 0;
+               return $code->($conf);
+           });
+       };
 
-           die "unexpected state change\n" if $verify_running != $running;
+       my $src_conf = PVE::LXC::Config->set_lock($vmid, 'disk');
 
-           die "snapshot '$snapname' does not exist\n"
-               if $snapname && !defined( $conf->{snapshots}->{$snapname});
+       $running = PVE::LXC::check_running($vmid) || 0;
 
-           my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
+       my $full = extract_param($param, 'full');
+       if (!defined($full)) {
+           $full = !PVE::LXC::Config->is_template($src_conf);
+       }
 
-           my $conffile = PVE::LXC::Config->config_file($newid);
-           die "unable to create CT $newid: config file already exists\n"
-               if -f $conffile;
+       eval {
+           die "parameter 'storage' not allowed for linked clones\n"
+               if defined($storage) && !$full;
 
-           my $newconf = { lock => 'clone' };
-           my $mountpoints = {};
-           my $fullclone = {};
-           my $vollist = [];
+           die "snapshot '$snapname' does not exist\n"
+               if $snapname && !defined($src_conf->{snapshots}->{$snapname});
 
-           foreach my $opt (keys %$oldconf) {
-               my $value = $oldconf->{$opt};
+           my $src_conf = $snapname ? $src_conf->{snapshots}->{$snapname} : $src_conf;
 
-               # no need to copy unused images, because VMID(owner) changes anyways
+           my $sharedvm = 1;
+           for my $opt (sort keys %$src_conf) {
                next if $opt =~ m/^unused\d+$/;
 
+               my $value = $src_conf->{$opt};
+
                if (($opt eq 'rootfs') || ($opt =~ m/^mp\d+$/)) {
-                   my $mp = $opt eq 'rootfs' ?
-                       PVE::LXC::Config->parse_ct_rootfs($value) :
-                       PVE::LXC::Config->parse_ct_mountpoint($value);
+                   my $mp = PVE::LXC::Config->parse_volume($opt, $value);
 
                    if ($mp->{type} eq 'volume') {
                        my $volid = $mp->{volume};
-                       if ($param->{full}) {
-                           die "fixme: full clone not implemented";
 
-                           die "Full clone feature for '$volid' is not available\n"
-                               if !PVE::Storage::volume_has_feature($storecfg, 'copy', $volid, $snapname, $running);
+                       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;
+                       }
+
+                       $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 {
                            # 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);
+                               if !PVE::Storage::volume_has_feature($storecfg, 'clone', $volid, $snapname, $running, {'valid_target_formats' => ['raw', 'subvol']});
                        }
 
                        $mountpoints->{$opt} = $mp;
@@ -1232,15 +1462,27 @@ __PACKAGE__->register_method({
 
                    } else {
                        # TODO: allow bind mounts?
-                       die "unable to clone mountpint '$opt' (type $mp->{type})\n";
+                       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;
 
+           # 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};
@@ -1250,63 +1492,133 @@ __PACKAGE__->register_method({
                $newconf->{description} = $param->{description};
            }
 
-           # create empty/temp config - this fails if CT already exists on other node
-           PVE::Tools::file_set_contents($conffile, "# ctclone temporary file\nlock: clone\n");
+           $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 $@;
 
-           my $realcmd = sub {
-               my $upid = shift;
+           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 $@;
 
-               my $newvollist = [];
+           die $err;
+       }
 
-               eval {
-                   local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
+       my $update_conf = sub {
+           my ($key, $value) = @_;
+           return $lock_and_reload->($newid, sub {
+               my $conf = shift;
+               $conf->{$key} = $value;
+               PVE::LXC::Config->write_config($newid, $conf);
+           });
+       };
 
-                   PVE::Storage::activate_volumes($storecfg, $vollist, $snapname);
+       my $realcmd = sub {
+           my ($upid) = @_;
 
-                   foreach my $opt (keys %$mountpoints) {
-                       my $mp = $mountpoints->{$opt};
-                       my $volid = $mp->{volume};
+           my $newvollist = [];
 
-                       if ($fullclone->{$opt}) {
-                           die "fixme: full clone not implemented\n";
-                       } else {
-                           print "create linked clone of mount point $opt ($volid)\n";
-                           my $newvolid = PVE::Storage::vdisk_clone($storecfg, $volid, $newid, $snapname);
-                           push @$newvollist, $newvolid;
-                           $mp->{volume} = $newvolid;
+           my $verify_running = PVE::LXC::check_running($vmid) || 0;
+           die "unexpected state change\n" if $verify_running != $running;
 
-                           $newconf->{$opt} = PVE::LXC::Config->print_ct_mountpoint($mp, $opt eq 'rootfs');
-                           PVE::LXC::Config->write_config($newid, $newconf);
-                       }
+           eval {
+               local $SIG{INT} =
+                   local $SIG{TERM} =
+                   local $SIG{QUIT} =
+                   local $SIG{HUP} = sub { die "interrupted by signal\n"; };
+
+               PVE::Storage::activate_volumes($storecfg, $vollist, $snapname);
+               my $bwlimit = extract_param($param, 'bwlimit');
+
+               foreach my $opt (keys %$mountpoints) {
+                   my $mp = $mountpoints->{$opt};
+                   my $volid = $mp->{volume};
+
+                   my $newvolid;
+                   if ($fullclone->{$opt}) {
+                       print "create full clone of mountpoint $opt ($volid)\n";
+                       my $source_storage = PVE::Storage::parse_volume_id($volid);
+                       my $target_storage = $storage // $source_storage;
+                       my $clonelimit = PVE::Storage::get_bandwidth_limit('clone', [$source_storage, $target_storage], $bwlimit);
+                       $newvolid = PVE::LXC::copy_volume($mp, $newid, $target_storage, $storecfg, $newconf, $snapname, $clonelimit);
+                   } else {
+                       print "create linked clone of mount point $opt ($volid)\n";
+                       $newvolid = PVE::Storage::vdisk_clone($storecfg, $volid, $newid, $snapname);
                    }
 
-                   delete $newconf->{lock};
-                   PVE::LXC::Config->write_config($newid, $newconf);
-
-                   PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
-               };
-               if (my $err = $@) {
-                   unlink $conffile;
+                   push @$newvollist, $newvolid;
+                   $mp->{volume} = $newvolid;
 
-                   sleep 1; # some storage like rbd need to wait before release volume - really?
+                   $update_conf->($opt, PVE::LXC::Config->print_ct_mountpoint($mp, $opt eq 'rootfs'));
+               }
 
-                   foreach my $volid (@$newvollist) {
-                       eval { PVE::Storage::vdisk_free($storecfg, $volid); };
-                       warn $@ if $@;
+               PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
+
+               $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 $@;
                    }
-                   die "clone failed: $err";
+               });
+           };
+           my $err = $@;
+           # Unlock the source config in any case:
+           eval { PVE::LXC::Config->remove_lock($vmid, 'disk') };
+           warn $@ if $@;
+
+           if ($err) {
+               # Now cleanup the config & disks:
+               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 $@;
                }
 
-               return;
-           };
+               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 $@;
 
-           PVE::Firewall::clone_vmfw_conf($vmid, $newid);
+               die "clone failed: $err";
+           }
+
+           $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);
 
-           return $rpcenv->fork_worker('vzclone', $vmid, $authuser, $realcmd);
+                   PVE::LXC::Config->move_config_to_node($newid, $target);
+               }
+           });
 
+           return;
        };
 
-       return PVE::LXC::Config->lock_config($vmid, $clonefn);
+       return $rpcenv->fork_worker('vzclone', $vmid, $authuser, $realcmd);
     }});
 
 
@@ -1328,7 +1640,7 @@ __PACKAGE__->register_method({
            disk => {
                type => 'string',
                description => "The disk you want to resize.",
-               enum => [PVE::LXC::Config->mountpoint_names()],
+               enum => [PVE::LXC::Config->valid_volume_keys()],
            },
            size => {
                type => 'string',
@@ -1381,8 +1693,7 @@ __PACKAGE__->register_method({
            my $running = PVE::LXC::check_running($vmid);
 
            my $disk = $param->{disk};
-           my $mp = $disk eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($conf->{$disk}) :
-               PVE::LXC::Config->parse_ct_mountpoint($conf->{$disk});
+           my $mp = PVE::LXC::Config->parse_volume($disk, $conf->{$disk});
 
            my $volid = $mp->{volume};
 
@@ -1402,12 +1713,15 @@ __PACKAGE__->register_method({
            PVE::Storage::activate_volumes($storage_cfg, [$volid]);
 
            my $size = PVE::Storage::volume_size_info($storage_cfg, $volid, 5);
+
+           die "Could not determine current size of volume '$volid'\n" if !defined($size);
+
            $newsize += $size if $ext;
            $newsize = int($newsize);
 
            die "unable to shrink disk size\n" if $newsize < $size;
 
-           return if $size == $newsize;
+           die "disk is already at specified size\n" if $size == $newsize;
 
            PVE::Cluster::log_msg('info', $authuser, "update CT $vmid: resize --disk $disk --size $sizestr");
            my $realcmd = sub {
@@ -1421,7 +1735,9 @@ __PACKAGE__->register_method({
                PVE::LXC::Config->write_config($vmid, $conf);
 
                if ($format eq 'raw') {
-                   my $path = PVE::Storage::path($storage_cfg, $volid, undef);
+                   # we need to ensure that the volume is mapped, if not needed this is a NOP
+                   my $path = PVE::Storage::map_volume($storage_cfg, $volid);
+                   $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
                    if ($running) {
 
                        $mp->{mp} = '/';
@@ -1449,6 +1765,9 @@ __PACKAGE__->register_method({
                            PVE::Tools::run_command(['resize2fs', $path]);
                        };
                        warn "Failed to update the container's filesystem: $@\n" if $@;
+
+                       # always un-map if not running, this is a NOP if not needed
+                       PVE::Storage::unmap_volume($storage_cfg, $volid);
                    }
                }
            };
@@ -1459,4 +1778,228 @@ __PACKAGE__->register_method({
        return PVE::LXC::Config->lock_config($vmid, $code);;
     }});
 
+__PACKAGE__->register_method({
+    name => 'move_volume',
+    path => '{vmid}/move_volume',
+    method => 'POST',
+    protected => 1,
+    proxyto => 'node',
+    description => "Move a rootfs-/mp-volume to a different storage",
+    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' ]],
+       ],
+    },
+    parameters => {
+       additionalProperties => 0,
+       properties => {
+           node => get_standard_option('pve-node'),
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
+           volume => {
+               type => 'string',
+               enum => [ PVE::LXC::Config->valid_volume_keys() ],
+               description => "Volume which will be moved.",
+           },
+           storage => get_standard_option('pve-storage-id', {
+               description => "Target Storage.",
+               completion => \&PVE::Storage::complete_storage_enabled,
+           }),
+           delete => {
+               type => 'boolean',
+               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.',
+               maxLength => 40,
+               optional => 1,
+           },
+           bwlimit => {
+               description => "Override I/O bandwidth limit (in KiB/s).",
+               optional => 1,
+               type => 'number',
+               minimum => '0',
+               default => 'clone limit from datacenter or storage config',
+           },
+       },
+    },
+    returns => {
+       type => 'string',
+    },
+    code => sub {
+       my ($param) = @_;
+
+       my $rpcenv = PVE::RPCEnvironment::get();
+
+       my $authuser = $rpcenv->get_user();
+
+       my $vmid = extract_param($param, 'vmid');
+
+       my $storage = extract_param($param, 'storage');
+
+       my $mpkey = extract_param($param, 'volume');
+
+       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 "cannot move volumes of a running container\n" if PVE::LXC::check_running($vmid);
+
+           $mpdata = PVE::LXC::Config->parse_volume($mpkey, $conf->{$mpkey});
+           $old_volid = $mpdata->{volume};
+
+           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($param->{digest}, $conf->{digest});
+
+           PVE::LXC::Config->set_lock($vmid, $lockname);
+       });
+
+       my $realcmd = sub {
+           eval {
+               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();
+
+               my $new_volid;
+
+               eval {
+                   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);
+                   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);
+                       $mpdata->{volume} = $template_volid;
+                   } else {
+                       $mpdata->{volume} = $new_volid;
+                   }
+
+                   PVE::LXC::Config->lock_config($vmid, sub {
+                       my $digest = $conf->{digest};
+                       $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');
+
+                       PVE::LXC::Config->add_unused_volume($conf, $old_volid) if !$param->{delete};
+
+                       PVE::LXC::Config->write_config($vmid, $conf);
+                   });
+
+                   eval {
+                       # try to deactivate volumes - avoid lvm LVs to be active on several nodes
+                       PVE::Storage::deactivate_volumes($storage_cfg, [ $new_volid ])
+                   };
+                   warn $@ if $@;
+               };
+               if (my $err = $@) {
+                   eval {
+                       PVE::Storage::vdisk_free($storage_cfg, $new_volid)
+                           if defined($new_volid);
+                   };
+                   warn $@ if $@;
+                   die $err;
+               }
+
+               if ($param->{delete}) {
+                   eval {
+                       PVE::Storage::deactivate_volumes($storage_cfg, [ $old_volid ]);
+                       PVE::Storage::vdisk_free($storage_cfg, $old_volid);
+                   };
+                   if (my $err = $@) {
+                       warn $err;
+                       PVE::LXC::Config->lock_config($vmid, sub {
+                           my $conf = PVE::LXC::Config->load_config($vmid);
+                           PVE::LXC::Config->add_unused_volume($conf, $old_volid);
+                           PVE::LXC::Config->write_config($vmid, $conf);
+                       });
+                   }
+               }
+           };
+           my $err = $@;
+           eval { PVE::LXC::Config->remove_lock($vmid, $lockname) };
+           warn $@ if $@;
+           die $err if $err;
+       };
+       my $task = eval {
+           $rpcenv->fork_worker('move_volume', $vmid, $authuser, $realcmd);
+       };
+       if (my $err = $@) {
+           eval { PVE::LXC::Config->remove_lock($vmid, $lockname) };
+           warn $@ if $@;
+           die $err;
+       }
+       return $task;
+  }});
+
+__PACKAGE__->register_method({
+    name => 'vm_pending',
+    path => '{vmid}/pending',
+    method => 'GET',
+    proxyto => 'node',
+    description => 'Get container configuration, including pending changes.',
+    permissions => {
+       check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
+    },
+    parameters => {
+       additionalProperties => 0,
+       properties => {
+           node => get_standard_option('pve-node'),
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
+       },
+    },
+    returns => {
+       type => "array",
+       items => {
+           type => "object",
+           properties => {
+               key => {
+                   description => 'Configuration option name.',
+                   type => 'string',
+               },
+               value => {
+                   description => 'Current value.',
+                   type => 'string',
+                   optional => 1,
+               },
+               pending => {
+                   description => 'Pending value.',
+                   type => 'string',
+                   optional => 1,
+               },
+               delete => {
+                   description => "Indicates a pending delete request if present and not 0.",
+                   type => 'integer',
+                   minimum => 0,
+                   maximum => 2,
+                   optional => 1,
+               },
+           },
+       },
+    },
+    code => sub {
+       my ($param) = @_;
+
+       my $conf = PVE::LXC::Config->load_config($param->{vmid});
+
+       my $pending_delete_hash = PVE::LXC::Config->parse_pending_delete($conf->{pending}->{delete});
+
+       return PVE::GuestHelpers::config_with_pending_array($conf, $pending_delete_hash);
+    }});
+
 1;