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