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