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