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