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