]> git.proxmox.com Git - pve-container.git/blobdiff - src/PVE/CLI/pct.pm
pct: add 'remote-migrate' command
[pve-container.git] / src / PVE / CLI / pct.pm
index cdd9e6e92cf9940ae6f0d3b05135eaac16074552..3ade2bac46aa7571625b2a52ebcaadd2eb4cd330 100755 (executable)
@@ -3,24 +3,26 @@ package PVE::CLI::pct;
 use strict;
 use warnings;
 
-use POSIX;
 use Fcntl;
 use File::Copy 'copy';
+use POSIX;
 
-use PVE::GuestHelpers;
-use PVE::SafeSyslog;
-use PVE::Tools qw(extract_param);
-use PVE::CpuSet;
+use PVE::CLIHandler;
 use PVE::Cluster;
+use PVE::CpuSet;
+use PVE::Exception qw(raise_param_exc);
+use PVE::GuestHelpers;
 use PVE::INotify;
-use PVE::RPCEnvironment;
 use PVE::JSONSchema qw(get_standard_option);
-use PVE::CLIHandler;
-use PVE::API2::LXC;
+use PVE::LXC::CGroup;
+use PVE::RPCEnvironment;
+use PVE::SafeSyslog;
+use PVE::Tools qw(extract_param);
+
 use PVE::API2::LXC::Config;
-use PVE::API2::LXC::Status;
 use PVE::API2::LXC::Snapshot;
-use PVE::LXC::CGroup;
+use PVE::API2::LXC::Status;
+use PVE::API2::LXC;
 
 use base qw(PVE::CLIHandler);
 
@@ -29,7 +31,7 @@ my $nodename = PVE::INotify::nodename();
 my $upid_exit = sub {
     my $upid = shift;
     my $status = PVE::Tools::upid_read_status($upid);
-    exit($status eq 'OK' ? 0 : -1);
+    exit(PVE::Tools::upid_status_is_error($status) ? -1 : 0);
 };
 
 sub setup_environment {
@@ -158,10 +160,8 @@ __PACKAGE__->register_method ({
 
        my $vmid = $param->{vmid};
 
-       # test if container exists on this node
-       PVE::LXC::Config->load_config($vmid);
-
-       die "Error: container '$vmid' not running!\n" if !PVE::LXC::check_running($vmid);
+       PVE::LXC::Config->load_config($vmid); # test if container exists on this node
+       die "container '$vmid' not running!\n" if !PVE::LXC::check_running($vmid);
 
        exec('lxc-attach', '-n',  $vmid);
     }});
@@ -182,15 +182,13 @@ __PACKAGE__->register_method ({
     code => sub {
        my ($param) = @_;
 
-       # test if container exists on this node
-       PVE::LXC::Config->load_config($param->{vmid});
+       my $vmid = $param->{vmid};
+       PVE::LXC::Config->load_config($vmid); # test if container exists on this node
+       die "container '$vmid' not running!\n" if !PVE::LXC::check_running($vmid);
 
-       if (!@{$param->{'extra-args'}}) {
-           die "missing command";
-       }
-       die "Error: container '$param->{vmid}' not running!\n" if !PVE::LXC::check_running($param->{vmid});
+       die "missing command" if !@{$param->{'extra-args'}};
 
-       exec('lxc-attach', '-n', $param->{vmid}, '--', @{$param->{'extra-args'}});
+       exec('lxc-attach', '-n', $vmid, '--', @{$param->{'extra-args'}});
     }});
 
 __PACKAGE__->register_method ({
@@ -714,10 +712,10 @@ __PACKAGE__->register_method ({
            my $cgroup = PVE::LXC::CGroup->new($vmid);
 
            my ($cpuset, $path);
-           if (defined($path = $cgroup->get_path('cpuset'))) {
-               $cpuset = eval { PVE::CpuSet->new_from_path($path); };
-           } elsif (defined($path = $cgroup->get_path())) {
-               $cpuset = eval { PVE::CpuSet->new_from_path($path); };
+           if (defined($path = $cgroup->get_path('cpuset', 1))) {
+               $cpuset = eval { PVE::CpuSet->new_from_path($path, 1); };
+           } elsif (defined($path = $cgroup->get_path(undef, 1))) {
+               $cpuset = eval { PVE::CpuSet->new_from_path($path, 1); };
            } else {
                # Container not running.
                next;
@@ -795,7 +793,7 @@ __PACKAGE__->register_method ({
                $path = $mp->{mp};
                return if $param->{'ignore-mountpoints'} && $name =~ /^mp\d+/;
                my $cmd = ["fstrim", "-v", "$rootdir$path"];
-               PVE::Tools::run_command($cmd);
+               PVE::Tools::run_command($cmd, noerr => 1);
            });
        };
        warn $@ if $@;
@@ -806,6 +804,128 @@ __PACKAGE__->register_method ({
        return undef;
     }});
 
+
+__PACKAGE__->register_method({
+    name => 'remote_migrate_vm',
+    path => 'remote_migrate_vm',
+    method => 'POST',
+    description => "Migrate container to a remote cluster. Creates a new migration task. EXPERIMENTAL feature!",
+    permissions => {
+       check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
+    },
+    parameters => {
+       additionalProperties => 0,
+       properties => {
+           node => get_standard_option('pve-node'),
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
+           'target-vmid' => get_standard_option('pve-vmid', { optional => 1 }),
+           'target-endpoint' => get_standard_option('proxmox-remote', {
+               description => "Remote target endpoint",
+           }),
+           online => {
+               type => 'boolean',
+               description => "Use online/live migration.",
+               optional => 1,
+           },
+           restart => {
+               type => 'boolean',
+               description => "Use restart migration",
+               optional => 1,
+           },
+           timeout => {
+               type => 'integer',
+               description => "Timeout in seconds for shutdown for restart migration",
+               optional => 1,
+               default => 180,
+           },
+           delete => {
+               type => 'boolean',
+               description => "Delete the original CT and related data after successful migration. By default the original CT is kept on the source cluster in a stopped state.",
+               optional => 1,
+               default => 0,
+           },
+           'target-storage' => get_standard_option('pve-targetstorage', {
+               completion => \&PVE::QemuServer::complete_migration_storage,
+               optional => 0,
+           }),
+           'target-bridge' => {
+               type => 'string',
+               description => "Mapping from source to target bridges. Providing only a single bridge ID maps all source bridges to that bridge. Providing the special value '1' will map each source bridge to itself.",
+               format => 'bridge-pair-list',
+           },
+           bwlimit => {
+               description => "Override I/O bandwidth limit (in KiB/s).",
+               optional => 1,
+               type => 'integer',
+               minimum => '0',
+               default => 'migrate limit from datacenter or storage config',
+           },
+       },
+    },
+    returns => {
+       type => 'string',
+       description => "the task ID.",
+    },
+    code => sub {
+       my ($param) = @_;
+
+       my $rpcenv = PVE::RPCEnvironment::get();
+       my $authuser = $rpcenv->get_user();
+
+       my $source_vmid = $param->{vmid};
+       my $target_endpoint = $param->{'target-endpoint'};
+       my $target_vmid = $param->{'target-vmid'} // $source_vmid;
+
+       my $remote = PVE::JSONSchema::parse_property_string('proxmox-remote', $target_endpoint);
+
+       # TODO: move this as helper somewhere appropriate?
+       my $conn_args = {
+           protocol => 'https',
+           host => $remote->{host},
+           port => $remote->{port} // 8006,
+           apitoken => $remote->{apitoken},
+       };
+
+       $conn_args->{cached_fingerprints} = { uc($remote->{fingerprint}) => 1 }
+           if defined($remote->{fingerprint});
+
+       my $api_client = PVE::APIClient::LWP->new(%$conn_args);
+       my $resources = $api_client->get("/cluster/resources", { type => 'vm' });
+       if (grep { defined($_->{vmid}) && $_->{vmid} eq $target_vmid } @$resources) {
+           raise_param_exc({ target_vmid => "Guest with ID '$target_vmid' already exists on remote cluster" });
+       }
+
+       my $storages = $api_client->get("/nodes/localhost/storage", { enabled => 1 });
+
+       my $storecfg = PVE::Storage::config();
+       my $target_storage = $param->{'target-storage'};
+       my $storagemap = eval { PVE::JSONSchema::parse_idmap($target_storage, 'pve-storage-id') };
+       raise_param_exc({ 'target-storage' => "failed to parse storage map: $@" })
+           if $@;
+
+       my $check_remote_storage = sub {
+           my ($storage) = @_;
+           my $found = [ grep { $_->{storage} eq $storage } @$storages ];
+           die "remote: storage '$storage' does not exist!\n"
+               if !@$found;
+
+           $found = @$found[0];
+
+           my $content_types = [ PVE::Tools::split_list($found->{content}) ];
+           die "remote: storage '$storage' cannot store CT rootdir\n"
+               if !grep { $_ eq 'rootdir' } @$content_types;
+       };
+
+       foreach my $target_sid (values %{$storagemap->{entries}}) {
+           $check_remote_storage->($target_sid);
+       }
+
+       $check_remote_storage->($storagemap->{default})
+           if $storagemap->{default};
+
+       return PVE::API2::LXC->remote_migrate_vm($param);
+    }});
+
 our $cmddef = {
     list=> [ 'PVE::API2::LXC', 'vmlist', [], { node => $nodename }, sub {
        my $res = shift;
@@ -817,25 +937,22 @@ our $cmddef = {
            printf($format, $d->{vmid}, $d->{status}, $lock, $d->{name});
        }
     }],
-    config => [ "PVE::API2::LXC::Config", 'vm_config', ['vmid'], 
-               { node => $nodename }, sub {
-                   my $config = shift;
-                   foreach my $k (sort (keys %$config)) {
-                       next if $k eq 'digest';
-                       next if $k eq 'lxc';
-                       my $v = $config->{$k};
-                       if ($k eq 'description') {
-                           $v = PVE::Tools::encode_text($v);
-                       }
-                       print "$k: $v\n";
-                   }
-                   if (defined($config->{'lxc'})) {
-                       my $lxc_list = $config->{'lxc'};
-                       foreach my $lxc_opt (@$lxc_list) {
-                           print "$lxc_opt->[0]: $lxc_opt->[1]\n"
-                       }
-                   }
-               }],
+    config => [ "PVE::API2::LXC::Config", 'vm_config', ['vmid'], { node => $nodename }, sub {
+       my $config = shift;
+       for my $k (sort (keys %$config)) {
+           next if $k eq 'digest' || $k eq 'lxc';
+           my $v = $config->{$k};
+           if ($k eq 'description') {
+               $v = PVE::Tools::encode_text($v);
+           }
+           print "$k: $v\n";
+       }
+       if (defined(my $lxc_list = $config->{'lxc'})) {
+           for my $lxc_opt (@$lxc_list) {
+               print "$lxc_opt->[0]: $lxc_opt->[1]\n"
+           }
+       }
+    }],
 
     pending => [ "PVE::API2::LXC", "vm_pending", ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::format_pending ],
     set => [ 'PVE::API2::LXC::Config', 'update_vm', ['vmid'], { node => $nodename }],
@@ -855,7 +972,9 @@ our $cmddef = {
 
     clone => [ "PVE::API2::LXC", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
     migrate => [ "PVE::API2::LXC", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit],
-    move_volume => [ "PVE::API2::LXC", 'move_volume', ['vmid', 'volume', 'storage'], { node => $nodename }, $upid_exit ],
+    'move-volume' => [ "PVE::API2::LXC", 'move_volume', ['vmid', 'volume', 'storage', 'target-vmid', 'target-volume'], { node => $nodename }, $upid_exit ],
+    move_volume => { alias => 'move-volume' },
+    'remote-migrate' => [ __PACKAGE__, 'remote_migrate_vm', ['vmid', 'target-vmid', 'target-endpoint'], { node => $nodename }, $upid_exit ],
 
     snapshot => [ "PVE::API2::LXC::Snapshot", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
     delsnapshot => [ "PVE::API2::LXC::Snapshot", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
@@ -881,5 +1000,4 @@ our $cmddef = {
     fstrim => [ __PACKAGE__, 'fstrim', ['vmid']],
 };
 
-
 1;