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