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