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