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