]> git.proxmox.com Git - pve-container.git/blob - src/PVE/API2/LXC.pm
fix mount_all, improve bind mount handling
[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::LXC;
17 use PVE::LXC::Create;
18 use PVE::LXC::Migrate;
19 use PVE::API2::LXC::Config;
20 use PVE::API2::LXC::Status;
21 use PVE::API2::LXC::Snapshot;
22 use PVE::HA::Config;
23 use PVE::JSONSchema qw(get_standard_option);
24 use base qw(PVE::RESTHandler);
25
26 use Data::Dumper; # fixme: remove
27
28 __PACKAGE__->register_method ({
29 subclass => "PVE::API2::LXC::Config",
30 path => '{vmid}/config',
31 });
32
33 __PACKAGE__->register_method ({
34 subclass => "PVE::API2::LXC::Status",
35 path => '{vmid}/status',
36 });
37
38 __PACKAGE__->register_method ({
39 subclass => "PVE::API2::LXC::Snapshot",
40 path => '{vmid}/snapshot',
41 });
42
43 __PACKAGE__->register_method ({
44 subclass => "PVE::API2::Firewall::CT",
45 path => '{vmid}/firewall',
46 });
47
48 __PACKAGE__->register_method({
49 name => 'vmlist',
50 path => '',
51 method => 'GET',
52 description => "LXC container index (per node).",
53 permissions => {
54 description => "Only list CTs where you have VM.Audit permissons on /vms/<vmid>.",
55 user => 'all',
56 },
57 proxyto => 'node',
58 protected => 1, # /proc files are only readable by root
59 parameters => {
60 additionalProperties => 0,
61 properties => {
62 node => get_standard_option('pve-node'),
63 },
64 },
65 returns => {
66 type => 'array',
67 items => {
68 type => "object",
69 properties => {},
70 },
71 links => [ { rel => 'child', href => "{vmid}" } ],
72 },
73 code => sub {
74 my ($param) = @_;
75
76 my $rpcenv = PVE::RPCEnvironment::get();
77 my $authuser = $rpcenv->get_user();
78
79 my $vmstatus = PVE::LXC::vmstatus();
80
81 my $res = [];
82 foreach my $vmid (keys %$vmstatus) {
83 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
84
85 my $data = $vmstatus->{$vmid};
86 $data->{vmid} = $vmid;
87 push @$res, $data;
88 }
89
90 return $res;
91
92 }});
93
94 __PACKAGE__->register_method({
95 name => 'create_vm',
96 path => '',
97 method => 'POST',
98 description => "Create or restore a container.",
99 permissions => {
100 user => 'all', # check inside
101 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. " .
102 "For restore, it is enough if the user has 'VM.Backup' permission and the VM already exists. " .
103 "You also need 'Datastore.AllocateSpace' permissions on the storage.",
104 },
105 protected => 1,
106 proxyto => 'node',
107 parameters => {
108 additionalProperties => 0,
109 properties => PVE::LXC::json_config_properties({
110 node => get_standard_option('pve-node'),
111 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
112 ostemplate => {
113 description => "The OS template or backup file.",
114 type => 'string',
115 maxLength => 255,
116 completion => \&PVE::LXC::complete_os_templates,
117 },
118 password => {
119 optional => 1,
120 type => 'string',
121 description => "Sets root password inside container.",
122 minLength => 5,
123 },
124 storage => get_standard_option('pve-storage-id', {
125 description => "Default Storage.",
126 default => 'local',
127 optional => 1,
128 completion => \&PVE::Storage::complete_storage_enabled,
129 }),
130 force => {
131 optional => 1,
132 type => 'boolean',
133 description => "Allow to overwrite existing container.",
134 },
135 restore => {
136 optional => 1,
137 type => 'boolean',
138 description => "Mark this as restore task.",
139 },
140 pool => {
141 optional => 1,
142 type => 'string', format => 'pve-poolid',
143 description => "Add the VM to the specified pool.",
144 },
145 'ignore-unpack-errors' => {
146 optional => 1,
147 type => 'boolean',
148 description => "Ignore errors when extracting the template.",
149 },
150 }),
151 },
152 returns => {
153 type => 'string',
154 },
155 code => sub {
156 my ($param) = @_;
157
158 my $rpcenv = PVE::RPCEnvironment::get();
159
160 my $authuser = $rpcenv->get_user();
161
162 my $node = extract_param($param, 'node');
163
164 my $vmid = extract_param($param, 'vmid');
165
166 my $ignore_unpack_errors = extract_param($param, 'ignore-unpack-errors');
167
168 my $basecfg_fn = PVE::LXC::config_file($vmid);
169
170 my $same_container_exists = -f $basecfg_fn;
171
172 # 'unprivileged' is read-only, so we can't pass it to update_pct_config
173 my $unprivileged = extract_param($param, 'unprivileged');
174
175 my $restore = extract_param($param, 'restore');
176
177 if ($restore) {
178 # fixme: limit allowed parameters
179
180 }
181
182 my $force = extract_param($param, 'force');
183
184 if (!($same_container_exists && $restore && $force)) {
185 PVE::Cluster::check_vmid_unused($vmid);
186 } else {
187 my $conf = PVE::LXC::load_config($vmid);
188 PVE::LXC::check_protection($conf, "unable to restore CT $vmid");
189 }
190
191 my $password = extract_param($param, 'password');
192
193 my $pool = extract_param($param, 'pool');
194
195 if (defined($pool)) {
196 $rpcenv->check_pool_exist($pool);
197 $rpcenv->check_perm_modify($authuser, "/pool/$pool");
198 }
199
200 if ($rpcenv->check($authuser, "/vms/$vmid", ['VM.Allocate'], 1)) {
201 # OK
202 } elsif ($pool && $rpcenv->check($authuser, "/pool/$pool", ['VM.Allocate'], 1)) {
203 # OK
204 } elsif ($restore && $force && $same_container_exists &&
205 $rpcenv->check($authuser, "/vms/$vmid", ['VM.Backup'], 1)) {
206 # OK: user has VM.Backup permissions, and want to restore an existing VM
207 } else {
208 raise_perm_exc();
209 }
210
211 PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
212
213 my $storage = extract_param($param, 'storage') // 'local';
214
215 my $storage_cfg = cfs_read_file("storage.cfg");
216
217 my $ostemplate = extract_param($param, 'ostemplate');
218
219 my $archive;
220
221 if ($ostemplate eq '-') {
222 die "pipe requires cli environment\n"
223 if $rpcenv->{type} ne 'cli';
224 die "pipe can only be used with restore tasks\n"
225 if !$restore;
226 $archive = '-';
227 die "restore from pipe requires rootfs parameter\n" if !defined($param->{rootfs});
228 } else {
229 $rpcenv->check_volume_access($authuser, $storage_cfg, $vmid, $ostemplate);
230 $archive = PVE::Storage::abs_filesystem_path($storage_cfg, $ostemplate);
231 }
232
233 my $check_and_activate_storage = sub {
234 my ($sid) = @_;
235
236 my $scfg = PVE::Storage::storage_check_node($storage_cfg, $sid, $node);
237
238 raise_param_exc({ storage => "storage '$sid' does not support container directories"})
239 if !$scfg->{content}->{rootdir};
240
241 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
242
243 PVE::Storage::activate_storage($storage_cfg, $sid);
244 };
245
246 my $conf = {};
247
248 my $no_disk_param = {};
249 foreach my $opt (keys %$param) {
250 my $value = $param->{$opt};
251 if ($opt eq 'rootfs' || $opt =~ m/^mp\d+$/) {
252 # allow to use simple numbers (add default storage in that case)
253 $param->{$opt} = "$storage:$value" if $value =~ m/^\d+(\.\d+)?$/;
254 } else {
255 $no_disk_param->{$opt} = $value;
256 }
257 }
258
259 # check storage access, activate storage
260 PVE::LXC::foreach_mountpoint($param, sub {
261 my ($ms, $mountpoint) = @_;
262
263 my $volid = $mountpoint->{volume};
264 my $mp = $mountpoint->{mp};
265
266 if ($mountpoint->{type} ne 'volume') { # bind or device
267 die "Only root can pass arbitrary filesystem paths.\n"
268 if $authuser ne 'root@pam';
269 } else {
270 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
271 &$check_and_activate_storage($sid);
272 }
273 });
274
275 # check/activate default storage
276 &$check_and_activate_storage($storage) if !defined($param->{rootfs});
277
278 PVE::LXC::update_pct_config($vmid, $conf, 0, $no_disk_param);
279
280 $conf->{unprivileged} = 1 if $unprivileged;
281
282 my $check_vmid_usage = sub {
283 if ($force) {
284 die "can't overwrite running container\n"
285 if PVE::LXC::check_running($vmid);
286 } else {
287 PVE::Cluster::check_vmid_unused($vmid);
288 }
289 };
290
291 my $code = sub {
292 &$check_vmid_usage(); # final check after locking
293
294 PVE::Cluster::check_cfs_quorum();
295 my $vollist = [];
296
297 eval {
298 if (!defined($param->{rootfs})) {
299 if ($restore) {
300 my (undef, $disksize) = PVE::LXC::Create::recover_config($archive);
301 die "unable to detect disk size - please specify rootfs (size)\n"
302 if !$disksize;
303 $disksize /= 1024 * 1024 * 1024; # create_disks expects GB as unit size
304 $param->{rootfs} = "$storage:$disksize";
305 } else {
306 $param->{rootfs} = "$storage:4"; # defaults to 4GB
307 }
308 }
309
310 $vollist = PVE::LXC::create_disks($storage_cfg, $vmid, $param, $conf);
311
312 PVE::LXC::Create::create_rootfs($storage_cfg, $vmid, $conf, $archive, $password, $restore, $ignore_unpack_errors);
313 # set some defaults
314 $conf->{hostname} ||= "CT$vmid";
315 $conf->{memory} ||= 512;
316 $conf->{swap} //= 512;
317 PVE::LXC::create_config($vmid, $conf);
318 };
319 if (my $err = $@) {
320 PVE::LXC::destroy_disks($storage_cfg, $vollist);
321 PVE::LXC::destroy_config($vmid);
322 die $err;
323 }
324 PVE::AccessControl::add_vm_to_pool($vmid, $pool) if $pool;
325 };
326
327 my $realcmd = sub { PVE::LXC::lock_container($vmid, 1, $code); };
328
329 &$check_vmid_usage(); # first check before locking
330
331 return $rpcenv->fork_worker($restore ? 'vzrestore' : 'vzcreate',
332 $vmid, $authuser, $realcmd);
333
334 }});
335
336 __PACKAGE__->register_method({
337 name => 'vmdiridx',
338 path => '{vmid}',
339 method => 'GET',
340 proxyto => 'node',
341 description => "Directory index",
342 permissions => {
343 user => 'all',
344 },
345 parameters => {
346 additionalProperties => 0,
347 properties => {
348 node => get_standard_option('pve-node'),
349 vmid => get_standard_option('pve-vmid'),
350 },
351 },
352 returns => {
353 type => 'array',
354 items => {
355 type => "object",
356 properties => {
357 subdir => { type => 'string' },
358 },
359 },
360 links => [ { rel => 'child', href => "{subdir}" } ],
361 },
362 code => sub {
363 my ($param) = @_;
364
365 # test if VM exists
366 my $conf = PVE::LXC::load_config($param->{vmid});
367
368 my $res = [
369 { subdir => 'config' },
370 { subdir => 'status' },
371 { subdir => 'vncproxy' },
372 { subdir => 'vncwebsocket' },
373 { subdir => 'spiceproxy' },
374 { subdir => 'migrate' },
375 # { subdir => 'initlog' },
376 { subdir => 'rrd' },
377 { subdir => 'rrddata' },
378 { subdir => 'firewall' },
379 { subdir => 'snapshot' },
380 { subdir => 'resize' },
381 ];
382
383 return $res;
384 }});
385
386 __PACKAGE__->register_method({
387 name => 'rrd',
388 path => '{vmid}/rrd',
389 method => 'GET',
390 protected => 1, # fixme: can we avoid that?
391 permissions => {
392 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
393 },
394 description => "Read VM RRD statistics (returns PNG)",
395 parameters => {
396 additionalProperties => 0,
397 properties => {
398 node => get_standard_option('pve-node'),
399 vmid => get_standard_option('pve-vmid'),
400 timeframe => {
401 description => "Specify the time frame you are interested in.",
402 type => 'string',
403 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
404 },
405 ds => {
406 description => "The list of datasources you want to display.",
407 type => 'string', format => 'pve-configid-list',
408 },
409 cf => {
410 description => "The RRD consolidation function",
411 type => 'string',
412 enum => [ 'AVERAGE', 'MAX' ],
413 optional => 1,
414 },
415 },
416 },
417 returns => {
418 type => "object",
419 properties => {
420 filename => { type => 'string' },
421 },
422 },
423 code => sub {
424 my ($param) = @_;
425
426 return PVE::Cluster::create_rrd_graph(
427 "pve2-vm/$param->{vmid}", $param->{timeframe},
428 $param->{ds}, $param->{cf});
429
430 }});
431
432 __PACKAGE__->register_method({
433 name => 'rrddata',
434 path => '{vmid}/rrddata',
435 method => 'GET',
436 protected => 1, # fixme: can we avoid that?
437 permissions => {
438 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
439 },
440 description => "Read VM RRD statistics",
441 parameters => {
442 additionalProperties => 0,
443 properties => {
444 node => get_standard_option('pve-node'),
445 vmid => get_standard_option('pve-vmid'),
446 timeframe => {
447 description => "Specify the time frame you are interested in.",
448 type => 'string',
449 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
450 },
451 cf => {
452 description => "The RRD consolidation function",
453 type => 'string',
454 enum => [ 'AVERAGE', 'MAX' ],
455 optional => 1,
456 },
457 },
458 },
459 returns => {
460 type => "array",
461 items => {
462 type => "object",
463 properties => {},
464 },
465 },
466 code => sub {
467 my ($param) = @_;
468
469 return PVE::Cluster::create_rrd_data(
470 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
471 }});
472
473 __PACKAGE__->register_method({
474 name => 'destroy_vm',
475 path => '{vmid}',
476 method => 'DELETE',
477 protected => 1,
478 proxyto => 'node',
479 description => "Destroy the container (also delete all uses files).",
480 permissions => {
481 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
482 },
483 parameters => {
484 additionalProperties => 0,
485 properties => {
486 node => get_standard_option('pve-node'),
487 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
488 },
489 },
490 returns => {
491 type => 'string',
492 },
493 code => sub {
494 my ($param) = @_;
495
496 my $rpcenv = PVE::RPCEnvironment::get();
497
498 my $authuser = $rpcenv->get_user();
499
500 my $vmid = $param->{vmid};
501
502 # test if container exists
503 my $conf = PVE::LXC::load_config($vmid);
504
505 my $storage_cfg = cfs_read_file("storage.cfg");
506
507 PVE::LXC::check_protection($conf, "can't remove CT $vmid");
508
509 die "unable to remove CT $vmid - used in HA resources\n"
510 if PVE::HA::Config::vm_is_ha_managed($vmid);
511
512 my $running_error_msg = "unable to destroy CT $vmid - container is running\n";
513
514 die $running_error_msg if PVE::LXC::check_running($vmid); # check early
515
516 my $code = sub {
517 # reload config after lock
518 $conf = PVE::LXC::load_config($vmid);
519 PVE::LXC::check_lock($conf);
520
521 die $running_error_msg if PVE::LXC::check_running($vmid);
522
523 PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $conf);
524 PVE::AccessControl::remove_vm_access($vmid);
525 PVE::Firewall::remove_vmfw_conf($vmid);
526 };
527
528 my $realcmd = sub { PVE::LXC::lock_container($vmid, 1, $code); };
529
530 return $rpcenv->fork_worker('vzdestroy', $vmid, $authuser, $realcmd);
531 }});
532
533 my $sslcert;
534
535 __PACKAGE__->register_method ({
536 name => 'vncproxy',
537 path => '{vmid}/vncproxy',
538 method => 'POST',
539 protected => 1,
540 permissions => {
541 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
542 },
543 description => "Creates a TCP VNC proxy connections.",
544 parameters => {
545 additionalProperties => 0,
546 properties => {
547 node => get_standard_option('pve-node'),
548 vmid => get_standard_option('pve-vmid'),
549 websocket => {
550 optional => 1,
551 type => 'boolean',
552 description => "use websocket instead of standard VNC.",
553 },
554 },
555 },
556 returns => {
557 additionalProperties => 0,
558 properties => {
559 user => { type => 'string' },
560 ticket => { type => 'string' },
561 cert => { type => 'string' },
562 port => { type => 'integer' },
563 upid => { type => 'string' },
564 },
565 },
566 code => sub {
567 my ($param) = @_;
568
569 my $rpcenv = PVE::RPCEnvironment::get();
570
571 my $authuser = $rpcenv->get_user();
572
573 my $vmid = $param->{vmid};
574 my $node = $param->{node};
575
576 my $authpath = "/vms/$vmid";
577
578 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
579
580 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
581 if !$sslcert;
582
583 my ($remip, $family);
584
585 if ($node ne PVE::INotify::nodename()) {
586 ($remip, $family) = PVE::Cluster::remote_node_ip($node);
587 } else {
588 $family = PVE::Tools::get_host_address_family($node);
589 }
590
591 my $port = PVE::Tools::next_vnc_port($family);
592
593 # NOTE: vncterm VNC traffic is already TLS encrypted,
594 # so we select the fastest chipher here (or 'none'?)
595 my $remcmd = $remip ?
596 ['/usr/bin/ssh', '-t', $remip] : [];
597
598 my $conf = PVE::LXC::load_config($vmid, $node);
599 my $concmd = PVE::LXC::get_console_command($vmid, $conf);
600
601 my $shcmd = [ '/usr/bin/dtach', '-A',
602 "/var/run/dtach/vzctlconsole$vmid",
603 '-r', 'winch', '-z', @$concmd];
604
605 my $realcmd = sub {
606 my $upid = shift;
607
608 syslog ('info', "starting lxc vnc proxy $upid\n");
609
610 my $timeout = 10;
611
612 my $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
613 '-timeout', $timeout, '-authpath', $authpath,
614 '-perm', 'VM.Console'];
615
616 if ($param->{websocket}) {
617 $ENV{PVE_VNC_TICKET} = $ticket; # pass ticket to vncterm
618 push @$cmd, '-notls', '-listen', 'localhost';
619 }
620
621 push @$cmd, '-c', @$remcmd, @$shcmd;
622
623 run_command($cmd);
624
625 return;
626 };
627
628 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
629
630 PVE::Tools::wait_for_vnc_port($port);
631
632 return {
633 user => $authuser,
634 ticket => $ticket,
635 port => $port,
636 upid => $upid,
637 cert => $sslcert,
638 };
639 }});
640
641 __PACKAGE__->register_method({
642 name => 'vncwebsocket',
643 path => '{vmid}/vncwebsocket',
644 method => 'GET',
645 permissions => {
646 description => "You also need to pass a valid ticket (vncticket).",
647 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
648 },
649 description => "Opens a weksocket for VNC traffic.",
650 parameters => {
651 additionalProperties => 0,
652 properties => {
653 node => get_standard_option('pve-node'),
654 vmid => get_standard_option('pve-vmid'),
655 vncticket => {
656 description => "Ticket from previous call to vncproxy.",
657 type => 'string',
658 maxLength => 512,
659 },
660 port => {
661 description => "Port number returned by previous vncproxy call.",
662 type => 'integer',
663 minimum => 5900,
664 maximum => 5999,
665 },
666 },
667 },
668 returns => {
669 type => "object",
670 properties => {
671 port => { type => 'string' },
672 },
673 },
674 code => sub {
675 my ($param) = @_;
676
677 my $rpcenv = PVE::RPCEnvironment::get();
678
679 my $authuser = $rpcenv->get_user();
680
681 my $authpath = "/vms/$param->{vmid}";
682
683 PVE::AccessControl::verify_vnc_ticket($param->{vncticket}, $authuser, $authpath);
684
685 my $port = $param->{port};
686
687 return { port => $port };
688 }});
689
690 __PACKAGE__->register_method ({
691 name => 'spiceproxy',
692 path => '{vmid}/spiceproxy',
693 method => 'POST',
694 protected => 1,
695 proxyto => 'node',
696 permissions => {
697 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
698 },
699 description => "Returns a SPICE configuration to connect to the CT.",
700 parameters => {
701 additionalProperties => 0,
702 properties => {
703 node => get_standard_option('pve-node'),
704 vmid => get_standard_option('pve-vmid'),
705 proxy => get_standard_option('spice-proxy', { optional => 1 }),
706 },
707 },
708 returns => get_standard_option('remote-viewer-config'),
709 code => sub {
710 my ($param) = @_;
711
712 my $vmid = $param->{vmid};
713 my $node = $param->{node};
714 my $proxy = $param->{proxy};
715
716 my $authpath = "/vms/$vmid";
717 my $permissions = 'VM.Console';
718
719 my $conf = PVE::LXC::load_config($vmid);
720
721 die "CT $vmid not running\n" if !PVE::LXC::check_running($vmid);
722
723 my $concmd = PVE::LXC::get_console_command($vmid, $conf);
724
725 my $shcmd = ['/usr/bin/dtach', '-A',
726 "/var/run/dtach/vzctlconsole$vmid",
727 '-r', 'winch', '-z', @$concmd];
728
729 my $title = "CT $vmid";
730
731 return PVE::API2Tools::run_spiceterm($authpath, $permissions, $vmid, $node, $proxy, $title, $shcmd);
732 }});
733
734
735 __PACKAGE__->register_method({
736 name => 'migrate_vm',
737 path => '{vmid}/migrate',
738 method => 'POST',
739 protected => 1,
740 proxyto => 'node',
741 description => "Migrate the container to another node. Creates a new migration task.",
742 permissions => {
743 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
744 },
745 parameters => {
746 additionalProperties => 0,
747 properties => {
748 node => get_standard_option('pve-node'),
749 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
750 target => get_standard_option('pve-node', {
751 description => "Target node.",
752 completion => \&PVE::Cluster::complete_migration_target,
753 }),
754 online => {
755 type => 'boolean',
756 description => "Use online/live migration.",
757 optional => 1,
758 },
759 },
760 },
761 returns => {
762 type => 'string',
763 description => "the task ID.",
764 },
765 code => sub {
766 my ($param) = @_;
767
768 my $rpcenv = PVE::RPCEnvironment::get();
769
770 my $authuser = $rpcenv->get_user();
771
772 my $target = extract_param($param, 'target');
773
774 my $localnode = PVE::INotify::nodename();
775 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
776
777 PVE::Cluster::check_cfs_quorum();
778
779 PVE::Cluster::check_node_exists($target);
780
781 my $targetip = PVE::Cluster::remote_node_ip($target);
782
783 my $vmid = extract_param($param, 'vmid');
784
785 # test if VM exists
786 PVE::LXC::load_config($vmid);
787
788 # try to detect errors early
789 if (PVE::LXC::check_running($vmid)) {
790 die "can't migrate running container without --online\n"
791 if !$param->{online};
792 }
793
794 if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
795
796 my $hacmd = sub {
797 my $upid = shift;
798
799 my $service = "ct:$vmid";
800
801 my $cmd = ['ha-manager', 'migrate', $service, $target];
802
803 print "Executing HA migrate for CT $vmid to node $target\n";
804
805 PVE::Tools::run_command($cmd);
806
807 return;
808 };
809
810 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
811
812 } else {
813
814 my $realcmd = sub {
815 my $upid = shift;
816
817 PVE::LXC::Migrate->migrate($target, $targetip, $vmid, $param);
818
819 return;
820 };
821
822 return $rpcenv->fork_worker('vzmigrate', $vmid, $authuser, $realcmd);
823 }
824 }});
825
826 __PACKAGE__->register_method({
827 name => 'vm_feature',
828 path => '{vmid}/feature',
829 method => 'GET',
830 proxyto => 'node',
831 protected => 1,
832 description => "Check if feature for virtual machine is available.",
833 permissions => {
834 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
835 },
836 parameters => {
837 additionalProperties => 0,
838 properties => {
839 node => get_standard_option('pve-node'),
840 vmid => get_standard_option('pve-vmid'),
841 feature => {
842 description => "Feature to check.",
843 type => 'string',
844 enum => [ 'snapshot' ],
845 },
846 snapname => get_standard_option('pve-lxc-snapshot-name', {
847 optional => 1,
848 }),
849 },
850 },
851 returns => {
852 type => "object",
853 properties => {
854 hasFeature => { type => 'boolean' },
855 #nodes => {
856 #type => 'array',
857 #items => { type => 'string' },
858 #}
859 },
860 },
861 code => sub {
862 my ($param) = @_;
863
864 my $node = extract_param($param, 'node');
865
866 my $vmid = extract_param($param, 'vmid');
867
868 my $snapname = extract_param($param, 'snapname');
869
870 my $feature = extract_param($param, 'feature');
871
872 my $conf = PVE::LXC::load_config($vmid);
873
874 if($snapname){
875 my $snap = $conf->{snapshots}->{$snapname};
876 die "snapshot '$snapname' does not exist\n" if !defined($snap);
877 $conf = $snap;
878 }
879 my $storage_cfg = PVE::Storage::config();
880 #Maybe include later
881 #my $nodelist = PVE::LXC::shared_nodes($conf, $storage_cfg);
882 my $hasFeature = PVE::LXC::has_feature($feature, $conf, $storage_cfg, $snapname);
883
884 return {
885 hasFeature => $hasFeature,
886 #nodes => [ keys %$nodelist ],
887 };
888 }});
889
890 __PACKAGE__->register_method({
891 name => 'template',
892 path => '{vmid}/template',
893 method => 'POST',
894 protected => 1,
895 proxyto => 'node',
896 description => "Create a Template.",
897 permissions => {
898 description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
899 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
900 },
901 parameters => {
902 additionalProperties => 0,
903 properties => {
904 node => get_standard_option('pve-node'),
905 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
906 },
907 },
908 returns => { type => 'null'},
909 code => sub {
910 my ($param) = @_;
911
912 my $rpcenv = PVE::RPCEnvironment::get();
913
914 my $authuser = $rpcenv->get_user();
915
916 my $node = extract_param($param, 'node');
917
918 my $vmid = extract_param($param, 'vmid');
919
920 my $updatefn = sub {
921
922 my $conf = PVE::LXC::load_config($vmid);
923 PVE::LXC::check_lock($conf);
924
925 die "unable to create template, because CT contains snapshots\n"
926 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
927
928 die "you can't convert a template to a template\n"
929 if PVE::LXC::is_template($conf);
930
931 die "you can't convert a CT to template if the CT is running\n"
932 if PVE::LXC::check_running($vmid);
933
934 my $realcmd = sub {
935 PVE::LXC::template_create($vmid, $conf);
936 };
937
938 $conf->{template} = 1;
939
940 PVE::LXC::write_config($vmid, $conf);
941 # and remove lxc config
942 PVE::LXC::update_lxc_config(undef, $vmid, $conf);
943
944 return $rpcenv->fork_worker('vztemplate', $vmid, $authuser, $realcmd);
945 };
946
947 PVE::LXC::lock_container($vmid, undef, $updatefn);
948
949 return undef;
950 }});
951
952 __PACKAGE__->register_method({
953 name => 'resize_vm',
954 path => '{vmid}/resize',
955 method => 'PUT',
956 protected => 1,
957 proxyto => 'node',
958 description => "Resize a container mountpoint.",
959 permissions => {
960 check => ['perm', '/vms/{vmid}', ['VM.Config.Disk'], any => 1],
961 },
962 parameters => {
963 additionalProperties => 0,
964 properties => {
965 node => get_standard_option('pve-node'),
966 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
967 disk => {
968 type => 'string',
969 description => "The disk you want to resize.",
970 enum => [PVE::LXC::mountpoint_names()],
971 },
972 size => {
973 type => 'string',
974 pattern => '\+?\d+(\.\d+)?[KMGT]?',
975 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.",
976 },
977 digest => {
978 type => 'string',
979 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
980 maxLength => 40,
981 optional => 1,
982 }
983 },
984 },
985 returns => {
986 type => 'string',
987 description => "the task ID.",
988 },
989 code => sub {
990 my ($param) = @_;
991
992 my $rpcenv = PVE::RPCEnvironment::get();
993
994 my $authuser = $rpcenv->get_user();
995
996 my $node = extract_param($param, 'node');
997
998 my $vmid = extract_param($param, 'vmid');
999
1000 my $digest = extract_param($param, 'digest');
1001
1002 my $sizestr = extract_param($param, 'size');
1003 my $ext = ($sizestr =~ s/^\+//);
1004 my $newsize = PVE::JSONSchema::parse_size($sizestr);
1005 die "invalid size string" if !defined($newsize);
1006
1007 die "no options specified\n" if !scalar(keys %$param);
1008
1009 PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
1010
1011 my $storage_cfg = cfs_read_file("storage.cfg");
1012
1013 my $code = sub {
1014
1015 my $conf = PVE::LXC::load_config($vmid);
1016 PVE::LXC::check_lock($conf);
1017
1018 PVE::Tools::assert_if_modified($digest, $conf->{digest});
1019
1020 my $running = PVE::LXC::check_running($vmid);
1021
1022 my $disk = $param->{disk};
1023 my $mp = $disk eq 'rootfs' ? PVE::LXC::parse_ct_rootfs($conf->{$disk}) :
1024 PVE::LXC::parse_ct_mountpoint($conf->{$disk});
1025
1026 my $volid = $mp->{volume};
1027
1028 my (undef, undef, $owner, undef, undef, undef, $format) =
1029 PVE::Storage::parse_volname($storage_cfg, $volid);
1030
1031 die "can't resize mountpoint owned by another container ($owner)"
1032 if $vmid != $owner;
1033
1034 die "can't resize volume: $disk if snapshot exists\n"
1035 if %{$conf->{snapshots}} && $format eq 'qcow2';
1036
1037 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
1038
1039 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
1040
1041 my $size = PVE::Storage::volume_size_info($storage_cfg, $volid, 5);
1042 $newsize += $size if $ext;
1043 $newsize = int($newsize);
1044
1045 die "unable to shrink disk size\n" if $newsize < $size;
1046
1047 return if $size == $newsize;
1048
1049 PVE::Cluster::log_msg('info', $authuser, "update CT $vmid: resize --disk $disk --size $sizestr");
1050 my $realcmd = sub {
1051 # Note: PVE::Storage::volume_resize doesn't do anything if $running=1, so
1052 # we pass 0 here (parameter only makes sense for qemu)
1053 PVE::Storage::volume_resize($storage_cfg, $volid, $newsize, 0);
1054
1055 $mp->{size} = $newsize;
1056 $conf->{$disk} = PVE::LXC::print_ct_mountpoint($mp, $disk eq 'rootfs');
1057
1058 PVE::LXC::write_config($vmid, $conf);
1059
1060 if ($format eq 'raw') {
1061 my $path = PVE::Storage::path($storage_cfg, $volid, undef);
1062 if ($running) {
1063
1064 $mp->{mp} = '/';
1065 my $use_loopdev = (PVE::LXC::mountpoint_mount_path($mp, $storage_cfg))[1];
1066 $path = PVE::LXC::query_loopdev($path) if $use_loopdev;
1067 die "internal error: CT running but mountpoint not attached to a loop device"
1068 if !$path;
1069 PVE::Tools::run_command(['losetup', '--set-capacity', $path]) if $use_loopdev;
1070
1071 # In order for resize2fs to know that we need online-resizing a mountpoint needs
1072 # to be visible to it in its namespace.
1073 # To not interfere with the rest of the system we unshare the current mount namespace,
1074 # mount over /tmp and then run resize2fs.
1075
1076 # interestingly we don't need to e2fsck on mounted systems...
1077 my $quoted = PVE::Tools::shellquote($path);
1078 my $cmd = "mount --make-rprivate / && mount $quoted /tmp && resize2fs $quoted";
1079 PVE::Tools::run_command(['unshare', '-m', '--', 'sh', '-c', $cmd]);
1080 } else {
1081 PVE::Tools::run_command(['e2fsck', '-f', '-y', $path]);
1082 PVE::Tools::run_command(['resize2fs', $path]);
1083 }
1084 }
1085 };
1086
1087 return $rpcenv->fork_worker('resize', $vmid, $authuser, $realcmd);
1088 };
1089
1090 return PVE::LXC::lock_container($vmid, undef, $code);;
1091 }});
1092
1093 1;