]> git.proxmox.com Git - pve-container.git/blob - src/PVE/API2/LXC.pm
be765d89647f2a88208e56972de9e4795d4610c9
[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::Env::PVE2;
23 use PVE::HA::Config;
24 use PVE::JSONSchema qw(get_standard_option);
25 use base qw(PVE::RESTHandler);
26
27 use Data::Dumper; # fixme: remove
28
29 __PACKAGE__->register_method ({
30 subclass => "PVE::API2::LXC::Config",
31 path => '{vmid}/config',
32 });
33
34 __PACKAGE__->register_method ({
35 subclass => "PVE::API2::LXC::Status",
36 path => '{vmid}/status',
37 });
38
39 __PACKAGE__->register_method ({
40 subclass => "PVE::API2::LXC::Snapshot",
41 path => '{vmid}/snapshot',
42 });
43
44 __PACKAGE__->register_method ({
45 subclass => "PVE::API2::Firewall::CT",
46 path => '{vmid}/firewall',
47 });
48
49 __PACKAGE__->register_method({
50 name => 'vmlist',
51 path => '',
52 method => 'GET',
53 description => "LXC container index (per node).",
54 permissions => {
55 description => "Only list CTs where you have VM.Audit permissons on /vms/<vmid>.",
56 user => 'all',
57 },
58 proxyto => 'node',
59 protected => 1, # /proc files are only readable by root
60 parameters => {
61 additionalProperties => 0,
62 properties => {
63 node => get_standard_option('pve-node'),
64 },
65 },
66 returns => {
67 type => 'array',
68 items => {
69 type => "object",
70 properties => {},
71 },
72 links => [ { rel => 'child', href => "{vmid}" } ],
73 },
74 code => sub {
75 my ($param) = @_;
76
77 my $rpcenv = PVE::RPCEnvironment::get();
78 my $authuser = $rpcenv->get_user();
79
80 my $vmstatus = PVE::LXC::vmstatus();
81
82 my $res = [];
83 foreach my $vmid (keys %$vmstatus) {
84 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
85
86 my $data = $vmstatus->{$vmid};
87 $data->{vmid} = $vmid;
88 push @$res, $data;
89 }
90
91 return $res;
92
93 }});
94
95 __PACKAGE__->register_method({
96 name => 'create_vm',
97 path => '',
98 method => 'POST',
99 description => "Create or restore a container.",
100 permissions => {
101 user => 'all', # check inside
102 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. " .
103 "For restore, it is enough if the user has 'VM.Backup' permission and the VM already exists. " .
104 "You also need 'Datastore.AllocateSpace' permissions on the storage.",
105 },
106 protected => 1,
107 proxyto => 'node',
108 parameters => {
109 additionalProperties => 0,
110 properties => PVE::LXC::Config->json_config_properties({
111 node => get_standard_option('pve-node'),
112 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
113 ostemplate => {
114 description => "The OS template or backup file.",
115 type => 'string',
116 maxLength => 255,
117 completion => \&PVE::LXC::complete_os_templates,
118 },
119 password => {
120 optional => 1,
121 type => 'string',
122 description => "Sets root password inside container.",
123 minLength => 5,
124 },
125 storage => get_standard_option('pve-storage-id', {
126 description => "Default Storage.",
127 default => 'local',
128 optional => 1,
129 completion => \&PVE::Storage::complete_storage_enabled,
130 }),
131 force => {
132 optional => 1,
133 type => 'boolean',
134 description => "Allow to overwrite existing container.",
135 },
136 restore => {
137 optional => 1,
138 type => 'boolean',
139 description => "Mark this as restore task.",
140 },
141 pool => {
142 optional => 1,
143 type => 'string', format => 'pve-poolid',
144 description => "Add the VM to the specified pool.",
145 },
146 'ignore-unpack-errors' => {
147 optional => 1,
148 type => 'boolean',
149 description => "Ignore errors when extracting the template.",
150 },
151 'ssh-public-keys' => {
152 optional => 1,
153 type => 'string',
154 description => "Setup public SSH keys (one key per line, " .
155 "OpenSSH format).",
156 },
157 }),
158 },
159 returns => {
160 type => 'string',
161 },
162 code => sub {
163 my ($param) = @_;
164
165 my $rpcenv = PVE::RPCEnvironment::get();
166
167 my $authuser = $rpcenv->get_user();
168
169 my $node = extract_param($param, 'node');
170
171 my $vmid = extract_param($param, 'vmid');
172
173 my $ignore_unpack_errors = extract_param($param, 'ignore-unpack-errors');
174
175 my $basecfg_fn = PVE::LXC::Config->config_file($vmid);
176
177 my $same_container_exists = -f $basecfg_fn;
178
179 # 'unprivileged' is read-only, so we can't pass it to update_pct_config
180 my $unprivileged = extract_param($param, 'unprivileged');
181
182 my $restore = extract_param($param, 'restore');
183
184 if ($restore) {
185 # fixme: limit allowed parameters
186
187 }
188
189 my $force = extract_param($param, 'force');
190
191 if (!($same_container_exists && $restore && $force)) {
192 PVE::Cluster::check_vmid_unused($vmid);
193 } else {
194 my $conf = PVE::LXC::Config->load_config($vmid);
195 PVE::LXC::Config->check_protection($conf, "unable to restore CT $vmid");
196 }
197
198 my $password = extract_param($param, 'password');
199
200 my $ssh_keys = extract_param($param, 'ssh-public-keys');
201 PVE::Tools::validate_ssh_public_keys($ssh_keys) if defined($ssh_keys);
202
203 my $pool = extract_param($param, 'pool');
204
205 if (defined($pool)) {
206 $rpcenv->check_pool_exist($pool);
207 $rpcenv->check_perm_modify($authuser, "/pool/$pool");
208 }
209
210 if ($rpcenv->check($authuser, "/vms/$vmid", ['VM.Allocate'], 1)) {
211 # OK
212 } elsif ($pool && $rpcenv->check($authuser, "/pool/$pool", ['VM.Allocate'], 1)) {
213 # OK
214 } elsif ($restore && $force && $same_container_exists &&
215 $rpcenv->check($authuser, "/vms/$vmid", ['VM.Backup'], 1)) {
216 # OK: user has VM.Backup permissions, and want to restore an existing VM
217 } else {
218 raise_perm_exc();
219 }
220
221 PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, $pool, $param, []);
222
223 my $storage = extract_param($param, 'storage') // 'local';
224
225 my $storage_cfg = cfs_read_file("storage.cfg");
226
227 my $ostemplate = extract_param($param, 'ostemplate');
228
229 my $archive;
230
231 if ($ostemplate eq '-') {
232 die "pipe requires cli environment\n"
233 if $rpcenv->{type} ne 'cli';
234 die "pipe can only be used with restore tasks\n"
235 if !$restore;
236 $archive = '-';
237 die "restore from pipe requires rootfs parameter\n" if !defined($param->{rootfs});
238 } else {
239 $rpcenv->check_volume_access($authuser, $storage_cfg, $vmid, $ostemplate);
240 $archive = PVE::Storage::abs_filesystem_path($storage_cfg, $ostemplate);
241 }
242
243 my $check_and_activate_storage = sub {
244 my ($sid) = @_;
245
246 my $scfg = PVE::Storage::storage_check_node($storage_cfg, $sid, $node);
247
248 raise_param_exc({ storage => "storage '$sid' does not support container directories"})
249 if !$scfg->{content}->{rootdir};
250
251 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
252
253 PVE::Storage::activate_storage($storage_cfg, $sid);
254 };
255
256 my $conf = {};
257
258 my $no_disk_param = {};
259 my $mp_param = {};
260 my $storage_only_mode = 1;
261 foreach my $opt (keys %$param) {
262 my $value = $param->{$opt};
263 if ($opt eq 'rootfs' || $opt =~ m/^mp\d+$/) {
264 # allow to use simple numbers (add default storage in that case)
265 if ($value =~ m/^\d+(\.\d+)?$/) {
266 $mp_param->{$opt} = "$storage:$value";
267 } else {
268 $mp_param->{$opt} = $value;
269 }
270 $storage_only_mode = 0;
271 } elsif ($opt =~ m/^unused\d+$/) {
272 warn "ignoring '$opt', cannot create/restore with unused volume\n";
273 delete $param->{$opt};
274 } else {
275 $no_disk_param->{$opt} = $value;
276 }
277 }
278
279 die "mountpoints configured, but 'rootfs' not set - aborting\n"
280 if !$storage_only_mode && !defined($mp_param->{rootfs});
281
282 # check storage access, activate storage
283 my $delayed_mp_param = {};
284 PVE::LXC::Config->foreach_mountpoint($mp_param, sub {
285 my ($ms, $mountpoint) = @_;
286
287 my $volid = $mountpoint->{volume};
288 my $mp = $mountpoint->{mp};
289
290 if ($mountpoint->{type} ne 'volume') { # bind or device
291 die "Only root can pass arbitrary filesystem paths.\n"
292 if $authuser ne 'root@pam';
293 } else {
294 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
295 &$check_and_activate_storage($sid);
296 }
297 });
298
299 # check/activate default storage
300 &$check_and_activate_storage($storage) if !defined($mp_param->{rootfs});
301
302 PVE::LXC::Config->update_pct_config($vmid, $conf, 0, $no_disk_param);
303
304 $conf->{unprivileged} = 1 if $unprivileged;
305
306 my $check_vmid_usage = sub {
307 if ($force) {
308 die "can't overwrite running container\n"
309 if PVE::LXC::check_running($vmid);
310 } else {
311 PVE::Cluster::check_vmid_unused($vmid);
312 }
313 };
314
315 my $code = sub {
316 &$check_vmid_usage(); # final check after locking
317
318 PVE::Cluster::check_cfs_quorum();
319 my $vollist = [];
320
321 eval {
322 if ($storage_only_mode) {
323 if ($restore) {
324 (undef, $mp_param) = PVE::LXC::Create::recover_config($archive);
325 die "rootfs configuration could not be recovered, please check and specify manually!\n"
326 if !defined($mp_param->{rootfs});
327 PVE::LXC::Config->foreach_mountpoint($mp_param, sub {
328 my ($ms, $mountpoint) = @_;
329 my $type = $mountpoint->{type};
330 if ($type eq 'volume') {
331 die "unable to detect disk size - please specify $ms (size)\n"
332 if !defined($mountpoint->{size});
333 my $disksize = $mountpoint->{size} / (1024 * 1024 * 1024); # create_disks expects GB as unit size
334 delete $mountpoint->{size};
335 $mountpoint->{volume} = "$storage:$disksize";
336 $mp_param->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
337 } else {
338 my $type = $mountpoint->{type};
339 die "restoring rootfs to $type mount is only possible by specifying -rootfs manually!\n"
340 if ($ms eq 'rootfs');
341
342 if ($mountpoint->{backup}) {
343 warn "WARNING - unsupported configuration!\n";
344 warn "backup was enabled for $type mountpoint $ms ('$mountpoint->{mp}')\n";
345 warn "mountpoint configuration will be restored after archive extraction!\n";
346 warn "contained files will be restored to wrong directory!\n";
347 }
348 $delayed_mp_param->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
349 }
350 });
351 } else {
352 $mp_param->{rootfs} = "$storage:4"; # defaults to 4GB
353 }
354 }
355
356 $vollist = PVE::LXC::create_disks($storage_cfg, $vmid, $mp_param, $conf);
357
358 my $config_fn = PVE::LXC::Config->config_file($vmid);
359 if (-f $config_fn) {
360 die "container exists" if !$restore; # just to be sure
361 my $old_conf = PVE::LXC::Config->load_config($vmid);
362
363 # destroy old container volumes
364 PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $old_conf);
365 }
366 PVE::LXC::Config->write_config($vmid, $conf);
367
368 eval {
369 my $rootdir = PVE::LXC::mount_all($vmid, $storage_cfg, $conf, 1);
370 PVE::LXC::Create::restore_archive($archive, $rootdir, $conf, $ignore_unpack_errors);
371
372 if ($restore) {
373 PVE::LXC::Create::restore_configuration($vmid, $rootdir, $conf);
374 } else {
375 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir); # detect OS
376 PVE::LXC::Config->write_config($vmid, $conf); # safe config (after OS detection)
377 $lxc_setup->post_create_hook($password, $ssh_keys);
378 }
379 };
380 my $err = $@;
381 PVE::LXC::umount_all($vmid, $storage_cfg, $conf, $err ? 1 : 0);
382 PVE::Storage::deactivate_volumes($storage_cfg, PVE::LXC::Config->get_vm_volumes($conf));
383 die $err if $err;
384 # set some defaults
385 $conf->{hostname} ||= "CT$vmid";
386 $conf->{memory} ||= 512;
387 $conf->{swap} //= 512;
388 foreach my $mp (keys %$delayed_mp_param) {
389 $conf->{$mp} = $delayed_mp_param->{$mp};
390 }
391 PVE::LXC::Config->write_config($vmid, $conf);
392 };
393 if (my $err = $@) {
394 PVE::LXC::destroy_disks($storage_cfg, $vollist);
395 PVE::LXC::destroy_config($vmid);
396 die $err;
397 }
398 PVE::AccessControl::add_vm_to_pool($vmid, $pool) if $pool;
399 };
400
401 my $realcmd = sub { PVE::LXC::Config->lock_config($vmid, $code); };
402
403 &$check_vmid_usage(); # first check before locking
404
405 return $rpcenv->fork_worker($restore ? 'vzrestore' : 'vzcreate',
406 $vmid, $authuser, $realcmd);
407
408 }});
409
410 __PACKAGE__->register_method({
411 name => 'vmdiridx',
412 path => '{vmid}',
413 method => 'GET',
414 proxyto => 'node',
415 description => "Directory index",
416 permissions => {
417 user => 'all',
418 },
419 parameters => {
420 additionalProperties => 0,
421 properties => {
422 node => get_standard_option('pve-node'),
423 vmid => get_standard_option('pve-vmid'),
424 },
425 },
426 returns => {
427 type => 'array',
428 items => {
429 type => "object",
430 properties => {
431 subdir => { type => 'string' },
432 },
433 },
434 links => [ { rel => 'child', href => "{subdir}" } ],
435 },
436 code => sub {
437 my ($param) = @_;
438
439 # test if VM exists
440 my $conf = PVE::LXC::Config->load_config($param->{vmid});
441
442 my $res = [
443 { subdir => 'config' },
444 { subdir => 'status' },
445 { subdir => 'vncproxy' },
446 { subdir => 'vncwebsocket' },
447 { subdir => 'spiceproxy' },
448 { subdir => 'migrate' },
449 { subdir => 'clone' },
450 # { subdir => 'initlog' },
451 { subdir => 'rrd' },
452 { subdir => 'rrddata' },
453 { subdir => 'firewall' },
454 { subdir => 'snapshot' },
455 { subdir => 'resize' },
456 ];
457
458 return $res;
459 }});
460
461
462 __PACKAGE__->register_method({
463 name => 'rrd',
464 path => '{vmid}/rrd',
465 method => 'GET',
466 protected => 1, # fixme: can we avoid that?
467 permissions => {
468 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
469 },
470 description => "Read VM RRD statistics (returns PNG)",
471 parameters => {
472 additionalProperties => 0,
473 properties => {
474 node => get_standard_option('pve-node'),
475 vmid => get_standard_option('pve-vmid'),
476 timeframe => {
477 description => "Specify the time frame you are interested in.",
478 type => 'string',
479 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
480 },
481 ds => {
482 description => "The list of datasources you want to display.",
483 type => 'string', format => 'pve-configid-list',
484 },
485 cf => {
486 description => "The RRD consolidation function",
487 type => 'string',
488 enum => [ 'AVERAGE', 'MAX' ],
489 optional => 1,
490 },
491 },
492 },
493 returns => {
494 type => "object",
495 properties => {
496 filename => { type => 'string' },
497 },
498 },
499 code => sub {
500 my ($param) = @_;
501
502 return PVE::Cluster::create_rrd_graph(
503 "pve2-vm/$param->{vmid}", $param->{timeframe},
504 $param->{ds}, $param->{cf});
505
506 }});
507
508 __PACKAGE__->register_method({
509 name => 'rrddata',
510 path => '{vmid}/rrddata',
511 method => 'GET',
512 protected => 1, # fixme: can we avoid that?
513 permissions => {
514 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
515 },
516 description => "Read VM RRD statistics",
517 parameters => {
518 additionalProperties => 0,
519 properties => {
520 node => get_standard_option('pve-node'),
521 vmid => get_standard_option('pve-vmid'),
522 timeframe => {
523 description => "Specify the time frame you are interested in.",
524 type => 'string',
525 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
526 },
527 cf => {
528 description => "The RRD consolidation function",
529 type => 'string',
530 enum => [ 'AVERAGE', 'MAX' ],
531 optional => 1,
532 },
533 },
534 },
535 returns => {
536 type => "array",
537 items => {
538 type => "object",
539 properties => {},
540 },
541 },
542 code => sub {
543 my ($param) = @_;
544
545 return PVE::Cluster::create_rrd_data(
546 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
547 }});
548
549 __PACKAGE__->register_method({
550 name => 'destroy_vm',
551 path => '{vmid}',
552 method => 'DELETE',
553 protected => 1,
554 proxyto => 'node',
555 description => "Destroy the container (also delete all uses files).",
556 permissions => {
557 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
558 },
559 parameters => {
560 additionalProperties => 0,
561 properties => {
562 node => get_standard_option('pve-node'),
563 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
564 },
565 },
566 returns => {
567 type => 'string',
568 },
569 code => sub {
570 my ($param) = @_;
571
572 my $rpcenv = PVE::RPCEnvironment::get();
573
574 my $authuser = $rpcenv->get_user();
575
576 my $vmid = $param->{vmid};
577
578 # test if container exists
579 my $conf = PVE::LXC::Config->load_config($vmid);
580
581 my $storage_cfg = cfs_read_file("storage.cfg");
582
583 PVE::LXC::Config->check_protection($conf, "can't remove CT $vmid");
584
585 die "unable to remove CT $vmid - used in HA resources\n"
586 if PVE::HA::Config::vm_is_ha_managed($vmid);
587
588 my $running_error_msg = "unable to destroy CT $vmid - container is running\n";
589
590 die $running_error_msg if PVE::LXC::check_running($vmid); # check early
591
592 my $code = sub {
593 # reload config after lock
594 $conf = PVE::LXC::Config->load_config($vmid);
595 PVE::LXC::Config->check_lock($conf);
596
597 die $running_error_msg if PVE::LXC::check_running($vmid);
598
599 PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $conf);
600 PVE::AccessControl::remove_vm_access($vmid);
601 PVE::Firewall::remove_vmfw_conf($vmid);
602 };
603
604 my $realcmd = sub { PVE::LXC::Config->lock_config($vmid, $code); };
605
606 return $rpcenv->fork_worker('vzdestroy', $vmid, $authuser, $realcmd);
607 }});
608
609 my $sslcert;
610
611 __PACKAGE__->register_method ({
612 name => 'vncproxy',
613 path => '{vmid}/vncproxy',
614 method => 'POST',
615 protected => 1,
616 permissions => {
617 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
618 },
619 description => "Creates a TCP VNC proxy connections.",
620 parameters => {
621 additionalProperties => 0,
622 properties => {
623 node => get_standard_option('pve-node'),
624 vmid => get_standard_option('pve-vmid'),
625 websocket => {
626 optional => 1,
627 type => 'boolean',
628 description => "use websocket instead of standard VNC.",
629 },
630 },
631 },
632 returns => {
633 additionalProperties => 0,
634 properties => {
635 user => { type => 'string' },
636 ticket => { type => 'string' },
637 cert => { type => 'string' },
638 port => { type => 'integer' },
639 upid => { type => 'string' },
640 },
641 },
642 code => sub {
643 my ($param) = @_;
644
645 my $rpcenv = PVE::RPCEnvironment::get();
646
647 my $authuser = $rpcenv->get_user();
648
649 my $vmid = $param->{vmid};
650 my $node = $param->{node};
651
652 my $authpath = "/vms/$vmid";
653
654 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
655
656 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
657 if !$sslcert;
658
659 my ($remip, $family);
660
661 if ($node ne PVE::INotify::nodename()) {
662 ($remip, $family) = PVE::Cluster::remote_node_ip($node);
663 } else {
664 $family = PVE::Tools::get_host_address_family($node);
665 }
666
667 my $port = PVE::Tools::next_vnc_port($family);
668
669 # NOTE: vncterm VNC traffic is already TLS encrypted,
670 # so we select the fastest chipher here (or 'none'?)
671 my $remcmd = $remip ?
672 ['/usr/bin/ssh', '-t', $remip] : [];
673
674 my $conf = PVE::LXC::Config->load_config($vmid, $node);
675 my $concmd = PVE::LXC::get_console_command($vmid, $conf);
676
677 my $shcmd = [ '/usr/bin/dtach', '-A',
678 "/var/run/dtach/vzctlconsole$vmid",
679 '-r', 'winch', '-z', @$concmd];
680
681 my $realcmd = sub {
682 my $upid = shift;
683
684 syslog ('info', "starting lxc vnc proxy $upid\n");
685
686 my $timeout = 10;
687
688 my $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
689 '-timeout', $timeout, '-authpath', $authpath,
690 '-perm', 'VM.Console'];
691
692 if ($param->{websocket}) {
693 $ENV{PVE_VNC_TICKET} = $ticket; # pass ticket to vncterm
694 push @$cmd, '-notls', '-listen', 'localhost';
695 }
696
697 push @$cmd, '-c', @$remcmd, @$shcmd;
698
699 run_command($cmd);
700
701 return;
702 };
703
704 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
705
706 PVE::Tools::wait_for_vnc_port($port);
707
708 return {
709 user => $authuser,
710 ticket => $ticket,
711 port => $port,
712 upid => $upid,
713 cert => $sslcert,
714 };
715 }});
716
717 __PACKAGE__->register_method({
718 name => 'vncwebsocket',
719 path => '{vmid}/vncwebsocket',
720 method => 'GET',
721 permissions => {
722 description => "You also need to pass a valid ticket (vncticket).",
723 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
724 },
725 description => "Opens a weksocket for VNC traffic.",
726 parameters => {
727 additionalProperties => 0,
728 properties => {
729 node => get_standard_option('pve-node'),
730 vmid => get_standard_option('pve-vmid'),
731 vncticket => {
732 description => "Ticket from previous call to vncproxy.",
733 type => 'string',
734 maxLength => 512,
735 },
736 port => {
737 description => "Port number returned by previous vncproxy call.",
738 type => 'integer',
739 minimum => 5900,
740 maximum => 5999,
741 },
742 },
743 },
744 returns => {
745 type => "object",
746 properties => {
747 port => { type => 'string' },
748 },
749 },
750 code => sub {
751 my ($param) = @_;
752
753 my $rpcenv = PVE::RPCEnvironment::get();
754
755 my $authuser = $rpcenv->get_user();
756
757 my $authpath = "/vms/$param->{vmid}";
758
759 PVE::AccessControl::verify_vnc_ticket($param->{vncticket}, $authuser, $authpath);
760
761 my $port = $param->{port};
762
763 return { port => $port };
764 }});
765
766 __PACKAGE__->register_method ({
767 name => 'spiceproxy',
768 path => '{vmid}/spiceproxy',
769 method => 'POST',
770 protected => 1,
771 proxyto => 'node',
772 permissions => {
773 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
774 },
775 description => "Returns a SPICE configuration to connect to the CT.",
776 parameters => {
777 additionalProperties => 0,
778 properties => {
779 node => get_standard_option('pve-node'),
780 vmid => get_standard_option('pve-vmid'),
781 proxy => get_standard_option('spice-proxy', { optional => 1 }),
782 },
783 },
784 returns => get_standard_option('remote-viewer-config'),
785 code => sub {
786 my ($param) = @_;
787
788 my $vmid = $param->{vmid};
789 my $node = $param->{node};
790 my $proxy = $param->{proxy};
791
792 my $authpath = "/vms/$vmid";
793 my $permissions = 'VM.Console';
794
795 my $conf = PVE::LXC::Config->load_config($vmid);
796
797 die "CT $vmid not running\n" if !PVE::LXC::check_running($vmid);
798
799 my $concmd = PVE::LXC::get_console_command($vmid, $conf);
800
801 my $shcmd = ['/usr/bin/dtach', '-A',
802 "/var/run/dtach/vzctlconsole$vmid",
803 '-r', 'winch', '-z', @$concmd];
804
805 my $title = "CT $vmid";
806
807 return PVE::API2Tools::run_spiceterm($authpath, $permissions, $vmid, $node, $proxy, $title, $shcmd);
808 }});
809
810
811 __PACKAGE__->register_method({
812 name => 'migrate_vm',
813 path => '{vmid}/migrate',
814 method => 'POST',
815 protected => 1,
816 proxyto => 'node',
817 description => "Migrate the container to another node. Creates a new migration task.",
818 permissions => {
819 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
820 },
821 parameters => {
822 additionalProperties => 0,
823 properties => {
824 node => get_standard_option('pve-node'),
825 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
826 target => get_standard_option('pve-node', {
827 description => "Target node.",
828 completion => \&PVE::Cluster::complete_migration_target,
829 }),
830 online => {
831 type => 'boolean',
832 description => "Use online/live migration.",
833 optional => 1,
834 },
835 force => {
836 type => 'boolean',
837 description => "Force migration despite local bind / device" .
838 " mounts. WARNING: identical bind / device mounts need to ".
839 " be available on the target node.",
840 optional => 1,
841 },
842 },
843 },
844 returns => {
845 type => 'string',
846 description => "the task ID.",
847 },
848 code => sub {
849 my ($param) = @_;
850
851 my $rpcenv = PVE::RPCEnvironment::get();
852
853 my $authuser = $rpcenv->get_user();
854
855 my $target = extract_param($param, 'target');
856
857 my $localnode = PVE::INotify::nodename();
858 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
859
860 PVE::Cluster::check_cfs_quorum();
861
862 PVE::Cluster::check_node_exists($target);
863
864 my $targetip = PVE::Cluster::remote_node_ip($target);
865
866 my $vmid = extract_param($param, 'vmid');
867
868 # test if VM exists
869 PVE::LXC::Config->load_config($vmid);
870
871 # try to detect errors early
872 if (PVE::LXC::check_running($vmid)) {
873 die "can't migrate running container without --online\n"
874 if !$param->{online};
875 }
876
877 if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
878
879 my $hacmd = sub {
880 my $upid = shift;
881
882 my $service = "ct:$vmid";
883
884 my $cmd = ['ha-manager', 'migrate', $service, $target];
885
886 print "Executing HA migrate for CT $vmid to node $target\n";
887
888 PVE::Tools::run_command($cmd);
889
890 return;
891 };
892
893 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
894
895 } else {
896
897 my $realcmd = sub {
898 my $upid = shift;
899
900 PVE::LXC::Migrate->migrate($target, $targetip, $vmid, $param);
901
902 return;
903 };
904
905 return $rpcenv->fork_worker('vzmigrate', $vmid, $authuser, $realcmd);
906 }
907 }});
908
909 __PACKAGE__->register_method({
910 name => 'vm_feature',
911 path => '{vmid}/feature',
912 method => 'GET',
913 proxyto => 'node',
914 protected => 1,
915 description => "Check if feature for virtual machine is available.",
916 permissions => {
917 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
918 },
919 parameters => {
920 additionalProperties => 0,
921 properties => {
922 node => get_standard_option('pve-node'),
923 vmid => get_standard_option('pve-vmid'),
924 feature => {
925 description => "Feature to check.",
926 type => 'string',
927 enum => [ 'snapshot' ],
928 },
929 snapname => get_standard_option('pve-lxc-snapshot-name', {
930 optional => 1,
931 }),
932 },
933 },
934 returns => {
935 type => "object",
936 properties => {
937 hasFeature => { type => 'boolean' },
938 #nodes => {
939 #type => 'array',
940 #items => { type => 'string' },
941 #}
942 },
943 },
944 code => sub {
945 my ($param) = @_;
946
947 my $node = extract_param($param, 'node');
948
949 my $vmid = extract_param($param, 'vmid');
950
951 my $snapname = extract_param($param, 'snapname');
952
953 my $feature = extract_param($param, 'feature');
954
955 my $conf = PVE::LXC::Config->load_config($vmid);
956
957 if($snapname){
958 my $snap = $conf->{snapshots}->{$snapname};
959 die "snapshot '$snapname' does not exist\n" if !defined($snap);
960 $conf = $snap;
961 }
962 my $storage_cfg = PVE::Storage::config();
963 #Maybe include later
964 #my $nodelist = PVE::LXC::shared_nodes($conf, $storage_cfg);
965 my $hasFeature = PVE::LXC::Config->has_feature($feature, $conf, $storage_cfg, $snapname);
966
967 return {
968 hasFeature => $hasFeature,
969 #nodes => [ keys %$nodelist ],
970 };
971 }});
972
973 __PACKAGE__->register_method({
974 name => 'template',
975 path => '{vmid}/template',
976 method => 'POST',
977 protected => 1,
978 proxyto => 'node',
979 description => "Create a Template.",
980 permissions => {
981 description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
982 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
983 },
984 parameters => {
985 additionalProperties => 0,
986 properties => {
987 node => get_standard_option('pve-node'),
988 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
989 experimental => {
990 type => 'boolean',
991 description => "The template feature is experimental, set this " .
992 "flag if you know what you are doing.",
993 default => 0,
994 },
995 },
996 },
997 returns => { type => 'null'},
998 code => sub {
999 my ($param) = @_;
1000
1001 my $rpcenv = PVE::RPCEnvironment::get();
1002
1003 my $authuser = $rpcenv->get_user();
1004
1005 my $node = extract_param($param, 'node');
1006
1007 my $vmid = extract_param($param, 'vmid');
1008
1009 my $updatefn = sub {
1010
1011 my $conf = PVE::LXC::Config->load_config($vmid);
1012 PVE::LXC::Config->check_lock($conf);
1013
1014 die "unable to create template, because CT contains snapshots\n"
1015 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
1016
1017 die "you can't convert a template to a template\n"
1018 if PVE::LXC::Config->is_template($conf);
1019
1020 die "you can't convert a CT to template if the CT is running\n"
1021 if PVE::LXC::check_running($vmid);
1022
1023 my $realcmd = sub {
1024 PVE::LXC::template_create($vmid, $conf);
1025 };
1026
1027 $conf->{template} = 1;
1028
1029 PVE::LXC::Config->write_config($vmid, $conf);
1030 # and remove lxc config
1031 PVE::LXC::update_lxc_config(undef, $vmid, $conf);
1032
1033 return $rpcenv->fork_worker('vztemplate', $vmid, $authuser, $realcmd);
1034 };
1035
1036 PVE::LXC::Config->lock_config($vmid, $updatefn);
1037
1038 return undef;
1039 }});
1040
1041 __PACKAGE__->register_method({
1042 name => 'clone_vm',
1043 path => '{vmid}/clone',
1044 method => 'POST',
1045 protected => 1,
1046 proxyto => 'node',
1047 description => "Create a container clone/copy",
1048 permissions => {
1049 description => "You need 'VM.Clone' permissions on /vms/{vmid}, " .
1050 "and 'VM.Allocate' permissions " .
1051 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
1052 "'Datastore.AllocateSpace' on any used storage.",
1053 check =>
1054 [ 'and',
1055 ['perm', '/vms/{vmid}', [ 'VM.Clone' ]],
1056 [ 'or',
1057 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
1058 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
1059 ],
1060 ]
1061 },
1062 parameters => {
1063 additionalProperties => 0,
1064 properties => {
1065 node => get_standard_option('pve-node'),
1066 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
1067 newid => get_standard_option('pve-vmid', {
1068 completion => \&PVE::Cluster::complete_next_vmid,
1069 description => 'VMID for the clone.' }),
1070 hostname => {
1071 optional => 1,
1072 type => 'string', format => 'dns-name',
1073 description => "Set a hostname for the new CT.",
1074 },
1075 description => {
1076 optional => 1,
1077 type => 'string',
1078 description => "Description for the new CT.",
1079 },
1080 pool => {
1081 optional => 1,
1082 type => 'string', format => 'pve-poolid',
1083 description => "Add the new CT to the specified pool.",
1084 },
1085 snapname => get_standard_option('pve-lxc-snapshot-name', {
1086 optional => 1,
1087 }),
1088 storage => get_standard_option('pve-storage-id', {
1089 description => "Target storage for full clone.",
1090 requires => 'full',
1091 optional => 1,
1092 }),
1093 full => {
1094 optional => 1,
1095 type => 'boolean',
1096 description => "Create a full copy of all disk. This is always done when " .
1097 "you clone a normal CT. For CT templates, we try to create a linked clone by default.",
1098 default => 0,
1099 },
1100 experimental => {
1101 type => 'boolean',
1102 description => "The clone feature is experimental, set this " .
1103 "flag if you know what you are doing.",
1104 default => 0,
1105 },
1106 # target => get_standard_option('pve-node', {
1107 # description => "Target node. Only allowed if the original VM is on shared storage.",
1108 # optional => 1,
1109 # }),
1110 },
1111 },
1112 returns => {
1113 type => 'string',
1114 },
1115 code => sub {
1116 my ($param) = @_;
1117
1118 my $rpcenv = PVE::RPCEnvironment::get();
1119
1120 my $authuser = $rpcenv->get_user();
1121
1122 my $node = extract_param($param, 'node');
1123
1124 my $vmid = extract_param($param, 'vmid');
1125
1126 my $newid = extract_param($param, 'newid');
1127
1128 my $pool = extract_param($param, 'pool');
1129
1130 if (defined($pool)) {
1131 $rpcenv->check_pool_exist($pool);
1132 }
1133
1134 my $snapname = extract_param($param, 'snapname');
1135
1136 my $storage = extract_param($param, 'storage');
1137
1138 my $localnode = PVE::INotify::nodename();
1139
1140 my $storecfg = PVE::Storage::config();
1141
1142 if ($storage) {
1143 # check if storage is enabled on local node
1144 PVE::Storage::storage_check_enabled($storecfg, $storage);
1145 }
1146
1147 PVE::Cluster::check_cfs_quorum();
1148
1149 my $running = PVE::LXC::check_running($vmid) || 0;
1150
1151 my $clonefn = sub {
1152
1153 # do all tests after lock
1154 # we also try to do all tests before we fork the worker
1155 my $conf = PVE::LXC::Config->load_config($vmid);
1156
1157 PVE::LXC::Config->check_lock($conf);
1158
1159 my $verify_running = PVE::LXC::check_running($vmid) || 0;
1160
1161 die "unexpected state change\n" if $verify_running != $running;
1162
1163 die "snapshot '$snapname' does not exist\n"
1164 if $snapname && !defined( $conf->{snapshots}->{$snapname});
1165
1166 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
1167
1168 my $conffile = PVE::LXC::Config->config_file($newid);
1169 die "unable to create CT $newid: config file already exists\n"
1170 if -f $conffile;
1171
1172 my $newconf = { lock => 'clone' };
1173 my $mountpoints = {};
1174 my $fullclone = {};
1175 my $vollist = [];
1176
1177 foreach my $opt (keys %$oldconf) {
1178 my $value = $oldconf->{$opt};
1179
1180 # no need to copy unused images, because VMID(owner) changes anyways
1181 next if $opt =~ m/^unused\d+$/;
1182
1183 if (($opt eq 'rootfs') || ($opt =~ m/^mp\d+$/)) {
1184 my $mp = $opt eq 'rootfs' ?
1185 PVE::LXC::Config->parse_ct_rootfs($value) :
1186 PVE::LXC::Config->parse_ct_mountpoint($value);
1187
1188 if ($mp->{type} eq 'volume') {
1189 my $volid = $mp->{volume};
1190 if ($param->{full}) {
1191 die "fixme: full clone not implemented";
1192
1193 die "Full clone feature for '$volid' is not available\n"
1194 if !PVE::Storage::volume_has_feature($storecfg, 'copy', $volid, $snapname, $running);
1195 $fullclone->{$opt} = 1;
1196 } else {
1197 # not full means clone instead of copy
1198 die "Linked clone feature for '$volid' is not available\n"
1199 if !PVE::Storage::volume_has_feature($storecfg, 'clone', $volid, $snapname, $running);
1200 }
1201
1202 $mountpoints->{$opt} = $mp;
1203 push @$vollist, $volid;
1204
1205 } else {
1206 # TODO: allow bind mounts?
1207 die "unable to clone mountpint '$opt' (type $mp->{type})\n";
1208 }
1209
1210 } else {
1211 # copy everything else
1212 $newconf->{$opt} = $value;
1213 }
1214 }
1215
1216 delete $newconf->{template};
1217 if ($param->{hostname}) {
1218 $newconf->{hostname} = $param->{hostname};
1219 }
1220
1221 if ($param->{description}) {
1222 $newconf->{description} = $param->{description};
1223 }
1224
1225 # create empty/temp config - this fails if CT already exists on other node
1226 PVE::Tools::file_set_contents($conffile, "# ctclone temporary file\nlock: clone\n");
1227
1228 my $realcmd = sub {
1229 my $upid = shift;
1230
1231 my $newvollist = [];
1232
1233 eval {
1234 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
1235
1236 PVE::Storage::activate_volumes($storecfg, $vollist, $snapname);
1237
1238 foreach my $opt (keys %$mountpoints) {
1239 my $mp = $mountpoints->{$opt};
1240 my $volid = $mp->{volume};
1241
1242 if ($fullclone->{$opt}) {
1243 die "fixme: full clone not implemented\n";
1244 } else {
1245 print "create linked clone of mountpoint $opt ($volid)\n";
1246 my $newvolid = PVE::Storage::vdisk_clone($storecfg, $volid, $newid, $snapname);
1247 push @$newvollist, $newvolid;
1248 $mp->{volume} = $newvolid;
1249
1250 $newconf->{$opt} = PVE::LXC::Config->print_ct_mountpoint($mp, $opt eq 'rootfs');
1251 PVE::LXC::Config->write_config($newid, $newconf);
1252 }
1253 }
1254
1255 delete $newconf->{lock};
1256 PVE::LXC::Config->write_config($newid, $newconf);
1257
1258 PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
1259 };
1260 if (my $err = $@) {
1261 unlink $conffile;
1262
1263 sleep 1; # some storage like rbd need to wait before release volume - really?
1264
1265 foreach my $volid (@$newvollist) {
1266 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1267 warn $@ if $@;
1268 }
1269 die "clone failed: $err";
1270 }
1271
1272 return;
1273 };
1274
1275 PVE::Firewall::clone_vmfw_conf($vmid, $newid);
1276
1277 return $rpcenv->fork_worker('vzclone', $vmid, $authuser, $realcmd);
1278
1279 };
1280
1281 return PVE::LXC::Config->lock_config($vmid, $clonefn);
1282 }});
1283
1284
1285 __PACKAGE__->register_method({
1286 name => 'resize_vm',
1287 path => '{vmid}/resize',
1288 method => 'PUT',
1289 protected => 1,
1290 proxyto => 'node',
1291 description => "Resize a container mountpoint.",
1292 permissions => {
1293 check => ['perm', '/vms/{vmid}', ['VM.Config.Disk'], any => 1],
1294 },
1295 parameters => {
1296 additionalProperties => 0,
1297 properties => {
1298 node => get_standard_option('pve-node'),
1299 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
1300 disk => {
1301 type => 'string',
1302 description => "The disk you want to resize.",
1303 enum => [PVE::LXC::Config->mountpoint_names()],
1304 },
1305 size => {
1306 type => 'string',
1307 pattern => '\+?\d+(\.\d+)?[KMGT]?',
1308 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.",
1309 },
1310 digest => {
1311 type => 'string',
1312 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1313 maxLength => 40,
1314 optional => 1,
1315 }
1316 },
1317 },
1318 returns => {
1319 type => 'string',
1320 description => "the task ID.",
1321 },
1322 code => sub {
1323 my ($param) = @_;
1324
1325 my $rpcenv = PVE::RPCEnvironment::get();
1326
1327 my $authuser = $rpcenv->get_user();
1328
1329 my $node = extract_param($param, 'node');
1330
1331 my $vmid = extract_param($param, 'vmid');
1332
1333 my $digest = extract_param($param, 'digest');
1334
1335 my $sizestr = extract_param($param, 'size');
1336 my $ext = ($sizestr =~ s/^\+//);
1337 my $newsize = PVE::JSONSchema::parse_size($sizestr);
1338 die "invalid size string" if !defined($newsize);
1339
1340 die "no options specified\n" if !scalar(keys %$param);
1341
1342 PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, $param, []);
1343
1344 my $storage_cfg = cfs_read_file("storage.cfg");
1345
1346 my $code = sub {
1347
1348 my $conf = PVE::LXC::Config->load_config($vmid);
1349 PVE::LXC::Config->check_lock($conf);
1350
1351 PVE::Tools::assert_if_modified($digest, $conf->{digest});
1352
1353 my $running = PVE::LXC::check_running($vmid);
1354
1355 my $disk = $param->{disk};
1356 my $mp = $disk eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($conf->{$disk}) :
1357 PVE::LXC::Config->parse_ct_mountpoint($conf->{$disk});
1358
1359 my $volid = $mp->{volume};
1360
1361 my (undef, undef, $owner, undef, undef, undef, $format) =
1362 PVE::Storage::parse_volname($storage_cfg, $volid);
1363
1364 die "can't resize mountpoint owned by another container ($owner)"
1365 if $vmid != $owner;
1366
1367 die "can't resize volume: $disk if snapshot exists\n"
1368 if %{$conf->{snapshots}} && $format eq 'qcow2';
1369
1370 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
1371
1372 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
1373
1374 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1375
1376 my $size = PVE::Storage::volume_size_info($storage_cfg, $volid, 5);
1377 $newsize += $size if $ext;
1378 $newsize = int($newsize);
1379
1380 die "unable to shrink disk size\n" if $newsize < $size;
1381
1382 return if $size == $newsize;
1383
1384 PVE::Cluster::log_msg('info', $authuser, "update CT $vmid: resize --disk $disk --size $sizestr");
1385 my $realcmd = sub {
1386 # Note: PVE::Storage::volume_resize doesn't do anything if $running=1, so
1387 # we pass 0 here (parameter only makes sense for qemu)
1388 PVE::Storage::volume_resize($storage_cfg, $volid, $newsize, 0);
1389
1390 $mp->{size} = $newsize;
1391 $conf->{$disk} = PVE::LXC::Config->print_ct_mountpoint($mp, $disk eq 'rootfs');
1392
1393 PVE::LXC::Config->write_config($vmid, $conf);
1394
1395 if ($format eq 'raw') {
1396 my $path = PVE::Storage::path($storage_cfg, $volid, undef);
1397 if ($running) {
1398
1399 $mp->{mp} = '/';
1400 my $use_loopdev = (PVE::LXC::mountpoint_mount_path($mp, $storage_cfg))[1];
1401 $path = PVE::LXC::query_loopdev($path) if $use_loopdev;
1402 die "internal error: CT running but mountpoint not attached to a loop device"
1403 if !$path;
1404 PVE::Tools::run_command(['losetup', '--set-capacity', $path]) if $use_loopdev;
1405
1406 # In order for resize2fs to know that we need online-resizing a mountpoint needs
1407 # to be visible to it in its namespace.
1408 # To not interfere with the rest of the system we unshare the current mount namespace,
1409 # mount over /tmp and then run resize2fs.
1410
1411 # interestingly we don't need to e2fsck on mounted systems...
1412 my $quoted = PVE::Tools::shellquote($path);
1413 my $cmd = "mount --make-rprivate / && mount $quoted /tmp && resize2fs $quoted";
1414 eval {
1415 PVE::Tools::run_command(['unshare', '-m', '--', 'sh', '-c', $cmd]);
1416 };
1417 warn "Failed to update the container's filesystem: $@\n" if $@;
1418 } else {
1419 eval {
1420 PVE::Tools::run_command(['e2fsck', '-f', '-y', $path]);
1421 PVE::Tools::run_command(['resize2fs', $path]);
1422 };
1423 warn "Failed to update the container's filesystem: $@\n" if $@;
1424 }
1425 }
1426 };
1427
1428 return $rpcenv->fork_worker('resize', $vmid, $authuser, $realcmd);
1429 };
1430
1431 return PVE::LXC::Config->lock_config($vmid, $code);;
1432 }});
1433
1434 1;