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