]> git.proxmox.com Git - pve-container.git/blame - src/PVE/API2/LXC.pm
fix #3313: restore: keep unprivileged status from archive config
[pve-container.git] / src / PVE / API2 / LXC.pm
CommitLineData
f76a2828
DM
1package PVE::API2::LXC;
2
3use strict;
4use warnings;
5
6use PVE::SafeSyslog;
7use PVE::Tools qw(extract_param run_command);
0620edda 8use PVE::Exception qw(raise raise_param_exc raise_perm_exc);
f76a2828 9use PVE::INotify;
9c2d4ce9 10use PVE::Cluster qw(cfs_read_file);
d949527f 11use PVE::RRD;
8b076579 12use PVE::DataCenterConfig;
f76a2828 13use PVE::AccessControl;
2f9b5ead 14use PVE::Firewall;
f76a2828
DM
15use PVE::Storage;
16use PVE::RESTHandler;
17use PVE::RPCEnvironment;
c5a8e04f 18use PVE::ReplicationConfig;
f76a2828 19use PVE::LXC;
7af97ad5 20use PVE::LXC::Create;
6f42807e 21use PVE::LXC::Migrate;
56462053 22use PVE::GuestHelpers;
c5a09704 23use PVE::VZDump::Plugin;
52389a07
DM
24use PVE::API2::LXC::Config;
25use PVE::API2::LXC::Status;
26use PVE::API2::LXC::Snapshot;
f76a2828
DM
27use PVE::JSONSchema qw(get_standard_option);
28use base qw(PVE::RESTHandler);
29
6c2e9377
WB
30BEGIN {
31 if (!$ENV{PVE_GENERATING_DOCS}) {
32 require PVE::HA::Env::PVE2;
33 import PVE::HA::Env::PVE2;
34 require PVE::HA::Config;
35 import PVE::HA::Config;
36 }
37}
f76a2828 38
52389a07
DM
39__PACKAGE__->register_method ({
40 subclass => "PVE::API2::LXC::Config",
fa91e46f 41 path => '{vmid}/config',
52389a07 42});
f76a2828 43
52389a07
DM
44__PACKAGE__->register_method ({
45 subclass => "PVE::API2::LXC::Status",
46 path => '{vmid}/status',
47});
f76a2828 48
52389a07
DM
49__PACKAGE__->register_method ({
50 subclass => "PVE::API2::LXC::Snapshot",
51 path => '{vmid}/snapshot',
52});
f76a2828 53
52389a07
DM
54__PACKAGE__->register_method ({
55 subclass => "PVE::API2::Firewall::CT",
56 path => '{vmid}/firewall',
57});
1e6c8d5b 58
f76a2828 59__PACKAGE__->register_method({
5c752bbf
DM
60 name => 'vmlist',
61 path => '',
f76a2828
DM
62 method => 'GET',
63 description => "LXC container index (per node).",
64 permissions => {
65 description => "Only list CTs where you have VM.Audit permissons on /vms/<vmid>.",
66 user => 'all',
67 },
68 proxyto => 'node',
69 protected => 1, # /proc files are only readable by root
70 parameters => {
71 additionalProperties => 0,
72 properties => {
73 node => get_standard_option('pve-node'),
74 },
75 },
76 returns => {
77 type => 'array',
78 items => {
79 type => "object",
8233d33d 80 properties => $PVE::LXC::vmstatus_return_properties,
f76a2828
DM
81 },
82 links => [ { rel => 'child', href => "{vmid}" } ],
83 },
84 code => sub {
85 my ($param) = @_;
86
87 my $rpcenv = PVE::RPCEnvironment::get();
88 my $authuser = $rpcenv->get_user();
89
90 my $vmstatus = PVE::LXC::vmstatus();
91
92 my $res = [];
93 foreach my $vmid (keys %$vmstatus) {
94 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
95
96 my $data = $vmstatus->{$vmid};
f76a2828
DM
97 push @$res, $data;
98 }
99
100 return $res;
5c752bbf 101
f76a2828
DM
102 }});
103
9c2d4ce9 104__PACKAGE__->register_method({
5c752bbf
DM
105 name => 'create_vm',
106 path => '',
9c2d4ce9
DM
107 method => 'POST',
108 description => "Create or restore a container.",
109 permissions => {
110 user => 'all', # check inside
111 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. " .
112 "For restore, it is enough if the user has 'VM.Backup' permission and the VM already exists. " .
113 "You also need 'Datastore.AllocateSpace' permissions on the storage.",
114 },
115 protected => 1,
116 proxyto => 'node',
117 parameters => {
118 additionalProperties => 0,
1b4cf758 119 properties => PVE::LXC::Config->json_config_properties({
9c2d4ce9 120 node => get_standard_option('pve-node'),
781e26b2 121 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
9c2d4ce9
DM
122 ostemplate => {
123 description => "The OS template or backup file.",
5c752bbf 124 type => 'string',
9c2d4ce9 125 maxLength => 255,
68e8f3c5 126 completion => \&PVE::LXC::complete_os_templates,
9c2d4ce9 127 },
5c752bbf
DM
128 password => {
129 optional => 1,
9c2d4ce9
DM
130 type => 'string',
131 description => "Sets root password inside container.",
168d6b07 132 minLength => 5,
9c2d4ce9
DM
133 },
134 storage => get_standard_option('pve-storage-id', {
eb35f9c0 135 description => "Default Storage.",
9c2d4ce9
DM
136 default => 'local',
137 optional => 1,
c5362cda 138 completion => \&PVE::Storage::complete_storage_enabled,
9c2d4ce9
DM
139 }),
140 force => {
5c752bbf 141 optional => 1,
9c2d4ce9
DM
142 type => 'boolean',
143 description => "Allow to overwrite existing container.",
144 },
145 restore => {
5c752bbf 146 optional => 1,
9c2d4ce9
DM
147 type => 'boolean',
148 description => "Mark this as restore task.",
149 },
43912111
CE
150 unique => {
151 optional => 1,
152 type => 'boolean',
153 description => "Assign a unique random ethernet address.",
154 requires => 'restore',
155 },
5c752bbf 156 pool => {
9c2d4ce9
DM
157 optional => 1,
158 type => 'string', format => 'pve-poolid',
159 description => "Add the VM to the specified pool.",
160 },
7c78b6cc
WB
161 'ignore-unpack-errors' => {
162 optional => 1,
163 type => 'boolean',
164 description => "Ignore errors when extracting the template.",
165 },
34ddbf08
FG
166 'ssh-public-keys' => {
167 optional => 1,
168 type => 'string',
169 description => "Setup public SSH keys (one key per line, " .
170 "OpenSSH format).",
171 },
f9b4407e 172 bwlimit => {
8ead60ef 173 description => "Override I/O bandwidth limit (in KiB/s).",
f9b4407e
WB
174 optional => 1,
175 type => 'number',
176 minimum => '0',
41e9b65c 177 default => 'restore limit from datacenter or storage config',
f9b4407e 178 },
9d0225fb
TL
179 start => {
180 optional => 1,
181 type => 'boolean',
182 default => 0,
183 description => "Start the CT after its creation finished successfully.",
184 },
9c2d4ce9
DM
185 }),
186 },
5c752bbf 187 returns => {
9c2d4ce9
DM
188 type => 'string',
189 },
190 code => sub {
191 my ($param) = @_;
192
61783321
TL
193 PVE::Cluster::check_cfs_quorum();
194
9c2d4ce9 195 my $rpcenv = PVE::RPCEnvironment::get();
9c2d4ce9
DM
196 my $authuser = $rpcenv->get_user();
197
198 my $node = extract_param($param, 'node');
9c2d4ce9 199 my $vmid = extract_param($param, 'vmid');
7c78b6cc 200 my $ignore_unpack_errors = extract_param($param, 'ignore-unpack-errors');
f9b4407e 201 my $bwlimit = extract_param($param, 'bwlimit');
9d0225fb
TL
202 my $start_after_create = extract_param($param, 'start');
203
67afe46e 204 my $basecfg_fn = PVE::LXC::Config->config_file($vmid);
9c2d4ce9
DM
205 my $same_container_exists = -f $basecfg_fn;
206
425b62cb
WB
207 # 'unprivileged' is read-only, so we can't pass it to update_pct_config
208 my $unprivileged = extract_param($param, 'unprivileged');
9c2d4ce9 209 my $restore = extract_param($param, 'restore');
43912111 210 my $unique = extract_param($param, 'unique');
9c2d4ce9 211
39170644
FG
212 # used to skip firewall config restore if user lacks permission
213 my $skip_fw_config_restore = 0;
214
148d1cb4
DM
215 if ($restore) {
216 # fixme: limit allowed parameters
148d1cb4 217 }
351bc0c4 218
9c2d4ce9
DM
219 my $force = extract_param($param, 'force');
220
221 if (!($same_container_exists && $restore && $force)) {
222 PVE::Cluster::check_vmid_unused($vmid);
e22af68f 223 } else {
61783321 224 die "can't overwrite running container\n" if PVE::LXC::check_running($vmid);
67afe46e
FG
225 my $conf = PVE::LXC::Config->load_config($vmid);
226 PVE::LXC::Config->check_protection($conf, "unable to restore CT $vmid");
9c2d4ce9 227 }
5c752bbf 228
9c2d4ce9 229 my $password = extract_param($param, 'password');
34ddbf08 230 my $ssh_keys = extract_param($param, 'ssh-public-keys');
2130286f 231 PVE::Tools::validate_ssh_public_keys($ssh_keys) if defined($ssh_keys);
34ddbf08 232
27916659 233 my $pool = extract_param($param, 'pool');
9c2d4ce9
DM
234 if (defined($pool)) {
235 $rpcenv->check_pool_exist($pool);
236 $rpcenv->check_perm_modify($authuser, "/pool/$pool");
5c752bbf 237 }
9c2d4ce9
DM
238
239 if ($rpcenv->check($authuser, "/vms/$vmid", ['VM.Allocate'], 1)) {
240 # OK
241 } elsif ($pool && $rpcenv->check($authuser, "/pool/$pool", ['VM.Allocate'], 1)) {
242 # OK
243 } elsif ($restore && $force && $same_container_exists &&
244 $rpcenv->check($authuser, "/vms/$vmid", ['VM.Backup'], 1)) {
245 # OK: user has VM.Backup permissions, and want to restore an existing VM
39170644
FG
246
247 # we don't want to restore a container-provided FW conf in this case
248 # since the user is lacking permission to configure the container's FW
249 $skip_fw_config_restore = 1;
9c2d4ce9
DM
250 } else {
251 raise_perm_exc();
252 }
253
9eb69152 254 my $ostemplate = extract_param($param, 'ostemplate');
bb6afcb0
DM
255 my $storage = extract_param($param, 'storage') // 'local';
256
9eb69152
FG
257 PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, $pool, $param, []);
258
bb6afcb0 259 my $storage_cfg = cfs_read_file("storage.cfg");
9c2d4ce9 260
9c2d4ce9 261 my $archive;
9c2d4ce9 262 if ($ostemplate eq '-') {
351bc0c4
TM
263 die "pipe requires cli environment\n"
264 if $rpcenv->{type} ne 'cli';
265 die "pipe can only be used with restore tasks\n"
148d1cb4
DM
266 if !$restore;
267 $archive = '-';
b51a98d4 268 die "restore from pipe requires rootfs parameter\n" if !defined($param->{rootfs});
9c2d4ce9 269 } else {
f26c66e0 270 PVE::Storage::check_volume_access($rpcenv, $authuser, $storage_cfg, $vmid, $ostemplate);
99a0bcb0 271 $archive = $ostemplate;
9c2d4ce9
DM
272 }
273
f9b4407e 274 my %used_storages;
bb6afcb0
DM
275 my $check_and_activate_storage = sub {
276 my ($sid) = @_;
277
278 my $scfg = PVE::Storage::storage_check_node($storage_cfg, $sid, $node);
279
280 raise_param_exc({ storage => "storage '$sid' does not support container directories"})
281 if !$scfg->{content}->{rootdir};
282
283 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
284
285 PVE::Storage::activate_storage($storage_cfg, $sid);
f9b4407e 286 $used_storages{$sid} = 1;
bb6afcb0
DM
287 };
288
9c2d4ce9 289 my $conf = {};
5b4657d0 290
99132ce0
WB
291 my $is_root = $authuser eq 'root@pam';
292
b51a98d4 293 my $no_disk_param = {};
db18c1e4
FG
294 my $mp_param = {};
295 my $storage_only_mode = 1;
b51a98d4 296 foreach my $opt (keys %$param) {
78ccc99b
DM
297 my $value = $param->{$opt};
298 if ($opt eq 'rootfs' || $opt =~ m/^mp\d+$/) {
299 # allow to use simple numbers (add default storage in that case)
db18c1e4
FG
300 if ($value =~ m/^\d+(\.\d+)?$/) {
301 $mp_param->{$opt} = "$storage:$value";
302 } else {
303 $mp_param->{$opt} = $value;
304 }
305 $storage_only_mode = 0;
a9dd8015
FG
306 } elsif ($opt =~ m/^unused\d+$/) {
307 warn "ignoring '$opt', cannot create/restore with unused volume\n";
308 delete $param->{$opt};
78ccc99b
DM
309 } else {
310 $no_disk_param->{$opt} = $value;
311 }
b51a98d4 312 }
bb6afcb0 313
235dbdf3 314 die "mount points configured, but 'rootfs' not set - aborting\n"
db18c1e4
FG
315 if !$storage_only_mode && !defined($mp_param->{rootfs});
316
bb6afcb0 317 # check storage access, activate storage
db18c1e4 318 my $delayed_mp_param = {};
015740e6 319 PVE::LXC::Config->foreach_volume($mp_param, sub {
bb6afcb0
DM
320 my ($ms, $mountpoint) = @_;
321
322 my $volid = $mountpoint->{volume};
323 my $mp = $mountpoint->{mp};
324
e2007ac2
DM
325 if ($mountpoint->{type} ne 'volume') { # bind or device
326 die "Only root can pass arbitrary filesystem paths.\n"
99132ce0 327 if !$is_root;
e2007ac2
DM
328 } else {
329 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
330 &$check_and_activate_storage($sid);
331 }
bb6afcb0
DM
332 });
333
334 # check/activate default storage
db18c1e4 335 &$check_and_activate_storage($storage) if !defined($mp_param->{rootfs});
bb6afcb0 336
1b4cf758 337 PVE::LXC::Config->update_pct_config($vmid, $conf, 0, $no_disk_param);
9c2d4ce9 338
425b62cb
WB
339 $conf->{unprivileged} = 1 if $unprivileged;
340
61783321 341 my $emsg = $restore ? "unable to restore CT $vmid -" : "unable to create CT $vmid -";
bccaa371 342
61783321
TL
343 eval { PVE::LXC::Config->create_and_lock_config($vmid, $force) };
344 die "$emsg $@" if $@;
bccaa371 345
61783321
TL
346 my $code = sub {
347 my $old_conf = PVE::LXC::Config->load_config($vmid);
a2d3e5c3 348 my $was_template;
bccaa371 349
eb35f9c0 350 my $vollist = [];
27916659 351 eval {
5a7a51d0
WB
352 my $orig_mp_param; # only used if $restore
353 if ($restore) {
61783321 354 die "can't overwrite running container\n" if PVE::LXC::check_running($vmid);
32e56bed 355 if ($archive ne '-') {
a48e5562 356 my $orig_conf;
bc871ffb 357 print "recovering backed-up configuration from '$archive'\n";
12aec1d2 358 ($orig_conf, $orig_mp_param) = PVE::LXC::Create::recover_config($storage_cfg, $archive, $vmid);
a2d3e5c3 359 $was_template = delete $orig_conf->{template};
a67908f1 360 # When we're root call 'restore_configuration' with restricted=0,
5a7a51d0
WB
361 # causing it to restore the raw lxc entries, among which there may be
362 # 'lxc.idmap' entries. We need to make sure that the extracted contents
363 # of the container match up with the restored configuration afterwards:
32e56bed 364 $conf->{lxc} = $orig_conf->{lxc} if $is_root;
8ffdc116
OB
365
366 $conf->{unprivileged} = $orig_conf->{unprivileged}
367 if !defined($unprivileged) && defined($orig_conf->{unprivileged});
5a7a51d0 368 }
f360d7f1 369 }
db18c1e4 370 if ($storage_only_mode) {
b51a98d4 371 if ($restore) {
a48e5562 372 if (!defined($orig_mp_param)) {
bc871ffb 373 print "recovering backed-up configuration from '$archive'\n";
12aec1d2 374 (undef, $orig_mp_param) = PVE::LXC::Create::recover_config($storage_cfg, $archive, $vmid);
a5246958 375 }
f360d7f1 376 $mp_param = $orig_mp_param;
db18c1e4
FG
377 die "rootfs configuration could not be recovered, please check and specify manually!\n"
378 if !defined($mp_param->{rootfs});
015740e6 379 PVE::LXC::Config->foreach_volume($mp_param, sub {
db18c1e4
FG
380 my ($ms, $mountpoint) = @_;
381 my $type = $mountpoint->{type};
382 if ($type eq 'volume') {
383 die "unable to detect disk size - please specify $ms (size)\n"
384 if !defined($mountpoint->{size});
385 my $disksize = $mountpoint->{size} / (1024 * 1024 * 1024); # create_disks expects GB as unit size
386 delete $mountpoint->{size};
387 $mountpoint->{volume} = "$storage:$disksize";
388 $mp_param->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
389 } else {
15e4d443 390 my $type = $mountpoint->{type};
7e0e7f38
FG
391 die "restoring rootfs to $type mount is only possible by specifying -rootfs manually!\n"
392 if ($ms eq 'rootfs');
20f9339d 393 die "restoring '$ms' to $type mount is only possible for root\n"
99132ce0 394 if !$is_root;
7e0e7f38 395
15e4d443
FG
396 if ($mountpoint->{backup}) {
397 warn "WARNING - unsupported configuration!\n";
235dbdf3
FG
398 warn "backup was enabled for $type mount point $ms ('$mountpoint->{mp}')\n";
399 warn "mount point configuration will be restored after archive extraction!\n";
15e4d443
FG
400 warn "contained files will be restored to wrong directory!\n";
401 }
136040f4 402 delete $mp_param->{$ms}; # actually delay bind/dev mps
db18c1e4
FG
403 $delayed_mp_param->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
404 }
405 });
b51a98d4 406 } else {
db18c1e4 407 $mp_param->{rootfs} = "$storage:4"; # defaults to 4GB
b51a98d4
DM
408 }
409 }
410
db18c1e4
FG
411 $vollist = PVE::LXC::create_disks($storage_cfg, $vmid, $mp_param, $conf);
412
61783321
TL
413 # we always have the 'create' lock so check for more than 1 entry
414 if (scalar(keys %$old_conf) > 1) {
51665c2d 415 # destroy old container volumes
61783321 416 PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $old_conf, { lock => 'create' });
51665c2d 417 }
51665c2d
FG
418
419 eval {
420 my $rootdir = PVE::LXC::mount_all($vmid, $storage_cfg, $conf, 1);
f9b4407e 421 $bwlimit = PVE::Storage::get_bandwidth_limit('restore', [keys %used_storages], $bwlimit);
bc871ffb
FG
422 print "restoring '$archive' now..\n"
423 if $restore && $archive ne '-';
99a0bcb0 424 PVE::LXC::Create::restore_archive($storage_cfg, $archive, $rootdir, $conf, $ignore_unpack_errors, $bwlimit);
51665c2d
FG
425
426 if ($restore) {
bc871ffb 427 print "merging backed-up and given configuration..\n";
99a0bcb0 428 PVE::LXC::Create::restore_configuration($vmid, $storage_cfg, $archive, $rootdir, $conf, !$is_root, $unique, $skip_fw_config_restore);
4b4bbe55
OB
429 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
430 $lxc_setup->template_fixup($conf);
51665c2d
FG
431 } else {
432 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir); # detect OS
433 PVE::LXC::Config->write_config($vmid, $conf); # safe config (after OS detection)
434 $lxc_setup->post_create_hook($password, $ssh_keys);
435 }
436 };
437 my $err = $@;
438 PVE::LXC::umount_all($vmid, $storage_cfg, $conf, $err ? 1 : 0);
439 PVE::Storage::deactivate_volumes($storage_cfg, PVE::LXC::Config->get_vm_volumes($conf));
440 die $err if $err;
27916659
DM
441 # set some defaults
442 $conf->{hostname} ||= "CT$vmid";
443 $conf->{memory} ||= 512;
444 $conf->{swap} //= 512;
db18c1e4
FG
445 foreach my $mp (keys %$delayed_mp_param) {
446 $conf->{$mp} = $delayed_mp_param->{$mp};
447 }
a2d3e5c3
CE
448 # If the template flag was set, we try to convert again to template after restore
449 if ($was_template) {
450 print STDERR "Convert restored container to template...\n";
4c64d0db
FE
451 PVE::LXC::template_create($vmid, $conf);
452 $conf->{template} = 1;
a2d3e5c3 453 }
67afe46e 454 PVE::LXC::Config->write_config($vmid, $conf);
27916659
DM
455 };
456 if (my $err = $@) {
6c871c36 457 PVE::LXC::destroy_disks($storage_cfg, $vollist);
4eeb9af1 458 eval { PVE::LXC::Config->destroy_config($vmid) };
d7d48be6 459 warn $@ if $@;
61783321 460 die "$emsg $err";
6d098bf4 461 }
87273b2b 462 PVE::AccessControl::add_vm_to_pool($vmid, $pool) if $pool;
9d0225fb
TL
463
464 PVE::API2::LXC::Status->vm_start({ vmid => $vmid, node => $node })
465 if $start_after_create;
9c2d4ce9 466 };
5c752bbf 467
8a6fc617 468 my $workername = $restore ? 'vzrestore' : 'vzcreate';
67afe46e 469 my $realcmd = sub { PVE::LXC::Config->lock_config($vmid, $code); };
9c2d4ce9 470
8a6fc617 471 return $rpcenv->fork_worker($workername, $vmid, $authuser, $realcmd);
9c2d4ce9
DM
472 }});
473
f76a2828
DM
474__PACKAGE__->register_method({
475 name => 'vmdiridx',
5c752bbf 476 path => '{vmid}',
f76a2828
DM
477 method => 'GET',
478 proxyto => 'node',
479 description => "Directory index",
480 permissions => {
481 user => 'all',
482 },
483 parameters => {
484 additionalProperties => 0,
485 properties => {
486 node => get_standard_option('pve-node'),
487 vmid => get_standard_option('pve-vmid'),
488 },
489 },
490 returns => {
491 type => 'array',
492 items => {
493 type => "object",
494 properties => {
495 subdir => { type => 'string' },
496 },
497 },
498 links => [ { rel => 'child', href => "{subdir}" } ],
499 },
500 code => sub {
501 my ($param) = @_;
502
503 # test if VM exists
67afe46e 504 my $conf = PVE::LXC::Config->load_config($param->{vmid});
f76a2828
DM
505
506 my $res = [
507 { subdir => 'config' },
37c2dba8 508 { subdir => 'pending' },
fff3a342
DM
509 { subdir => 'status' },
510 { subdir => 'vncproxy' },
a0226a00 511 { subdir => 'termproxy' },
fff3a342
DM
512 { subdir => 'vncwebsocket' },
513 { subdir => 'spiceproxy' },
514 { subdir => 'migrate' },
c4a33727 515 { subdir => 'clone' },
f76a2828
DM
516# { subdir => 'initlog' },
517 { subdir => 'rrd' },
518 { subdir => 'rrddata' },
519 { subdir => 'firewall' },
cc5392c8 520 { subdir => 'snapshot' },
985b18ed 521 { subdir => 'resize' },
f76a2828 522 ];
5c752bbf 523
f76a2828
DM
524 return $res;
525 }});
526
c4a33727 527
f76a2828 528__PACKAGE__->register_method({
5c752bbf
DM
529 name => 'rrd',
530 path => '{vmid}/rrd',
f76a2828
DM
531 method => 'GET',
532 protected => 1, # fixme: can we avoid that?
533 permissions => {
534 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
535 },
536 description => "Read VM RRD statistics (returns PNG)",
537 parameters => {
538 additionalProperties => 0,
539 properties => {
540 node => get_standard_option('pve-node'),
541 vmid => get_standard_option('pve-vmid'),
542 timeframe => {
543 description => "Specify the time frame you are interested in.",
544 type => 'string',
545 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
546 },
547 ds => {
548 description => "The list of datasources you want to display.",
549 type => 'string', format => 'pve-configid-list',
550 },
551 cf => {
552 description => "The RRD consolidation function",
553 type => 'string',
554 enum => [ 'AVERAGE', 'MAX' ],
555 optional => 1,
556 },
557 },
558 },
559 returns => {
560 type => "object",
561 properties => {
562 filename => { type => 'string' },
563 },
564 },
565 code => sub {
566 my ($param) = @_;
567
d949527f 568 return PVE::RRD::create_rrd_graph(
5c752bbf 569 "pve2-vm/$param->{vmid}", $param->{timeframe},
f76a2828 570 $param->{ds}, $param->{cf});
5c752bbf 571
f76a2828
DM
572 }});
573
574__PACKAGE__->register_method({
5c752bbf
DM
575 name => 'rrddata',
576 path => '{vmid}/rrddata',
f76a2828
DM
577 method => 'GET',
578 protected => 1, # fixme: can we avoid that?
579 permissions => {
580 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
581 },
582 description => "Read VM RRD statistics",
583 parameters => {
584 additionalProperties => 0,
585 properties => {
586 node => get_standard_option('pve-node'),
587 vmid => get_standard_option('pve-vmid'),
588 timeframe => {
589 description => "Specify the time frame you are interested in.",
590 type => 'string',
591 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
592 },
593 cf => {
594 description => "The RRD consolidation function",
595 type => 'string',
596 enum => [ 'AVERAGE', 'MAX' ],
597 optional => 1,
598 },
599 },
600 },
601 returns => {
602 type => "array",
603 items => {
604 type => "object",
605 properties => {},
606 },
607 },
608 code => sub {
609 my ($param) = @_;
610
d949527f 611 return PVE::RRD::create_rrd_data(
f76a2828
DM
612 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
613 }});
614
f76a2828 615__PACKAGE__->register_method({
5c752bbf
DM
616 name => 'destroy_vm',
617 path => '{vmid}',
f76a2828
DM
618 method => 'DELETE',
619 protected => 1,
620 proxyto => 'node',
621 description => "Destroy the container (also delete all uses files).",
622 permissions => {
623 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
624 },
625 parameters => {
626 additionalProperties => 0,
627 properties => {
628 node => get_standard_option('pve-node'),
68e8f3c5 629 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
d51b84ff
TL
630 force => {
631 type => 'boolean',
632 description => "Force destroy, even if running.",
633 default => 0,
634 optional => 1,
635 },
c5a09704
CE
636 purge => {
637 type => 'boolean',
796e8eee
TL
638 description => "Remove container from all related configurations."
639 ." For example, backup jobs, replication jobs or HA."
640 ." Related ACLs and Firewall entries will *always* be removed.",
641 default => 0,
c5a09704
CE
642 optional => 1,
643 },
3b1c0970
TL
644 'destroy-unreferenced-disks' => {
645 type => 'boolean',
646 description => "If set, destroy additionally all disks with the VMID from all"
647 ." enabled storages which are not referenced in the config.",
648 optional => 1,
649 },
f76a2828
DM
650 },
651 },
5c752bbf 652 returns => {
f76a2828
DM
653 type => 'string',
654 },
655 code => sub {
656 my ($param) = @_;
657
658 my $rpcenv = PVE::RPCEnvironment::get();
f76a2828 659 my $authuser = $rpcenv->get_user();
f76a2828
DM
660 my $vmid = $param->{vmid};
661
662 # test if container exists
0512c360 663
67afe46e 664 my $conf = PVE::LXC::Config->load_config($vmid);
0512c360
FG
665 my $early_checks = sub {
666 my ($conf) = @_;
667 PVE::LXC::Config->check_protection($conf, "can't remove CT $vmid");
668 PVE::LXC::Config->check_lock($conf);
7e806596 669
0512c360 670 my $ha_managed = PVE::HA::Config::service_is_configured("ct:$vmid");
b6e0b774 671
0512c360
FG
672 if (!$param->{purge}) {
673 die "unable to remove CT $vmid - used in HA resources and purge parameter not set.\n"
674 if $ha_managed;
3207b81a 675
0512c360
FG
676 # do not allow destroy if there are replication jobs without purge
677 my $repl_conf = PVE::ReplicationConfig->new();
678 $repl_conf->check_for_existing_jobs($vmid);
679 }
680
681 return $ha_managed;
682 };
683
684 $early_checks->($conf);
c5a8e04f 685
d607c17d 686 my $running_error_msg = "unable to destroy CT $vmid - container is running\n";
d51b84ff 687 die $running_error_msg if !$param->{force} && PVE::LXC::check_running($vmid); # check early
d607c17d 688
611fe3aa 689 my $code = sub {
673cf209 690 # reload config after lock
67afe46e 691 $conf = PVE::LXC::Config->load_config($vmid);
0512c360 692 my $ha_managed = $early_checks->($conf);
673cf209 693
d51b84ff
TL
694 if (PVE::LXC::check_running($vmid)) {
695 die $running_error_msg if !$param->{force};
696 warn "forced to stop CT $vmid before destroying!\n";
697 if (!$ha_managed) {
698 PVE::LXC::vm_stop($vmid, 1);
699 } else {
700 run_command(['ha-manager', 'crm-command', 'stop', "ct:$vmid", '120']);
701 }
702 }
d607c17d 703
0512c360 704 my $storage_cfg = cfs_read_file("storage.cfg");
3b1c0970
TL
705 PVE::LXC::destroy_lxc_container(
706 $storage_cfg,
707 $vmid,
708 $conf,
709 { lock => 'destroyed' },
710 $param->{'destroy-unreferenced-disks'},
711 );
7fc1d9eb 712
be5fc936 713 PVE::AccessControl::remove_vm_access($vmid);
2f9b5ead 714 PVE::Firewall::remove_vmfw_conf($vmid);
c5a09704 715 if ($param->{purge}) {
3207b81a 716 print "purging CT $vmid from related configurations..\n";
c5a09704
CE
717 PVE::ReplicationConfig::remove_vmid_jobs($vmid);
718 PVE::VZDump::Plugin::remove_vmid_from_backup_jobs($vmid);
3207b81a
TL
719
720 if ($ha_managed) {
721 PVE::HA::Config::delete_service_from_config("ct:$vmid");
722 print "NOTE: removed CT $vmid from HA resource configuration.\n";
723 }
c5a09704 724 }
7fc1d9eb
TL
725
726 # only now remove the zombie config, else we can have reuse race
727 PVE::LXC::Config->destroy_config($vmid);
f76a2828
DM
728 };
729
67afe46e 730 my $realcmd = sub { PVE::LXC::Config->lock_config($vmid, $code); };
351bc0c4 731
f76a2828
DM
732 return $rpcenv->fork_worker('vzdestroy', $vmid, $authuser, $realcmd);
733 }});
734
fff3a342
DM
735my $sslcert;
736
737__PACKAGE__->register_method ({
5b4657d0
DM
738 name => 'vncproxy',
739 path => '{vmid}/vncproxy',
fff3a342
DM
740 method => 'POST',
741 protected => 1,
742 permissions => {
743 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
744 },
745 description => "Creates a TCP VNC proxy connections.",
746 parameters => {
747 additionalProperties => 0,
748 properties => {
749 node => get_standard_option('pve-node'),
750 vmid => get_standard_option('pve-vmid'),
751 websocket => {
752 optional => 1,
753 type => 'boolean',
754 description => "use websocket instead of standard VNC.",
755 },
bd0f4d6d
DC
756 width => {
757 optional => 1,
758 description => "sets the width of the console in pixels.",
759 type => 'integer',
760 minimum => 16,
761 maximum => 4096,
762 },
763 height => {
764 optional => 1,
765 description => "sets the height of the console in pixels.",
766 type => 'integer',
767 minimum => 16,
768 maximum => 2160,
769 },
fff3a342
DM
770 },
771 },
5b4657d0 772 returns => {
fff3a342
DM
773 additionalProperties => 0,
774 properties => {
775 user => { type => 'string' },
776 ticket => { type => 'string' },
777 cert => { type => 'string' },
778 port => { type => 'integer' },
779 upid => { type => 'string' },
780 },
781 },
782 code => sub {
783 my ($param) = @_;
784
785 my $rpcenv = PVE::RPCEnvironment::get();
786
787 my $authuser = $rpcenv->get_user();
788
789 my $vmid = $param->{vmid};
790 my $node = $param->{node};
791
792 my $authpath = "/vms/$vmid";
793
794 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
795
796 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
797 if !$sslcert;
798
ec2c57eb 799 my ($remip, $family);
5b4657d0 800
fff3a342 801 if ($node ne PVE::INotify::nodename()) {
85ae6211 802 ($remip, $family) = PVE::Cluster::remote_node_ip($node);
ec2c57eb
WB
803 } else {
804 $family = PVE::Tools::get_host_address_family($node);
fff3a342
DM
805 }
806
ec2c57eb
WB
807 my $port = PVE::Tools::next_vnc_port($family);
808
fff3a342
DM
809 # NOTE: vncterm VNC traffic is already TLS encrypted,
810 # so we select the fastest chipher here (or 'none'?)
5b4657d0 811 my $remcmd = $remip ?
806eae70 812 ['/usr/bin/ssh', '-e', 'none', '-t', $remip] : [];
fff3a342 813
67afe46e 814 my $conf = PVE::LXC::Config->load_config($vmid, $node);
65213b67 815 my $concmd = PVE::LXC::get_console_command($vmid, $conf, -1);
aca816ad 816
5b4657d0
DM
817 my $shcmd = [ '/usr/bin/dtach', '-A',
818 "/var/run/dtach/vzctlconsole$vmid",
aca816ad 819 '-r', 'winch', '-z', @$concmd];
fff3a342
DM
820
821 my $realcmd = sub {
822 my $upid = shift;
823
5b4657d0 824 syslog ('info', "starting lxc vnc proxy $upid\n");
fff3a342 825
5b4657d0 826 my $timeout = 10;
fff3a342
DM
827
828 my $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
5b4657d0 829 '-timeout', $timeout, '-authpath', $authpath,
fff3a342
DM
830 '-perm', 'VM.Console'];
831
bd0f4d6d
DC
832 if ($param->{width}) {
833 push @$cmd, '-width', $param->{width};
834 }
835
836 if ($param->{height}) {
837 push @$cmd, '-height', $param->{height};
838 }
839
fff3a342 840 if ($param->{websocket}) {
5b4657d0 841 $ENV{PVE_VNC_TICKET} = $ticket; # pass ticket to vncterm
fff3a342
DM
842 push @$cmd, '-notls', '-listen', 'localhost';
843 }
844
845 push @$cmd, '-c', @$remcmd, @$shcmd;
846
37634d3d 847 run_command($cmd, keeplocale => 1);
fff3a342
DM
848
849 return;
850 };
851
852 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
853
854 PVE::Tools::wait_for_vnc_port($port);
855
856 return {
857 user => $authuser,
858 ticket => $ticket,
5b4657d0
DM
859 port => $port,
860 upid => $upid,
861 cert => $sslcert,
fff3a342
DM
862 };
863 }});
864
a0226a00
DC
865__PACKAGE__->register_method ({
866 name => 'termproxy',
867 path => '{vmid}/termproxy',
868 method => 'POST',
869 protected => 1,
870 permissions => {
871 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
872 },
873 description => "Creates a TCP proxy connection.",
874 parameters => {
875 additionalProperties => 0,
876 properties => {
877 node => get_standard_option('pve-node'),
878 vmid => get_standard_option('pve-vmid'),
879 },
880 },
881 returns => {
882 additionalProperties => 0,
883 properties => {
884 user => { type => 'string' },
885 ticket => { type => 'string' },
886 port => { type => 'integer' },
887 upid => { type => 'string' },
888 },
889 },
890 code => sub {
891 my ($param) = @_;
892
893 my $rpcenv = PVE::RPCEnvironment::get();
894
895 my $authuser = $rpcenv->get_user();
896
897 my $vmid = $param->{vmid};
898 my $node = $param->{node};
899
900 my $authpath = "/vms/$vmid";
901
902 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
903
904 my ($remip, $family);
905
906 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
907 ($remip, $family) = PVE::Cluster::remote_node_ip($node);
908 } else {
909 $family = PVE::Tools::get_host_address_family($node);
910 }
911
912 my $port = PVE::Tools::next_vnc_port($family);
913
914 my $remcmd = $remip ?
915 ['/usr/bin/ssh', '-e', 'none', '-t', $remip, '--'] : [];
916
917 my $conf = PVE::LXC::Config->load_config($vmid, $node);
65213b67 918 my $concmd = PVE::LXC::get_console_command($vmid, $conf, -1);
a0226a00
DC
919
920 my $shcmd = [ '/usr/bin/dtach', '-A',
921 "/var/run/dtach/vzctlconsole$vmid",
922 '-r', 'winch', '-z', @$concmd];
923
924 my $realcmd = sub {
925 my $upid = shift;
926
927 syslog ('info', "starting lxc termproxy $upid\n");
928
929 my $cmd = ['/usr/bin/termproxy', $port, '--path', $authpath,
930 '--perm', 'VM.Console', '--'];
931 push @$cmd, @$remcmd, @$shcmd;
932
933 PVE::Tools::run_command($cmd);
934 };
935
936 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd, 1);
937
938 PVE::Tools::wait_for_vnc_port($port);
939
940 return {
941 user => $authuser,
942 ticket => $ticket,
943 port => $port,
944 upid => $upid,
945 };
946 }});
947
fff3a342
DM
948__PACKAGE__->register_method({
949 name => 'vncwebsocket',
950 path => '{vmid}/vncwebsocket',
951 method => 'GET',
5b4657d0 952 permissions => {
fff3a342
DM
953 description => "You also need to pass a valid ticket (vncticket).",
954 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
955 },
956 description => "Opens a weksocket for VNC traffic.",
957 parameters => {
958 additionalProperties => 0,
959 properties => {
960 node => get_standard_option('pve-node'),
961 vmid => get_standard_option('pve-vmid'),
962 vncticket => {
963 description => "Ticket from previous call to vncproxy.",
964 type => 'string',
965 maxLength => 512,
966 },
967 port => {
968 description => "Port number returned by previous vncproxy call.",
969 type => 'integer',
970 minimum => 5900,
971 maximum => 5999,
972 },
973 },
974 },
975 returns => {
976 type => "object",
977 properties => {
978 port => { type => 'string' },
979 },
980 },
981 code => sub {
982 my ($param) = @_;
983
984 my $rpcenv = PVE::RPCEnvironment::get();
985
986 my $authuser = $rpcenv->get_user();
987
988 my $authpath = "/vms/$param->{vmid}";
989
990 PVE::AccessControl::verify_vnc_ticket($param->{vncticket}, $authuser, $authpath);
991
992 my $port = $param->{port};
5b4657d0 993
fff3a342
DM
994 return { port => $port };
995 }});
996
997__PACKAGE__->register_method ({
5b4657d0
DM
998 name => 'spiceproxy',
999 path => '{vmid}/spiceproxy',
fff3a342
DM
1000 method => 'POST',
1001 protected => 1,
1002 proxyto => 'node',
1003 permissions => {
1004 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1005 },
1006 description => "Returns a SPICE configuration to connect to the CT.",
1007 parameters => {
1008 additionalProperties => 0,
1009 properties => {
1010 node => get_standard_option('pve-node'),
1011 vmid => get_standard_option('pve-vmid'),
1012 proxy => get_standard_option('spice-proxy', { optional => 1 }),
1013 },
1014 },
1015 returns => get_standard_option('remote-viewer-config'),
1016 code => sub {
1017 my ($param) = @_;
1018
1019 my $vmid = $param->{vmid};
1020 my $node = $param->{node};
1021 my $proxy = $param->{proxy};
1022
1023 my $authpath = "/vms/$vmid";
1024 my $permissions = 'VM.Console';
1025
67afe46e 1026 my $conf = PVE::LXC::Config->load_config($vmid);
da4db334
TL
1027
1028 die "CT $vmid not running\n" if !PVE::LXC::check_running($vmid);
1029
aca816ad
DM
1030 my $concmd = PVE::LXC::get_console_command($vmid, $conf);
1031
5b4657d0
DM
1032 my $shcmd = ['/usr/bin/dtach', '-A',
1033 "/var/run/dtach/vzctlconsole$vmid",
aca816ad 1034 '-r', 'winch', '-z', @$concmd];
fff3a342
DM
1035
1036 my $title = "CT $vmid";
1037
1038 return PVE::API2Tools::run_spiceterm($authpath, $permissions, $vmid, $node, $proxy, $title, $shcmd);
1039 }});
5c752bbf 1040
5c752bbf
DM
1041
1042__PACKAGE__->register_method({
52389a07
DM
1043 name => 'migrate_vm',
1044 path => '{vmid}/migrate',
5c752bbf
DM
1045 method => 'POST',
1046 protected => 1,
1047 proxyto => 'node',
52389a07 1048 description => "Migrate the container to another node. Creates a new migration task.",
5c752bbf 1049 permissions => {
52389a07 1050 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
5c752bbf
DM
1051 },
1052 parameters => {
1053 additionalProperties => 0,
1054 properties => {
1055 node => get_standard_option('pve-node'),
68e8f3c5
DM
1056 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
1057 target => get_standard_option('pve-node', {
1058 description => "Target node.",
39bb88df 1059 completion => \&PVE::Cluster::complete_migration_target,
68e8f3c5 1060 }),
52389a07
DM
1061 online => {
1062 type => 'boolean',
1063 description => "Use online/live migration.",
1064 optional => 1,
1065 },
00d8cdc0
DC
1066 restart => {
1067 type => 'boolean',
1068 description => "Use restart migration",
1069 optional => 1,
1070 },
1071 timeout => {
1072 type => 'integer',
1073 description => "Timeout in seconds for shutdown for restart migration",
1074 optional => 1,
1075 default => 180,
1076 },
9746c095
FG
1077 force => {
1078 type => 'boolean',
1079 description => "Force migration despite local bind / device" .
552e168f 1080 " mounts. NOTE: deprecated, use 'shared' property of mount point instead.",
9746c095
FG
1081 optional => 1,
1082 },
8ead60ef
SI
1083 bwlimit => {
1084 description => "Override I/O bandwidth limit (in KiB/s).",
1085 optional => 1,
1086 type => 'number',
1087 minimum => '0',
41e9b65c 1088 default => 'migrate limit from datacenter or storage config',
8ead60ef 1089 },
5c752bbf
DM
1090 },
1091 },
1092 returns => {
1093 type => 'string',
52389a07 1094 description => "the task ID.",
5c752bbf
DM
1095 },
1096 code => sub {
1097 my ($param) = @_;
1098
1099 my $rpcenv = PVE::RPCEnvironment::get();
1100
1101 my $authuser = $rpcenv->get_user();
1102
52389a07 1103 my $target = extract_param($param, 'target');
bb1ac2de 1104
52389a07
DM
1105 my $localnode = PVE::INotify::nodename();
1106 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
bb1ac2de 1107
52389a07 1108 PVE::Cluster::check_cfs_quorum();
5c752bbf 1109
52389a07 1110 PVE::Cluster::check_node_exists($target);
27916659 1111
52389a07 1112 my $targetip = PVE::Cluster::remote_node_ip($target);
5c752bbf 1113
52389a07 1114 my $vmid = extract_param($param, 'vmid');
5c752bbf 1115
52389a07 1116 # test if VM exists
67afe46e 1117 PVE::LXC::Config->load_config($vmid);
5c752bbf 1118
52389a07
DM
1119 # try to detect errors early
1120 if (PVE::LXC::check_running($vmid)) {
00d8cdc0
DC
1121 die "can't migrate running container without --online or --restart\n"
1122 if !$param->{online} && !$param->{restart};
5c752bbf 1123 }
5c752bbf
DM
1124
1125 if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
1126
1127 my $hacmd = sub {
1128 my $upid = shift;
1129
1130 my $service = "ct:$vmid";
1131
52389a07 1132 my $cmd = ['ha-manager', 'migrate', $service, $target];
5c752bbf 1133
545dd4e1 1134 print "Requesting HA migration for CT $vmid to node $target\n";
5c752bbf
DM
1135
1136 PVE::Tools::run_command($cmd);
1137
1138 return;
1139 };
1140
52389a07 1141 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
5c752bbf
DM
1142
1143 } else {
1144
22557519
DM
1145 my $realcmd = sub {
1146 PVE::LXC::Migrate->migrate($target, $targetip, $vmid, $param);
1147 };
56462053 1148
22557519
DM
1149 my $worker = sub {
1150 return PVE::GuestHelpers::guest_migration_lock($vmid, 10, $realcmd);
5c752bbf
DM
1151 };
1152
22557519 1153 return $rpcenv->fork_worker('vzmigrate', $vmid, $authuser, $worker);
5c752bbf
DM
1154 }
1155 }});
1156
cc5392c8
WL
1157__PACKAGE__->register_method({
1158 name => 'vm_feature',
1159 path => '{vmid}/feature',
1160 method => 'GET',
1161 proxyto => 'node',
1162 protected => 1,
1163 description => "Check if feature for virtual machine is available.",
1164 permissions => {
1165 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1166 },
1167 parameters => {
1168 additionalProperties => 0,
1169 properties => {
1170 node => get_standard_option('pve-node'),
1171 vmid => get_standard_option('pve-vmid'),
1172 feature => {
1173 description => "Feature to check.",
1174 type => 'string',
d53e5c58 1175 enum => [ 'snapshot', 'clone', 'copy' ],
cc5392c8 1176 },
5ec3949c 1177 snapname => get_standard_option('pve-snapshot-name', {
cc5392c8
WL
1178 optional => 1,
1179 }),
1180 },
1181 },
1182 returns => {
1183 type => "object",
1184 properties => {
1185 hasFeature => { type => 'boolean' },
1186 #nodes => {
1187 #type => 'array',
1188 #items => { type => 'string' },
1189 #}
1190 },
1191 },
1192 code => sub {
1193 my ($param) = @_;
1194
1195 my $node = extract_param($param, 'node');
1196
1197 my $vmid = extract_param($param, 'vmid');
1198
1199 my $snapname = extract_param($param, 'snapname');
1200
1201 my $feature = extract_param($param, 'feature');
1202
67afe46e 1203 my $conf = PVE::LXC::Config->load_config($vmid);
cc5392c8
WL
1204
1205 if($snapname){
1206 my $snap = $conf->{snapshots}->{$snapname};
1207 die "snapshot '$snapname' does not exist\n" if !defined($snap);
1208 $conf = $snap;
1209 }
ef241384 1210 my $storage_cfg = PVE::Storage::config();
cc5392c8 1211 #Maybe include later
ef241384 1212 #my $nodelist = PVE::LXC::shared_nodes($conf, $storage_cfg);
4518000b 1213 my $hasFeature = PVE::LXC::Config->has_feature($feature, $conf, $storage_cfg, $snapname);
cc5392c8
WL
1214
1215 return {
1216 hasFeature => $hasFeature,
1217 #nodes => [ keys %$nodelist ],
1218 };
1219 }});
bb1ac2de
DM
1220
1221__PACKAGE__->register_method({
1222 name => 'template',
1223 path => '{vmid}/template',
1224 method => 'POST',
1225 protected => 1,
1226 proxyto => 'node',
1227 description => "Create a Template.",
1228 permissions => {
1229 description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
1230 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
1231 },
1232 parameters => {
1233 additionalProperties => 0,
1234 properties => {
1235 node => get_standard_option('pve-node'),
68e8f3c5 1236 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
bb1ac2de
DM
1237 },
1238 },
1239 returns => { type => 'null'},
1240 code => sub {
1241 my ($param) = @_;
1242
1243 my $rpcenv = PVE::RPCEnvironment::get();
1244
1245 my $authuser = $rpcenv->get_user();
1246
1247 my $node = extract_param($param, 'node');
1248
1249 my $vmid = extract_param($param, 'vmid');
1250
1251 my $updatefn = sub {
1252
67afe46e
FG
1253 my $conf = PVE::LXC::Config->load_config($vmid);
1254 PVE::LXC::Config->check_lock($conf);
bb1ac2de
DM
1255
1256 die "unable to create template, because CT contains snapshots\n"
1257 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
1258
1259 die "you can't convert a template to a template\n"
67afe46e 1260 if PVE::LXC::Config->is_template($conf);
bb1ac2de
DM
1261
1262 die "you can't convert a CT to template if the CT is running\n"
1263 if PVE::LXC::check_running($vmid);
1264
1265 my $realcmd = sub {
1266 PVE::LXC::template_create($vmid, $conf);
bb1ac2de 1267
c2182c49 1268 $conf->{template} = 1;
bb1ac2de 1269
c2182c49
WL
1270 PVE::LXC::Config->write_config($vmid, $conf);
1271 # and remove lxc config
1272 PVE::LXC::update_lxc_config($vmid, $conf);
1273 };
bb1ac2de
DM
1274
1275 return $rpcenv->fork_worker('vztemplate', $vmid, $authuser, $realcmd);
1276 };
1277
67afe46e 1278 PVE::LXC::Config->lock_config($vmid, $updatefn);
bb1ac2de
DM
1279
1280 return undef;
1281 }});
1282
c4a33727
DM
1283__PACKAGE__->register_method({
1284 name => 'clone_vm',
1285 path => '{vmid}/clone',
1286 method => 'POST',
1287 protected => 1,
1288 proxyto => 'node',
1289 description => "Create a container clone/copy",
1290 permissions => {
1291 description => "You need 'VM.Clone' permissions on /vms/{vmid}, " .
1292 "and 'VM.Allocate' permissions " .
1293 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
1294 "'Datastore.AllocateSpace' on any used storage.",
1295 check =>
1296 [ 'and',
1297 ['perm', '/vms/{vmid}', [ 'VM.Clone' ]],
1298 [ 'or',
1299 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
1300 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
1301 ],
1302 ]
1303 },
1304 parameters => {
1305 additionalProperties => 0,
1306 properties => {
1307 node => get_standard_option('pve-node'),
1308 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
1309 newid => get_standard_option('pve-vmid', {
1310 completion => \&PVE::Cluster::complete_next_vmid,
1311 description => 'VMID for the clone.' }),
1312 hostname => {
1313 optional => 1,
1314 type => 'string', format => 'dns-name',
1315 description => "Set a hostname for the new CT.",
1316 },
1317 description => {
1318 optional => 1,
1319 type => 'string',
1320 description => "Description for the new CT.",
1321 },
1322 pool => {
1323 optional => 1,
1324 type => 'string', format => 'pve-poolid',
1325 description => "Add the new CT to the specified pool.",
1326 },
5ec3949c 1327 snapname => get_standard_option('pve-snapshot-name', {
c4a33727
DM
1328 optional => 1,
1329 }),
1330 storage => get_standard_option('pve-storage-id', {
1331 description => "Target storage for full clone.",
c4a33727
DM
1332 optional => 1,
1333 }),
1334 full => {
1335 optional => 1,
1336 type => 'boolean',
c4b4cb83 1337 description => "Create a full copy of all disks. This is always done when " .
c4a33727 1338 "you clone a normal CT. For CT templates, we try to create a linked clone by default.",
c4a33727 1339 },
411ae12c
DM
1340 target => get_standard_option('pve-node', {
1341 description => "Target node. Only allowed if the original VM is on shared storage.",
1342 optional => 1,
1343 }),
8ead60ef
SI
1344 bwlimit => {
1345 description => "Override I/O bandwidth limit (in KiB/s).",
1346 optional => 1,
1347 type => 'number',
1348 minimum => '0',
41e9b65c 1349 default => 'clone limit from datacenter or storage config',
8ead60ef 1350 },
c4a33727
DM
1351 },
1352 },
1353 returns => {
1354 type => 'string',
1355 },
1356 code => sub {
1357 my ($param) = @_;
1358
1359 my $rpcenv = PVE::RPCEnvironment::get();
1360
1361 my $authuser = $rpcenv->get_user();
1362
1363 my $node = extract_param($param, 'node');
1364
1365 my $vmid = extract_param($param, 'vmid');
1366
1367 my $newid = extract_param($param, 'newid');
1368
1369 my $pool = extract_param($param, 'pool');
1370
1371 if (defined($pool)) {
1372 $rpcenv->check_pool_exist($pool);
1373 }
1374
1375 my $snapname = extract_param($param, 'snapname');
1376
1377 my $storage = extract_param($param, 'storage');
1378
411ae12c
DM
1379 my $target = extract_param($param, 'target');
1380
c4a33727
DM
1381 my $localnode = PVE::INotify::nodename();
1382
411ae12c
DM
1383 undef $target if $target && ($target eq $localnode || $target eq 'localhost');
1384
1385 PVE::Cluster::check_node_exists($target) if $target;
1386
c4a33727
DM
1387 my $storecfg = PVE::Storage::config();
1388
1389 if ($storage) {
1390 # check if storage is enabled on local node
1391 PVE::Storage::storage_check_enabled($storecfg, $storage);
411ae12c
DM
1392 if ($target) {
1393 # check if storage is available on target node
1394 PVE::Storage::storage_check_node($storecfg, $storage, $target);
1395 # clone only works if target storage is shared
1396 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1397 die "can't clone to non-shared storage '$storage'\n" if !$scfg->{shared};
1398 }
c4a33727
DM
1399 }
1400
1401 PVE::Cluster::check_cfs_quorum();
1402
db01d674
WB
1403 my $conffile;
1404 my $newconf = {};
1405 my $mountpoints = {};
1406 my $fullclone = {};
1407 my $vollist = [];
411ae12c 1408 my $running;
c4a33727 1409
db01d674
WB
1410 PVE::LXC::Config->lock_config($vmid, sub {
1411 my $src_conf = PVE::LXC::Config->set_lock($vmid, 'disk');
e7d553c7 1412
411ae12c
DM
1413 $running = PVE::LXC::check_running($vmid) || 0;
1414
e7d553c7
DM
1415 my $full = extract_param($param, 'full');
1416 if (!defined($full)) {
1417 $full = !PVE::LXC::Config->is_template($src_conf);
1418 }
1419 die "parameter 'storage' not allowed for linked clones\n" if defined($storage) && !$full;
1420
db01d674
WB
1421 eval {
1422 die "snapshot '$snapname' does not exist\n"
1423 if $snapname && !defined($src_conf->{snapshots}->{$snapname});
c4a33727 1424
c4a33727 1425
db01d674 1426 my $src_conf = $snapname ? $src_conf->{snapshots}->{$snapname} : $src_conf;
c4a33727 1427
db01d674
WB
1428 $conffile = PVE::LXC::Config->config_file($newid);
1429 die "unable to create CT $newid: config file already exists\n"
1430 if -f $conffile;
c4a33727 1431
24f9d440 1432 my $sharedvm = 1;
db01d674
WB
1433 foreach my $opt (keys %$src_conf) {
1434 next if $opt =~ m/^unused\d+$/;
c4a33727 1435
db01d674 1436 my $value = $src_conf->{$opt};
c4a33727 1437
db01d674 1438 if (($opt eq 'rootfs') || ($opt =~ m/^mp\d+$/)) {
e4034859 1439 my $mp = PVE::LXC::Config->parse_volume($opt, $value);
c4a33727 1440
db01d674
WB
1441 if ($mp->{type} eq 'volume') {
1442 my $volid = $mp->{volume};
09687674
DM
1443
1444 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
1445 $sid = $storage if defined($storage);
1446 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
24f9d440
WB
1447 if (!$scfg->{shared}) {
1448 $sharedvm = 0;
1449 warn "found non-shared volume: $volid\n" if $target;
1450 }
09687674
DM
1451
1452 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
1453
e7d553c7 1454 if ($full) {
db01d674
WB
1455 die "Cannot do full clones on a running container without snapshots\n"
1456 if $running && !defined($snapname);
1457 $fullclone->{$opt} = 1;
1458 } else {
1459 # not full means clone instead of copy
1460 die "Linked clone feature for '$volid' is not available\n"
4a954457 1461 if !PVE::Storage::volume_has_feature($storecfg, 'clone', $volid, $snapname, $running, {'valid_target_formats' => ['raw', 'subvol']});
db01d674 1462 }
c4a33727 1463
db01d674
WB
1464 $mountpoints->{$opt} = $mp;
1465 push @$vollist, $volid;
c4a33727 1466
c4a33727 1467 } else {
db01d674
WB
1468 # TODO: allow bind mounts?
1469 die "unable to clone mountpint '$opt' (type $mp->{type})\n";
c4a33727 1470 }
63231f52
TL
1471 } elsif ($opt =~ m/^net(\d+)$/) {
1472 # always change MAC! address
1473 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
1474 my $net = PVE::LXC::Config->parse_lxc_network($value);
1475 $net->{hwaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
1476 $newconf->{$opt} = PVE::LXC::Config->print_lxc_network($net);
c4a33727 1477 } else {
db01d674
WB
1478 # copy everything else
1479 $newconf->{$opt} = $value;
c4a33727 1480 }
db01d674 1481 }
24f9d440
WB
1482 die "can't clone CT to node '$target' (CT uses local storage)\n"
1483 if $target && !$sharedvm;
c4a33727 1484
db01d674
WB
1485 # Replace the 'disk' lock with a 'create' lock.
1486 $newconf->{lock} = 'create';
1487
679cd2ff 1488 delete $newconf->{snapshots};
037dc1e2 1489 delete $newconf->{pending};
db01d674
WB
1490 delete $newconf->{template};
1491 if ($param->{hostname}) {
1492 $newconf->{hostname} = $param->{hostname};
c4a33727 1493 }
c4a33727 1494
db01d674
WB
1495 if ($param->{description}) {
1496 $newconf->{description} = $param->{description};
1497 }
c4a33727 1498
db01d674
WB
1499 # create empty/temp config - this fails if CT already exists on other node
1500 PVE::LXC::Config->write_config($newid, $newconf);
1501 };
1502 if (my $err = $@) {
1503 eval { PVE::LXC::Config->remove_lock($vmid, 'disk') };
1504 warn $@ if $@;
1505 die $err;
c4a33727 1506 }
db01d674 1507 });
c4a33727 1508
db01d674
WB
1509 my $update_conf = sub {
1510 my ($key, $value) = @_;
1511 return PVE::LXC::Config->lock_config($newid, sub {
1512 my $conf = PVE::LXC::Config->load_config($newid);
1513 die "Lost 'create' config lock, aborting.\n"
1514 if !PVE::LXC::Config->has_lock($conf, 'create');
1515 $conf->{$key} = $value;
1516 PVE::LXC::Config->write_config($newid, $conf);
1517 });
1518 };
c4a33727 1519
db01d674
WB
1520 my $realcmd = sub {
1521 my ($upid) = @_;
c4a33727 1522
db01d674 1523 my $newvollist = [];
c4a33727 1524
411ae12c
DM
1525 my $verify_running = PVE::LXC::check_running($vmid) || 0;
1526 die "unexpected state change\n" if $verify_running != $running;
1527
db01d674
WB
1528 eval {
1529 local $SIG{INT} =
1530 local $SIG{TERM} =
1531 local $SIG{QUIT} =
1532 local $SIG{HUP} = sub { die "interrupted by signal\n"; };
c4a33727 1533
db01d674 1534 PVE::Storage::activate_volumes($storecfg, $vollist, $snapname);
8ead60ef 1535 my $bwlimit = extract_param($param, 'bwlimit');
c4a33727 1536
db01d674
WB
1537 foreach my $opt (keys %$mountpoints) {
1538 my $mp = $mountpoints->{$opt};
1539 my $volid = $mp->{volume};
c4a33727 1540
db01d674
WB
1541 my $newvolid;
1542 if ($fullclone->{$opt}) {
1543 print "create full clone of mountpoint $opt ($volid)\n";
8ead60ef
SI
1544 my $source_storage = PVE::Storage::parse_volume_id($volid);
1545 my $target_storage = $storage // $source_storage;
1546 my $clonelimit = PVE::Storage::get_bandwidth_limit('clone', [$source_storage, $target_storage], $bwlimit);
1547 $newvolid = PVE::LXC::copy_volume($mp, $newid, $target_storage, $storecfg, $newconf, $snapname, $clonelimit);
db01d674
WB
1548 } else {
1549 print "create linked clone of mount point $opt ($volid)\n";
1550 $newvolid = PVE::Storage::vdisk_clone($storecfg, $volid, $newid, $snapname);
c4a33727
DM
1551 }
1552
db01d674
WB
1553 push @$newvollist, $newvolid;
1554 $mp->{volume} = $newvolid;
c4a33727 1555
db01d674 1556 $update_conf->($opt, PVE::LXC::Config->print_ct_mountpoint($mp, $opt eq 'rootfs'));
c4a33727
DM
1557 }
1558
db01d674
WB
1559 PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
1560 PVE::LXC::Config->remove_lock($newid, 'create');
411ae12c
DM
1561
1562 if ($target) {
1563 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1564 PVE::Storage::deactivate_volumes($storecfg, $vollist, $snapname) if !$running;
1565 PVE::Storage::deactivate_volumes($storecfg, $newvollist);
1566
1567 my $newconffile = PVE::LXC::Config->config_file($newid, $target);
1568 die "Failed to move config to node '$target' - rename failed: $!\n"
1569 if !rename($conffile, $newconffile);
1570 }
c4a33727 1571 };
db01d674 1572 my $err = $@;
c4a33727 1573
db01d674
WB
1574 # Unlock the source config in any case:
1575 eval { PVE::LXC::Config->remove_lock($vmid, 'disk') };
1576 warn $@ if $@;
c4a33727 1577
db01d674
WB
1578 if ($err) {
1579 # Now cleanup the config & disks:
1580 unlink $conffile;
c4a33727 1581
db01d674
WB
1582 sleep 1; # some storages like rbd need to wait before release volume - really?
1583
1584 foreach my $volid (@$newvollist) {
1585 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1586 warn $@ if $@;
1587 }
1588 die "clone failed: $err";
1589 }
1590
1591 return;
c4a33727
DM
1592 };
1593
db01d674
WB
1594 PVE::Firewall::clone_vmfw_conf($vmid, $newid);
1595 return $rpcenv->fork_worker('vzclone', $vmid, $authuser, $realcmd);
c4a33727
DM
1596 }});
1597
1598
985b18ed
WL
1599__PACKAGE__->register_method({
1600 name => 'resize_vm',
1601 path => '{vmid}/resize',
1602 method => 'PUT',
1603 protected => 1,
1604 proxyto => 'node',
235dbdf3 1605 description => "Resize a container mount point.",
985b18ed
WL
1606 permissions => {
1607 check => ['perm', '/vms/{vmid}', ['VM.Config.Disk'], any => 1],
1608 },
1609 parameters => {
1610 additionalProperties => 0,
b8c5a95f
WB
1611 properties => {
1612 node => get_standard_option('pve-node'),
1613 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
1614 disk => {
1615 type => 'string',
1616 description => "The disk you want to resize.",
5e5d76cf 1617 enum => [PVE::LXC::Config->valid_volume_keys()],
b8c5a95f
WB
1618 },
1619 size => {
1620 type => 'string',
1621 pattern => '\+?\d+(\.\d+)?[KMGT]?',
1622 description => "The new size. With the '+' sign the value is added to the actual size of the volume and without it, the value is taken as an absolute one. Shrinking disk size is not supported.",
1623 },
1624 digest => {
1625 type => 'string',
1626 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1627 maxLength => 40,
1628 optional => 1,
1629 }
1630 },
985b18ed 1631 },
9f3f7963
WL
1632 returns => {
1633 type => 'string',
1634 description => "the task ID.",
1635 },
985b18ed
WL
1636 code => sub {
1637 my ($param) = @_;
1638
1639 my $rpcenv = PVE::RPCEnvironment::get();
1640
1641 my $authuser = $rpcenv->get_user();
1642
1643 my $node = extract_param($param, 'node');
1644
1645 my $vmid = extract_param($param, 'vmid');
1646
1647 my $digest = extract_param($param, 'digest');
1648
1649 my $sizestr = extract_param($param, 'size');
1650 my $ext = ($sizestr =~ s/^\+//);
1651 my $newsize = PVE::JSONSchema::parse_size($sizestr);
1652 die "invalid size string" if !defined($newsize);
1653
1654 die "no options specified\n" if !scalar(keys %$param);
1655
f1ba1a4b 1656 PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, $param, []);
985b18ed
WL
1657
1658 my $storage_cfg = cfs_read_file("storage.cfg");
1659
985b18ed
WL
1660 my $code = sub {
1661
67afe46e
FG
1662 my $conf = PVE::LXC::Config->load_config($vmid);
1663 PVE::LXC::Config->check_lock($conf);
985b18ed
WL
1664
1665 PVE::Tools::assert_if_modified($digest, $conf->{digest});
1666
1667 my $running = PVE::LXC::check_running($vmid);
1668
1669 my $disk = $param->{disk};
e4034859 1670 my $mp = PVE::LXC::Config->parse_volume($disk, $conf->{$disk});
44a9face 1671
985b18ed
WL
1672 my $volid = $mp->{volume};
1673
1674 my (undef, undef, $owner, undef, undef, undef, $format) =
1675 PVE::Storage::parse_volname($storage_cfg, $volid);
1676
235dbdf3 1677 die "can't resize mount point owned by another container ($owner)"
985b18ed
WL
1678 if $vmid != $owner;
1679
1680 die "can't resize volume: $disk if snapshot exists\n"
1681 if %{$conf->{snapshots}} && $format eq 'qcow2';
1682
1683 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
1684
1685 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
1686
4e1e1791
WB
1687 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1688
985b18ed 1689 my $size = PVE::Storage::volume_size_info($storage_cfg, $volid, 5);
2e8bcfef 1690
16f6c7c6 1691 die "Could not determine current size of volume '$volid'\n" if !defined($size);
2e8bcfef 1692
985b18ed
WL
1693 $newsize += $size if $ext;
1694 $newsize = int($newsize);
1695
1696 die "unable to shrink disk size\n" if $newsize < $size;
1697
5c36822a 1698 die "disk is already at specified size\n" if $size == $newsize;
985b18ed
WL
1699
1700 PVE::Cluster::log_msg('info', $authuser, "update CT $vmid: resize --disk $disk --size $sizestr");
9f3f7963 1701 my $realcmd = sub {
e72c8b0e
DM
1702 # Note: PVE::Storage::volume_resize doesn't do anything if $running=1, so
1703 # we pass 0 here (parameter only makes sense for qemu)
9f3f7963
WL
1704 PVE::Storage::volume_resize($storage_cfg, $volid, $newsize, 0);
1705
1706 $mp->{size} = $newsize;
1b4cf758 1707 $conf->{$disk} = PVE::LXC::Config->print_ct_mountpoint($mp, $disk eq 'rootfs');
9f3f7963 1708
67afe46e 1709 PVE::LXC::Config->write_config($vmid, $conf);
9f3f7963
WL
1710
1711 if ($format eq 'raw') {
46e62d2d
TL
1712 # we need to ensure that the volume is mapped, if not needed this is a NOP
1713 my $path = PVE::Storage::map_volume($storage_cfg, $volid);
1714 $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
9f3f7963 1715 if ($running) {
2a993004
WL
1716
1717 $mp->{mp} = '/';
1718 my $use_loopdev = (PVE::LXC::mountpoint_mount_path($mp, $storage_cfg))[1];
21f292ff 1719 $path = PVE::LXC::query_loopdev($path) if $use_loopdev;
235dbdf3 1720 die "internal error: CT running but mount point not attached to a loop device"
2a993004
WL
1721 if !$path;
1722 PVE::Tools::run_command(['losetup', '--set-capacity', $path]) if $use_loopdev;
9f3f7963
WL
1723
1724 # In order for resize2fs to know that we need online-resizing a mountpoint needs
1725 # to be visible to it in its namespace.
1726 # To not interfere with the rest of the system we unshare the current mount namespace,
1727 # mount over /tmp and then run resize2fs.
1728
1729 # interestingly we don't need to e2fsck on mounted systems...
1730 my $quoted = PVE::Tools::shellquote($path);
1731 my $cmd = "mount --make-rprivate / && mount $quoted /tmp && resize2fs $quoted";
ce9e6458
WB
1732 eval {
1733 PVE::Tools::run_command(['unshare', '-m', '--', 'sh', '-c', $cmd]);
1734 };
1735 warn "Failed to update the container's filesystem: $@\n" if $@;
9f3f7963 1736 } else {
ce9e6458
WB
1737 eval {
1738 PVE::Tools::run_command(['e2fsck', '-f', '-y', $path]);
1739 PVE::Tools::run_command(['resize2fs', $path]);
1740 };
1741 warn "Failed to update the container's filesystem: $@\n" if $@;
80440faa 1742
46ea6368
TL
1743 # always un-map if not running, this is a NOP if not needed
1744 PVE::Storage::unmap_volume($storage_cfg, $volid);
9f3f7963 1745 }
985b18ed 1746 }
9f3f7963 1747 };
985b18ed 1748
9f3f7963
WL
1749 return $rpcenv->fork_worker('resize', $vmid, $authuser, $realcmd);
1750 };
985b18ed 1751
67afe46e 1752 return PVE::LXC::Config->lock_config($vmid, $code);;
985b18ed
WL
1753 }});
1754
3c0f6806
WB
1755__PACKAGE__->register_method({
1756 name => 'move_volume',
1757 path => '{vmid}/move_volume',
1758 method => 'POST',
1759 protected => 1,
1760 proxyto => 'node',
1761 description => "Move a rootfs-/mp-volume to a different storage",
1762 permissions => {
1763 description => "You need 'VM.Config.Disk' permissions on /vms/{vmid}, " .
1764 "and 'Datastore.AllocateSpace' permissions on the storage.",
1765 check =>
1766 [ 'and',
1767 ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
1768 ['perm', '/storage/{storage}', [ 'Datastore.AllocateSpace' ]],
1769 ],
1770 },
1771 parameters => {
1772 additionalProperties => 0,
1773 properties => {
1774 node => get_standard_option('pve-node'),
1775 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
1776 volume => {
1777 type => 'string',
5e5d76cf 1778 enum => [ PVE::LXC::Config->valid_volume_keys() ],
3c0f6806
WB
1779 description => "Volume which will be moved.",
1780 },
1781 storage => get_standard_option('pve-storage-id', {
1782 description => "Target Storage.",
1783 completion => \&PVE::Storage::complete_storage_enabled,
1784 }),
1785 delete => {
1786 type => 'boolean',
1787 description => "Delete the original volume after successful copy. By default the original is kept as an unused volume entry.",
1788 optional => 1,
1789 default => 0,
1790 },
1791 digest => {
1792 type => 'string',
1793 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1794 maxLength => 40,
1795 optional => 1,
8ead60ef
SI
1796 },
1797 bwlimit => {
1798 description => "Override I/O bandwidth limit (in KiB/s).",
1799 optional => 1,
1800 type => 'number',
1801 minimum => '0',
41e9b65c 1802 default => 'clone limit from datacenter or storage config',
8ead60ef 1803 },
3c0f6806
WB
1804 },
1805 },
1806 returns => {
1807 type => 'string',
1808 },
1809 code => sub {
1810 my ($param) = @_;
1811
1812 my $rpcenv = PVE::RPCEnvironment::get();
1813
1814 my $authuser = $rpcenv->get_user();
1815
1816 my $vmid = extract_param($param, 'vmid');
1817
1818 my $storage = extract_param($param, 'storage');
1819
1820 my $mpkey = extract_param($param, 'volume');
1821
1822 my $lockname = 'disk';
1823
1824 my ($mpdata, $old_volid);
1825
1826 PVE::LXC::Config->lock_config($vmid, sub {
1827 my $conf = PVE::LXC::Config->load_config($vmid);
1828 PVE::LXC::Config->check_lock($conf);
1829
1830 die "cannot move volumes of a running container\n" if PVE::LXC::check_running($vmid);
1831
c14508b1 1832 $mpdata = PVE::LXC::Config->parse_volume($mpkey, $conf->{$mpkey});
3c0f6806
WB
1833 $old_volid = $mpdata->{volume};
1834
1835 die "you can't move a volume with snapshots and delete the source\n"
1836 if $param->{delete} && PVE::LXC::Config->is_volume_in_use_by_snapshots($conf, $old_volid);
1837
1838 PVE::Tools::assert_if_modified($param->{digest}, $conf->{digest});
1839
1840 PVE::LXC::Config->set_lock($vmid, $lockname);
1841 });
1842
1843 my $realcmd = sub {
1844 eval {
1845 PVE::Cluster::log_msg('info', $authuser, "move volume CT $vmid: move --volume $mpkey --storage $storage");
1846
1847 my $conf = PVE::LXC::Config->load_config($vmid);
1848 my $storage_cfg = PVE::Storage::config();
1849
1850 my $new_volid;
1851
1852 eval {
1853 PVE::Storage::activate_volumes($storage_cfg, [ $old_volid ]);
8ead60ef
SI
1854 my $bwlimit = extract_param($param, 'bwlimit');
1855 my $source_storage = PVE::Storage::parse_volume_id($old_volid);
1856 my $movelimit = PVE::Storage::get_bandwidth_limit('move', [$source_storage, $storage], $bwlimit);
1857 $new_volid = PVE::LXC::copy_volume($mpdata, $vmid, $storage, $storage_cfg, $conf, undef, $movelimit);
3bfbd900
FE
1858 if (PVE::LXC::Config->is_template($conf)) {
1859 PVE::Storage::activate_volumes($storage_cfg, [ $new_volid ]);
1860 my $template_volid = PVE::Storage::vdisk_create_base($storage_cfg, $new_volid);
1861 $mpdata->{volume} = $template_volid;
1862 } else {
1863 $mpdata->{volume} = $new_volid;
1864 }
3c0f6806
WB
1865
1866 PVE::LXC::Config->lock_config($vmid, sub {
1867 my $digest = $conf->{digest};
1868 $conf = PVE::LXC::Config->load_config($vmid);
1869 PVE::Tools::assert_if_modified($digest, $conf->{digest});
1870
1871 $conf->{$mpkey} = PVE::LXC::Config->print_ct_mountpoint($mpdata, $mpkey eq 'rootfs');
1872
1873 PVE::LXC::Config->add_unused_volume($conf, $old_volid) if !$param->{delete};
1874
1875 PVE::LXC::Config->write_config($vmid, $conf);
1876 });
1877
1878 eval {
1879 # try to deactivate volumes - avoid lvm LVs to be active on several nodes
1880 PVE::Storage::deactivate_volumes($storage_cfg, [ $new_volid ])
1881 };
1882 warn $@ if $@;
1883 };
1884 if (my $err = $@) {
1885 eval {
1886 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
1887 if defined($new_volid);
1888 };
1889 warn $@ if $@;
1890 die $err;
1891 }
1892
1893 if ($param->{delete}) {
1894 eval {
1895 PVE::Storage::deactivate_volumes($storage_cfg, [ $old_volid ]);
1896 PVE::Storage::vdisk_free($storage_cfg, $old_volid);
1897 };
9abb0f8a
FE
1898 if (my $err = $@) {
1899 warn $err;
1900 PVE::LXC::Config->lock_config($vmid, sub {
1901 my $conf = PVE::LXC::Config->load_config($vmid);
1902 PVE::LXC::Config->add_unused_volume($conf, $old_volid);
1903 PVE::LXC::Config->write_config($vmid, $conf);
1904 });
1905 }
3c0f6806
WB
1906 }
1907 };
1908 my $err = $@;
1909 eval { PVE::LXC::Config->remove_lock($vmid, $lockname) };
1910 warn $@ if $@;
1911 die $err if $err;
1912 };
1913 my $task = eval {
1914 $rpcenv->fork_worker('move_volume', $vmid, $authuser, $realcmd);
1915 };
1916 if (my $err = $@) {
1917 eval { PVE::LXC::Config->remove_lock($vmid, $lockname) };
1918 warn $@ if $@;
1919 die $err;
1920 }
1921 return $task;
1922 }});
1923
37c2dba8
OB
1924__PACKAGE__->register_method({
1925 name => 'vm_pending',
1926 path => '{vmid}/pending',
1927 method => 'GET',
1928 proxyto => 'node',
1929 description => 'Get container configuration, including pending changes.',
1930 permissions => {
1931 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1932 },
1933 parameters => {
1934 additionalProperties => 0,
1935 properties => {
1936 node => get_standard_option('pve-node'),
1937 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
1938 },
1939 },
1940 returns => {
1941 type => "array",
1942 items => {
1943 type => "object",
1944 properties => {
1945 key => {
1946 description => 'Configuration option name.',
1947 type => 'string',
1948 },
1949 value => {
1950 description => 'Current value.',
1951 type => 'string',
1952 optional => 1,
1953 },
1954 pending => {
1955 description => 'Pending value.',
1956 type => 'string',
1957 optional => 1,
1958 },
1959 delete => {
1960 description => "Indicates a pending delete request if present and not 0.",
1961 type => 'integer',
1962 minimum => 0,
1963 maximum => 2,
1964 optional => 1,
1965 },
1966 },
1967 },
1968 },
1969 code => sub {
1970 my ($param) = @_;
1971
1972 my $conf = PVE::LXC::Config->load_config($param->{vmid});
1973
1974 my $pending_delete_hash = PVE::LXC::Config->parse_pending_delete($conf->{pending}->{delete});
1975
f622e7dc 1976 return PVE::GuestHelpers::config_with_pending_array($conf, $pending_delete_hash);
37c2dba8
OB
1977 }});
1978
f76a2828 19791;