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