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