]> git.proxmox.com Git - qemu-server.git/blob - PVE/API2/Qemu.pm
api: update: also check access for currently configured bridge
[qemu-server.git] / PVE / API2 / Qemu.pm
1 package PVE::API2::Qemu;
2
3 use strict;
4 use warnings;
5 use Cwd 'abs_path';
6 use Net::SSLeay;
7 use IO::Socket::IP;
8 use IO::Socket::UNIX;
9 use IPC::Open3;
10 use JSON;
11 use URI::Escape;
12 use Crypt::OpenSSL::Random;
13 use Socket qw(SOCK_STREAM);
14
15 use PVE::APIClient::LWP;
16 use PVE::CGroup;
17 use PVE::Cluster qw (cfs_read_file cfs_write_file);;
18 use PVE::RRD;
19 use PVE::SafeSyslog;
20 use PVE::Tools qw(extract_param);
21 use PVE::Exception qw(raise raise_param_exc raise_perm_exc);
22 use PVE::Storage;
23 use PVE::JSONSchema qw(get_standard_option);
24 use PVE::RESTHandler;
25 use PVE::ReplicationConfig;
26 use PVE::GuestHelpers qw(assert_tag_permissions);
27 use PVE::QemuConfig;
28 use PVE::QemuServer;
29 use PVE::QemuServer::Cloudinit;
30 use PVE::QemuServer::CPUConfig;
31 use PVE::QemuServer::Drive;
32 use PVE::QemuServer::ImportDisk;
33 use PVE::QemuServer::Monitor qw(mon_cmd);
34 use PVE::QemuServer::Machine;
35 use PVE::QemuServer::PCI;
36 use PVE::QemuServer::USB;
37 use PVE::QemuMigrate;
38 use PVE::RPCEnvironment;
39 use PVE::AccessControl;
40 use PVE::INotify;
41 use PVE::Network;
42 use PVE::Firewall;
43 use PVE::API2::Firewall::VM;
44 use PVE::API2::Qemu::Agent;
45 use PVE::VZDump::Plugin;
46 use PVE::DataCenterConfig;
47 use PVE::SSHInfo;
48 use PVE::Replication;
49 use PVE::StorageTunnel;
50
51 BEGIN {
52 if (!$ENV{PVE_GENERATING_DOCS}) {
53 require PVE::HA::Env::PVE2;
54 import PVE::HA::Env::PVE2;
55 require PVE::HA::Config;
56 import PVE::HA::Config;
57 }
58 }
59
60 use base qw(PVE::RESTHandler);
61
62 my $opt_force_description = "Force physical removal. Without this, we simple remove the disk from the config file and create an additional configuration entry called 'unused[n]', which contains the volume ID. Unlink of unused[n] always cause physical removal.";
63
64 my $resolve_cdrom_alias = sub {
65 my $param = shift;
66
67 if (my $value = $param->{cdrom}) {
68 $value .= ",media=cdrom" if $value !~ m/media=/;
69 $param->{ide2} = $value;
70 delete $param->{cdrom};
71 }
72 };
73
74 # Used in import-enabled API endpoints. Parses drives using the extended '_with_alloc' schema.
75 my $foreach_volume_with_alloc = sub {
76 my ($param, $func) = @_;
77
78 for my $opt (sort keys $param->%*) {
79 next if !PVE::QemuServer::is_valid_drivename($opt);
80
81 my $drive = PVE::QemuServer::Drive::parse_drive($opt, $param->{$opt}, 1);
82 next if !$drive;
83
84 $func->($opt, $drive);
85 }
86 };
87
88 my $NEW_DISK_RE = qr!^(([^/:\s]+):)?(\d+(\.\d+)?)$!;
89
90 my $check_drive_param = sub {
91 my ($param, $storecfg, $extra_checks) = @_;
92
93 for my $opt (sort keys $param->%*) {
94 next if !PVE::QemuServer::is_valid_drivename($opt);
95
96 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt}, 1);
97 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
98
99 if ($drive->{'import-from'}) {
100 if ($drive->{file} !~ $NEW_DISK_RE || $3 != 0) {
101 raise_param_exc({
102 $opt => "'import-from' requires special syntax - ".
103 "use <storage ID>:0,import-from=<source>",
104 });
105 }
106
107 if ($opt eq 'efidisk0') {
108 for my $required (qw(efitype pre-enrolled-keys)) {
109 if (!defined($drive->{$required})) {
110 raise_param_exc({
111 $opt => "need to specify '$required' when using 'import-from'",
112 });
113 }
114 }
115 } elsif ($opt eq 'tpmstate0') {
116 raise_param_exc({ $opt => "need to specify 'version' when using 'import-from'" })
117 if !defined($drive->{version});
118 }
119 }
120
121 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
122
123 $extra_checks->($drive) if $extra_checks;
124
125 $param->{$opt} = PVE::QemuServer::print_drive($drive, 1);
126 }
127 };
128
129 my $check_storage_access = sub {
130 my ($rpcenv, $authuser, $storecfg, $vmid, $settings, $default_storage) = @_;
131
132 $foreach_volume_with_alloc->($settings, sub {
133 my ($ds, $drive) = @_;
134
135 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
136
137 my $volid = $drive->{file};
138 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
139
140 if (!$volid || ($volid eq 'none' || $volid eq 'cloudinit' || (defined($volname) && $volname eq 'cloudinit'))) {
141 # nothing to check
142 } elsif ($isCDROM && ($volid eq 'cdrom')) {
143 $rpcenv->check($authuser, "/", ['Sys.Console']);
144 } elsif (!$isCDROM && ($volid =~ $NEW_DISK_RE)) {
145 my ($storeid, $size) = ($2 || $default_storage, $3);
146 die "no storage ID specified (and no default storage)\n" if !$storeid;
147 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
148 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
149 raise_param_exc({ storage => "storage '$storeid' does not support vm images"})
150 if !$scfg->{content}->{images};
151 } else {
152 PVE::Storage::check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $volid);
153 if ($storeid) {
154 my ($vtype) = PVE::Storage::parse_volname($storecfg, $volid);
155 raise_param_exc({ $ds => "content type needs to be 'images' or 'iso'" })
156 if $vtype ne 'images' && $vtype ne 'iso';
157 }
158 }
159
160 if (my $src_image = $drive->{'import-from'}) {
161 my $src_vmid;
162 if (PVE::Storage::parse_volume_id($src_image, 1)) { # PVE-managed volume
163 (my $vtype, undef, $src_vmid) = PVE::Storage::parse_volname($storecfg, $src_image);
164 raise_param_exc({ $ds => "$src_image has wrong type '$vtype' - not an image" })
165 if $vtype ne 'images';
166 }
167
168 if ($src_vmid) { # might be actively used by VM and will be copied via clone_disk()
169 $rpcenv->check($authuser, "/vms/${src_vmid}", ['VM.Clone']);
170 } else {
171 PVE::Storage::check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $src_image);
172 }
173 }
174 });
175
176 $rpcenv->check($authuser, "/storage/$settings->{vmstatestorage}", ['Datastore.AllocateSpace'])
177 if defined($settings->{vmstatestorage});
178 };
179
180 my $check_storage_access_clone = sub {
181 my ($rpcenv, $authuser, $storecfg, $conf, $storage) = @_;
182
183 my $sharedvm = 1;
184
185 PVE::QemuConfig->foreach_volume($conf, sub {
186 my ($ds, $drive) = @_;
187
188 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
189
190 my $volid = $drive->{file};
191
192 return if !$volid || $volid eq 'none';
193
194 if ($isCDROM) {
195 if ($volid eq 'cdrom') {
196 $rpcenv->check($authuser, "/", ['Sys.Console']);
197 } else {
198 # we simply allow access
199 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
200 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
201 $sharedvm = 0 if !$scfg->{shared};
202
203 }
204 } else {
205 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
206 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
207 $sharedvm = 0 if !$scfg->{shared};
208
209 $sid = $storage if $storage;
210 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
211 }
212 });
213
214 $rpcenv->check($authuser, "/storage/$conf->{vmstatestorage}", ['Datastore.AllocateSpace'])
215 if defined($conf->{vmstatestorage});
216
217 return $sharedvm;
218 };
219
220 my $check_storage_access_migrate = sub {
221 my ($rpcenv, $authuser, $storecfg, $storage, $node) = @_;
222
223 PVE::Storage::storage_check_enabled($storecfg, $storage, $node);
224
225 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace']);
226
227 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
228 die "storage '$storage' does not support vm images\n"
229 if !$scfg->{content}->{images};
230 };
231
232 my $import_from_volid = sub {
233 my ($storecfg, $src_volid, $dest_info, $vollist) = @_;
234
235 die "could not get size of $src_volid\n"
236 if !PVE::Storage::volume_size_info($storecfg, $src_volid, 10);
237
238 die "cannot import from cloudinit disk\n"
239 if PVE::QemuServer::Drive::drive_is_cloudinit({ file => $src_volid });
240
241 my $src_vmid = (PVE::Storage::parse_volname($storecfg, $src_volid))[2];
242
243 my $src_vm_state = sub {
244 my $exists = $src_vmid && PVE::Cluster::get_vmlist()->{ids}->{$src_vmid} ? 1 : 0;
245
246 my $runs = 0;
247 if ($exists) {
248 eval { PVE::QemuConfig::assert_config_exists_on_node($src_vmid); };
249 die "owner VM $src_vmid not on local node\n" if $@;
250 $runs = PVE::QemuServer::Helpers::vm_running_locally($src_vmid) || 0;
251 }
252
253 return ($exists, $runs);
254 };
255
256 my ($src_vm_exists, $running) = $src_vm_state->();
257
258 die "cannot import from '$src_volid' - full clone feature is not supported\n"
259 if !PVE::Storage::volume_has_feature($storecfg, 'copy', $src_volid, undef, $running);
260
261 my $clonefn = sub {
262 my ($src_vm_exists_now, $running_now) = $src_vm_state->();
263
264 die "owner VM $src_vmid changed state unexpectedly\n"
265 if $src_vm_exists_now != $src_vm_exists || $running_now != $running;
266
267 my $src_conf = $src_vm_exists_now ? PVE::QemuConfig->load_config($src_vmid) : {};
268
269 my $src_drive = { file => $src_volid };
270 my $src_drivename;
271 PVE::QemuConfig->foreach_volume($src_conf, sub {
272 my ($ds, $drive) = @_;
273
274 return if $src_drivename;
275
276 if ($drive->{file} eq $src_volid) {
277 $src_drive = $drive;
278 $src_drivename = $ds;
279 }
280 });
281
282 my $source_info = {
283 vmid => $src_vmid,
284 running => $running_now,
285 drivename => $src_drivename,
286 drive => $src_drive,
287 snapname => undef,
288 };
289
290 my ($src_storeid) = PVE::Storage::parse_volume_id($src_volid);
291
292 return PVE::QemuServer::clone_disk(
293 $storecfg,
294 $source_info,
295 $dest_info,
296 1,
297 $vollist,
298 undef,
299 undef,
300 $src_conf->{agent},
301 PVE::Storage::get_bandwidth_limit('clone', [$src_storeid, $dest_info->{storage}]),
302 );
303 };
304
305 my $cloned;
306 if ($running) {
307 $cloned = PVE::QemuConfig->lock_config_full($src_vmid, 30, $clonefn);
308 } elsif ($src_vmid) {
309 $cloned = PVE::QemuConfig->lock_config_shared($src_vmid, 30, $clonefn);
310 } else {
311 $cloned = $clonefn->();
312 }
313
314 return $cloned->@{qw(file size)};
315 };
316
317 # Note: $pool is only needed when creating a VM, because pool permissions
318 # are automatically inherited if VM already exists inside a pool.
319 my $create_disks = sub {
320 my ($rpcenv, $authuser, $conf, $arch, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
321
322 my $vollist = [];
323
324 my $res = {};
325
326 my $code = sub {
327 my ($ds, $disk) = @_;
328
329 my $volid = $disk->{file};
330 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
331
332 if (!$volid || $volid eq 'none' || $volid eq 'cdrom') {
333 delete $disk->{size};
334 $res->{$ds} = PVE::QemuServer::print_drive($disk);
335 } elsif (defined($volname) && $volname eq 'cloudinit') {
336 $storeid = $storeid // $default_storage;
337 die "no storage ID specified (and no default storage)\n" if !$storeid;
338
339 if (
340 my $ci_key = PVE::QemuConfig->has_cloudinit($conf, $ds)
341 || PVE::QemuConfig->has_cloudinit($conf->{pending} || {}, $ds)
342 || PVE::QemuConfig->has_cloudinit($res, $ds)
343 ) {
344 die "$ds - cloud-init drive is already attached at '$ci_key'\n";
345 }
346
347 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
348 my $name = "vm-$vmid-cloudinit";
349
350 my $fmt = undef;
351 if ($scfg->{path}) {
352 $fmt = $disk->{format} // "qcow2";
353 $name .= ".$fmt";
354 } else {
355 $fmt = $disk->{format} // "raw";
356 }
357
358 # Initial disk created with 4 MB and aligned to 4MB on regeneration
359 my $ci_size = PVE::QemuServer::Cloudinit::CLOUDINIT_DISK_SIZE;
360 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $fmt, $name, $ci_size/1024);
361 $disk->{file} = $volid;
362 $disk->{media} = 'cdrom';
363 push @$vollist, $volid;
364 delete $disk->{format}; # no longer needed
365 $res->{$ds} = PVE::QemuServer::print_drive($disk);
366 print "$ds: successfully created disk '$res->{$ds}'\n";
367 } elsif ($volid =~ $NEW_DISK_RE) {
368 my ($storeid, $size) = ($2 || $default_storage, $3);
369 die "no storage ID specified (and no default storage)\n" if !$storeid;
370
371 if (my $source = delete $disk->{'import-from'}) {
372 my $dst_volid;
373
374 if (PVE::Storage::parse_volume_id($source, 1)) { # PVE-managed volume
375 my $dest_info = {
376 vmid => $vmid,
377 drivename => $ds,
378 storage => $storeid,
379 format => $disk->{format},
380 };
381
382 $dest_info->{efisize} = PVE::QemuServer::get_efivars_size($conf, $disk)
383 if $ds eq 'efidisk0';
384
385 ($dst_volid, $size) = eval {
386 $import_from_volid->($storecfg, $source, $dest_info, $vollist);
387 };
388 die "cannot import from '$source' - $@" if $@;
389 } else {
390 $source = PVE::Storage::abs_filesystem_path($storecfg, $source, 1);
391 $size = PVE::Storage::file_size_info($source);
392 die "could not get file size of $source\n" if !$size;
393
394 (undef, $dst_volid) = PVE::QemuServer::ImportDisk::do_import(
395 $source,
396 $vmid,
397 $storeid,
398 {
399 drive_name => $ds,
400 format => $disk->{format},
401 'skip-config-update' => 1,
402 },
403 );
404 push @$vollist, $dst_volid;
405 }
406
407 $disk->{file} = $dst_volid;
408 $disk->{size} = $size;
409 delete $disk->{format}; # no longer needed
410 $res->{$ds} = PVE::QemuServer::print_drive($disk);
411 } else {
412 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
413 my $fmt = $disk->{format} || $defformat;
414
415 $size = PVE::Tools::convert_size($size, 'gb' => 'kb'); # vdisk_alloc uses kb
416
417 my $volid;
418 if ($ds eq 'efidisk0') {
419 my $smm = PVE::QemuServer::Machine::machine_type_is_q35($conf);
420 ($volid, $size) = PVE::QemuServer::create_efidisk(
421 $storecfg, $storeid, $vmid, $fmt, $arch, $disk, $smm);
422 } elsif ($ds eq 'tpmstate0') {
423 # swtpm can only use raw volumes, and uses a fixed size
424 $size = PVE::Tools::convert_size(PVE::QemuServer::Drive::TPMSTATE_DISK_SIZE, 'b' => 'kb');
425 $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, "raw", undef, $size);
426 } else {
427 $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $fmt, undef, $size);
428 }
429 push @$vollist, $volid;
430 $disk->{file} = $volid;
431 $disk->{size} = PVE::Tools::convert_size($size, 'kb' => 'b');
432 delete $disk->{format}; # no longer needed
433 $res->{$ds} = PVE::QemuServer::print_drive($disk);
434 }
435
436 print "$ds: successfully created disk '$res->{$ds}'\n";
437 } else {
438 PVE::Storage::check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $volid);
439 if ($storeid) {
440 my ($vtype) = PVE::Storage::parse_volname($storecfg, $volid);
441 die "cannot use volume $volid - content type needs to be 'images' or 'iso'"
442 if $vtype ne 'images' && $vtype ne 'iso';
443
444 if (PVE::QemuServer::Drive::drive_is_cloudinit($disk)) {
445 if (
446 my $ci_key = PVE::QemuConfig->has_cloudinit($conf, $ds)
447 || PVE::QemuConfig->has_cloudinit($conf->{pending} || {}, $ds)
448 || PVE::QemuConfig->has_cloudinit($res, $ds)
449 ) {
450 die "$ds - cloud-init drive is already attached at '$ci_key'\n";
451 }
452 }
453 }
454
455 PVE::Storage::activate_volumes($storecfg, [ $volid ]) if $storeid;
456
457 my $size = PVE::Storage::volume_size_info($storecfg, $volid);
458 die "volume $volid does not exist\n" if !$size;
459 $disk->{size} = $size;
460
461 $res->{$ds} = PVE::QemuServer::print_drive($disk);
462 }
463 };
464
465 eval { $foreach_volume_with_alloc->($settings, $code); };
466
467 # free allocated images on error
468 if (my $err = $@) {
469 syslog('err', "VM $vmid creating disks failed");
470 foreach my $volid (@$vollist) {
471 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
472 warn $@ if $@;
473 }
474 die $err;
475 }
476
477 return ($vollist, $res);
478 };
479
480 my $check_cpu_model_access = sub {
481 my ($rpcenv, $authuser, $new, $existing) = @_;
482
483 return if !defined($new->{cpu});
484
485 my $cpu = PVE::JSONSchema::check_format('pve-vm-cpu-conf', $new->{cpu});
486 return if !$cpu || !$cpu->{cputype}; # always allow default
487 my $cputype = $cpu->{cputype};
488
489 if ($existing && $existing->{cpu}) {
490 # changing only other settings doesn't require permissions for CPU model
491 my $existingCpu = PVE::JSONSchema::check_format('pve-vm-cpu-conf', $existing->{cpu});
492 return if $existingCpu->{cputype} eq $cputype;
493 }
494
495 if (PVE::QemuServer::CPUConfig::is_custom_model($cputype)) {
496 $rpcenv->check($authuser, "/nodes", ['Sys.Audit']);
497 }
498 };
499
500 my $cpuoptions = {
501 'cores' => 1,
502 'cpu' => 1,
503 'cpulimit' => 1,
504 'cpuunits' => 1,
505 'numa' => 1,
506 'smp' => 1,
507 'sockets' => 1,
508 'vcpus' => 1,
509 };
510
511 my $memoryoptions = {
512 'memory' => 1,
513 'balloon' => 1,
514 'shares' => 1,
515 };
516
517 my $hwtypeoptions = {
518 'acpi' => 1,
519 'hotplug' => 1,
520 'kvm' => 1,
521 'machine' => 1,
522 'scsihw' => 1,
523 'smbios1' => 1,
524 'tablet' => 1,
525 'vga' => 1,
526 'watchdog' => 1,
527 'audio0' => 1,
528 };
529
530 my $generaloptions = {
531 'agent' => 1,
532 'autostart' => 1,
533 'bios' => 1,
534 'description' => 1,
535 'keyboard' => 1,
536 'localtime' => 1,
537 'migrate_downtime' => 1,
538 'migrate_speed' => 1,
539 'name' => 1,
540 'onboot' => 1,
541 'ostype' => 1,
542 'protection' => 1,
543 'reboot' => 1,
544 'startdate' => 1,
545 'startup' => 1,
546 'tdf' => 1,
547 'template' => 1,
548 };
549
550 my $vmpoweroptions = {
551 'freeze' => 1,
552 };
553
554 my $diskoptions = {
555 'boot' => 1,
556 'bootdisk' => 1,
557 'vmstatestorage' => 1,
558 };
559
560 my $cloudinitoptions = {
561 cicustom => 1,
562 cipassword => 1,
563 citype => 1,
564 ciuser => 1,
565 nameserver => 1,
566 searchdomain => 1,
567 sshkeys => 1,
568 };
569
570 my $check_vm_create_serial_perm = sub {
571 my ($rpcenv, $authuser, $vmid, $pool, $param) = @_;
572
573 return 1 if $authuser eq 'root@pam';
574
575 foreach my $opt (keys %{$param}) {
576 next if $opt !~ m/^serial\d+$/;
577
578 if ($param->{$opt} eq 'socket') {
579 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
580 } else {
581 die "only root can set '$opt' config for real devices\n";
582 }
583 }
584
585 return 1;
586 };
587
588 my sub check_usb_perm {
589 my ($rpcenv, $authuser, $vmid, $pool, $opt, $value) = @_;
590
591 return 1 if $authuser eq 'root@pam';
592
593 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
594
595 my $device = PVE::JSONSchema::parse_property_string('pve-qm-usb', $value);
596 if ($device->{host} && $device->{host} !~ m/^spice$/i) {
597 die "only root can set '$opt' config for real devices\n";
598 } elsif ($device->{mapping}) {
599 $rpcenv->check_full($authuser, "/mapping/usb/$device->{mapping}", ['Mapping.Use']);
600 } else {
601 die "either 'host' or 'mapping' must be set.\n";
602 }
603
604 return 1;
605 }
606
607 my sub check_vm_create_usb_perm {
608 my ($rpcenv, $authuser, $vmid, $pool, $param) = @_;
609
610 return 1 if $authuser eq 'root@pam';
611
612 foreach my $opt (keys %{$param}) {
613 next if $opt !~ m/^usb\d+$/;
614 check_usb_perm($rpcenv, $authuser, $vmid, $pool, $opt, $param->{$opt});
615 }
616
617 return 1;
618 };
619
620 my sub check_hostpci_perm {
621 my ($rpcenv, $authuser, $vmid, $pool, $opt, $value) = @_;
622
623 return 1 if $authuser eq 'root@pam';
624
625 my $device = PVE::JSONSchema::parse_property_string('pve-qm-hostpci', $value);
626 if ($device->{host}) {
627 die "only root can set '$opt' config for non-mapped devices\n";
628 } elsif ($device->{mapping}) {
629 $rpcenv->check_full($authuser, "/mapping/pci/$device->{mapping}", ['Mapping.Use']);
630 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
631 } else {
632 die "either 'host' or 'mapping' must be set.\n";
633 }
634
635 return 1;
636 }
637
638 my sub check_vm_create_hostpci_perm {
639 my ($rpcenv, $authuser, $vmid, $pool, $param) = @_;
640
641 return 1 if $authuser eq 'root@pam';
642
643 foreach my $opt (keys %{$param}) {
644 next if $opt !~ m/^hostpci\d+$/;
645 check_hostpci_perm($rpcenv, $authuser, $vmid, $pool, $opt, $param->{$opt});
646 }
647
648 return 1;
649 };
650
651 my $check_vm_modify_config_perm = sub {
652 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
653
654 return 1 if $authuser eq 'root@pam';
655
656 foreach my $opt (@$key_list) {
657 # some checks (e.g., disk, serial port, usb) need to be done somewhere
658 # else, as there the permission can be value dependend
659 next if PVE::QemuServer::is_valid_drivename($opt);
660 next if $opt eq 'cdrom';
661 next if $opt =~ m/^(?:unused|serial|usb|hostpci)\d+$/;
662 next if $opt eq 'tags';
663
664
665 if ($cpuoptions->{$opt} || $opt =~ m/^numa\d+$/) {
666 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
667 } elsif ($memoryoptions->{$opt}) {
668 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
669 } elsif ($hwtypeoptions->{$opt}) {
670 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
671 } elsif ($generaloptions->{$opt}) {
672 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
673 # special case for startup since it changes host behaviour
674 if ($opt eq 'startup') {
675 $rpcenv->check_full($authuser, "/", ['Sys.Modify']);
676 }
677 } elsif ($vmpoweroptions->{$opt}) {
678 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.PowerMgmt']);
679 } elsif ($diskoptions->{$opt}) {
680 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
681 } elsif ($opt =~ m/^net\d+$/) {
682 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
683 } elsif ($cloudinitoptions->{$opt} || $opt =~ m/^ipconfig\d+$/) {
684 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Cloudinit', 'VM.Config.Network'], 1);
685 } elsif ($opt eq 'vmstate') {
686 # the user needs Disk and PowerMgmt privileges to change the vmstate
687 # also needs privileges on the storage, that will be checked later
688 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk', 'VM.PowerMgmt' ]);
689 } else {
690 # catches args, lock, etc.
691 # new options will be checked here
692 die "only root can set '$opt' config\n";
693 }
694 }
695
696 return 1;
697 };
698
699 __PACKAGE__->register_method({
700 name => 'vmlist',
701 path => '',
702 method => 'GET',
703 description => "Virtual machine index (per node).",
704 permissions => {
705 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
706 user => 'all',
707 },
708 proxyto => 'node',
709 protected => 1, # qemu pid files are only readable by root
710 parameters => {
711 additionalProperties => 0,
712 properties => {
713 node => get_standard_option('pve-node'),
714 full => {
715 type => 'boolean',
716 optional => 1,
717 description => "Determine the full status of active VMs.",
718 },
719 },
720 },
721 returns => {
722 type => 'array',
723 items => {
724 type => "object",
725 properties => $PVE::QemuServer::vmstatus_return_properties,
726 },
727 links => [ { rel => 'child', href => "{vmid}" } ],
728 },
729 code => sub {
730 my ($param) = @_;
731
732 my $rpcenv = PVE::RPCEnvironment::get();
733 my $authuser = $rpcenv->get_user();
734
735 my $vmstatus = PVE::QemuServer::vmstatus(undef, $param->{full});
736
737 my $res = [];
738 foreach my $vmid (keys %$vmstatus) {
739 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
740
741 my $data = $vmstatus->{$vmid};
742 push @$res, $data;
743 }
744
745 return $res;
746 }});
747
748 my $parse_restore_archive = sub {
749 my ($storecfg, $archive) = @_;
750
751 my ($archive_storeid, $archive_volname) = PVE::Storage::parse_volume_id($archive, 1);
752
753 my $res = {};
754
755 if (defined($archive_storeid)) {
756 my $scfg = PVE::Storage::storage_config($storecfg, $archive_storeid);
757 $res->{volid} = $archive;
758 if ($scfg->{type} eq 'pbs') {
759 $res->{type} = 'pbs';
760 return $res;
761 }
762 }
763 my $path = PVE::Storage::abs_filesystem_path($storecfg, $archive);
764 $res->{type} = 'file';
765 $res->{path} = $path;
766 return $res;
767 };
768
769
770 __PACKAGE__->register_method({
771 name => 'create_vm',
772 path => '',
773 method => 'POST',
774 description => "Create or restore a virtual machine.",
775 permissions => {
776 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. " .
777 "For restore (option 'archive'), it is enough if the user has 'VM.Backup' permission and the VM already exists. " .
778 "If you create disks you need 'Datastore.AllocateSpace' on any used storage." .
779 "If you use a bridge/vlan, you need 'SDN.Use' on any used bridge/vlan.",
780 user => 'all', # check inside
781 },
782 protected => 1,
783 proxyto => 'node',
784 parameters => {
785 additionalProperties => 0,
786 properties => PVE::QemuServer::json_config_properties(
787 {
788 node => get_standard_option('pve-node'),
789 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
790 archive => {
791 description => "The backup archive. Either the file system path to a .tar or .vma file (use '-' to pipe data from stdin) or a proxmox storage backup volume identifier.",
792 type => 'string',
793 optional => 1,
794 maxLength => 255,
795 completion => \&PVE::QemuServer::complete_backup_archives,
796 },
797 storage => get_standard_option('pve-storage-id', {
798 description => "Default storage.",
799 optional => 1,
800 completion => \&PVE::QemuServer::complete_storage,
801 }),
802 force => {
803 optional => 1,
804 type => 'boolean',
805 description => "Allow to overwrite existing VM.",
806 requires => 'archive',
807 },
808 unique => {
809 optional => 1,
810 type => 'boolean',
811 description => "Assign a unique random ethernet address.",
812 requires => 'archive',
813 },
814 'live-restore' => {
815 optional => 1,
816 type => 'boolean',
817 description => "Start the VM immediately from the backup and restore in background. PBS only.",
818 requires => 'archive',
819 },
820 pool => {
821 optional => 1,
822 type => 'string', format => 'pve-poolid',
823 description => "Add the VM to the specified pool.",
824 },
825 bwlimit => {
826 description => "Override I/O bandwidth limit (in KiB/s).",
827 optional => 1,
828 type => 'integer',
829 minimum => '0',
830 default => 'restore limit from datacenter or storage config',
831 },
832 start => {
833 optional => 1,
834 type => 'boolean',
835 default => 0,
836 description => "Start VM after it was created successfully.",
837 },
838 },
839 1, # with_disk_alloc
840 ),
841 },
842 returns => {
843 type => 'string',
844 },
845 code => sub {
846 my ($param) = @_;
847
848 my $rpcenv = PVE::RPCEnvironment::get();
849 my $authuser = $rpcenv->get_user();
850
851 my $node = extract_param($param, 'node');
852 my $vmid = extract_param($param, 'vmid');
853
854 my $archive = extract_param($param, 'archive');
855 my $is_restore = !!$archive;
856
857 my $bwlimit = extract_param($param, 'bwlimit');
858 my $force = extract_param($param, 'force');
859 my $pool = extract_param($param, 'pool');
860 my $start_after_create = extract_param($param, 'start');
861 my $storage = extract_param($param, 'storage');
862 my $unique = extract_param($param, 'unique');
863 my $live_restore = extract_param($param, 'live-restore');
864
865 if (defined(my $ssh_keys = $param->{sshkeys})) {
866 $ssh_keys = URI::Escape::uri_unescape($ssh_keys);
867 PVE::Tools::validate_ssh_public_keys($ssh_keys);
868 }
869
870 $param->{cpuunits} = PVE::CGroup::clamp_cpu_shares($param->{cpuunits})
871 if defined($param->{cpuunits}); # clamp value depending on cgroup version
872
873 PVE::Cluster::check_cfs_quorum();
874
875 my $filename = PVE::QemuConfig->config_file($vmid);
876 my $storecfg = PVE::Storage::config();
877
878 if (defined($pool)) {
879 $rpcenv->check_pool_exist($pool);
880 }
881
882 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace'])
883 if defined($storage);
884
885 if ($rpcenv->check($authuser, "/vms/$vmid", ['VM.Allocate'], 1)) {
886 # OK
887 } elsif ($pool && $rpcenv->check($authuser, "/pool/$pool", ['VM.Allocate'], 1)) {
888 # OK
889 } elsif ($archive && $force && (-f $filename) &&
890 $rpcenv->check($authuser, "/vms/$vmid", ['VM.Backup'], 1)) {
891 # OK: user has VM.Backup permissions and wants to restore an existing VM
892 } else {
893 raise_perm_exc();
894 }
895
896 if ($archive) {
897 for my $opt (sort keys $param->%*) {
898 if (PVE::QemuServer::Drive::is_valid_drivename($opt)) {
899 raise_param_exc({ $opt => "option conflicts with option 'archive'" });
900 }
901 }
902
903 if ($archive eq '-') {
904 die "pipe requires cli environment\n" if $rpcenv->{type} ne 'cli';
905 $archive = { type => 'pipe' };
906 } else {
907 PVE::Storage::check_volume_access(
908 $rpcenv,
909 $authuser,
910 $storecfg,
911 $vmid,
912 $archive,
913 'backup',
914 );
915
916 $archive = $parse_restore_archive->($storecfg, $archive);
917 }
918 }
919
920 if (scalar(keys $param->%*) > 0) {
921 &$resolve_cdrom_alias($param);
922
923 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param, $storage);
924
925 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
926
927 &$check_vm_create_serial_perm($rpcenv, $authuser, $vmid, $pool, $param);
928 check_vm_create_usb_perm($rpcenv, $authuser, $vmid, $pool, $param);
929 check_vm_create_hostpci_perm($rpcenv, $authuser, $vmid, $pool, $param);
930
931 PVE::QemuServer::check_bridge_access($rpcenv, $authuser, $param);
932 &$check_cpu_model_access($rpcenv, $authuser, $param);
933
934 $check_drive_param->($param, $storecfg);
935
936 PVE::QemuServer::add_random_macs($param);
937 }
938
939 my $emsg = $is_restore ? "unable to restore VM $vmid -" : "unable to create VM $vmid -";
940
941 eval { PVE::QemuConfig->create_and_lock_config($vmid, $force) };
942 die "$emsg $@" if $@;
943
944 my $restored_data = 0;
945 my $restorefn = sub {
946 my $conf = PVE::QemuConfig->load_config($vmid);
947
948 PVE::QemuConfig->check_protection($conf, $emsg);
949
950 die "$emsg vm is running\n" if PVE::QemuServer::check_running($vmid);
951
952 my $realcmd = sub {
953 my $restore_options = {
954 storage => $storage,
955 pool => $pool,
956 unique => $unique,
957 bwlimit => $bwlimit,
958 live => $live_restore,
959 override_conf => $param,
960 };
961 if (my $volid = $archive->{volid}) {
962 # best effort, real check is after restoring!
963 my $merged = eval {
964 my $old_conf = PVE::Storage::extract_vzdump_config($storecfg, $volid);
965 PVE::QemuServer::restore_merge_config("backup/qemu-server/$vmid.conf", $old_conf, $param);
966 };
967 if ($@) {
968 warn "Could not extract backed up config: $@\n";
969 warn "Skipping early checks!\n";
970 } else {
971 PVE::QemuServer::check_restore_permissions($rpcenv, $authuser, $merged);
972 }
973 }
974 if ($archive->{type} eq 'file' || $archive->{type} eq 'pipe') {
975 die "live-restore is only compatible with backup images from a Proxmox Backup Server\n"
976 if $live_restore;
977 PVE::QemuServer::restore_file_archive($archive->{path} // '-', $vmid, $authuser, $restore_options);
978 } elsif ($archive->{type} eq 'pbs') {
979 PVE::QemuServer::restore_proxmox_backup_archive($archive->{volid}, $vmid, $authuser, $restore_options);
980 } else {
981 die "unknown backup archive type\n";
982 }
983 $restored_data = 1;
984
985 my $restored_conf = PVE::QemuConfig->load_config($vmid);
986 # Convert restored VM to template if backup was VM template
987 if (PVE::QemuConfig->is_template($restored_conf)) {
988 warn "Convert to template.\n";
989 eval { PVE::QemuServer::template_create($vmid, $restored_conf) };
990 warn $@ if $@;
991 }
992 };
993
994 # ensure no old replication state are exists
995 PVE::ReplicationState::delete_guest_states($vmid);
996
997 PVE::QemuConfig->lock_config_full($vmid, 1, $realcmd);
998
999 if ($start_after_create && !$live_restore) {
1000 print "Execute autostart\n";
1001 eval { PVE::API2::Qemu->vm_start({ vmid => $vmid, node => $node }) };
1002 warn $@ if $@;
1003 }
1004 };
1005
1006 my $createfn = sub {
1007 # ensure no old replication state are exists
1008 PVE::ReplicationState::delete_guest_states($vmid);
1009
1010 my $realcmd = sub {
1011 my $conf = $param;
1012 my $arch = PVE::QemuServer::get_vm_arch($conf);
1013
1014 $conf->{meta} = PVE::QemuServer::new_meta_info_string();
1015
1016 my $vollist = [];
1017 eval {
1018 ($vollist, my $created_opts) = $create_disks->(
1019 $rpcenv,
1020 $authuser,
1021 $conf,
1022 $arch,
1023 $storecfg,
1024 $vmid,
1025 $pool,
1026 $param,
1027 $storage,
1028 );
1029 $conf->{$_} = $created_opts->{$_} for keys $created_opts->%*;
1030
1031 if (!$conf->{boot}) {
1032 my $devs = PVE::QemuServer::get_default_bootdevices($conf);
1033 $conf->{boot} = PVE::QemuServer::print_bootorder($devs);
1034 }
1035
1036 # auto generate uuid if user did not specify smbios1 option
1037 if (!$conf->{smbios1}) {
1038 $conf->{smbios1} = PVE::QemuServer::generate_smbios1_uuid();
1039 }
1040
1041 if ((!defined($conf->{vmgenid}) || $conf->{vmgenid} eq '1') && $arch ne 'aarch64') {
1042 $conf->{vmgenid} = PVE::QemuServer::generate_uuid();
1043 }
1044
1045 my $machine = $conf->{machine};
1046 if (!$machine || $machine =~ m/^(?:pc|q35|virt)$/) {
1047 # always pin Windows' machine version on create, they get to easily confused
1048 if (PVE::QemuServer::Helpers::windows_version($conf->{ostype})) {
1049 $conf->{machine} = PVE::QemuServer::windows_get_pinned_machine_version($machine);
1050 }
1051 }
1052
1053 PVE::QemuConfig->write_config($vmid, $conf);
1054
1055 };
1056 my $err = $@;
1057
1058 if ($err) {
1059 foreach my $volid (@$vollist) {
1060 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1061 warn $@ if $@;
1062 }
1063 die "$emsg $err";
1064 }
1065
1066 PVE::AccessControl::add_vm_to_pool($vmid, $pool) if $pool;
1067 };
1068
1069 PVE::QemuConfig->lock_config_full($vmid, 1, $realcmd);
1070
1071 if ($start_after_create) {
1072 print "Execute autostart\n";
1073 eval { PVE::API2::Qemu->vm_start({vmid => $vmid, node => $node}) };
1074 warn $@ if $@;
1075 }
1076 };
1077
1078 my ($code, $worker_name);
1079 if ($is_restore) {
1080 $worker_name = 'qmrestore';
1081 $code = sub {
1082 eval { $restorefn->() };
1083 if (my $err = $@) {
1084 eval { PVE::QemuConfig->remove_lock($vmid, 'create') };
1085 warn $@ if $@;
1086 if ($restored_data) {
1087 warn "error after data was restored, VM disks should be OK but config may "
1088 ."require adaptions. VM $vmid state is NOT cleaned up.\n";
1089 } else {
1090 warn "error before or during data restore, some or all disks were not "
1091 ."completely restored. VM $vmid state is NOT cleaned up.\n";
1092 }
1093 die $err;
1094 }
1095 };
1096 } else {
1097 $worker_name = 'qmcreate';
1098 $code = sub {
1099 eval { $createfn->() };
1100 if (my $err = $@) {
1101 eval {
1102 my $conffile = PVE::QemuConfig->config_file($vmid);
1103 unlink($conffile) or die "failed to remove config file: $!\n";
1104 };
1105 warn $@ if $@;
1106 die $err;
1107 }
1108 };
1109 }
1110
1111 return $rpcenv->fork_worker($worker_name, $vmid, $authuser, $code);
1112 }});
1113
1114 __PACKAGE__->register_method({
1115 name => 'vmdiridx',
1116 path => '{vmid}',
1117 method => 'GET',
1118 proxyto => 'node',
1119 description => "Directory index",
1120 permissions => {
1121 user => 'all',
1122 },
1123 parameters => {
1124 additionalProperties => 0,
1125 properties => {
1126 node => get_standard_option('pve-node'),
1127 vmid => get_standard_option('pve-vmid'),
1128 },
1129 },
1130 returns => {
1131 type => 'array',
1132 items => {
1133 type => "object",
1134 properties => {
1135 subdir => { type => 'string' },
1136 },
1137 },
1138 links => [ { rel => 'child', href => "{subdir}" } ],
1139 },
1140 code => sub {
1141 my ($param) = @_;
1142
1143 my $res = [
1144 { subdir => 'config' },
1145 { subdir => 'cloudinit' },
1146 { subdir => 'pending' },
1147 { subdir => 'status' },
1148 { subdir => 'unlink' },
1149 { subdir => 'vncproxy' },
1150 { subdir => 'termproxy' },
1151 { subdir => 'migrate' },
1152 { subdir => 'resize' },
1153 { subdir => 'move' },
1154 { subdir => 'rrd' },
1155 { subdir => 'rrddata' },
1156 { subdir => 'monitor' },
1157 { subdir => 'agent' },
1158 { subdir => 'snapshot' },
1159 { subdir => 'spiceproxy' },
1160 { subdir => 'sendkey' },
1161 { subdir => 'firewall' },
1162 { subdir => 'mtunnel' },
1163 { subdir => 'remote_migrate' },
1164 ];
1165
1166 return $res;
1167 }});
1168
1169 __PACKAGE__->register_method ({
1170 subclass => "PVE::API2::Firewall::VM",
1171 path => '{vmid}/firewall',
1172 });
1173
1174 __PACKAGE__->register_method ({
1175 subclass => "PVE::API2::Qemu::Agent",
1176 path => '{vmid}/agent',
1177 });
1178
1179 __PACKAGE__->register_method({
1180 name => 'rrd',
1181 path => '{vmid}/rrd',
1182 method => 'GET',
1183 protected => 1, # fixme: can we avoid that?
1184 permissions => {
1185 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1186 },
1187 description => "Read VM RRD statistics (returns PNG)",
1188 parameters => {
1189 additionalProperties => 0,
1190 properties => {
1191 node => get_standard_option('pve-node'),
1192 vmid => get_standard_option('pve-vmid'),
1193 timeframe => {
1194 description => "Specify the time frame you are interested in.",
1195 type => 'string',
1196 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
1197 },
1198 ds => {
1199 description => "The list of datasources you want to display.",
1200 type => 'string', format => 'pve-configid-list',
1201 },
1202 cf => {
1203 description => "The RRD consolidation function",
1204 type => 'string',
1205 enum => [ 'AVERAGE', 'MAX' ],
1206 optional => 1,
1207 },
1208 },
1209 },
1210 returns => {
1211 type => "object",
1212 properties => {
1213 filename => { type => 'string' },
1214 },
1215 },
1216 code => sub {
1217 my ($param) = @_;
1218
1219 return PVE::RRD::create_rrd_graph(
1220 "pve2-vm/$param->{vmid}", $param->{timeframe},
1221 $param->{ds}, $param->{cf});
1222
1223 }});
1224
1225 __PACKAGE__->register_method({
1226 name => 'rrddata',
1227 path => '{vmid}/rrddata',
1228 method => 'GET',
1229 protected => 1, # fixme: can we avoid that?
1230 permissions => {
1231 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1232 },
1233 description => "Read VM RRD statistics",
1234 parameters => {
1235 additionalProperties => 0,
1236 properties => {
1237 node => get_standard_option('pve-node'),
1238 vmid => get_standard_option('pve-vmid'),
1239 timeframe => {
1240 description => "Specify the time frame you are interested in.",
1241 type => 'string',
1242 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
1243 },
1244 cf => {
1245 description => "The RRD consolidation function",
1246 type => 'string',
1247 enum => [ 'AVERAGE', 'MAX' ],
1248 optional => 1,
1249 },
1250 },
1251 },
1252 returns => {
1253 type => "array",
1254 items => {
1255 type => "object",
1256 properties => {},
1257 },
1258 },
1259 code => sub {
1260 my ($param) = @_;
1261
1262 return PVE::RRD::create_rrd_data(
1263 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
1264 }});
1265
1266
1267 __PACKAGE__->register_method({
1268 name => 'vm_config',
1269 path => '{vmid}/config',
1270 method => 'GET',
1271 proxyto => 'node',
1272 description => "Get the virtual machine configuration with pending configuration " .
1273 "changes applied. Set the 'current' parameter to get the current configuration instead.",
1274 permissions => {
1275 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1276 },
1277 parameters => {
1278 additionalProperties => 0,
1279 properties => {
1280 node => get_standard_option('pve-node'),
1281 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
1282 current => {
1283 description => "Get current values (instead of pending values).",
1284 optional => 1,
1285 default => 0,
1286 type => 'boolean',
1287 },
1288 snapshot => get_standard_option('pve-snapshot-name', {
1289 description => "Fetch config values from given snapshot.",
1290 optional => 1,
1291 completion => sub {
1292 my ($cmd, $pname, $cur, $args) = @_;
1293 PVE::QemuConfig->snapshot_list($args->[0]);
1294 },
1295 }),
1296 },
1297 },
1298 returns => {
1299 description => "The VM configuration.",
1300 type => "object",
1301 properties => PVE::QemuServer::json_config_properties({
1302 digest => {
1303 type => 'string',
1304 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
1305 }
1306 }),
1307 },
1308 code => sub {
1309 my ($param) = @_;
1310
1311 raise_param_exc({ snapshot => "cannot use 'snapshot' parameter with 'current'",
1312 current => "cannot use 'snapshot' parameter with 'current'"})
1313 if ($param->{snapshot} && $param->{current});
1314
1315 my $conf;
1316 if ($param->{snapshot}) {
1317 $conf = PVE::QemuConfig->load_snapshot_config($param->{vmid}, $param->{snapshot});
1318 } else {
1319 $conf = PVE::QemuConfig->load_current_config($param->{vmid}, $param->{current});
1320 }
1321 $conf->{cipassword} = '**********' if $conf->{cipassword};
1322 return $conf;
1323
1324 }});
1325
1326 __PACKAGE__->register_method({
1327 name => 'vm_pending',
1328 path => '{vmid}/pending',
1329 method => 'GET',
1330 proxyto => 'node',
1331 description => "Get the virtual machine configuration with both current and pending values.",
1332 permissions => {
1333 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1334 },
1335 parameters => {
1336 additionalProperties => 0,
1337 properties => {
1338 node => get_standard_option('pve-node'),
1339 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
1340 },
1341 },
1342 returns => {
1343 type => "array",
1344 items => {
1345 type => "object",
1346 properties => {
1347 key => {
1348 description => "Configuration option name.",
1349 type => 'string',
1350 },
1351 value => {
1352 description => "Current value.",
1353 type => 'string',
1354 optional => 1,
1355 },
1356 pending => {
1357 description => "Pending value.",
1358 type => 'string',
1359 optional => 1,
1360 },
1361 delete => {
1362 description => "Indicates a pending delete request if present and not 0. " .
1363 "The value 2 indicates a force-delete request.",
1364 type => 'integer',
1365 minimum => 0,
1366 maximum => 2,
1367 optional => 1,
1368 },
1369 },
1370 },
1371 },
1372 code => sub {
1373 my ($param) = @_;
1374
1375 my $conf = PVE::QemuConfig->load_config($param->{vmid});
1376
1377 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
1378
1379 $conf->{cipassword} = '**********' if defined($conf->{cipassword});
1380 $conf->{pending}->{cipassword} = '********** ' if defined($conf->{pending}->{cipassword});
1381
1382 return PVE::GuestHelpers::config_with_pending_array($conf, $pending_delete_hash);
1383 }});
1384
1385 __PACKAGE__->register_method({
1386 name => 'cloudinit_pending',
1387 path => '{vmid}/cloudinit',
1388 method => 'GET',
1389 proxyto => 'node',
1390 description => "Get the cloudinit configuration with both current and pending values.",
1391 permissions => {
1392 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1393 },
1394 parameters => {
1395 additionalProperties => 0,
1396 properties => {
1397 node => get_standard_option('pve-node'),
1398 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
1399 },
1400 },
1401 returns => {
1402 type => "array",
1403 items => {
1404 type => "object",
1405 properties => {
1406 key => {
1407 description => "Configuration option name.",
1408 type => 'string',
1409 },
1410 value => {
1411 description => "Value as it was used to generate the current cloudinit image.",
1412 type => 'string',
1413 optional => 1,
1414 },
1415 pending => {
1416 description => "The new pending value.",
1417 type => 'string',
1418 optional => 1,
1419 },
1420 delete => {
1421 description => "Indicates a pending delete request if present and not 0. ",
1422 type => 'integer',
1423 minimum => 0,
1424 maximum => 1,
1425 optional => 1,
1426 },
1427 },
1428 },
1429 },
1430 code => sub {
1431 my ($param) = @_;
1432
1433 my $vmid = $param->{vmid};
1434 my $conf = PVE::QemuConfig->load_config($vmid);
1435
1436 my $ci = $conf->{cloudinit};
1437
1438 $conf->{cipassword} = '**********' if exists $conf->{cipassword};
1439 $ci->{cipassword} = '**********' if exists $ci->{cipassword};
1440
1441 my $res = [];
1442
1443 # All the values that got added
1444 my $added = delete($ci->{added}) // '';
1445 for my $key (PVE::Tools::split_list($added)) {
1446 push @$res, { key => $key, pending => $conf->{$key} };
1447 }
1448
1449 # All already existing values (+ their new value, if it exists)
1450 for my $opt (keys %$cloudinitoptions) {
1451 next if !$conf->{$opt};
1452 next if $added =~ m/$opt/;
1453 my $item = {
1454 key => $opt,
1455 };
1456
1457 if (my $pending = $ci->{$opt}) {
1458 $item->{value} = $pending;
1459 $item->{pending} = $conf->{$opt};
1460 } else {
1461 $item->{value} = $conf->{$opt},
1462 }
1463
1464 push @$res, $item;
1465 }
1466
1467 # Now, we'll find the deleted ones
1468 for my $opt (keys %$ci) {
1469 next if $conf->{$opt};
1470 push @$res, { key => $opt, delete => 1 };
1471 }
1472
1473 return $res;
1474 }});
1475
1476 __PACKAGE__->register_method({
1477 name => 'cloudinit_update',
1478 path => '{vmid}/cloudinit',
1479 method => 'PUT',
1480 protected => 1,
1481 proxyto => 'node',
1482 description => "Regenerate and change cloudinit config drive.",
1483 permissions => {
1484 check => ['perm', '/vms/{vmid}', 'VM.Config.Cloudinit'],
1485 },
1486 parameters => {
1487 additionalProperties => 0,
1488 properties => {
1489 node => get_standard_option('pve-node'),
1490 vmid => get_standard_option('pve-vmid'),
1491 },
1492 },
1493 returns => { type => 'null' },
1494 code => sub {
1495 my ($param) = @_;
1496
1497 my $rpcenv = PVE::RPCEnvironment::get();
1498 my $authuser = $rpcenv->get_user();
1499
1500 my $vmid = extract_param($param, 'vmid');
1501
1502 PVE::QemuConfig->lock_config($vmid, sub {
1503 my $conf = PVE::QemuConfig->load_config($vmid);
1504 PVE::QemuConfig->check_lock($conf);
1505
1506 my $storecfg = PVE::Storage::config();
1507 PVE::QemuServer::vmconfig_update_cloudinit_drive($storecfg, $conf, $vmid);
1508 });
1509 return;
1510 }});
1511
1512 # POST/PUT {vmid}/config implementation
1513 #
1514 # The original API used PUT (idempotent) an we assumed that all operations
1515 # are fast. But it turned out that almost any configuration change can
1516 # involve hot-plug actions, or disk alloc/free. Such actions can take long
1517 # time to complete and have side effects (not idempotent).
1518 #
1519 # The new implementation uses POST and forks a worker process. We added
1520 # a new option 'background_delay'. If specified we wait up to
1521 # 'background_delay' second for the worker task to complete. It returns null
1522 # if the task is finished within that time, else we return the UPID.
1523
1524 my $update_vm_api = sub {
1525 my ($param, $sync) = @_;
1526
1527 my $rpcenv = PVE::RPCEnvironment::get();
1528
1529 my $authuser = $rpcenv->get_user();
1530
1531 my $node = extract_param($param, 'node');
1532
1533 my $vmid = extract_param($param, 'vmid');
1534
1535 my $digest = extract_param($param, 'digest');
1536
1537 my $background_delay = extract_param($param, 'background_delay');
1538
1539 my $skip_cloud_init = extract_param($param, 'skip_cloud_init');
1540
1541 if (defined(my $cipassword = $param->{cipassword})) {
1542 # Same logic as in cloud-init (but with the regex fixed...)
1543 $param->{cipassword} = PVE::Tools::encrypt_pw($cipassword)
1544 if $cipassword !~ /^\$(?:[156]|2[ay])(\$.+){2}/;
1545 }
1546
1547 my @paramarr = (); # used for log message
1548 foreach my $key (sort keys %$param) {
1549 my $value = $key eq 'cipassword' ? '<hidden>' : $param->{$key};
1550 push @paramarr, "-$key", $value;
1551 }
1552
1553 my $skiplock = extract_param($param, 'skiplock');
1554 raise_param_exc({ skiplock => "Only root may use this option." })
1555 if $skiplock && $authuser ne 'root@pam';
1556
1557 my $delete_str = extract_param($param, 'delete');
1558
1559 my $revert_str = extract_param($param, 'revert');
1560
1561 my $force = extract_param($param, 'force');
1562
1563 if (defined(my $ssh_keys = $param->{sshkeys})) {
1564 $ssh_keys = URI::Escape::uri_unescape($ssh_keys);
1565 PVE::Tools::validate_ssh_public_keys($ssh_keys);
1566 }
1567
1568 $param->{cpuunits} = PVE::CGroup::clamp_cpu_shares($param->{cpuunits})
1569 if defined($param->{cpuunits}); # clamp value depending on cgroup version
1570
1571 die "no options specified\n" if !$delete_str && !$revert_str && !scalar(keys %$param);
1572
1573 my $storecfg = PVE::Storage::config();
1574
1575 my $defaults = PVE::QemuServer::load_defaults();
1576
1577 &$resolve_cdrom_alias($param);
1578
1579 # now try to verify all parameters
1580
1581 my $revert = {};
1582 foreach my $opt (PVE::Tools::split_list($revert_str)) {
1583 if (!PVE::QemuServer::option_exists($opt)) {
1584 raise_param_exc({ revert => "unknown option '$opt'" });
1585 }
1586
1587 raise_param_exc({ delete => "you can't use '-$opt' and " .
1588 "-revert $opt' at the same time" })
1589 if defined($param->{$opt});
1590
1591 $revert->{$opt} = 1;
1592 }
1593
1594 my @delete = ();
1595 foreach my $opt (PVE::Tools::split_list($delete_str)) {
1596 $opt = 'ide2' if $opt eq 'cdrom';
1597
1598 raise_param_exc({ delete => "you can't use '-$opt' and " .
1599 "-delete $opt' at the same time" })
1600 if defined($param->{$opt});
1601
1602 raise_param_exc({ revert => "you can't use '-delete $opt' and " .
1603 "-revert $opt' at the same time" })
1604 if $revert->{$opt};
1605
1606 if (!PVE::QemuServer::option_exists($opt)) {
1607 raise_param_exc({ delete => "unknown option '$opt'" });
1608 }
1609
1610 push @delete, $opt;
1611 }
1612
1613 my $repl_conf = PVE::ReplicationConfig->new();
1614 my $is_replicated = $repl_conf->check_for_existing_jobs($vmid, 1);
1615 my $check_replication = sub {
1616 my ($drive) = @_;
1617 return if !$is_replicated;
1618 my $volid = $drive->{file};
1619 return if !$volid || !($drive->{replicate}//1);
1620 return if PVE::QemuServer::drive_is_cdrom($drive);
1621
1622 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1623 die "cannot add non-managed/pass-through volume to a replicated VM\n"
1624 if !defined($storeid);
1625
1626 return if defined($volname) && $volname eq 'cloudinit';
1627
1628 my $format;
1629 if ($volid =~ $NEW_DISK_RE) {
1630 $storeid = $2;
1631 $format = $drive->{format} || PVE::Storage::storage_default_format($storecfg, $storeid);
1632 } else {
1633 $format = (PVE::Storage::parse_volname($storecfg, $volid))[6];
1634 }
1635 return if PVE::Storage::storage_can_replicate($storecfg, $storeid, $format);
1636 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
1637 return if $scfg->{shared};
1638 die "cannot add non-replicatable volume to a replicated VM\n";
1639 };
1640
1641 $check_drive_param->($param, $storecfg, $check_replication);
1642
1643 foreach my $opt (keys %$param) {
1644 if ($opt =~ m/^net(\d+)$/) {
1645 # add macaddr
1646 my $net = PVE::QemuServer::parse_net($param->{$opt});
1647 $param->{$opt} = PVE::QemuServer::print_net($net);
1648 } elsif ($opt eq 'vmgenid') {
1649 if ($param->{$opt} eq '1') {
1650 $param->{$opt} = PVE::QemuServer::generate_uuid();
1651 }
1652 } elsif ($opt eq 'hookscript') {
1653 eval { PVE::GuestHelpers::check_hookscript($param->{$opt}, $storecfg); };
1654 raise_param_exc({ $opt => $@ }) if $@;
1655 }
1656 }
1657
1658 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
1659
1660 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
1661
1662 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1663
1664 PVE::QemuServer::check_bridge_access($rpcenv, $authuser, $param);
1665
1666 my $updatefn = sub {
1667
1668 my $conf = PVE::QemuConfig->load_config($vmid);
1669
1670 die "checksum missmatch (file change by other user?)\n"
1671 if $digest && $digest ne $conf->{digest};
1672
1673 &$check_cpu_model_access($rpcenv, $authuser, $param, $conf);
1674
1675 # FIXME: 'suspended' lock should probabyl be a state or "weak" lock?!
1676 if (scalar(@delete) && grep { $_ eq 'vmstate'} @delete) {
1677 if (defined($conf->{lock}) && $conf->{lock} eq 'suspended') {
1678 delete $conf->{lock}; # for check lock check, not written out
1679 push @delete, 'lock'; # this is the real deal to write it out
1680 }
1681 push @delete, 'runningmachine' if $conf->{runningmachine};
1682 push @delete, 'runningcpu' if $conf->{runningcpu};
1683 }
1684
1685 PVE::QemuConfig->check_lock($conf) if !$skiplock;
1686
1687 foreach my $opt (keys %$revert) {
1688 if (defined($conf->{$opt})) {
1689 $param->{$opt} = $conf->{$opt};
1690 } elsif (defined($conf->{pending}->{$opt})) {
1691 push @delete, $opt;
1692 }
1693 }
1694
1695 if ($param->{memory} || defined($param->{balloon})) {
1696 my $maxmem = $param->{memory} || $conf->{pending}->{memory} || $conf->{memory} || $defaults->{memory};
1697 my $balloon = defined($param->{balloon}) ? $param->{balloon} : $conf->{pending}->{balloon} || $conf->{balloon};
1698
1699 die "balloon value too large (must be smaller than assigned memory)\n"
1700 if $balloon && $balloon > $maxmem;
1701 }
1702
1703 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
1704
1705 my $worker = sub {
1706
1707 print "update VM $vmid: " . join (' ', @paramarr) . "\n";
1708
1709 # write updates to pending section
1710
1711 my $modified = {}; # record what $option we modify
1712
1713 my @bootorder;
1714 if (my $boot = $conf->{boot}) {
1715 my $bootcfg = PVE::JSONSchema::parse_property_string('pve-qm-boot', $boot);
1716 @bootorder = PVE::Tools::split_list($bootcfg->{order}) if $bootcfg && $bootcfg->{order};
1717 }
1718 my $bootorder_deleted = grep {$_ eq 'bootorder'} @delete;
1719
1720 my $check_drive_perms = sub {
1721 my ($opt, $val) = @_;
1722 my $drive = PVE::QemuServer::parse_drive($opt, $val, 1);
1723 if (PVE::QemuServer::drive_is_cloudinit($drive)) {
1724 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Cloudinit', 'VM.Config.CDROM']);
1725 } elsif (PVE::QemuServer::drive_is_cdrom($drive, 1)) { # CDROM
1726 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
1727 } else {
1728 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
1729
1730 }
1731 };
1732
1733 foreach my $opt (@delete) {
1734 $modified->{$opt} = 1;
1735 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
1736
1737 # value of what we want to delete, independent if pending or not
1738 my $val = $conf->{$opt} // $conf->{pending}->{$opt};
1739 if (!defined($val)) {
1740 warn "cannot delete '$opt' - not set in current configuration!\n";
1741 $modified->{$opt} = 0;
1742 next;
1743 }
1744 my $is_pending_val = defined($conf->{pending}->{$opt});
1745 delete $conf->{pending}->{$opt};
1746
1747 # remove from bootorder if necessary
1748 if (!$bootorder_deleted && @bootorder && grep {$_ eq $opt} @bootorder) {
1749 @bootorder = grep {$_ ne $opt} @bootorder;
1750 $conf->{pending}->{boot} = PVE::QemuServer::print_bootorder(\@bootorder);
1751 $modified->{boot} = 1;
1752 }
1753
1754 if ($opt =~ m/^unused/) {
1755 my $drive = PVE::QemuServer::parse_drive($opt, $val);
1756 PVE::QemuConfig->check_protection($conf, "can't remove unused disk '$drive->{file}'");
1757 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
1758 if (PVE::QemuServer::try_deallocate_drive($storecfg, $vmid, $conf, $opt, $drive, $rpcenv, $authuser)) {
1759 delete $conf->{$opt};
1760 PVE::QemuConfig->write_config($vmid, $conf);
1761 }
1762 } elsif ($opt eq 'vmstate') {
1763 PVE::QemuConfig->check_protection($conf, "can't remove vmstate '$val'");
1764 if (PVE::QemuServer::try_deallocate_drive($storecfg, $vmid, $conf, $opt, { file => $val }, $rpcenv, $authuser, 1)) {
1765 delete $conf->{$opt};
1766 PVE::QemuConfig->write_config($vmid, $conf);
1767 }
1768 } elsif (PVE::QemuServer::is_valid_drivename($opt)) {
1769 PVE::QemuConfig->check_protection($conf, "can't remove drive '$opt'");
1770 $check_drive_perms->($opt, $val);
1771 PVE::QemuServer::vmconfig_register_unused_drive($storecfg, $vmid, $conf, PVE::QemuServer::parse_drive($opt, $val))
1772 if $is_pending_val;
1773 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1774 PVE::QemuConfig->write_config($vmid, $conf);
1775 } elsif ($opt =~ m/^serial\d+$/) {
1776 if ($val eq 'socket') {
1777 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.HWType']);
1778 } elsif ($authuser ne 'root@pam') {
1779 die "only root can delete '$opt' config for real devices\n";
1780 }
1781 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1782 PVE::QemuConfig->write_config($vmid, $conf);
1783 } elsif ($opt =~ m/^usb\d+$/) {
1784 check_usb_perm($rpcenv, $authuser, $vmid, undef, $opt, $val);
1785 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1786 PVE::QemuConfig->write_config($vmid, $conf);
1787 } elsif ($opt =~ m/^hostpci\d+$/) {
1788 check_hostpci_perm($rpcenv, $authuser, $vmid, undef, $opt, $val);
1789 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1790 PVE::QemuConfig->write_config($vmid, $conf);
1791 } elsif ($opt eq 'tags') {
1792 assert_tag_permissions($vmid, $val, '', $rpcenv, $authuser);
1793 delete $conf->{$opt};
1794 PVE::QemuConfig->write_config($vmid, $conf);
1795 } elsif ($opt =~ m/^net\d+$/) {
1796 if ($conf->{$opt}) {
1797 PVE::QemuServer::check_bridge_access(
1798 $rpcenv, $authuser, { $opt => $conf->{$opt} });
1799 }
1800 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1801 PVE::QemuConfig->write_config($vmid, $conf);
1802 } else {
1803 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1804 PVE::QemuConfig->write_config($vmid, $conf);
1805 }
1806 }
1807
1808 foreach my $opt (keys %$param) { # add/change
1809 $modified->{$opt} = 1;
1810 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
1811 next if defined($conf->{pending}->{$opt}) && ($param->{$opt} eq $conf->{pending}->{$opt}); # skip if nothing changed
1812
1813 my $arch = PVE::QemuServer::get_vm_arch($conf);
1814
1815 if (PVE::QemuServer::is_valid_drivename($opt)) {
1816 # old drive
1817 if ($conf->{$opt}) {
1818 $check_drive_perms->($opt, $conf->{$opt});
1819 }
1820
1821 # new drive
1822 $check_drive_perms->($opt, $param->{$opt});
1823 PVE::QemuServer::vmconfig_register_unused_drive($storecfg, $vmid, $conf, PVE::QemuServer::parse_drive($opt, $conf->{pending}->{$opt}))
1824 if defined($conf->{pending}->{$opt});
1825
1826 my (undef, $created_opts) = $create_disks->(
1827 $rpcenv,
1828 $authuser,
1829 $conf,
1830 $arch,
1831 $storecfg,
1832 $vmid,
1833 undef,
1834 {$opt => $param->{$opt}},
1835 );
1836 $conf->{pending}->{$_} = $created_opts->{$_} for keys $created_opts->%*;
1837
1838 # default legacy boot order implies all cdroms anyway
1839 if (@bootorder) {
1840 # append new CD drives to bootorder to mark them bootable
1841 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt}, 1);
1842 if (PVE::QemuServer::drive_is_cdrom($drive, 1) && !grep(/^$opt$/, @bootorder)) {
1843 push @bootorder, $opt;
1844 $conf->{pending}->{boot} = PVE::QemuServer::print_bootorder(\@bootorder);
1845 $modified->{boot} = 1;
1846 }
1847 }
1848 } elsif ($opt =~ m/^serial\d+/) {
1849 if ((!defined($conf->{$opt}) || $conf->{$opt} eq 'socket') && $param->{$opt} eq 'socket') {
1850 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.HWType']);
1851 } elsif ($authuser ne 'root@pam') {
1852 die "only root can modify '$opt' config for real devices\n";
1853 }
1854 $conf->{pending}->{$opt} = $param->{$opt};
1855 } elsif ($opt =~ m/^usb\d+/) {
1856 if (my $olddevice = $conf->{$opt}) {
1857 check_usb_perm($rpcenv, $authuser, $vmid, undef, $opt, $conf->{$opt});
1858 }
1859 check_usb_perm($rpcenv, $authuser, $vmid, undef, $opt, $param->{$opt});
1860 $conf->{pending}->{$opt} = $param->{$opt};
1861 } elsif ($opt =~ m/^hostpci\d+$/) {
1862 if (my $oldvalue = $conf->{$opt}) {
1863 check_hostpci_perm($rpcenv, $authuser, $vmid, undef, $opt, $oldvalue);
1864 }
1865 check_hostpci_perm($rpcenv, $authuser, $vmid, undef, $opt, $param->{$opt});
1866 $conf->{pending}->{$opt} = $param->{$opt};
1867 } elsif ($opt eq 'tags') {
1868 assert_tag_permissions($vmid, $conf->{$opt}, $param->{$opt}, $rpcenv, $authuser);
1869 $conf->{pending}->{$opt} = PVE::GuestHelpers::get_unique_tags($param->{$opt});
1870 } elsif ($opt =~ m/^net\d+$/) {
1871 if ($conf->{$opt}) {
1872 PVE::QemuServer::check_bridge_access(
1873 $rpcenv, $authuser, { $opt => $conf->{$opt} });
1874 }
1875 $conf->{pending}->{$opt} = $param->{$opt};
1876 } else {
1877 $conf->{pending}->{$opt} = $param->{$opt};
1878
1879 if ($opt eq 'boot') {
1880 my $new_bootcfg = PVE::JSONSchema::parse_property_string('pve-qm-boot', $param->{$opt});
1881 if ($new_bootcfg->{order}) {
1882 my @devs = PVE::Tools::split_list($new_bootcfg->{order});
1883 for my $dev (@devs) {
1884 my $exists = $conf->{$dev} || $conf->{pending}->{$dev} || $param->{$dev};
1885 my $deleted = grep {$_ eq $dev} @delete;
1886 die "invalid bootorder: device '$dev' does not exist'\n"
1887 if !$exists || $deleted;
1888 }
1889
1890 # remove legacy boot order settings if new one set
1891 $conf->{pending}->{$opt} = PVE::QemuServer::print_bootorder(\@devs);
1892 PVE::QemuConfig->add_to_pending_delete($conf, "bootdisk")
1893 if $conf->{bootdisk};
1894 }
1895 }
1896 }
1897 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
1898 PVE::QemuConfig->write_config($vmid, $conf);
1899 }
1900
1901 # remove pending changes when nothing changed
1902 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
1903 my $changes = PVE::QemuConfig->cleanup_pending($conf);
1904 PVE::QemuConfig->write_config($vmid, $conf) if $changes;
1905
1906 return if !scalar(keys %{$conf->{pending}});
1907
1908 my $running = PVE::QemuServer::check_running($vmid);
1909
1910 # apply pending changes
1911
1912 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
1913
1914 my $errors = {};
1915 if ($running) {
1916 PVE::QemuServer::vmconfig_hotplug_pending($vmid, $conf, $storecfg, $modified, $errors);
1917 } else {
1918 # cloud_init must be skipped if we are in an incoming, remote live migration
1919 PVE::QemuServer::vmconfig_apply_pending($vmid, $conf, $storecfg, $errors, $skip_cloud_init);
1920 }
1921 raise_param_exc($errors) if scalar(keys %$errors);
1922
1923 return;
1924 };
1925
1926 if ($sync) {
1927 &$worker();
1928 return;
1929 } else {
1930 my $upid = $rpcenv->fork_worker('qmconfig', $vmid, $authuser, $worker);
1931
1932 if ($background_delay) {
1933
1934 # Note: It would be better to do that in the Event based HTTPServer
1935 # to avoid blocking call to sleep.
1936
1937 my $end_time = time() + $background_delay;
1938
1939 my $task = PVE::Tools::upid_decode($upid);
1940
1941 my $running = 1;
1942 while (time() < $end_time) {
1943 $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
1944 last if !$running;
1945 sleep(1); # this gets interrupted when child process ends
1946 }
1947
1948 if (!$running) {
1949 my $status = PVE::Tools::upid_read_status($upid);
1950 return if !PVE::Tools::upid_status_is_error($status);
1951 die "failed to update VM $vmid: $status\n";
1952 }
1953 }
1954
1955 return $upid;
1956 }
1957 };
1958
1959 return PVE::QemuConfig->lock_config($vmid, $updatefn);
1960 };
1961
1962 my $vm_config_perm_list = [
1963 'VM.Config.Disk',
1964 'VM.Config.CDROM',
1965 'VM.Config.CPU',
1966 'VM.Config.Memory',
1967 'VM.Config.Network',
1968 'VM.Config.HWType',
1969 'VM.Config.Options',
1970 'VM.Config.Cloudinit',
1971 ];
1972
1973 __PACKAGE__->register_method({
1974 name => 'update_vm_async',
1975 path => '{vmid}/config',
1976 method => 'POST',
1977 protected => 1,
1978 proxyto => 'node',
1979 description => "Set virtual machine options (asynchrounous API).",
1980 permissions => {
1981 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
1982 },
1983 parameters => {
1984 additionalProperties => 0,
1985 properties => PVE::QemuServer::json_config_properties(
1986 {
1987 node => get_standard_option('pve-node'),
1988 vmid => get_standard_option('pve-vmid'),
1989 skiplock => get_standard_option('skiplock'),
1990 delete => {
1991 type => 'string', format => 'pve-configid-list',
1992 description => "A list of settings you want to delete.",
1993 optional => 1,
1994 },
1995 revert => {
1996 type => 'string', format => 'pve-configid-list',
1997 description => "Revert a pending change.",
1998 optional => 1,
1999 },
2000 force => {
2001 type => 'boolean',
2002 description => $opt_force_description,
2003 optional => 1,
2004 requires => 'delete',
2005 },
2006 digest => {
2007 type => 'string',
2008 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2009 maxLength => 40,
2010 optional => 1,
2011 },
2012 background_delay => {
2013 type => 'integer',
2014 description => "Time to wait for the task to finish. We return 'null' if the task finish within that time.",
2015 minimum => 1,
2016 maximum => 30,
2017 optional => 1,
2018 },
2019 },
2020 1, # with_disk_alloc
2021 ),
2022 },
2023 returns => {
2024 type => 'string',
2025 optional => 1,
2026 },
2027 code => $update_vm_api,
2028 });
2029
2030 __PACKAGE__->register_method({
2031 name => 'update_vm',
2032 path => '{vmid}/config',
2033 method => 'PUT',
2034 protected => 1,
2035 proxyto => 'node',
2036 description => "Set virtual machine options (synchrounous API) - You should consider using the POST method instead for any actions involving hotplug or storage allocation.",
2037 permissions => {
2038 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
2039 },
2040 parameters => {
2041 additionalProperties => 0,
2042 properties => PVE::QemuServer::json_config_properties(
2043 {
2044 node => get_standard_option('pve-node'),
2045 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
2046 skiplock => get_standard_option('skiplock'),
2047 delete => {
2048 type => 'string', format => 'pve-configid-list',
2049 description => "A list of settings you want to delete.",
2050 optional => 1,
2051 },
2052 revert => {
2053 type => 'string', format => 'pve-configid-list',
2054 description => "Revert a pending change.",
2055 optional => 1,
2056 },
2057 force => {
2058 type => 'boolean',
2059 description => $opt_force_description,
2060 optional => 1,
2061 requires => 'delete',
2062 },
2063 digest => {
2064 type => 'string',
2065 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2066 maxLength => 40,
2067 optional => 1,
2068 },
2069 },
2070 1, # with_disk_alloc
2071 ),
2072 },
2073 returns => { type => 'null' },
2074 code => sub {
2075 my ($param) = @_;
2076 &$update_vm_api($param, 1);
2077 return;
2078 }
2079 });
2080
2081 __PACKAGE__->register_method({
2082 name => 'destroy_vm',
2083 path => '{vmid}',
2084 method => 'DELETE',
2085 protected => 1,
2086 proxyto => 'node',
2087 description => "Destroy the VM and all used/owned volumes. Removes any VM specific permissions"
2088 ." and firewall rules",
2089 permissions => {
2090 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
2091 },
2092 parameters => {
2093 additionalProperties => 0,
2094 properties => {
2095 node => get_standard_option('pve-node'),
2096 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_stopped }),
2097 skiplock => get_standard_option('skiplock'),
2098 purge => {
2099 type => 'boolean',
2100 description => "Remove VMID from configurations, like backup & replication jobs and HA.",
2101 optional => 1,
2102 },
2103 'destroy-unreferenced-disks' => {
2104 type => 'boolean',
2105 description => "If set, destroy additionally all disks not referenced in the config"
2106 ." but with a matching VMID from all enabled storages.",
2107 optional => 1,
2108 default => 0,
2109 },
2110 },
2111 },
2112 returns => {
2113 type => 'string',
2114 },
2115 code => sub {
2116 my ($param) = @_;
2117
2118 my $rpcenv = PVE::RPCEnvironment::get();
2119 my $authuser = $rpcenv->get_user();
2120 my $vmid = $param->{vmid};
2121
2122 my $skiplock = $param->{skiplock};
2123 raise_param_exc({ skiplock => "Only root may use this option." })
2124 if $skiplock && $authuser ne 'root@pam';
2125
2126 my $early_checks = sub {
2127 # test if VM exists
2128 my $conf = PVE::QemuConfig->load_config($vmid);
2129 PVE::QemuConfig->check_protection($conf, "can't remove VM $vmid");
2130
2131 my $ha_managed = PVE::HA::Config::service_is_configured("vm:$vmid");
2132
2133 if (!$param->{purge}) {
2134 die "unable to remove VM $vmid - used in HA resources and purge parameter not set.\n"
2135 if $ha_managed;
2136 # don't allow destroy if with replication jobs but no purge param
2137 my $repl_conf = PVE::ReplicationConfig->new();
2138 $repl_conf->check_for_existing_jobs($vmid);
2139 }
2140
2141 die "VM $vmid is running - destroy failed\n"
2142 if PVE::QemuServer::check_running($vmid);
2143
2144 return $ha_managed;
2145 };
2146
2147 $early_checks->();
2148
2149 my $realcmd = sub {
2150 my $upid = shift;
2151
2152 my $storecfg = PVE::Storage::config();
2153
2154 syslog('info', "destroy VM $vmid: $upid\n");
2155 PVE::QemuConfig->lock_config($vmid, sub {
2156 # repeat, config might have changed
2157 my $ha_managed = $early_checks->();
2158
2159 my $purge_unreferenced = $param->{'destroy-unreferenced-disks'};
2160
2161 PVE::QemuServer::destroy_vm(
2162 $storecfg,
2163 $vmid,
2164 $skiplock, { lock => 'destroyed' },
2165 $purge_unreferenced,
2166 );
2167
2168 PVE::AccessControl::remove_vm_access($vmid);
2169 PVE::Firewall::remove_vmfw_conf($vmid);
2170 if ($param->{purge}) {
2171 print "purging VM $vmid from related configurations..\n";
2172 PVE::ReplicationConfig::remove_vmid_jobs($vmid);
2173 PVE::VZDump::Plugin::remove_vmid_from_backup_jobs($vmid);
2174
2175 if ($ha_managed) {
2176 PVE::HA::Config::delete_service_from_config("vm:$vmid");
2177 print "NOTE: removed VM $vmid from HA resource configuration.\n";
2178 }
2179 }
2180
2181 # only now remove the zombie config, else we can have reuse race
2182 PVE::QemuConfig->destroy_config($vmid);
2183 });
2184 };
2185
2186 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
2187 }});
2188
2189 __PACKAGE__->register_method({
2190 name => 'unlink',
2191 path => '{vmid}/unlink',
2192 method => 'PUT',
2193 protected => 1,
2194 proxyto => 'node',
2195 description => "Unlink/delete disk images.",
2196 permissions => {
2197 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
2198 },
2199 parameters => {
2200 additionalProperties => 0,
2201 properties => {
2202 node => get_standard_option('pve-node'),
2203 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
2204 idlist => {
2205 type => 'string', format => 'pve-configid-list',
2206 description => "A list of disk IDs you want to delete.",
2207 },
2208 force => {
2209 type => 'boolean',
2210 description => $opt_force_description,
2211 optional => 1,
2212 },
2213 },
2214 },
2215 returns => { type => 'null'},
2216 code => sub {
2217 my ($param) = @_;
2218
2219 $param->{delete} = extract_param($param, 'idlist');
2220
2221 __PACKAGE__->update_vm($param);
2222
2223 return;
2224 }});
2225
2226 # uses good entropy, each char is limited to 6 bit to get printable chars simply
2227 my $gen_rand_chars = sub {
2228 my ($length) = @_;
2229
2230 die "invalid length $length" if $length < 1;
2231
2232 my $min = ord('!'); # first printable ascii
2233
2234 my $rand_bytes = Crypt::OpenSSL::Random::random_bytes($length);
2235 die "failed to generate random bytes!\n"
2236 if !$rand_bytes;
2237
2238 my $str = join('', map { chr((ord($_) & 0x3F) + $min) } split('', $rand_bytes));
2239
2240 return $str;
2241 };
2242
2243 my $sslcert;
2244
2245 __PACKAGE__->register_method({
2246 name => 'vncproxy',
2247 path => '{vmid}/vncproxy',
2248 method => 'POST',
2249 protected => 1,
2250 permissions => {
2251 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
2252 },
2253 description => "Creates a TCP VNC proxy connections.",
2254 parameters => {
2255 additionalProperties => 0,
2256 properties => {
2257 node => get_standard_option('pve-node'),
2258 vmid => get_standard_option('pve-vmid'),
2259 websocket => {
2260 optional => 1,
2261 type => 'boolean',
2262 description => "starts websockify instead of vncproxy",
2263 },
2264 'generate-password' => {
2265 optional => 1,
2266 type => 'boolean',
2267 default => 0,
2268 description => "Generates a random password to be used as ticket instead of the API ticket.",
2269 },
2270 },
2271 },
2272 returns => {
2273 additionalProperties => 0,
2274 properties => {
2275 user => { type => 'string' },
2276 ticket => { type => 'string' },
2277 password => {
2278 optional => 1,
2279 description => "Returned if requested with 'generate-password' param."
2280 ." Consists of printable ASCII characters ('!' .. '~').",
2281 type => 'string',
2282 },
2283 cert => { type => 'string' },
2284 port => { type => 'integer' },
2285 upid => { type => 'string' },
2286 },
2287 },
2288 code => sub {
2289 my ($param) = @_;
2290
2291 my $rpcenv = PVE::RPCEnvironment::get();
2292
2293 my $authuser = $rpcenv->get_user();
2294
2295 my $vmid = $param->{vmid};
2296 my $node = $param->{node};
2297 my $websocket = $param->{websocket};
2298
2299 my $conf = PVE::QemuConfig->load_config($vmid, $node); # check if VM exists
2300
2301 my $serial;
2302 if ($conf->{vga}) {
2303 my $vga = PVE::QemuServer::parse_vga($conf->{vga});
2304 $serial = $vga->{type} if $vga->{type} =~ m/^serial\d+$/;
2305 }
2306
2307 my $authpath = "/vms/$vmid";
2308
2309 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
2310 my $password = $ticket;
2311 if ($param->{'generate-password'}) {
2312 $password = $gen_rand_chars->(8);
2313 }
2314
2315 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
2316 if !$sslcert;
2317
2318 my $family;
2319 my $remcmd = [];
2320
2321 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
2322 (undef, $family) = PVE::Cluster::remote_node_ip($node);
2323 my $sshinfo = PVE::SSHInfo::get_ssh_info($node);
2324 # NOTE: kvm VNC traffic is already TLS encrypted or is known unsecure
2325 $remcmd = PVE::SSHInfo::ssh_info_to_command($sshinfo, defined($serial) ? '-t' : '-T');
2326 } else {
2327 $family = PVE::Tools::get_host_address_family($node);
2328 }
2329
2330 my $port = PVE::Tools::next_vnc_port($family);
2331
2332 my $timeout = 10;
2333
2334 my $realcmd = sub {
2335 my $upid = shift;
2336
2337 syslog('info', "starting vnc proxy $upid\n");
2338
2339 my $cmd;
2340
2341 if (defined($serial)) {
2342
2343 my $termcmd = [ '/usr/sbin/qm', 'terminal', $vmid, '-iface', $serial, '-escape', '0' ];
2344
2345 $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
2346 '-timeout', $timeout, '-authpath', $authpath,
2347 '-perm', 'Sys.Console'];
2348
2349 if ($param->{websocket}) {
2350 $ENV{PVE_VNC_TICKET} = $password; # pass ticket to vncterm
2351 push @$cmd, '-notls', '-listen', 'localhost';
2352 }
2353
2354 push @$cmd, '-c', @$remcmd, @$termcmd;
2355
2356 PVE::Tools::run_command($cmd);
2357
2358 } else {
2359
2360 $ENV{LC_PVE_TICKET} = $password if $websocket; # set ticket with "qm vncproxy"
2361
2362 $cmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
2363
2364 my $sock = IO::Socket::IP->new(
2365 ReuseAddr => 1,
2366 Listen => 1,
2367 LocalPort => $port,
2368 Proto => 'tcp',
2369 GetAddrInfoFlags => 0,
2370 ) or die "failed to create socket: $!\n";
2371 # Inside the worker we shouldn't have any previous alarms
2372 # running anyway...:
2373 alarm(0);
2374 local $SIG{ALRM} = sub { die "connection timed out\n" };
2375 alarm $timeout;
2376 accept(my $cli, $sock) or die "connection failed: $!\n";
2377 alarm(0);
2378 close($sock);
2379 if (PVE::Tools::run_command($cmd,
2380 output => '>&'.fileno($cli),
2381 input => '<&'.fileno($cli),
2382 noerr => 1) != 0)
2383 {
2384 die "Failed to run vncproxy.\n";
2385 }
2386 }
2387
2388 return;
2389 };
2390
2391 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd, 1);
2392
2393 PVE::Tools::wait_for_vnc_port($port);
2394
2395 my $res = {
2396 user => $authuser,
2397 ticket => $ticket,
2398 port => $port,
2399 upid => $upid,
2400 cert => $sslcert,
2401 };
2402 $res->{password} = $password if $param->{'generate-password'};
2403
2404 return $res;
2405 }});
2406
2407 __PACKAGE__->register_method({
2408 name => 'termproxy',
2409 path => '{vmid}/termproxy',
2410 method => 'POST',
2411 protected => 1,
2412 permissions => {
2413 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
2414 },
2415 description => "Creates a TCP proxy connections.",
2416 parameters => {
2417 additionalProperties => 0,
2418 properties => {
2419 node => get_standard_option('pve-node'),
2420 vmid => get_standard_option('pve-vmid'),
2421 serial=> {
2422 optional => 1,
2423 type => 'string',
2424 enum => [qw(serial0 serial1 serial2 serial3)],
2425 description => "opens a serial terminal (defaults to display)",
2426 },
2427 },
2428 },
2429 returns => {
2430 additionalProperties => 0,
2431 properties => {
2432 user => { type => 'string' },
2433 ticket => { type => 'string' },
2434 port => { type => 'integer' },
2435 upid => { type => 'string' },
2436 },
2437 },
2438 code => sub {
2439 my ($param) = @_;
2440
2441 my $rpcenv = PVE::RPCEnvironment::get();
2442
2443 my $authuser = $rpcenv->get_user();
2444
2445 my $vmid = $param->{vmid};
2446 my $node = $param->{node};
2447 my $serial = $param->{serial};
2448
2449 my $conf = PVE::QemuConfig->load_config($vmid, $node); # check if VM exists
2450
2451 if (!defined($serial)) {
2452 if ($conf->{vga}) {
2453 my $vga = PVE::QemuServer::parse_vga($conf->{vga});
2454 $serial = $vga->{type} if $vga->{type} =~ m/^serial\d+$/;
2455 }
2456 }
2457
2458 my $authpath = "/vms/$vmid";
2459
2460 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
2461
2462 my $family;
2463 my $remcmd = [];
2464
2465 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
2466 (undef, $family) = PVE::Cluster::remote_node_ip($node);
2467 my $sshinfo = PVE::SSHInfo::get_ssh_info($node);
2468 $remcmd = PVE::SSHInfo::ssh_info_to_command($sshinfo, '-t');
2469 push @$remcmd, '--';
2470 } else {
2471 $family = PVE::Tools::get_host_address_family($node);
2472 }
2473
2474 my $port = PVE::Tools::next_vnc_port($family);
2475
2476 my $termcmd = [ '/usr/sbin/qm', 'terminal', $vmid, '-escape', '0'];
2477 push @$termcmd, '-iface', $serial if $serial;
2478
2479 my $realcmd = sub {
2480 my $upid = shift;
2481
2482 syslog('info', "starting qemu termproxy $upid\n");
2483
2484 my $cmd = ['/usr/bin/termproxy', $port, '--path', $authpath,
2485 '--perm', 'VM.Console', '--'];
2486 push @$cmd, @$remcmd, @$termcmd;
2487
2488 PVE::Tools::run_command($cmd);
2489 };
2490
2491 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd, 1);
2492
2493 PVE::Tools::wait_for_vnc_port($port);
2494
2495 return {
2496 user => $authuser,
2497 ticket => $ticket,
2498 port => $port,
2499 upid => $upid,
2500 };
2501 }});
2502
2503 __PACKAGE__->register_method({
2504 name => 'vncwebsocket',
2505 path => '{vmid}/vncwebsocket',
2506 method => 'GET',
2507 permissions => {
2508 description => "You also need to pass a valid ticket (vncticket).",
2509 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
2510 },
2511 description => "Opens a weksocket for VNC traffic.",
2512 parameters => {
2513 additionalProperties => 0,
2514 properties => {
2515 node => get_standard_option('pve-node'),
2516 vmid => get_standard_option('pve-vmid'),
2517 vncticket => {
2518 description => "Ticket from previous call to vncproxy.",
2519 type => 'string',
2520 maxLength => 512,
2521 },
2522 port => {
2523 description => "Port number returned by previous vncproxy call.",
2524 type => 'integer',
2525 minimum => 5900,
2526 maximum => 5999,
2527 },
2528 },
2529 },
2530 returns => {
2531 type => "object",
2532 properties => {
2533 port => { type => 'string' },
2534 },
2535 },
2536 code => sub {
2537 my ($param) = @_;
2538
2539 my $rpcenv = PVE::RPCEnvironment::get();
2540
2541 my $authuser = $rpcenv->get_user();
2542
2543 my $vmid = $param->{vmid};
2544 my $node = $param->{node};
2545
2546 my $authpath = "/vms/$vmid";
2547
2548 PVE::AccessControl::verify_vnc_ticket($param->{vncticket}, $authuser, $authpath);
2549
2550 my $conf = PVE::QemuConfig->load_config($vmid, $node); # VM exists ?
2551
2552 # Note: VNC ports are acessible from outside, so we do not gain any
2553 # security if we verify that $param->{port} belongs to VM $vmid. This
2554 # check is done by verifying the VNC ticket (inside VNC protocol).
2555
2556 my $port = $param->{port};
2557
2558 return { port => $port };
2559 }});
2560
2561 __PACKAGE__->register_method({
2562 name => 'spiceproxy',
2563 path => '{vmid}/spiceproxy',
2564 method => 'POST',
2565 protected => 1,
2566 proxyto => 'node',
2567 permissions => {
2568 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
2569 },
2570 description => "Returns a SPICE configuration to connect to the VM.",
2571 parameters => {
2572 additionalProperties => 0,
2573 properties => {
2574 node => get_standard_option('pve-node'),
2575 vmid => get_standard_option('pve-vmid'),
2576 proxy => get_standard_option('spice-proxy', { optional => 1 }),
2577 },
2578 },
2579 returns => get_standard_option('remote-viewer-config'),
2580 code => sub {
2581 my ($param) = @_;
2582
2583 my $rpcenv = PVE::RPCEnvironment::get();
2584
2585 my $authuser = $rpcenv->get_user();
2586
2587 my $vmid = $param->{vmid};
2588 my $node = $param->{node};
2589 my $proxy = $param->{proxy};
2590
2591 my $conf = PVE::QemuConfig->load_config($vmid, $node);
2592 my $title = "VM $vmid";
2593 $title .= " - ". $conf->{name} if $conf->{name};
2594
2595 my $port = PVE::QemuServer::spice_port($vmid);
2596
2597 my ($ticket, undef, $remote_viewer_config) =
2598 PVE::AccessControl::remote_viewer_config($authuser, $vmid, $node, $proxy, $title, $port);
2599
2600 mon_cmd($vmid, "set_password", protocol => 'spice', password => $ticket);
2601 mon_cmd($vmid, "expire_password", protocol => 'spice', time => "+30");
2602
2603 return $remote_viewer_config;
2604 }});
2605
2606 __PACKAGE__->register_method({
2607 name => 'vmcmdidx',
2608 path => '{vmid}/status',
2609 method => 'GET',
2610 proxyto => 'node',
2611 description => "Directory index",
2612 permissions => {
2613 user => 'all',
2614 },
2615 parameters => {
2616 additionalProperties => 0,
2617 properties => {
2618 node => get_standard_option('pve-node'),
2619 vmid => get_standard_option('pve-vmid'),
2620 },
2621 },
2622 returns => {
2623 type => 'array',
2624 items => {
2625 type => "object",
2626 properties => {
2627 subdir => { type => 'string' },
2628 },
2629 },
2630 links => [ { rel => 'child', href => "{subdir}" } ],
2631 },
2632 code => sub {
2633 my ($param) = @_;
2634
2635 # test if VM exists
2636 my $conf = PVE::QemuConfig->load_config($param->{vmid});
2637
2638 my $res = [
2639 { subdir => 'current' },
2640 { subdir => 'start' },
2641 { subdir => 'stop' },
2642 { subdir => 'reset' },
2643 { subdir => 'shutdown' },
2644 { subdir => 'suspend' },
2645 { subdir => 'reboot' },
2646 ];
2647
2648 return $res;
2649 }});
2650
2651 __PACKAGE__->register_method({
2652 name => 'vm_status',
2653 path => '{vmid}/status/current',
2654 method => 'GET',
2655 proxyto => 'node',
2656 protected => 1, # qemu pid files are only readable by root
2657 description => "Get virtual machine status.",
2658 permissions => {
2659 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2660 },
2661 parameters => {
2662 additionalProperties => 0,
2663 properties => {
2664 node => get_standard_option('pve-node'),
2665 vmid => get_standard_option('pve-vmid'),
2666 },
2667 },
2668 returns => {
2669 type => 'object',
2670 properties => {
2671 %$PVE::QemuServer::vmstatus_return_properties,
2672 ha => {
2673 description => "HA manager service status.",
2674 type => 'object',
2675 },
2676 spice => {
2677 description => "QEMU VGA configuration supports spice.",
2678 type => 'boolean',
2679 optional => 1,
2680 },
2681 agent => {
2682 description => "QEMU Guest Agent is enabled in config.",
2683 type => 'boolean',
2684 optional => 1,
2685 },
2686 },
2687 },
2688 code => sub {
2689 my ($param) = @_;
2690
2691 # test if VM exists
2692 my $conf = PVE::QemuConfig->load_config($param->{vmid});
2693
2694 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
2695 my $status = $vmstatus->{$param->{vmid}};
2696
2697 $status->{ha} = PVE::HA::Config::get_service_status("vm:$param->{vmid}");
2698
2699 if ($conf->{vga}) {
2700 my $vga = PVE::QemuServer::parse_vga($conf->{vga});
2701 my $spice = defined($vga->{type}) && $vga->{type} =~ /^virtio/;
2702 $spice ||= PVE::QemuServer::vga_conf_has_spice($conf->{vga});
2703 $status->{spice} = 1 if $spice;
2704 }
2705 $status->{agent} = 1 if PVE::QemuServer::get_qga_key($conf, 'enabled');
2706
2707 return $status;
2708 }});
2709
2710 __PACKAGE__->register_method({
2711 name => 'vm_start',
2712 path => '{vmid}/status/start',
2713 method => 'POST',
2714 protected => 1,
2715 proxyto => 'node',
2716 description => "Start virtual machine.",
2717 permissions => {
2718 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2719 },
2720 parameters => {
2721 additionalProperties => 0,
2722 properties => {
2723 node => get_standard_option('pve-node'),
2724 vmid => get_standard_option('pve-vmid',
2725 { completion => \&PVE::QemuServer::complete_vmid_stopped }),
2726 skiplock => get_standard_option('skiplock'),
2727 stateuri => get_standard_option('pve-qm-stateuri'),
2728 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
2729 migration_type => {
2730 type => 'string',
2731 enum => ['secure', 'insecure'],
2732 description => "Migration traffic is encrypted using an SSH " .
2733 "tunnel by default. On secure, completely private networks " .
2734 "this can be disabled to increase performance.",
2735 optional => 1,
2736 },
2737 migration_network => {
2738 type => 'string', format => 'CIDR',
2739 description => "CIDR of the (sub) network that is used for migration.",
2740 optional => 1,
2741 },
2742 machine => get_standard_option('pve-qemu-machine'),
2743 'force-cpu' => {
2744 description => "Override QEMU's -cpu argument with the given string.",
2745 type => 'string',
2746 optional => 1,
2747 },
2748 targetstorage => get_standard_option('pve-targetstorage'),
2749 timeout => {
2750 description => "Wait maximal timeout seconds.",
2751 type => 'integer',
2752 minimum => 0,
2753 default => 'max(30, vm memory in GiB)',
2754 optional => 1,
2755 },
2756 },
2757 },
2758 returns => {
2759 type => 'string',
2760 },
2761 code => sub {
2762 my ($param) = @_;
2763
2764 my $rpcenv = PVE::RPCEnvironment::get();
2765 my $authuser = $rpcenv->get_user();
2766
2767 my $node = extract_param($param, 'node');
2768 my $vmid = extract_param($param, 'vmid');
2769 my $timeout = extract_param($param, 'timeout');
2770 my $machine = extract_param($param, 'machine');
2771
2772 my $get_root_param = sub {
2773 my $value = extract_param($param, $_[0]);
2774 raise_param_exc({ "$_[0]" => "Only root may use this option." })
2775 if $value && $authuser ne 'root@pam';
2776 return $value;
2777 };
2778
2779 my $stateuri = $get_root_param->('stateuri');
2780 my $skiplock = $get_root_param->('skiplock');
2781 my $migratedfrom = $get_root_param->('migratedfrom');
2782 my $migration_type = $get_root_param->('migration_type');
2783 my $migration_network = $get_root_param->('migration_network');
2784 my $targetstorage = $get_root_param->('targetstorage');
2785 my $force_cpu = $get_root_param->('force-cpu');
2786
2787 my $storagemap;
2788
2789 if ($targetstorage) {
2790 raise_param_exc({ targetstorage => "targetstorage can only by used with migratedfrom." })
2791 if !$migratedfrom;
2792 $storagemap = eval { PVE::JSONSchema::parse_idmap($targetstorage, 'pve-storage-id') };
2793 raise_param_exc({ targetstorage => "failed to parse storage map: $@" })
2794 if $@;
2795 }
2796
2797 # read spice ticket from STDIN
2798 my $spice_ticket;
2799 my $nbd_protocol_version = 0;
2800 my $replicated_volumes = {};
2801 my $offline_volumes = {};
2802 if ($stateuri && ($stateuri eq 'tcp' || $stateuri eq 'unix') && $migratedfrom && ($rpcenv->{type} eq 'cli')) {
2803 while (defined(my $line = <STDIN>)) {
2804 chomp $line;
2805 if ($line =~ m/^spice_ticket: (.+)$/) {
2806 $spice_ticket = $1;
2807 } elsif ($line =~ m/^nbd_protocol_version: (\d+)$/) {
2808 $nbd_protocol_version = $1;
2809 } elsif ($line =~ m/^replicated_volume: (.*)$/) {
2810 $replicated_volumes->{$1} = 1;
2811 } elsif ($line =~ m/^tpmstate0: (.*)$/) { # Deprecated, use offline_volume instead
2812 $offline_volumes->{tpmstate0} = $1;
2813 } elsif ($line =~ m/^offline_volume: ([^:]+): (.*)$/) {
2814 $offline_volumes->{$1} = $2;
2815 } elsif (!$spice_ticket) {
2816 # fallback for old source node
2817 $spice_ticket = $line;
2818 } else {
2819 warn "unknown 'start' parameter on STDIN: '$line'\n";
2820 }
2821 }
2822 }
2823
2824 PVE::Cluster::check_cfs_quorum();
2825
2826 my $storecfg = PVE::Storage::config();
2827
2828 if (PVE::HA::Config::vm_is_ha_managed($vmid) && !$stateuri && $rpcenv->{type} ne 'ha') {
2829 my $hacmd = sub {
2830 my $upid = shift;
2831
2832 print "Requesting HA start for VM $vmid\n";
2833
2834 my $cmd = ['ha-manager', 'set', "vm:$vmid", '--state', 'started'];
2835 PVE::Tools::run_command($cmd);
2836 return;
2837 };
2838
2839 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
2840
2841 } else {
2842
2843 my $realcmd = sub {
2844 my $upid = shift;
2845
2846 syslog('info', "start VM $vmid: $upid\n");
2847
2848 my $migrate_opts = {
2849 migratedfrom => $migratedfrom,
2850 spice_ticket => $spice_ticket,
2851 network => $migration_network,
2852 type => $migration_type,
2853 storagemap => $storagemap,
2854 nbd_proto_version => $nbd_protocol_version,
2855 replicated_volumes => $replicated_volumes,
2856 offline_volumes => $offline_volumes,
2857 };
2858
2859 my $params = {
2860 statefile => $stateuri,
2861 skiplock => $skiplock,
2862 forcemachine => $machine,
2863 timeout => $timeout,
2864 forcecpu => $force_cpu,
2865 };
2866
2867 PVE::QemuServer::vm_start($storecfg, $vmid, $params, $migrate_opts);
2868 return;
2869 };
2870
2871 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
2872 }
2873 }});
2874
2875 __PACKAGE__->register_method({
2876 name => 'vm_stop',
2877 path => '{vmid}/status/stop',
2878 method => 'POST',
2879 protected => 1,
2880 proxyto => 'node',
2881 description => "Stop virtual machine. The qemu process will exit immediately. This" .
2882 "is akin to pulling the power plug of a running computer and may damage the VM data",
2883 permissions => {
2884 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2885 },
2886 parameters => {
2887 additionalProperties => 0,
2888 properties => {
2889 node => get_standard_option('pve-node'),
2890 vmid => get_standard_option('pve-vmid',
2891 { completion => \&PVE::QemuServer::complete_vmid_running }),
2892 skiplock => get_standard_option('skiplock'),
2893 migratedfrom => get_standard_option('pve-node', { optional => 1 }),
2894 timeout => {
2895 description => "Wait maximal timeout seconds.",
2896 type => 'integer',
2897 minimum => 0,
2898 optional => 1,
2899 },
2900 keepActive => {
2901 description => "Do not deactivate storage volumes.",
2902 type => 'boolean',
2903 optional => 1,
2904 default => 0,
2905 }
2906 },
2907 },
2908 returns => {
2909 type => 'string',
2910 },
2911 code => sub {
2912 my ($param) = @_;
2913
2914 my $rpcenv = PVE::RPCEnvironment::get();
2915 my $authuser = $rpcenv->get_user();
2916
2917 my $node = extract_param($param, 'node');
2918 my $vmid = extract_param($param, 'vmid');
2919
2920 my $skiplock = extract_param($param, 'skiplock');
2921 raise_param_exc({ skiplock => "Only root may use this option." })
2922 if $skiplock && $authuser ne 'root@pam';
2923
2924 my $keepActive = extract_param($param, 'keepActive');
2925 raise_param_exc({ keepActive => "Only root may use this option." })
2926 if $keepActive && $authuser ne 'root@pam';
2927
2928 my $migratedfrom = extract_param($param, 'migratedfrom');
2929 raise_param_exc({ migratedfrom => "Only root may use this option." })
2930 if $migratedfrom && $authuser ne 'root@pam';
2931
2932
2933 my $storecfg = PVE::Storage::config();
2934
2935 if (PVE::HA::Config::vm_is_ha_managed($vmid) && ($rpcenv->{type} ne 'ha') && !defined($migratedfrom)) {
2936
2937 my $hacmd = sub {
2938 my $upid = shift;
2939
2940 print "Requesting HA stop for VM $vmid\n";
2941
2942 my $cmd = ['ha-manager', 'crm-command', 'stop', "vm:$vmid", '0'];
2943 PVE::Tools::run_command($cmd);
2944 return;
2945 };
2946
2947 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
2948
2949 } else {
2950 my $realcmd = sub {
2951 my $upid = shift;
2952
2953 syslog('info', "stop VM $vmid: $upid\n");
2954
2955 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
2956 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
2957 return;
2958 };
2959
2960 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
2961 }
2962 }});
2963
2964 __PACKAGE__->register_method({
2965 name => 'vm_reset',
2966 path => '{vmid}/status/reset',
2967 method => 'POST',
2968 protected => 1,
2969 proxyto => 'node',
2970 description => "Reset virtual machine.",
2971 permissions => {
2972 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2973 },
2974 parameters => {
2975 additionalProperties => 0,
2976 properties => {
2977 node => get_standard_option('pve-node'),
2978 vmid => get_standard_option('pve-vmid',
2979 { completion => \&PVE::QemuServer::complete_vmid_running }),
2980 skiplock => get_standard_option('skiplock'),
2981 },
2982 },
2983 returns => {
2984 type => 'string',
2985 },
2986 code => sub {
2987 my ($param) = @_;
2988
2989 my $rpcenv = PVE::RPCEnvironment::get();
2990
2991 my $authuser = $rpcenv->get_user();
2992
2993 my $node = extract_param($param, 'node');
2994
2995 my $vmid = extract_param($param, 'vmid');
2996
2997 my $skiplock = extract_param($param, 'skiplock');
2998 raise_param_exc({ skiplock => "Only root may use this option." })
2999 if $skiplock && $authuser ne 'root@pam';
3000
3001 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
3002
3003 my $realcmd = sub {
3004 my $upid = shift;
3005
3006 PVE::QemuServer::vm_reset($vmid, $skiplock);
3007
3008 return;
3009 };
3010
3011 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
3012 }});
3013
3014 __PACKAGE__->register_method({
3015 name => 'vm_shutdown',
3016 path => '{vmid}/status/shutdown',
3017 method => 'POST',
3018 protected => 1,
3019 proxyto => 'node',
3020 description => "Shutdown virtual machine. This is similar to pressing the power button on a physical machine." .
3021 "This will send an ACPI event for the guest OS, which should then proceed to a clean shutdown.",
3022 permissions => {
3023 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
3024 },
3025 parameters => {
3026 additionalProperties => 0,
3027 properties => {
3028 node => get_standard_option('pve-node'),
3029 vmid => get_standard_option('pve-vmid',
3030 { completion => \&PVE::QemuServer::complete_vmid_running }),
3031 skiplock => get_standard_option('skiplock'),
3032 timeout => {
3033 description => "Wait maximal timeout seconds.",
3034 type => 'integer',
3035 minimum => 0,
3036 optional => 1,
3037 },
3038 forceStop => {
3039 description => "Make sure the VM stops.",
3040 type => 'boolean',
3041 optional => 1,
3042 default => 0,
3043 },
3044 keepActive => {
3045 description => "Do not deactivate storage volumes.",
3046 type => 'boolean',
3047 optional => 1,
3048 default => 0,
3049 }
3050 },
3051 },
3052 returns => {
3053 type => 'string',
3054 },
3055 code => sub {
3056 my ($param) = @_;
3057
3058 my $rpcenv = PVE::RPCEnvironment::get();
3059 my $authuser = $rpcenv->get_user();
3060
3061 my $node = extract_param($param, 'node');
3062 my $vmid = extract_param($param, 'vmid');
3063
3064 my $skiplock = extract_param($param, 'skiplock');
3065 raise_param_exc({ skiplock => "Only root may use this option." })
3066 if $skiplock && $authuser ne 'root@pam';
3067
3068 my $keepActive = extract_param($param, 'keepActive');
3069 raise_param_exc({ keepActive => "Only root may use this option." })
3070 if $keepActive && $authuser ne 'root@pam';
3071
3072 my $storecfg = PVE::Storage::config();
3073
3074 my $shutdown = 1;
3075
3076 # if vm is paused, do not shutdown (but stop if forceStop = 1)
3077 # otherwise, we will infer a shutdown command, but run into the timeout,
3078 # then when the vm is resumed, it will instantly shutdown
3079 #
3080 # checking the qmp status here to get feedback to the gui/cli/api
3081 # and the status query should not take too long
3082 if (PVE::QemuServer::vm_is_paused($vmid)) {
3083 if ($param->{forceStop}) {
3084 warn "VM is paused - stop instead of shutdown\n";
3085 $shutdown = 0;
3086 } else {
3087 die "VM is paused - cannot shutdown\n";
3088 }
3089 }
3090
3091 if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3092
3093 my $timeout = $param->{timeout} // 60;
3094 my $hacmd = sub {
3095 my $upid = shift;
3096
3097 print "Requesting HA stop for VM $vmid\n";
3098
3099 my $cmd = ['ha-manager', 'crm-command', 'stop', "vm:$vmid", "$timeout"];
3100 PVE::Tools::run_command($cmd);
3101 return;
3102 };
3103
3104 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
3105
3106 } else {
3107
3108 my $realcmd = sub {
3109 my $upid = shift;
3110
3111 syslog('info', "shutdown VM $vmid: $upid\n");
3112
3113 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
3114 $shutdown, $param->{forceStop}, $keepActive);
3115 return;
3116 };
3117
3118 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
3119 }
3120 }});
3121
3122 __PACKAGE__->register_method({
3123 name => 'vm_reboot',
3124 path => '{vmid}/status/reboot',
3125 method => 'POST',
3126 protected => 1,
3127 proxyto => 'node',
3128 description => "Reboot the VM by shutting it down, and starting it again. Applies pending changes.",
3129 permissions => {
3130 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
3131 },
3132 parameters => {
3133 additionalProperties => 0,
3134 properties => {
3135 node => get_standard_option('pve-node'),
3136 vmid => get_standard_option('pve-vmid',
3137 { completion => \&PVE::QemuServer::complete_vmid_running }),
3138 timeout => {
3139 description => "Wait maximal timeout seconds for the shutdown.",
3140 type => 'integer',
3141 minimum => 0,
3142 optional => 1,
3143 },
3144 },
3145 },
3146 returns => {
3147 type => 'string',
3148 },
3149 code => sub {
3150 my ($param) = @_;
3151
3152 my $rpcenv = PVE::RPCEnvironment::get();
3153 my $authuser = $rpcenv->get_user();
3154
3155 my $node = extract_param($param, 'node');
3156 my $vmid = extract_param($param, 'vmid');
3157
3158 die "VM is paused - cannot shutdown\n" if PVE::QemuServer::vm_is_paused($vmid);
3159
3160 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
3161
3162 my $realcmd = sub {
3163 my $upid = shift;
3164
3165 syslog('info', "requesting reboot of VM $vmid: $upid\n");
3166 PVE::QemuServer::vm_reboot($vmid, $param->{timeout});
3167 return;
3168 };
3169
3170 return $rpcenv->fork_worker('qmreboot', $vmid, $authuser, $realcmd);
3171 }});
3172
3173 __PACKAGE__->register_method({
3174 name => 'vm_suspend',
3175 path => '{vmid}/status/suspend',
3176 method => 'POST',
3177 protected => 1,
3178 proxyto => 'node',
3179 description => "Suspend virtual machine.",
3180 permissions => {
3181 description => "You need 'VM.PowerMgmt' on /vms/{vmid}, and if you have set 'todisk',".
3182 " you need also 'VM.Config.Disk' on /vms/{vmid} and 'Datastore.AllocateSpace'".
3183 " on the storage for the vmstate.",
3184 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
3185 },
3186 parameters => {
3187 additionalProperties => 0,
3188 properties => {
3189 node => get_standard_option('pve-node'),
3190 vmid => get_standard_option('pve-vmid',
3191 { completion => \&PVE::QemuServer::complete_vmid_running }),
3192 skiplock => get_standard_option('skiplock'),
3193 todisk => {
3194 type => 'boolean',
3195 default => 0,
3196 optional => 1,
3197 description => 'If set, suspends the VM to disk. Will be resumed on next VM start.',
3198 },
3199 statestorage => get_standard_option('pve-storage-id', {
3200 description => "The storage for the VM state",
3201 requires => 'todisk',
3202 optional => 1,
3203 completion => \&PVE::Storage::complete_storage_enabled,
3204 }),
3205 },
3206 },
3207 returns => {
3208 type => 'string',
3209 },
3210 code => sub {
3211 my ($param) = @_;
3212
3213 my $rpcenv = PVE::RPCEnvironment::get();
3214 my $authuser = $rpcenv->get_user();
3215
3216 my $node = extract_param($param, 'node');
3217 my $vmid = extract_param($param, 'vmid');
3218
3219 my $todisk = extract_param($param, 'todisk') // 0;
3220
3221 my $statestorage = extract_param($param, 'statestorage');
3222
3223 my $skiplock = extract_param($param, 'skiplock');
3224 raise_param_exc({ skiplock => "Only root may use this option." })
3225 if $skiplock && $authuser ne 'root@pam';
3226
3227 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
3228
3229 die "Cannot suspend HA managed VM to disk\n"
3230 if $todisk && PVE::HA::Config::vm_is_ha_managed($vmid);
3231
3232 # early check for storage permission, for better user feedback
3233 if ($todisk) {
3234 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
3235 my $conf = PVE::QemuConfig->load_config($vmid);
3236
3237 # cannot save the state of a non-virtualized PCIe device, so resume cannot really work
3238 for my $key (keys %$conf) {
3239 next if $key !~ /^hostpci\d+/;
3240 die "cannot suspend VM to disk due to passed-through PCI device(s), which lack the"
3241 ." possibility to save/restore their internal state\n";
3242 }
3243
3244 if (!$statestorage) {
3245 # get statestorage from config if none is given
3246 my $storecfg = PVE::Storage::config();
3247 $statestorage = PVE::QemuServer::find_vmstate_storage($conf, $storecfg);
3248 }
3249
3250 $rpcenv->check($authuser, "/storage/$statestorage", ['Datastore.AllocateSpace']);
3251 }
3252
3253 my $realcmd = sub {
3254 my $upid = shift;
3255
3256 syslog('info', "suspend VM $vmid: $upid\n");
3257
3258 PVE::QemuServer::vm_suspend($vmid, $skiplock, $todisk, $statestorage);
3259
3260 return;
3261 };
3262
3263 my $taskname = $todisk ? 'qmsuspend' : 'qmpause';
3264 return $rpcenv->fork_worker($taskname, $vmid, $authuser, $realcmd);
3265 }});
3266
3267 __PACKAGE__->register_method({
3268 name => 'vm_resume',
3269 path => '{vmid}/status/resume',
3270 method => 'POST',
3271 protected => 1,
3272 proxyto => 'node',
3273 description => "Resume virtual machine.",
3274 permissions => {
3275 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
3276 },
3277 parameters => {
3278 additionalProperties => 0,
3279 properties => {
3280 node => get_standard_option('pve-node'),
3281 vmid => get_standard_option('pve-vmid',
3282 { completion => \&PVE::QemuServer::complete_vmid_running }),
3283 skiplock => get_standard_option('skiplock'),
3284 nocheck => { type => 'boolean', optional => 1 },
3285
3286 },
3287 },
3288 returns => {
3289 type => 'string',
3290 },
3291 code => sub {
3292 my ($param) = @_;
3293
3294 my $rpcenv = PVE::RPCEnvironment::get();
3295
3296 my $authuser = $rpcenv->get_user();
3297
3298 my $node = extract_param($param, 'node');
3299
3300 my $vmid = extract_param($param, 'vmid');
3301
3302 my $skiplock = extract_param($param, 'skiplock');
3303 raise_param_exc({ skiplock => "Only root may use this option." })
3304 if $skiplock && $authuser ne 'root@pam';
3305
3306 # nocheck is used as part of migration when config file might be still
3307 # be on source node
3308 my $nocheck = extract_param($param, 'nocheck');
3309 raise_param_exc({ nocheck => "Only root may use this option." })
3310 if $nocheck && $authuser ne 'root@pam';
3311
3312 my $to_disk_suspended;
3313 eval {
3314 PVE::QemuConfig->lock_config($vmid, sub {
3315 my $conf = PVE::QemuConfig->load_config($vmid);
3316 $to_disk_suspended = PVE::QemuConfig->has_lock($conf, 'suspended');
3317 });
3318 };
3319
3320 die "VM $vmid not running\n"
3321 if !$to_disk_suspended && !PVE::QemuServer::check_running($vmid, $nocheck);
3322
3323 my $realcmd = sub {
3324 my $upid = shift;
3325
3326 syslog('info', "resume VM $vmid: $upid\n");
3327
3328 if (!$to_disk_suspended) {
3329 PVE::QemuServer::vm_resume($vmid, $skiplock, $nocheck);
3330 } else {
3331 my $storecfg = PVE::Storage::config();
3332 PVE::QemuServer::vm_start($storecfg, $vmid, { skiplock => $skiplock });
3333 }
3334
3335 return;
3336 };
3337
3338 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
3339 }});
3340
3341 __PACKAGE__->register_method({
3342 name => 'vm_sendkey',
3343 path => '{vmid}/sendkey',
3344 method => 'PUT',
3345 protected => 1,
3346 proxyto => 'node',
3347 description => "Send key event to virtual machine.",
3348 permissions => {
3349 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
3350 },
3351 parameters => {
3352 additionalProperties => 0,
3353 properties => {
3354 node => get_standard_option('pve-node'),
3355 vmid => get_standard_option('pve-vmid',
3356 { completion => \&PVE::QemuServer::complete_vmid_running }),
3357 skiplock => get_standard_option('skiplock'),
3358 key => {
3359 description => "The key (qemu monitor encoding).",
3360 type => 'string'
3361 }
3362 },
3363 },
3364 returns => { type => 'null'},
3365 code => sub {
3366 my ($param) = @_;
3367
3368 my $rpcenv = PVE::RPCEnvironment::get();
3369
3370 my $authuser = $rpcenv->get_user();
3371
3372 my $node = extract_param($param, 'node');
3373
3374 my $vmid = extract_param($param, 'vmid');
3375
3376 my $skiplock = extract_param($param, 'skiplock');
3377 raise_param_exc({ skiplock => "Only root may use this option." })
3378 if $skiplock && $authuser ne 'root@pam';
3379
3380 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
3381
3382 return;
3383 }});
3384
3385 __PACKAGE__->register_method({
3386 name => 'vm_feature',
3387 path => '{vmid}/feature',
3388 method => 'GET',
3389 proxyto => 'node',
3390 protected => 1,
3391 description => "Check if feature for virtual machine is available.",
3392 permissions => {
3393 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
3394 },
3395 parameters => {
3396 additionalProperties => 0,
3397 properties => {
3398 node => get_standard_option('pve-node'),
3399 vmid => get_standard_option('pve-vmid'),
3400 feature => {
3401 description => "Feature to check.",
3402 type => 'string',
3403 enum => [ 'snapshot', 'clone', 'copy' ],
3404 },
3405 snapname => get_standard_option('pve-snapshot-name', {
3406 optional => 1,
3407 }),
3408 },
3409 },
3410 returns => {
3411 type => "object",
3412 properties => {
3413 hasFeature => { type => 'boolean' },
3414 nodes => {
3415 type => 'array',
3416 items => { type => 'string' },
3417 }
3418 },
3419 },
3420 code => sub {
3421 my ($param) = @_;
3422
3423 my $node = extract_param($param, 'node');
3424
3425 my $vmid = extract_param($param, 'vmid');
3426
3427 my $snapname = extract_param($param, 'snapname');
3428
3429 my $feature = extract_param($param, 'feature');
3430
3431 my $running = PVE::QemuServer::check_running($vmid);
3432
3433 my $conf = PVE::QemuConfig->load_config($vmid);
3434
3435 if($snapname){
3436 my $snap = $conf->{snapshots}->{$snapname};
3437 die "snapshot '$snapname' does not exist\n" if !defined($snap);
3438 $conf = $snap;
3439 }
3440 my $storecfg = PVE::Storage::config();
3441
3442 my $nodelist = PVE::QemuServer::shared_nodes($conf, $storecfg);
3443 my $hasFeature = PVE::QemuConfig->has_feature($feature, $conf, $storecfg, $snapname, $running);
3444
3445 return {
3446 hasFeature => $hasFeature,
3447 nodes => [ keys %$nodelist ],
3448 };
3449 }});
3450
3451 __PACKAGE__->register_method({
3452 name => 'clone_vm',
3453 path => '{vmid}/clone',
3454 method => 'POST',
3455 protected => 1,
3456 proxyto => 'node',
3457 description => "Create a copy of virtual machine/template.",
3458 permissions => {
3459 description => "You need 'VM.Clone' permissions on /vms/{vmid}, and 'VM.Allocate' permissions " .
3460 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
3461 "'Datastore.AllocateSpace' on any used storage and 'SDN.Use' on any used bridge/vnet",
3462 check =>
3463 [ 'and',
3464 ['perm', '/vms/{vmid}', [ 'VM.Clone' ]],
3465 [ 'or',
3466 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
3467 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
3468 ],
3469 ]
3470 },
3471 parameters => {
3472 additionalProperties => 0,
3473 properties => {
3474 node => get_standard_option('pve-node'),
3475 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
3476 newid => get_standard_option('pve-vmid', {
3477 completion => \&PVE::Cluster::complete_next_vmid,
3478 description => 'VMID for the clone.' }),
3479 name => {
3480 optional => 1,
3481 type => 'string', format => 'dns-name',
3482 description => "Set a name for the new VM.",
3483 },
3484 description => {
3485 optional => 1,
3486 type => 'string',
3487 description => "Description for the new VM.",
3488 },
3489 pool => {
3490 optional => 1,
3491 type => 'string', format => 'pve-poolid',
3492 description => "Add the new VM to the specified pool.",
3493 },
3494 snapname => get_standard_option('pve-snapshot-name', {
3495 optional => 1,
3496 }),
3497 storage => get_standard_option('pve-storage-id', {
3498 description => "Target storage for full clone.",
3499 optional => 1,
3500 }),
3501 'format' => {
3502 description => "Target format for file storage. Only valid for full clone.",
3503 type => 'string',
3504 optional => 1,
3505 enum => [ 'raw', 'qcow2', 'vmdk'],
3506 },
3507 full => {
3508 optional => 1,
3509 type => 'boolean',
3510 description => "Create a full copy of all disks. This is always done when " .
3511 "you clone a normal VM. For VM templates, we try to create a linked clone by default.",
3512 },
3513 target => get_standard_option('pve-node', {
3514 description => "Target node. Only allowed if the original VM is on shared storage.",
3515 optional => 1,
3516 }),
3517 bwlimit => {
3518 description => "Override I/O bandwidth limit (in KiB/s).",
3519 optional => 1,
3520 type => 'integer',
3521 minimum => '0',
3522 default => 'clone limit from datacenter or storage config',
3523 },
3524 },
3525 },
3526 returns => {
3527 type => 'string',
3528 },
3529 code => sub {
3530 my ($param) = @_;
3531
3532 my $rpcenv = PVE::RPCEnvironment::get();
3533 my $authuser = $rpcenv->get_user();
3534
3535 my $node = extract_param($param, 'node');
3536 my $vmid = extract_param($param, 'vmid');
3537 my $newid = extract_param($param, 'newid');
3538 my $pool = extract_param($param, 'pool');
3539
3540 my $snapname = extract_param($param, 'snapname');
3541 my $storage = extract_param($param, 'storage');
3542 my $format = extract_param($param, 'format');
3543 my $target = extract_param($param, 'target');
3544
3545 my $localnode = PVE::INotify::nodename();
3546
3547 if ($target && ($target eq $localnode || $target eq 'localhost')) {
3548 undef $target;
3549 }
3550
3551 my $running = PVE::QemuServer::check_running($vmid) || 0;
3552
3553 my $load_and_check = sub {
3554 $rpcenv->check_pool_exist($pool) if defined($pool);
3555 PVE::Cluster::check_node_exists($target) if $target;
3556
3557 my $storecfg = PVE::Storage::config();
3558
3559 if ($storage) {
3560 # check if storage is enabled on local node
3561 PVE::Storage::storage_check_enabled($storecfg, $storage);
3562 if ($target) {
3563 # check if storage is available on target node
3564 PVE::Storage::storage_check_enabled($storecfg, $storage, $target);
3565 # clone only works if target storage is shared
3566 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
3567 die "can't clone to non-shared storage '$storage'\n"
3568 if !$scfg->{shared};
3569 }
3570 }
3571
3572 PVE::Cluster::check_cfs_quorum();
3573
3574 my $conf = PVE::QemuConfig->load_config($vmid);
3575 PVE::QemuConfig->check_lock($conf);
3576
3577 my $verify_running = PVE::QemuServer::check_running($vmid) || 0;
3578 die "unexpected state change\n" if $verify_running != $running;
3579
3580 die "snapshot '$snapname' does not exist\n"
3581 if $snapname && !defined( $conf->{snapshots}->{$snapname});
3582
3583 my $full = $param->{full} // !PVE::QemuConfig->is_template($conf);
3584
3585 die "parameter 'storage' not allowed for linked clones\n"
3586 if defined($storage) && !$full;
3587
3588 die "parameter 'format' not allowed for linked clones\n"
3589 if defined($format) && !$full;
3590
3591 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
3592
3593 my $sharedvm = &$check_storage_access_clone($rpcenv, $authuser, $storecfg, $oldconf, $storage);
3594 PVE::QemuServer::check_mapping_access($rpcenv, $authuser, $oldconf);
3595
3596 PVE::QemuServer::check_bridge_access($rpcenv, $authuser, $oldconf);
3597
3598 die "can't clone VM to node '$target' (VM uses local storage)\n"
3599 if $target && !$sharedvm;
3600
3601 my $conffile = PVE::QemuConfig->config_file($newid);
3602 die "unable to create VM $newid: config file already exists\n"
3603 if -f $conffile;
3604
3605 my $newconf = { lock => 'clone' };
3606 my $drives = {};
3607 my $fullclone = {};
3608 my $vollist = [];
3609
3610 foreach my $opt (keys %$oldconf) {
3611 my $value = $oldconf->{$opt};
3612
3613 # do not copy snapshot related info
3614 next if $opt eq 'snapshots' || $opt eq 'parent' || $opt eq 'snaptime' ||
3615 $opt eq 'vmstate' || $opt eq 'snapstate';
3616
3617 # no need to copy unused images, because VMID(owner) changes anyways
3618 next if $opt =~ m/^unused\d+$/;
3619
3620 die "cannot clone TPM state while VM is running\n"
3621 if $full && $running && !$snapname && $opt eq 'tpmstate0';
3622
3623 # always change MAC! address
3624 if ($opt =~ m/^net(\d+)$/) {
3625 my $net = PVE::QemuServer::parse_net($value);
3626 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
3627 $net->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
3628 $newconf->{$opt} = PVE::QemuServer::print_net($net);
3629 } elsif (PVE::QemuServer::is_valid_drivename($opt)) {
3630 my $drive = PVE::QemuServer::parse_drive($opt, $value);
3631 die "unable to parse drive options for '$opt'\n" if !$drive;
3632 if (PVE::QemuServer::drive_is_cdrom($drive, 1)) {
3633 $newconf->{$opt} = $value; # simply copy configuration
3634 } else {
3635 if ($full || PVE::QemuServer::drive_is_cloudinit($drive)) {
3636 die "Full clone feature is not supported for drive '$opt'\n"
3637 if !PVE::Storage::volume_has_feature($storecfg, 'copy', $drive->{file}, $snapname, $running);
3638 $fullclone->{$opt} = 1;
3639 } else {
3640 # not full means clone instead of copy
3641 die "Linked clone feature is not supported for drive '$opt'\n"
3642 if !PVE::Storage::volume_has_feature($storecfg, 'clone', $drive->{file}, $snapname, $running);
3643 }
3644 $drives->{$opt} = $drive;
3645 next if PVE::QemuServer::drive_is_cloudinit($drive);
3646 push @$vollist, $drive->{file};
3647 }
3648 } else {
3649 # copy everything else
3650 $newconf->{$opt} = $value;
3651 }
3652 }
3653
3654 return ($conffile, $newconf, $oldconf, $vollist, $drives, $fullclone);
3655 };
3656
3657 my $clonefn = sub {
3658 my ($conffile, $newconf, $oldconf, $vollist, $drives, $fullclone) = $load_and_check->();
3659 my $storecfg = PVE::Storage::config();
3660
3661 # auto generate a new uuid
3662 my $smbios1 = PVE::QemuServer::parse_smbios1($newconf->{smbios1} || '');
3663 $smbios1->{uuid} = PVE::QemuServer::generate_uuid();
3664 $newconf->{smbios1} = PVE::QemuServer::print_smbios1($smbios1);
3665 # auto generate a new vmgenid only if the option was set for template
3666 if ($newconf->{vmgenid}) {
3667 $newconf->{vmgenid} = PVE::QemuServer::generate_uuid();
3668 }
3669
3670 delete $newconf->{template};
3671
3672 if ($param->{name}) {
3673 $newconf->{name} = $param->{name};
3674 } else {
3675 $newconf->{name} = "Copy-of-VM-" . ($oldconf->{name} // $vmid);
3676 }
3677
3678 if ($param->{description}) {
3679 $newconf->{description} = $param->{description};
3680 }
3681
3682 # create empty/temp config - this fails if VM already exists on other node
3683 # FIXME use PVE::QemuConfig->create_and_lock_config and adapt code
3684 PVE::Tools::file_set_contents($conffile, "# qmclone temporary file\nlock: clone\n");
3685
3686 PVE::Firewall::clone_vmfw_conf($vmid, $newid);
3687
3688 my $newvollist = [];
3689 my $jobs = {};
3690
3691 eval {
3692 local $SIG{INT} =
3693 local $SIG{TERM} =
3694 local $SIG{QUIT} =
3695 local $SIG{HUP} = sub { die "interrupted by signal\n"; };
3696
3697 PVE::Storage::activate_volumes($storecfg, $vollist, $snapname);
3698
3699 my $bwlimit = extract_param($param, 'bwlimit');
3700
3701 my $total_jobs = scalar(keys %{$drives});
3702 my $i = 1;
3703
3704 foreach my $opt (sort keys %$drives) {
3705 my $drive = $drives->{$opt};
3706 my $skipcomplete = ($total_jobs != $i); # finish after last drive
3707 my $completion = $skipcomplete ? 'skip' : 'complete';
3708
3709 my $src_sid = PVE::Storage::parse_volume_id($drive->{file});
3710 my $storage_list = [ $src_sid ];
3711 push @$storage_list, $storage if defined($storage);
3712 my $clonelimit = PVE::Storage::get_bandwidth_limit('clone', $storage_list, $bwlimit);
3713
3714 my $source_info = {
3715 vmid => $vmid,
3716 running => $running,
3717 drivename => $opt,
3718 drive => $drive,
3719 snapname => $snapname,
3720 };
3721
3722 my $dest_info = {
3723 vmid => $newid,
3724 drivename => $opt,
3725 storage => $storage,
3726 format => $format,
3727 };
3728
3729 $dest_info->{efisize} = PVE::QemuServer::get_efivars_size($oldconf)
3730 if $opt eq 'efidisk0';
3731
3732 my $newdrive = PVE::QemuServer::clone_disk(
3733 $storecfg,
3734 $source_info,
3735 $dest_info,
3736 $fullclone->{$opt},
3737 $newvollist,
3738 $jobs,
3739 $completion,
3740 $oldconf->{agent},
3741 $clonelimit,
3742 );
3743
3744 $newconf->{$opt} = PVE::QemuServer::print_drive($newdrive);
3745
3746 PVE::QemuConfig->write_config($newid, $newconf);
3747 $i++;
3748 }
3749
3750 delete $newconf->{lock};
3751
3752 # do not write pending changes
3753 if (my @changes = keys %{$newconf->{pending}}) {
3754 my $pending = join(',', @changes);
3755 warn "found pending changes for '$pending', discarding for clone\n";
3756 delete $newconf->{pending};
3757 }
3758
3759 PVE::QemuConfig->write_config($newid, $newconf);
3760
3761 if ($target) {
3762 # always deactivate volumes - avoid lvm LVs to be active on several nodes
3763 PVE::Storage::deactivate_volumes($storecfg, $vollist, $snapname) if !$running;
3764 PVE::Storage::deactivate_volumes($storecfg, $newvollist);
3765
3766 my $newconffile = PVE::QemuConfig->config_file($newid, $target);
3767 die "Failed to move config to node '$target' - rename failed: $!\n"
3768 if !rename($conffile, $newconffile);
3769 }
3770
3771 PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
3772 };
3773 if (my $err = $@) {
3774 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs) };
3775 sleep 1; # some storage like rbd need to wait before release volume - really?
3776
3777 foreach my $volid (@$newvollist) {
3778 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
3779 warn $@ if $@;
3780 }
3781
3782 PVE::Firewall::remove_vmfw_conf($newid);
3783
3784 unlink $conffile; # avoid races -> last thing before die
3785
3786 die "clone failed: $err";
3787 }
3788
3789 return;
3790 };
3791
3792 # Aquire exclusive lock lock for $newid
3793 my $lock_target_vm = sub {
3794 return PVE::QemuConfig->lock_config_full($newid, 1, $clonefn);
3795 };
3796
3797 my $lock_source_vm = sub {
3798 # exclusive lock if VM is running - else shared lock is enough;
3799 if ($running) {
3800 return PVE::QemuConfig->lock_config_full($vmid, 1, $lock_target_vm);
3801 } else {
3802 return PVE::QemuConfig->lock_config_shared($vmid, 1, $lock_target_vm);
3803 }
3804 };
3805
3806 $load_and_check->(); # early checks before forking/locking
3807
3808 return $rpcenv->fork_worker('qmclone', $vmid, $authuser, $lock_source_vm);
3809 }});
3810
3811 __PACKAGE__->register_method({
3812 name => 'move_vm_disk',
3813 path => '{vmid}/move_disk',
3814 method => 'POST',
3815 protected => 1,
3816 proxyto => 'node',
3817 description => "Move volume to different storage or to a different VM.",
3818 permissions => {
3819 description => "You need 'VM.Config.Disk' permissions on /vms/{vmid}, " .
3820 "and 'Datastore.AllocateSpace' permissions on the storage. To move ".
3821 "a disk to another VM, you need the permissions on the target VM as well.",
3822 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
3823 },
3824 parameters => {
3825 additionalProperties => 0,
3826 properties => {
3827 node => get_standard_option('pve-node'),
3828 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
3829 'target-vmid' => get_standard_option('pve-vmid', {
3830 completion => \&PVE::QemuServer::complete_vmid,
3831 optional => 1,
3832 }),
3833 disk => {
3834 type => 'string',
3835 description => "The disk you want to move.",
3836 enum => [PVE::QemuServer::Drive::valid_drive_names_with_unused()],
3837 },
3838 storage => get_standard_option('pve-storage-id', {
3839 description => "Target storage.",
3840 completion => \&PVE::QemuServer::complete_storage,
3841 optional => 1,
3842 }),
3843 'format' => {
3844 type => 'string',
3845 description => "Target Format.",
3846 enum => [ 'raw', 'qcow2', 'vmdk' ],
3847 optional => 1,
3848 },
3849 delete => {
3850 type => 'boolean',
3851 description => "Delete the original disk after successful copy. By default the"
3852 ." original disk is kept as unused disk.",
3853 optional => 1,
3854 default => 0,
3855 },
3856 digest => {
3857 type => 'string',
3858 description => 'Prevent changes if current configuration file has different SHA1"
3859 ." digest. This can be used to prevent concurrent modifications.',
3860 maxLength => 40,
3861 optional => 1,
3862 },
3863 bwlimit => {
3864 description => "Override I/O bandwidth limit (in KiB/s).",
3865 optional => 1,
3866 type => 'integer',
3867 minimum => '0',
3868 default => 'move limit from datacenter or storage config',
3869 },
3870 'target-disk' => {
3871 type => 'string',
3872 description => "The config key the disk will be moved to on the target VM"
3873 ." (for example, ide0 or scsi1). Default is the source disk key.",
3874 enum => [PVE::QemuServer::Drive::valid_drive_names_with_unused()],
3875 optional => 1,
3876 },
3877 'target-digest' => {
3878 type => 'string',
3879 description => 'Prevent changes if the current config file of the target VM has a"
3880 ." different SHA1 digest. This can be used to detect concurrent modifications.',
3881 maxLength => 40,
3882 optional => 1,
3883 },
3884 },
3885 },
3886 returns => {
3887 type => 'string',
3888 description => "the task ID.",
3889 },
3890 code => sub {
3891 my ($param) = @_;
3892
3893 my $rpcenv = PVE::RPCEnvironment::get();
3894 my $authuser = $rpcenv->get_user();
3895
3896 my $node = extract_param($param, 'node');
3897 my $vmid = extract_param($param, 'vmid');
3898 my $target_vmid = extract_param($param, 'target-vmid');
3899 my $digest = extract_param($param, 'digest');
3900 my $target_digest = extract_param($param, 'target-digest');
3901 my $disk = extract_param($param, 'disk');
3902 my $target_disk = extract_param($param, 'target-disk') // $disk;
3903 my $storeid = extract_param($param, 'storage');
3904 my $format = extract_param($param, 'format');
3905
3906 my $storecfg = PVE::Storage::config();
3907
3908 my $load_and_check_move = sub {
3909 my $conf = PVE::QemuConfig->load_config($vmid);
3910 PVE::QemuConfig->check_lock($conf);
3911
3912 PVE::Tools::assert_if_modified($digest, $conf->{digest});
3913
3914 die "disk '$disk' does not exist\n" if !$conf->{$disk};
3915
3916 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
3917
3918 die "disk '$disk' has no associated volume\n" if !$drive->{file};
3919 die "you can't move a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive, 1);
3920
3921 my $old_volid = $drive->{file};
3922 my $oldfmt;
3923 my ($oldstoreid, $oldvolname) = PVE::Storage::parse_volume_id($old_volid);
3924 if ($oldvolname =~ m/\.(raw|qcow2|vmdk)$/){
3925 $oldfmt = $1;
3926 }
3927
3928 die "you can't move to the same storage with same format\n"
3929 if $oldstoreid eq $storeid && (!$format || !$oldfmt || $oldfmt eq $format);
3930
3931 # this only checks snapshots because $disk is passed!
3932 my $snapshotted = PVE::QemuServer::Drive::is_volume_in_use(
3933 $storecfg,
3934 $conf,
3935 $disk,
3936 $old_volid
3937 );
3938 die "you can't move a disk with snapshots and delete the source\n"
3939 if $snapshotted && $param->{delete};
3940
3941 return ($conf, $drive, $oldstoreid, $snapshotted);
3942 };
3943
3944 my $move_updatefn = sub {
3945 my ($conf, $drive, $oldstoreid, $snapshotted) = $load_and_check_move->();
3946 my $old_volid = $drive->{file};
3947
3948 PVE::Cluster::log_msg(
3949 'info',
3950 $authuser,
3951 "move disk VM $vmid: move --disk $disk --storage $storeid"
3952 );
3953
3954 my $running = PVE::QemuServer::check_running($vmid);
3955
3956 PVE::Storage::activate_volumes($storecfg, [ $drive->{file} ]);
3957
3958 my $newvollist = [];
3959
3960 eval {
3961 local $SIG{INT} =
3962 local $SIG{TERM} =
3963 local $SIG{QUIT} =
3964 local $SIG{HUP} = sub { die "interrupted by signal\n"; };
3965
3966 warn "moving disk with snapshots, snapshots will not be moved!\n"
3967 if $snapshotted;
3968
3969 my $bwlimit = extract_param($param, 'bwlimit');
3970 my $movelimit = PVE::Storage::get_bandwidth_limit(
3971 'move',
3972 [$oldstoreid, $storeid],
3973 $bwlimit
3974 );
3975
3976 my $source_info = {
3977 vmid => $vmid,
3978 running => $running,
3979 drivename => $disk,
3980 drive => $drive,
3981 snapname => undef,
3982 };
3983
3984 my $dest_info = {
3985 vmid => $vmid,
3986 drivename => $disk,
3987 storage => $storeid,
3988 format => $format,
3989 };
3990
3991 $dest_info->{efisize} = PVE::QemuServer::get_efivars_size($conf)
3992 if $disk eq 'efidisk0';
3993
3994 my $newdrive = PVE::QemuServer::clone_disk(
3995 $storecfg,
3996 $source_info,
3997 $dest_info,
3998 1,
3999 $newvollist,
4000 undef,
4001 undef,
4002 undef,
4003 $movelimit,
4004 );
4005 $conf->{$disk} = PVE::QemuServer::print_drive($newdrive);
4006
4007 PVE::QemuConfig->add_unused_volume($conf, $old_volid) if !$param->{delete};
4008
4009 # convert moved disk to base if part of template
4010 PVE::QemuServer::template_create($vmid, $conf, $disk)
4011 if PVE::QemuConfig->is_template($conf);
4012
4013 PVE::QemuConfig->write_config($vmid, $conf);
4014
4015 my $do_trim = PVE::QemuServer::get_qga_key($conf, 'fstrim_cloned_disks');
4016 if ($running && $do_trim && PVE::QemuServer::qga_check_running($vmid)) {
4017 eval { mon_cmd($vmid, "guest-fstrim") };
4018 }
4019
4020 eval {
4021 # try to deactivate volumes - avoid lvm LVs to be active on several nodes
4022 PVE::Storage::deactivate_volumes($storecfg, [ $newdrive->{file} ])
4023 if !$running;
4024 };
4025 warn $@ if $@;
4026 };
4027 if (my $err = $@) {
4028 foreach my $volid (@$newvollist) {
4029 eval { PVE::Storage::vdisk_free($storecfg, $volid) };
4030 warn $@ if $@;
4031 }
4032 die "storage migration failed: $err";
4033 }
4034
4035 if ($param->{delete}) {
4036 eval {
4037 PVE::Storage::deactivate_volumes($storecfg, [$old_volid]);
4038 PVE::Storage::vdisk_free($storecfg, $old_volid);
4039 };
4040 warn $@ if $@;
4041 }
4042 };
4043
4044 my $load_and_check_reassign_configs = sub {
4045 my $vmlist = PVE::Cluster::get_vmlist()->{ids};
4046
4047 die "could not find VM ${vmid}\n" if !exists($vmlist->{$vmid});
4048 die "could not find target VM ${target_vmid}\n" if !exists($vmlist->{$target_vmid});
4049
4050 my $source_node = $vmlist->{$vmid}->{node};
4051 my $target_node = $vmlist->{$target_vmid}->{node};
4052
4053 die "Both VMs need to be on the same node ($source_node != $target_node)\n"
4054 if $source_node ne $target_node;
4055
4056 my $source_conf = PVE::QemuConfig->load_config($vmid);
4057 PVE::QemuConfig->check_lock($source_conf);
4058 my $target_conf = PVE::QemuConfig->load_config($target_vmid);
4059 PVE::QemuConfig->check_lock($target_conf);
4060
4061 die "Can't move disks from or to template VMs\n"
4062 if ($source_conf->{template} || $target_conf->{template});
4063
4064 if ($digest) {
4065 eval { PVE::Tools::assert_if_modified($digest, $source_conf->{digest}) };
4066 die "VM ${vmid}: $@" if $@;
4067 }
4068
4069 if ($target_digest) {
4070 eval { PVE::Tools::assert_if_modified($target_digest, $target_conf->{digest}) };
4071 die "VM ${target_vmid}: $@" if $@;
4072 }
4073
4074 die "Disk '${disk}' for VM '$vmid' does not exist\n" if !defined($source_conf->{$disk});
4075
4076 die "Target disk key '${target_disk}' is already in use for VM '$target_vmid'\n"
4077 if $target_conf->{$target_disk};
4078
4079 my $drive = PVE::QemuServer::parse_drive(
4080 $disk,
4081 $source_conf->{$disk},
4082 );
4083 die "failed to parse source disk - $@\n" if !$drive;
4084
4085 my $source_volid = $drive->{file};
4086
4087 die "disk '${disk}' has no associated volume\n" if !$source_volid;
4088 die "CD drive contents can't be moved to another VM\n"
4089 if PVE::QemuServer::drive_is_cdrom($drive, 1);
4090
4091 my $storeid = PVE::Storage::parse_volume_id($source_volid, 1);
4092 die "Volume '$source_volid' not managed by PVE\n" if !defined($storeid);
4093
4094 die "Can't move disk used by a snapshot to another VM\n"
4095 if PVE::QemuServer::Drive::is_volume_in_use($storecfg, $source_conf, $disk, $source_volid);
4096 die "Storage does not support moving of this disk to another VM\n"
4097 if (!PVE::Storage::volume_has_feature($storecfg, 'rename', $source_volid));
4098 die "Cannot move disk to another VM while the source VM is running - detach first\n"
4099 if PVE::QemuServer::check_running($vmid) && $disk !~ m/^unused\d+$/;
4100
4101 # now re-parse using target disk slot format
4102 if ($target_disk =~ /^unused\d+$/) {
4103 $drive = PVE::QemuServer::parse_drive(
4104 $target_disk,
4105 $source_volid,
4106 );
4107 } else {
4108 $drive = PVE::QemuServer::parse_drive(
4109 $target_disk,
4110 $source_conf->{$disk},
4111 );
4112 }
4113 die "failed to parse source disk for target disk format - $@\n" if !$drive;
4114
4115 my $repl_conf = PVE::ReplicationConfig->new();
4116 if ($repl_conf->check_for_existing_jobs($target_vmid, 1)) {
4117 my $format = (PVE::Storage::parse_volname($storecfg, $source_volid))[6];
4118 die "Cannot move disk to a replicated VM. Storage does not support replication!\n"
4119 if !PVE::Storage::storage_can_replicate($storecfg, $storeid, $format);
4120 }
4121
4122 return ($source_conf, $target_conf, $drive);
4123 };
4124
4125 my $logfunc = sub {
4126 my ($msg) = @_;
4127 print STDERR "$msg\n";
4128 };
4129
4130 my $disk_reassignfn = sub {
4131 return PVE::QemuConfig->lock_config($vmid, sub {
4132 return PVE::QemuConfig->lock_config($target_vmid, sub {
4133 my ($source_conf, $target_conf, $drive) = &$load_and_check_reassign_configs();
4134
4135 my $source_volid = $drive->{file};
4136
4137 print "moving disk '$disk' from VM '$vmid' to '$target_vmid'\n";
4138 my ($storeid, $source_volname) = PVE::Storage::parse_volume_id($source_volid);
4139
4140 my $fmt = (PVE::Storage::parse_volname($storecfg, $source_volid))[6];
4141
4142 my $new_volid = PVE::Storage::rename_volume(
4143 $storecfg,
4144 $source_volid,
4145 $target_vmid,
4146 );
4147
4148 $drive->{file} = $new_volid;
4149
4150 my $boot_order = PVE::QemuServer::device_bootorder($source_conf);
4151 if (defined(delete $boot_order->{$disk})) {
4152 print "removing disk '$disk' from boot order config\n";
4153 my $boot_devs = [ sort { $boot_order->{$a} <=> $boot_order->{$b} } keys %$boot_order ];
4154 $source_conf->{boot} = PVE::QemuServer::print_bootorder($boot_devs);
4155 }
4156
4157 delete $source_conf->{$disk};
4158 print "removing disk '${disk}' from VM '${vmid}' config\n";
4159 PVE::QemuConfig->write_config($vmid, $source_conf);
4160
4161 my $drive_string = PVE::QemuServer::print_drive($drive);
4162
4163 if ($target_disk =~ /^unused\d+$/) {
4164 $target_conf->{$target_disk} = $drive_string;
4165 PVE::QemuConfig->write_config($target_vmid, $target_conf);
4166 } else {
4167 &$update_vm_api(
4168 {
4169 node => $node,
4170 vmid => $target_vmid,
4171 digest => $target_digest,
4172 $target_disk => $drive_string,
4173 },
4174 1,
4175 );
4176 }
4177
4178 # remove possible replication snapshots
4179 if (PVE::Storage::volume_has_feature(
4180 $storecfg,
4181 'replicate',
4182 $source_volid),
4183 ) {
4184 eval {
4185 PVE::Replication::prepare(
4186 $storecfg,
4187 [$new_volid],
4188 undef,
4189 1,
4190 undef,
4191 $logfunc,
4192 )
4193 };
4194 if (my $err = $@) {
4195 print "Failed to remove replication snapshots on moved disk " .
4196 "'$target_disk'. Manual cleanup could be necessary.\n";
4197 }
4198 }
4199 });
4200 });
4201 };
4202
4203 if ($target_vmid && $storeid) {
4204 my $msg = "either set 'storage' or 'target-vmid', but not both";
4205 raise_param_exc({ 'target-vmid' => $msg, 'storage' => $msg });
4206 } elsif ($target_vmid) {
4207 $rpcenv->check_vm_perm($authuser, $target_vmid, undef, ['VM.Config.Disk'])
4208 if $authuser ne 'root@pam';
4209
4210 raise_param_exc({ 'target-vmid' => "must be different than source VMID to reassign disk" })
4211 if $vmid eq $target_vmid;
4212
4213 my (undef, undef, $drive) = &$load_and_check_reassign_configs();
4214 my $storage = PVE::Storage::parse_volume_id($drive->{file});
4215 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace']);
4216
4217 return $rpcenv->fork_worker(
4218 'qmmove',
4219 "${vmid}-${disk}>${target_vmid}-${target_disk}",
4220 $authuser,
4221 $disk_reassignfn
4222 );
4223 } elsif ($storeid) {
4224 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
4225
4226 die "cannot move disk '$disk', only configured disks can be moved to another storage\n"
4227 if $disk =~ m/^unused\d+$/;
4228
4229 $load_and_check_move->(); # early checks before forking/locking
4230
4231 my $realcmd = sub {
4232 PVE::QemuConfig->lock_config($vmid, $move_updatefn);
4233 };
4234
4235 return $rpcenv->fork_worker('qmmove', $vmid, $authuser, $realcmd);
4236 } else {
4237 my $msg = "both 'storage' and 'target-vmid' missing, either needs to be set";
4238 raise_param_exc({ 'target-vmid' => $msg, 'storage' => $msg });
4239 }
4240 }});
4241
4242 my $check_vm_disks_local = sub {
4243 my ($storecfg, $vmconf, $vmid) = @_;
4244
4245 my $local_disks = {};
4246
4247 # add some more information to the disks e.g. cdrom
4248 PVE::QemuServer::foreach_volid($vmconf, sub {
4249 my ($volid, $attr) = @_;
4250
4251 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
4252 if ($storeid) {
4253 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
4254 return if $scfg->{shared};
4255 }
4256 # The shared attr here is just a special case where the vdisk
4257 # is marked as shared manually
4258 return if $attr->{shared};
4259 return if $attr->{cdrom} and $volid eq "none";
4260
4261 if (exists $local_disks->{$volid}) {
4262 @{$local_disks->{$volid}}{keys %$attr} = values %$attr
4263 } else {
4264 $local_disks->{$volid} = $attr;
4265 # ensure volid is present in case it's needed
4266 $local_disks->{$volid}->{volid} = $volid;
4267 }
4268 });
4269
4270 return $local_disks;
4271 };
4272
4273 __PACKAGE__->register_method({
4274 name => 'migrate_vm_precondition',
4275 path => '{vmid}/migrate',
4276 method => 'GET',
4277 protected => 1,
4278 proxyto => 'node',
4279 description => "Get preconditions for migration.",
4280 permissions => {
4281 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
4282 },
4283 parameters => {
4284 additionalProperties => 0,
4285 properties => {
4286 node => get_standard_option('pve-node'),
4287 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
4288 target => get_standard_option('pve-node', {
4289 description => "Target node.",
4290 completion => \&PVE::Cluster::complete_migration_target,
4291 optional => 1,
4292 }),
4293 },
4294 },
4295 returns => {
4296 type => "object",
4297 properties => {
4298 running => { type => 'boolean' },
4299 allowed_nodes => {
4300 type => 'array',
4301 optional => 1,
4302 description => "List nodes allowed for offline migration, only passed if VM is offline"
4303 },
4304 not_allowed_nodes => {
4305 type => 'object',
4306 optional => 1,
4307 description => "List not allowed nodes with additional informations, only passed if VM is offline"
4308 },
4309 local_disks => {
4310 type => 'array',
4311 description => "List local disks including CD-Rom, unsused and not referenced disks"
4312 },
4313 local_resources => {
4314 type => 'array',
4315 description => "List local resources e.g. pci, usb"
4316 },
4317 'mapped-resources' => {
4318 type => 'array',
4319 description => "List of mapped resources e.g. pci, usb"
4320 },
4321 },
4322 },
4323 code => sub {
4324 my ($param) = @_;
4325
4326 my $rpcenv = PVE::RPCEnvironment::get();
4327
4328 my $authuser = $rpcenv->get_user();
4329
4330 PVE::Cluster::check_cfs_quorum();
4331
4332 my $res = {};
4333
4334 my $vmid = extract_param($param, 'vmid');
4335 my $target = extract_param($param, 'target');
4336 my $localnode = PVE::INotify::nodename();
4337
4338
4339 # test if VM exists
4340 my $vmconf = PVE::QemuConfig->load_config($vmid);
4341 my $storecfg = PVE::Storage::config();
4342
4343
4344 # try to detect errors early
4345 PVE::QemuConfig->check_lock($vmconf);
4346
4347 $res->{running} = PVE::QemuServer::check_running($vmid) ? 1:0;
4348
4349 my ($local_resources, $mapped_resources, $missing_mappings_by_node) =
4350 PVE::QemuServer::check_local_resources($vmconf, 1);
4351 delete $missing_mappings_by_node->{$localnode};
4352
4353 # if vm is not running, return target nodes where local storage/mapped devices are available
4354 # for offline migration
4355 if (!$res->{running}) {
4356 $res->{allowed_nodes} = [];
4357 my $checked_nodes = PVE::QemuServer::check_local_storage_availability($vmconf, $storecfg);
4358 delete $checked_nodes->{$localnode};
4359
4360 foreach my $node (keys %$checked_nodes) {
4361 my $missing_mappings = $missing_mappings_by_node->{$node};
4362 if (scalar($missing_mappings->@*)) {
4363 $checked_nodes->{$node}->{'unavailable-resources'} = $missing_mappings;
4364 next;
4365 }
4366
4367 if (!defined($checked_nodes->{$node}->{unavailable_storages})) {
4368 push @{$res->{allowed_nodes}}, $node;
4369 }
4370
4371 }
4372 $res->{not_allowed_nodes} = $checked_nodes;
4373 }
4374
4375 my $local_disks = &$check_vm_disks_local($storecfg, $vmconf, $vmid);
4376 $res->{local_disks} = [ values %$local_disks ];;
4377
4378 $res->{local_resources} = $local_resources;
4379 $res->{'mapped-resources'} = $mapped_resources;
4380
4381 return $res;
4382
4383
4384 }});
4385
4386 __PACKAGE__->register_method({
4387 name => 'migrate_vm',
4388 path => '{vmid}/migrate',
4389 method => 'POST',
4390 protected => 1,
4391 proxyto => 'node',
4392 description => "Migrate virtual machine. Creates a new migration task.",
4393 permissions => {
4394 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
4395 },
4396 parameters => {
4397 additionalProperties => 0,
4398 properties => {
4399 node => get_standard_option('pve-node'),
4400 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
4401 target => get_standard_option('pve-node', {
4402 description => "Target node.",
4403 completion => \&PVE::Cluster::complete_migration_target,
4404 }),
4405 online => {
4406 type => 'boolean',
4407 description => "Use online/live migration if VM is running. Ignored if VM is stopped.",
4408 optional => 1,
4409 },
4410 force => {
4411 type => 'boolean',
4412 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
4413 optional => 1,
4414 },
4415 migration_type => {
4416 type => 'string',
4417 enum => ['secure', 'insecure'],
4418 description => "Migration traffic is encrypted using an SSH tunnel by default. On secure, completely private networks this can be disabled to increase performance.",
4419 optional => 1,
4420 },
4421 migration_network => {
4422 type => 'string', format => 'CIDR',
4423 description => "CIDR of the (sub) network that is used for migration.",
4424 optional => 1,
4425 },
4426 "with-local-disks" => {
4427 type => 'boolean',
4428 description => "Enable live storage migration for local disk",
4429 optional => 1,
4430 },
4431 targetstorage => get_standard_option('pve-targetstorage', {
4432 completion => \&PVE::QemuServer::complete_migration_storage,
4433 }),
4434 bwlimit => {
4435 description => "Override I/O bandwidth limit (in KiB/s).",
4436 optional => 1,
4437 type => 'integer',
4438 minimum => '0',
4439 default => 'migrate limit from datacenter or storage config',
4440 },
4441 },
4442 },
4443 returns => {
4444 type => 'string',
4445 description => "the task ID.",
4446 },
4447 code => sub {
4448 my ($param) = @_;
4449
4450 my $rpcenv = PVE::RPCEnvironment::get();
4451 my $authuser = $rpcenv->get_user();
4452
4453 my $target = extract_param($param, 'target');
4454
4455 my $localnode = PVE::INotify::nodename();
4456 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
4457
4458 PVE::Cluster::check_cfs_quorum();
4459
4460 PVE::Cluster::check_node_exists($target);
4461
4462 my $targetip = PVE::Cluster::remote_node_ip($target);
4463
4464 my $vmid = extract_param($param, 'vmid');
4465
4466 raise_param_exc({ force => "Only root may use this option." })
4467 if $param->{force} && $authuser ne 'root@pam';
4468
4469 raise_param_exc({ migration_type => "Only root may use this option." })
4470 if $param->{migration_type} && $authuser ne 'root@pam';
4471
4472 # allow root only until better network permissions are available
4473 raise_param_exc({ migration_network => "Only root may use this option." })
4474 if $param->{migration_network} && $authuser ne 'root@pam';
4475
4476 # test if VM exists
4477 my $conf = PVE::QemuConfig->load_config($vmid);
4478
4479 # try to detect errors early
4480
4481 PVE::QemuConfig->check_lock($conf);
4482
4483 if (PVE::QemuServer::check_running($vmid)) {
4484 die "can't migrate running VM without --online\n" if !$param->{online};
4485
4486 my $repl_conf = PVE::ReplicationConfig->new();
4487 my $is_replicated = $repl_conf->check_for_existing_jobs($vmid, 1);
4488 my $is_replicated_to_target = defined($repl_conf->find_local_replication_job($vmid, $target));
4489 if (!$param->{force} && $is_replicated && !$is_replicated_to_target) {
4490 die "Cannot live-migrate replicated VM to node '$target' - not a replication " .
4491 "target. Use 'force' to override.\n";
4492 }
4493 } else {
4494 warn "VM isn't running. Doing offline migration instead.\n" if $param->{online};
4495 $param->{online} = 0;
4496 }
4497
4498 my $storecfg = PVE::Storage::config();
4499 if (my $targetstorage = $param->{targetstorage}) {
4500 my $storagemap = eval { PVE::JSONSchema::parse_idmap($targetstorage, 'pve-storage-id') };
4501 raise_param_exc({ targetstorage => "failed to parse storage map: $@" })
4502 if $@;
4503
4504 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk'])
4505 if !defined($storagemap->{identity});
4506
4507 foreach my $target_sid (values %{$storagemap->{entries}}) {
4508 $check_storage_access_migrate->($rpcenv, $authuser, $storecfg, $target_sid, $target);
4509 }
4510
4511 $check_storage_access_migrate->($rpcenv, $authuser, $storecfg, $storagemap->{default}, $target)
4512 if $storagemap->{default};
4513
4514 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target)
4515 if $storagemap->{identity};
4516
4517 $param->{storagemap} = $storagemap;
4518 } else {
4519 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
4520 }
4521
4522 if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
4523
4524 my $hacmd = sub {
4525 my $upid = shift;
4526
4527 print "Requesting HA migration for VM $vmid to node $target\n";
4528
4529 my $cmd = ['ha-manager', 'migrate', "vm:$vmid", $target];
4530 PVE::Tools::run_command($cmd);
4531 return;
4532 };
4533
4534 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
4535
4536 } else {
4537
4538 my $realcmd = sub {
4539 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
4540 };
4541
4542 my $worker = sub {
4543 return PVE::GuestHelpers::guest_migration_lock($vmid, 10, $realcmd);
4544 };
4545
4546 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $worker);
4547 }
4548
4549 }});
4550
4551 __PACKAGE__->register_method({
4552 name => 'remote_migrate_vm',
4553 path => '{vmid}/remote_migrate',
4554 method => 'POST',
4555 protected => 1,
4556 proxyto => 'node',
4557 description => "Migrate virtual machine to a remote cluster. Creates a new migration task. EXPERIMENTAL feature!",
4558 permissions => {
4559 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
4560 },
4561 parameters => {
4562 additionalProperties => 0,
4563 properties => {
4564 node => get_standard_option('pve-node'),
4565 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
4566 'target-vmid' => get_standard_option('pve-vmid', { optional => 1 }),
4567 'target-endpoint' => get_standard_option('proxmox-remote', {
4568 description => "Remote target endpoint",
4569 }),
4570 online => {
4571 type => 'boolean',
4572 description => "Use online/live migration if VM is running. Ignored if VM is stopped.",
4573 optional => 1,
4574 },
4575 delete => {
4576 type => 'boolean',
4577 description => "Delete the original VM and related data after successful migration. By default the original VM is kept on the source cluster in a stopped state.",
4578 optional => 1,
4579 default => 0,
4580 },
4581 'target-storage' => get_standard_option('pve-targetstorage', {
4582 completion => \&PVE::QemuServer::complete_migration_storage,
4583 optional => 0,
4584 }),
4585 'target-bridge' => {
4586 type => 'string',
4587 description => "Mapping from source to target bridges. Providing only a single bridge ID maps all source bridges to that bridge. Providing the special value '1' will map each source bridge to itself.",
4588 format => 'bridge-pair-list',
4589 },
4590 bwlimit => {
4591 description => "Override I/O bandwidth limit (in KiB/s).",
4592 optional => 1,
4593 type => 'integer',
4594 minimum => '0',
4595 default => 'migrate limit from datacenter or storage config',
4596 },
4597 },
4598 },
4599 returns => {
4600 type => 'string',
4601 description => "the task ID.",
4602 },
4603 code => sub {
4604 my ($param) = @_;
4605
4606 my $rpcenv = PVE::RPCEnvironment::get();
4607 my $authuser = $rpcenv->get_user();
4608
4609 my $source_vmid = extract_param($param, 'vmid');
4610 my $target_endpoint = extract_param($param, 'target-endpoint');
4611 my $target_vmid = extract_param($param, 'target-vmid') // $source_vmid;
4612
4613 my $delete = extract_param($param, 'delete') // 0;
4614
4615 PVE::Cluster::check_cfs_quorum();
4616
4617 # test if VM exists
4618 my $conf = PVE::QemuConfig->load_config($source_vmid);
4619
4620 PVE::QemuConfig->check_lock($conf);
4621
4622 raise_param_exc({ vmid => "cannot migrate HA-managed VM to remote cluster" })
4623 if PVE::HA::Config::vm_is_ha_managed($source_vmid);
4624
4625 my $remote = PVE::JSONSchema::parse_property_string('proxmox-remote', $target_endpoint);
4626
4627 # TODO: move this as helper somewhere appropriate?
4628 my $conn_args = {
4629 protocol => 'https',
4630 host => $remote->{host},
4631 port => $remote->{port} // 8006,
4632 apitoken => $remote->{apitoken},
4633 };
4634
4635 my $fp;
4636 if ($fp = $remote->{fingerprint}) {
4637 $conn_args->{cached_fingerprints} = { uc($fp) => 1 };
4638 }
4639
4640 print "Establishing API connection with remote at '$remote->{host}'\n";
4641
4642 my $api_client = PVE::APIClient::LWP->new(%$conn_args);
4643
4644 if (!defined($fp)) {
4645 my $cert_info = $api_client->get("/nodes/localhost/certificates/info");
4646 foreach my $cert (@$cert_info) {
4647 my $filename = $cert->{filename};
4648 next if $filename ne 'pveproxy-ssl.pem' && $filename ne 'pve-ssl.pem';
4649 $fp = $cert->{fingerprint} if !$fp || $filename eq 'pveproxy-ssl.pem';
4650 }
4651 $conn_args->{cached_fingerprints} = { uc($fp) => 1 }
4652 if defined($fp);
4653 }
4654
4655 my $repl_conf = PVE::ReplicationConfig->new();
4656 my $is_replicated = $repl_conf->check_for_existing_jobs($source_vmid, 1);
4657 die "cannot remote-migrate replicated VM\n" if $is_replicated;
4658
4659 if (PVE::QemuServer::check_running($source_vmid)) {
4660 die "can't migrate running VM without --online\n" if !$param->{online};
4661
4662 } else {
4663 warn "VM isn't running. Doing offline migration instead.\n" if $param->{online};
4664 $param->{online} = 0;
4665 }
4666
4667 my $storecfg = PVE::Storage::config();
4668 my $target_storage = extract_param($param, 'target-storage');
4669 my $storagemap = eval { PVE::JSONSchema::parse_idmap($target_storage, 'pve-storage-id') };
4670 raise_param_exc({ 'target-storage' => "failed to parse storage map: $@" })
4671 if $@;
4672
4673 my $target_bridge = extract_param($param, 'target-bridge');
4674 my $bridgemap = eval { PVE::JSONSchema::parse_idmap($target_bridge, 'pve-bridge-id') };
4675 raise_param_exc({ 'target-bridge' => "failed to parse bridge map: $@" })
4676 if $@;
4677
4678 die "remote migration requires explicit storage mapping!\n"
4679 if $storagemap->{identity};
4680
4681 $param->{storagemap} = $storagemap;
4682 $param->{bridgemap} = $bridgemap;
4683 $param->{remote} = {
4684 conn => $conn_args, # re-use fingerprint for tunnel
4685 client => $api_client,
4686 vmid => $target_vmid,
4687 };
4688 $param->{migration_type} = 'websocket';
4689 $param->{'with-local-disks'} = 1;
4690 $param->{delete} = $delete if $delete;
4691
4692 my $cluster_status = $api_client->get("/cluster/status");
4693 my $target_node;
4694 foreach my $entry (@$cluster_status) {
4695 next if $entry->{type} ne 'node';
4696 if ($entry->{local}) {
4697 $target_node = $entry->{name};
4698 last;
4699 }
4700 }
4701
4702 die "couldn't determine endpoint's node name\n"
4703 if !defined($target_node);
4704
4705 my $realcmd = sub {
4706 PVE::QemuMigrate->migrate($target_node, $remote->{host}, $source_vmid, $param);
4707 };
4708
4709 my $worker = sub {
4710 return PVE::GuestHelpers::guest_migration_lock($source_vmid, 10, $realcmd);
4711 };
4712
4713 return $rpcenv->fork_worker('qmigrate', $source_vmid, $authuser, $worker);
4714 }});
4715
4716 __PACKAGE__->register_method({
4717 name => 'monitor',
4718 path => '{vmid}/monitor',
4719 method => 'POST',
4720 protected => 1,
4721 proxyto => 'node',
4722 description => "Execute QEMU monitor commands.",
4723 permissions => {
4724 description => "Sys.Modify is required for (sub)commands which are not read-only ('info *' and 'help')",
4725 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
4726 },
4727 parameters => {
4728 additionalProperties => 0,
4729 properties => {
4730 node => get_standard_option('pve-node'),
4731 vmid => get_standard_option('pve-vmid'),
4732 command => {
4733 type => 'string',
4734 description => "The monitor command.",
4735 }
4736 },
4737 },
4738 returns => { type => 'string'},
4739 code => sub {
4740 my ($param) = @_;
4741
4742 my $rpcenv = PVE::RPCEnvironment::get();
4743 my $authuser = $rpcenv->get_user();
4744
4745 my $is_ro = sub {
4746 my $command = shift;
4747 return $command =~ m/^\s*info(\s+|$)/
4748 || $command =~ m/^\s*help\s*$/;
4749 };
4750
4751 $rpcenv->check_full($authuser, "/", ['Sys.Modify'])
4752 if !&$is_ro($param->{command});
4753
4754 my $vmid = $param->{vmid};
4755
4756 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
4757
4758 my $res = '';
4759 eval {
4760 $res = PVE::QemuServer::Monitor::hmp_cmd($vmid, $param->{command});
4761 };
4762 $res = "ERROR: $@" if $@;
4763
4764 return $res;
4765 }});
4766
4767 __PACKAGE__->register_method({
4768 name => 'resize_vm',
4769 path => '{vmid}/resize',
4770 method => 'PUT',
4771 protected => 1,
4772 proxyto => 'node',
4773 description => "Extend volume size.",
4774 permissions => {
4775 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
4776 },
4777 parameters => {
4778 additionalProperties => 0,
4779 properties => {
4780 node => get_standard_option('pve-node'),
4781 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
4782 skiplock => get_standard_option('skiplock'),
4783 disk => {
4784 type => 'string',
4785 description => "The disk you want to resize.",
4786 enum => [PVE::QemuServer::Drive::valid_drive_names()],
4787 },
4788 size => {
4789 type => 'string',
4790 pattern => '\+?\d+(\.\d+)?[KMGT]?',
4791 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.",
4792 },
4793 digest => {
4794 type => 'string',
4795 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
4796 maxLength => 40,
4797 optional => 1,
4798 },
4799 },
4800 },
4801 returns => {
4802 type => 'string',
4803 description => "the task ID.",
4804 },
4805 code => sub {
4806 my ($param) = @_;
4807
4808 my $rpcenv = PVE::RPCEnvironment::get();
4809
4810 my $authuser = $rpcenv->get_user();
4811
4812 my $node = extract_param($param, 'node');
4813
4814 my $vmid = extract_param($param, 'vmid');
4815
4816 my $digest = extract_param($param, 'digest');
4817
4818 my $disk = extract_param($param, 'disk');
4819
4820 my $sizestr = extract_param($param, 'size');
4821
4822 my $skiplock = extract_param($param, 'skiplock');
4823 raise_param_exc({ skiplock => "Only root may use this option." })
4824 if $skiplock && $authuser ne 'root@pam';
4825
4826 my $storecfg = PVE::Storage::config();
4827
4828 my $updatefn = sub {
4829
4830 my $conf = PVE::QemuConfig->load_config($vmid);
4831
4832 die "checksum missmatch (file change by other user?)\n"
4833 if $digest && $digest ne $conf->{digest};
4834 PVE::QemuConfig->check_lock($conf) if !$skiplock;
4835
4836 die "disk '$disk' does not exist\n" if !$conf->{$disk};
4837
4838 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
4839
4840 my (undef, undef, undef, undef, undef, undef, $format) =
4841 PVE::Storage::parse_volname($storecfg, $drive->{file});
4842
4843 my $volid = $drive->{file};
4844
4845 die "disk '$disk' has no associated volume\n" if !$volid;
4846
4847 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
4848
4849 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
4850
4851 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
4852
4853 PVE::Storage::activate_volumes($storecfg, [$volid]);
4854 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
4855
4856 die "Could not determine current size of volume '$volid'\n" if !defined($size);
4857
4858 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
4859 my ($ext, $newsize, $unit) = ($1, $2, $4);
4860 if ($unit) {
4861 if ($unit eq 'K') {
4862 $newsize = $newsize * 1024;
4863 } elsif ($unit eq 'M') {
4864 $newsize = $newsize * 1024 * 1024;
4865 } elsif ($unit eq 'G') {
4866 $newsize = $newsize * 1024 * 1024 * 1024;
4867 } elsif ($unit eq 'T') {
4868 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
4869 }
4870 }
4871 $newsize += $size if $ext;
4872 $newsize = int($newsize);
4873
4874 die "shrinking disks is not supported\n" if $newsize < $size;
4875
4876 return if $size == $newsize;
4877
4878 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
4879
4880 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
4881
4882 $drive->{size} = $newsize;
4883 $conf->{$disk} = PVE::QemuServer::print_drive($drive);
4884
4885 PVE::QemuConfig->write_config($vmid, $conf);
4886 };
4887
4888 my $worker = sub {
4889 PVE::QemuConfig->lock_config($vmid, $updatefn);
4890 };
4891
4892 return $rpcenv->fork_worker('resize', $vmid, $authuser, $worker);
4893 }});
4894
4895 __PACKAGE__->register_method({
4896 name => 'snapshot_list',
4897 path => '{vmid}/snapshot',
4898 method => 'GET',
4899 description => "List all snapshots.",
4900 permissions => {
4901 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
4902 },
4903 proxyto => 'node',
4904 protected => 1, # qemu pid files are only readable by root
4905 parameters => {
4906 additionalProperties => 0,
4907 properties => {
4908 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
4909 node => get_standard_option('pve-node'),
4910 },
4911 },
4912 returns => {
4913 type => 'array',
4914 items => {
4915 type => "object",
4916 properties => {
4917 name => {
4918 description => "Snapshot identifier. Value 'current' identifies the current VM.",
4919 type => 'string',
4920 },
4921 vmstate => {
4922 description => "Snapshot includes RAM.",
4923 type => 'boolean',
4924 optional => 1,
4925 },
4926 description => {
4927 description => "Snapshot description.",
4928 type => 'string',
4929 },
4930 snaptime => {
4931 description => "Snapshot creation time",
4932 type => 'integer',
4933 renderer => 'timestamp',
4934 optional => 1,
4935 },
4936 parent => {
4937 description => "Parent snapshot identifier.",
4938 type => 'string',
4939 optional => 1,
4940 },
4941 },
4942 },
4943 links => [ { rel => 'child', href => "{name}" } ],
4944 },
4945 code => sub {
4946 my ($param) = @_;
4947
4948 my $vmid = $param->{vmid};
4949
4950 my $conf = PVE::QemuConfig->load_config($vmid);
4951 my $snaphash = $conf->{snapshots} || {};
4952
4953 my $res = [];
4954
4955 foreach my $name (keys %$snaphash) {
4956 my $d = $snaphash->{$name};
4957 my $item = {
4958 name => $name,
4959 snaptime => $d->{snaptime} || 0,
4960 vmstate => $d->{vmstate} ? 1 : 0,
4961 description => $d->{description} || '',
4962 };
4963 $item->{parent} = $d->{parent} if $d->{parent};
4964 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
4965 push @$res, $item;
4966 }
4967
4968 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
4969 my $current = {
4970 name => 'current',
4971 digest => $conf->{digest},
4972 running => $running,
4973 description => "You are here!",
4974 };
4975 $current->{parent} = $conf->{parent} if $conf->{parent};
4976
4977 push @$res, $current;
4978
4979 return $res;
4980 }});
4981
4982 __PACKAGE__->register_method({
4983 name => 'snapshot',
4984 path => '{vmid}/snapshot',
4985 method => 'POST',
4986 protected => 1,
4987 proxyto => 'node',
4988 description => "Snapshot a VM.",
4989 permissions => {
4990 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
4991 },
4992 parameters => {
4993 additionalProperties => 0,
4994 properties => {
4995 node => get_standard_option('pve-node'),
4996 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
4997 snapname => get_standard_option('pve-snapshot-name'),
4998 vmstate => {
4999 optional => 1,
5000 type => 'boolean',
5001 description => "Save the vmstate",
5002 },
5003 description => {
5004 optional => 1,
5005 type => 'string',
5006 description => "A textual description or comment.",
5007 },
5008 },
5009 },
5010 returns => {
5011 type => 'string',
5012 description => "the task ID.",
5013 },
5014 code => sub {
5015 my ($param) = @_;
5016
5017 my $rpcenv = PVE::RPCEnvironment::get();
5018
5019 my $authuser = $rpcenv->get_user();
5020
5021 my $node = extract_param($param, 'node');
5022
5023 my $vmid = extract_param($param, 'vmid');
5024
5025 my $snapname = extract_param($param, 'snapname');
5026
5027 die "unable to use snapshot name 'current' (reserved name)\n"
5028 if $snapname eq 'current';
5029
5030 die "unable to use snapshot name 'pending' (reserved name)\n"
5031 if lc($snapname) eq 'pending';
5032
5033 my $realcmd = sub {
5034 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
5035 PVE::QemuConfig->snapshot_create($vmid, $snapname, $param->{vmstate},
5036 $param->{description});
5037 };
5038
5039 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
5040 }});
5041
5042 __PACKAGE__->register_method({
5043 name => 'snapshot_cmd_idx',
5044 path => '{vmid}/snapshot/{snapname}',
5045 description => '',
5046 method => 'GET',
5047 permissions => {
5048 user => 'all',
5049 },
5050 parameters => {
5051 additionalProperties => 0,
5052 properties => {
5053 vmid => get_standard_option('pve-vmid'),
5054 node => get_standard_option('pve-node'),
5055 snapname => get_standard_option('pve-snapshot-name'),
5056 },
5057 },
5058 returns => {
5059 type => 'array',
5060 items => {
5061 type => "object",
5062 properties => {},
5063 },
5064 links => [ { rel => 'child', href => "{cmd}" } ],
5065 },
5066 code => sub {
5067 my ($param) = @_;
5068
5069 my $res = [];
5070
5071 push @$res, { cmd => 'rollback' };
5072 push @$res, { cmd => 'config' };
5073
5074 return $res;
5075 }});
5076
5077 __PACKAGE__->register_method({
5078 name => 'update_snapshot_config',
5079 path => '{vmid}/snapshot/{snapname}/config',
5080 method => 'PUT',
5081 protected => 1,
5082 proxyto => 'node',
5083 description => "Update snapshot metadata.",
5084 permissions => {
5085 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
5086 },
5087 parameters => {
5088 additionalProperties => 0,
5089 properties => {
5090 node => get_standard_option('pve-node'),
5091 vmid => get_standard_option('pve-vmid'),
5092 snapname => get_standard_option('pve-snapshot-name'),
5093 description => {
5094 optional => 1,
5095 type => 'string',
5096 description => "A textual description or comment.",
5097 },
5098 },
5099 },
5100 returns => { type => 'null' },
5101 code => sub {
5102 my ($param) = @_;
5103
5104 my $rpcenv = PVE::RPCEnvironment::get();
5105
5106 my $authuser = $rpcenv->get_user();
5107
5108 my $vmid = extract_param($param, 'vmid');
5109
5110 my $snapname = extract_param($param, 'snapname');
5111
5112 return if !defined($param->{description});
5113
5114 my $updatefn = sub {
5115
5116 my $conf = PVE::QemuConfig->load_config($vmid);
5117
5118 PVE::QemuConfig->check_lock($conf);
5119
5120 my $snap = $conf->{snapshots}->{$snapname};
5121
5122 die "snapshot '$snapname' does not exist\n" if !defined($snap);
5123
5124 $snap->{description} = $param->{description} if defined($param->{description});
5125
5126 PVE::QemuConfig->write_config($vmid, $conf);
5127 };
5128
5129 PVE::QemuConfig->lock_config($vmid, $updatefn);
5130
5131 return;
5132 }});
5133
5134 __PACKAGE__->register_method({
5135 name => 'get_snapshot_config',
5136 path => '{vmid}/snapshot/{snapname}/config',
5137 method => 'GET',
5138 proxyto => 'node',
5139 description => "Get snapshot configuration",
5140 permissions => {
5141 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot', 'VM.Snapshot.Rollback', 'VM.Audit' ], any => 1],
5142 },
5143 parameters => {
5144 additionalProperties => 0,
5145 properties => {
5146 node => get_standard_option('pve-node'),
5147 vmid => get_standard_option('pve-vmid'),
5148 snapname => get_standard_option('pve-snapshot-name'),
5149 },
5150 },
5151 returns => { type => "object" },
5152 code => sub {
5153 my ($param) = @_;
5154
5155 my $rpcenv = PVE::RPCEnvironment::get();
5156
5157 my $authuser = $rpcenv->get_user();
5158
5159 my $vmid = extract_param($param, 'vmid');
5160
5161 my $snapname = extract_param($param, 'snapname');
5162
5163 my $conf = PVE::QemuConfig->load_config($vmid);
5164
5165 my $snap = $conf->{snapshots}->{$snapname};
5166
5167 die "snapshot '$snapname' does not exist\n" if !defined($snap);
5168
5169 return $snap;
5170 }});
5171
5172 __PACKAGE__->register_method({
5173 name => 'rollback',
5174 path => '{vmid}/snapshot/{snapname}/rollback',
5175 method => 'POST',
5176 protected => 1,
5177 proxyto => 'node',
5178 description => "Rollback VM state to specified snapshot.",
5179 permissions => {
5180 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot', 'VM.Snapshot.Rollback' ], any => 1],
5181 },
5182 parameters => {
5183 additionalProperties => 0,
5184 properties => {
5185 node => get_standard_option('pve-node'),
5186 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
5187 snapname => get_standard_option('pve-snapshot-name'),
5188 start => {
5189 type => 'boolean',
5190 description => "Whether the VM should get started after rolling back successfully."
5191 . " (Note: VMs will be automatically started if the snapshot includes RAM.)",
5192 optional => 1,
5193 default => 0,
5194 },
5195 },
5196 },
5197 returns => {
5198 type => 'string',
5199 description => "the task ID.",
5200 },
5201 code => sub {
5202 my ($param) = @_;
5203
5204 my $rpcenv = PVE::RPCEnvironment::get();
5205
5206 my $authuser = $rpcenv->get_user();
5207
5208 my $node = extract_param($param, 'node');
5209
5210 my $vmid = extract_param($param, 'vmid');
5211
5212 my $snapname = extract_param($param, 'snapname');
5213
5214 my $realcmd = sub {
5215 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
5216 PVE::QemuConfig->snapshot_rollback($vmid, $snapname);
5217
5218 if ($param->{start} && !PVE::QemuServer::Helpers::vm_running_locally($vmid)) {
5219 PVE::API2::Qemu->vm_start({ vmid => $vmid, node => $node });
5220 }
5221 };
5222
5223 my $worker = sub {
5224 # hold migration lock, this makes sure that nobody create replication snapshots
5225 return PVE::GuestHelpers::guest_migration_lock($vmid, 10, $realcmd);
5226 };
5227
5228 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $worker);
5229 }});
5230
5231 __PACKAGE__->register_method({
5232 name => 'delsnapshot',
5233 path => '{vmid}/snapshot/{snapname}',
5234 method => 'DELETE',
5235 protected => 1,
5236 proxyto => 'node',
5237 description => "Delete a VM snapshot.",
5238 permissions => {
5239 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
5240 },
5241 parameters => {
5242 additionalProperties => 0,
5243 properties => {
5244 node => get_standard_option('pve-node'),
5245 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
5246 snapname => get_standard_option('pve-snapshot-name'),
5247 force => {
5248 optional => 1,
5249 type => 'boolean',
5250 description => "For removal from config file, even if removing disk snapshots fails.",
5251 },
5252 },
5253 },
5254 returns => {
5255 type => 'string',
5256 description => "the task ID.",
5257 },
5258 code => sub {
5259 my ($param) = @_;
5260
5261 my $rpcenv = PVE::RPCEnvironment::get();
5262
5263 my $authuser = $rpcenv->get_user();
5264
5265 my $node = extract_param($param, 'node');
5266
5267 my $vmid = extract_param($param, 'vmid');
5268
5269 my $snapname = extract_param($param, 'snapname');
5270
5271 my $lock_obtained;
5272 my $do_delete = sub {
5273 $lock_obtained = 1;
5274 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
5275 PVE::QemuConfig->snapshot_delete($vmid, $snapname, $param->{force});
5276 };
5277
5278 my $realcmd = sub {
5279 if ($param->{force}) {
5280 $do_delete->();
5281 } else {
5282 eval { PVE::GuestHelpers::guest_migration_lock($vmid, 10, $do_delete); };
5283 if (my $err = $@) {
5284 die $err if $lock_obtained;
5285 die "Failed to obtain guest migration lock - replication running?\n";
5286 }
5287 }
5288 };
5289
5290 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
5291 }});
5292
5293 __PACKAGE__->register_method({
5294 name => 'template',
5295 path => '{vmid}/template',
5296 method => 'POST',
5297 protected => 1,
5298 proxyto => 'node',
5299 description => "Create a Template.",
5300 permissions => {
5301 description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
5302 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
5303 },
5304 parameters => {
5305 additionalProperties => 0,
5306 properties => {
5307 node => get_standard_option('pve-node'),
5308 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_stopped }),
5309 disk => {
5310 optional => 1,
5311 type => 'string',
5312 description => "If you want to convert only 1 disk to base image.",
5313 enum => [PVE::QemuServer::Drive::valid_drive_names()],
5314 },
5315
5316 },
5317 },
5318 returns => {
5319 type => 'string',
5320 description => "the task ID.",
5321 },
5322 code => sub {
5323 my ($param) = @_;
5324
5325 my $rpcenv = PVE::RPCEnvironment::get();
5326
5327 my $authuser = $rpcenv->get_user();
5328
5329 my $node = extract_param($param, 'node');
5330
5331 my $vmid = extract_param($param, 'vmid');
5332
5333 my $disk = extract_param($param, 'disk');
5334
5335 my $load_and_check = sub {
5336 my $conf = PVE::QemuConfig->load_config($vmid);
5337
5338 PVE::QemuConfig->check_lock($conf);
5339
5340 die "unable to create template, because VM contains snapshots\n"
5341 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
5342
5343 die "you can't convert a template to a template\n"
5344 if PVE::QemuConfig->is_template($conf) && !$disk;
5345
5346 die "you can't convert a VM to template if VM is running\n"
5347 if PVE::QemuServer::check_running($vmid);
5348
5349 return $conf;
5350 };
5351
5352 $load_and_check->();
5353
5354 my $realcmd = sub {
5355 PVE::QemuConfig->lock_config($vmid, sub {
5356 my $conf = $load_and_check->();
5357
5358 $conf->{template} = 1;
5359 PVE::QemuConfig->write_config($vmid, $conf);
5360
5361 PVE::QemuServer::template_create($vmid, $conf, $disk);
5362 });
5363 };
5364
5365 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
5366 }});
5367
5368 __PACKAGE__->register_method({
5369 name => 'cloudinit_generated_config_dump',
5370 path => '{vmid}/cloudinit/dump',
5371 method => 'GET',
5372 proxyto => 'node',
5373 description => "Get automatically generated cloudinit config.",
5374 permissions => {
5375 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
5376 },
5377 parameters => {
5378 additionalProperties => 0,
5379 properties => {
5380 node => get_standard_option('pve-node'),
5381 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
5382 type => {
5383 description => 'Config type.',
5384 type => 'string',
5385 enum => ['user', 'network', 'meta'],
5386 },
5387 },
5388 },
5389 returns => {
5390 type => 'string',
5391 },
5392 code => sub {
5393 my ($param) = @_;
5394
5395 my $conf = PVE::QemuConfig->load_config($param->{vmid});
5396
5397 return PVE::QemuServer::Cloudinit::dump_cloudinit_config($conf, $param->{vmid}, $param->{type});
5398 }});
5399
5400 __PACKAGE__->register_method({
5401 name => 'mtunnel',
5402 path => '{vmid}/mtunnel',
5403 method => 'POST',
5404 protected => 1,
5405 description => 'Migration tunnel endpoint - only for internal use by VM migration.',
5406 permissions => {
5407 check =>
5408 [ 'and',
5409 ['perm', '/vms/{vmid}', [ 'VM.Allocate' ]],
5410 ['perm', '/', [ 'Sys.Incoming' ]],
5411 ],
5412 description => "You need 'VM.Allocate' permissions on '/vms/{vmid}' and Sys.Incoming" .
5413 " on '/'. Further permission checks happen during the actual migration.",
5414 },
5415 parameters => {
5416 additionalProperties => 0,
5417 properties => {
5418 node => get_standard_option('pve-node'),
5419 vmid => get_standard_option('pve-vmid'),
5420 storages => {
5421 type => 'string',
5422 format => 'pve-storage-id-list',
5423 optional => 1,
5424 description => 'List of storages to check permission and availability. Will be checked again for all actually used storages during migration.',
5425 },
5426 bridges => {
5427 type => 'string',
5428 format => 'pve-bridge-id-list',
5429 optional => 1,
5430 description => 'List of network bridges to check availability. Will be checked again for actually used bridges during migration.',
5431 },
5432 },
5433 },
5434 returns => {
5435 additionalProperties => 0,
5436 properties => {
5437 upid => { type => 'string' },
5438 ticket => { type => 'string' },
5439 socket => { type => 'string' },
5440 },
5441 },
5442 code => sub {
5443 my ($param) = @_;
5444
5445 my $rpcenv = PVE::RPCEnvironment::get();
5446 my $authuser = $rpcenv->get_user();
5447
5448 my $node = extract_param($param, 'node');
5449 my $vmid = extract_param($param, 'vmid');
5450
5451 my $storages = extract_param($param, 'storages');
5452 my $bridges = extract_param($param, 'bridges');
5453
5454 my $nodename = PVE::INotify::nodename();
5455
5456 raise_param_exc({ node => "node needs to be 'localhost' or local hostname '$nodename'" })
5457 if $node ne 'localhost' && $node ne $nodename;
5458
5459 $node = $nodename;
5460
5461 my $storecfg = PVE::Storage::config();
5462 foreach my $storeid (PVE::Tools::split_list($storages)) {
5463 $check_storage_access_migrate->($rpcenv, $authuser, $storecfg, $storeid, $node);
5464 }
5465
5466 foreach my $bridge (PVE::Tools::split_list($bridges)) {
5467 PVE::Network::read_bridge_mtu($bridge);
5468 }
5469
5470 PVE::Cluster::check_cfs_quorum();
5471
5472 my $lock = 'create';
5473 eval { PVE::QemuConfig->create_and_lock_config($vmid, 0, $lock); };
5474
5475 raise_param_exc({ vmid => "unable to create empty VM config - $@"})
5476 if $@;
5477
5478 my $realcmd = sub {
5479 my $state = {
5480 storecfg => PVE::Storage::config(),
5481 lock => $lock,
5482 vmid => $vmid,
5483 };
5484
5485 my $run_locked = sub {
5486 my ($code, $params) = @_;
5487 return PVE::QemuConfig->lock_config($state->{vmid}, sub {
5488 my $conf = PVE::QemuConfig->load_config($state->{vmid});
5489
5490 $state->{conf} = $conf;
5491
5492 die "Encountered wrong lock - aborting mtunnel command handling.\n"
5493 if $state->{lock} && !PVE::QemuConfig->has_lock($conf, $state->{lock});
5494
5495 return $code->($params);
5496 });
5497 };
5498
5499 my $cmd_desc = {
5500 config => {
5501 conf => {
5502 type => 'string',
5503 description => 'Full VM config, adapted for target cluster/node',
5504 },
5505 'firewall-config' => {
5506 type => 'string',
5507 description => 'VM firewall config',
5508 optional => 1,
5509 },
5510 },
5511 disk => {
5512 format => PVE::JSONSchema::get_standard_option('pve-qm-image-format'),
5513 storage => {
5514 type => 'string',
5515 format => 'pve-storage-id',
5516 },
5517 drive => {
5518 type => 'object',
5519 description => 'parsed drive information without volid and format',
5520 },
5521 },
5522 start => {
5523 start_params => {
5524 type => 'object',
5525 description => 'params passed to vm_start_nolock',
5526 },
5527 migrate_opts => {
5528 type => 'object',
5529 description => 'migrate_opts passed to vm_start_nolock',
5530 },
5531 },
5532 ticket => {
5533 path => {
5534 type => 'string',
5535 description => 'socket path for which the ticket should be valid. must be known to current mtunnel instance.',
5536 },
5537 },
5538 quit => {
5539 cleanup => {
5540 type => 'boolean',
5541 description => 'remove VM config and disks, aborting migration',
5542 default => 0,
5543 },
5544 },
5545 'disk-import' => $PVE::StorageTunnel::cmd_schema->{'disk-import'},
5546 'query-disk-import' => $PVE::StorageTunnel::cmd_schema->{'query-disk-import'},
5547 bwlimit => $PVE::StorageTunnel::cmd_schema->{bwlimit},
5548 };
5549
5550 my $cmd_handlers = {
5551 'version' => sub {
5552 # compared against other end's version
5553 # bump/reset for breaking changes
5554 # bump/bump for opt-in changes
5555 return {
5556 api => $PVE::QemuMigrate::WS_TUNNEL_VERSION,
5557 age => 0,
5558 };
5559 },
5560 'config' => sub {
5561 my ($params) = @_;
5562
5563 # parse and write out VM FW config if given
5564 if (my $fw_conf = $params->{'firewall-config'}) {
5565 my ($path, $fh) = PVE::Tools::tempfile_contents($fw_conf, 700);
5566
5567 my $empty_conf = {
5568 rules => [],
5569 options => {},
5570 aliases => {},
5571 ipset => {} ,
5572 ipset_comments => {},
5573 };
5574 my $cluster_fw_conf = PVE::Firewall::load_clusterfw_conf();
5575
5576 # TODO: add flag for strict parsing?
5577 # TODO: add import sub that does all this given raw content?
5578 my $vmfw_conf = PVE::Firewall::generic_fw_config_parser($path, $cluster_fw_conf, $empty_conf, 'vm');
5579 $vmfw_conf->{vmid} = $state->{vmid};
5580 PVE::Firewall::save_vmfw_conf($state->{vmid}, $vmfw_conf);
5581
5582 $state->{cleanup}->{fw} = 1;
5583 }
5584
5585 my $conf_fn = "incoming/qemu-server/$state->{vmid}.conf";
5586 my $new_conf = PVE::QemuServer::parse_vm_config($conf_fn, $params->{conf}, 1);
5587 delete $new_conf->{lock};
5588 delete $new_conf->{digest};
5589
5590 # TODO handle properly?
5591 delete $new_conf->{snapshots};
5592 delete $new_conf->{parent};
5593 delete $new_conf->{pending};
5594
5595 # not handled by update_vm_api
5596 my $vmgenid = delete $new_conf->{vmgenid};
5597 my $meta = delete $new_conf->{meta};
5598 my $cloudinit = delete $new_conf->{cloudinit}; # this is informational only
5599 $new_conf->{skip_cloud_init} = 1; # re-use image from source side
5600
5601 $new_conf->{vmid} = $state->{vmid};
5602 $new_conf->{node} = $node;
5603
5604 PVE::QemuConfig->remove_lock($state->{vmid}, 'create');
5605
5606 eval {
5607 $update_vm_api->($new_conf, 1);
5608 };
5609 if (my $err = $@) {
5610 # revert to locked previous config
5611 my $conf = PVE::QemuConfig->load_config($state->{vmid});
5612 $conf->{lock} = 'create';
5613 PVE::QemuConfig->write_config($state->{vmid}, $conf);
5614
5615 die $err;
5616 }
5617
5618 my $conf = PVE::QemuConfig->load_config($state->{vmid});
5619 $conf->{lock} = 'migrate';
5620 $conf->{vmgenid} = $vmgenid if defined($vmgenid);
5621 $conf->{meta} = $meta if defined($meta);
5622 $conf->{cloudinit} = $cloudinit if defined($cloudinit);
5623 PVE::QemuConfig->write_config($state->{vmid}, $conf);
5624
5625 $state->{lock} = 'migrate';
5626
5627 return;
5628 },
5629 'bwlimit' => sub {
5630 my ($params) = @_;
5631 return PVE::StorageTunnel::handle_bwlimit($params);
5632 },
5633 'disk' => sub {
5634 my ($params) = @_;
5635
5636 my $format = $params->{format};
5637 my $storeid = $params->{storage};
5638 my $drive = $params->{drive};
5639
5640 $check_storage_access_migrate->($rpcenv, $authuser, $state->{storecfg}, $storeid, $node);
5641
5642 my $storagemap = {
5643 default => $storeid,
5644 };
5645
5646 my $source_volumes = {
5647 'disk' => [
5648 undef,
5649 $storeid,
5650 undef,
5651 $drive,
5652 0,
5653 $format,
5654 ],
5655 };
5656
5657 my $res = PVE::QemuServer::vm_migrate_alloc_nbd_disks($state->{storecfg}, $state->{vmid}, $source_volumes, $storagemap);
5658 if (defined($res->{disk})) {
5659 $state->{cleanup}->{volumes}->{$res->{disk}->{volid}} = 1;
5660 return $res->{disk};
5661 } else {
5662 die "failed to allocate NBD disk..\n";
5663 }
5664 },
5665 'disk-import' => sub {
5666 my ($params) = @_;
5667
5668 $check_storage_access_migrate->(
5669 $rpcenv,
5670 $authuser,
5671 $state->{storecfg},
5672 $params->{storage},
5673 $node
5674 );
5675
5676 $params->{unix} = "/run/qemu-server/$state->{vmid}.storage";
5677
5678 return PVE::StorageTunnel::handle_disk_import($state, $params);
5679 },
5680 'query-disk-import' => sub {
5681 my ($params) = @_;
5682
5683 return PVE::StorageTunnel::handle_query_disk_import($state, $params);
5684 },
5685 'start' => sub {
5686 my ($params) = @_;
5687
5688 my $info = PVE::QemuServer::vm_start_nolock(
5689 $state->{storecfg},
5690 $state->{vmid},
5691 $state->{conf},
5692 $params->{start_params},
5693 $params->{migrate_opts},
5694 );
5695
5696
5697 if ($info->{migrate}->{proto} ne 'unix') {
5698 PVE::QemuServer::vm_stop(undef, $state->{vmid}, 1, 1);
5699 die "migration over non-UNIX sockets not possible\n";
5700 }
5701
5702 my $socket = $info->{migrate}->{addr};
5703 chown $state->{socket_uid}, -1, $socket;
5704 $state->{sockets}->{$socket} = 1;
5705
5706 my $unix_sockets = $info->{migrate}->{unix_sockets};
5707 foreach my $socket (@$unix_sockets) {
5708 chown $state->{socket_uid}, -1, $socket;
5709 $state->{sockets}->{$socket} = 1;
5710 }
5711 return $info;
5712 },
5713 'fstrim' => sub {
5714 if (PVE::QemuServer::qga_check_running($state->{vmid})) {
5715 eval { mon_cmd($state->{vmid}, "guest-fstrim") };
5716 warn "fstrim failed: $@\n" if $@;
5717 }
5718 return;
5719 },
5720 'stop' => sub {
5721 PVE::QemuServer::vm_stop(undef, $state->{vmid}, 1, 1);
5722 return;
5723 },
5724 'nbdstop' => sub {
5725 PVE::QemuServer::nbd_stop($state->{vmid});
5726 return;
5727 },
5728 'resume' => sub {
5729 if (PVE::QemuServer::Helpers::vm_running_locally($state->{vmid})) {
5730 PVE::QemuServer::vm_resume($state->{vmid}, 1, 1);
5731 } else {
5732 die "VM $state->{vmid} not running\n";
5733 }
5734 return;
5735 },
5736 'unlock' => sub {
5737 PVE::QemuConfig->remove_lock($state->{vmid}, $state->{lock});
5738 delete $state->{lock};
5739 return;
5740 },
5741 'ticket' => sub {
5742 my ($params) = @_;
5743
5744 my $path = $params->{path};
5745
5746 die "Not allowed to generate ticket for unknown socket '$path'\n"
5747 if !defined($state->{sockets}->{$path});
5748
5749 return { ticket => PVE::AccessControl::assemble_tunnel_ticket($authuser, "/socket/$path") };
5750 },
5751 'quit' => sub {
5752 my ($params) = @_;
5753
5754 if ($params->{cleanup}) {
5755 if ($state->{cleanup}->{fw}) {
5756 PVE::Firewall::remove_vmfw_conf($state->{vmid});
5757 }
5758
5759 for my $volid (keys $state->{cleanup}->{volumes}->%*) {
5760 print "freeing volume '$volid' as part of cleanup\n";
5761 eval { PVE::Storage::vdisk_free($state->{storecfg}, $volid) };
5762 warn $@ if $@;
5763 }
5764
5765 PVE::QemuServer::destroy_vm($state->{storecfg}, $state->{vmid}, 1);
5766 }
5767
5768 print "switching to exit-mode, waiting for client to disconnect\n";
5769 $state->{exit} = 1;
5770 return;
5771 },
5772 };
5773
5774 $run_locked->(sub {
5775 my $socket_addr = "/run/qemu-server/$state->{vmid}.mtunnel";
5776 unlink $socket_addr;
5777
5778 $state->{socket} = IO::Socket::UNIX->new(
5779 Type => SOCK_STREAM(),
5780 Local => $socket_addr,
5781 Listen => 1,
5782 );
5783
5784 $state->{socket_uid} = getpwnam('www-data')
5785 or die "Failed to resolve user 'www-data' to numeric UID\n";
5786 chown $state->{socket_uid}, -1, $socket_addr;
5787 });
5788
5789 print "mtunnel started\n";
5790
5791 my $conn = eval { PVE::Tools::run_with_timeout(300, sub { $state->{socket}->accept() }) };
5792 if ($@) {
5793 warn "Failed to accept tunnel connection - $@\n";
5794
5795 warn "Removing tunnel socket..\n";
5796 unlink $state->{socket};
5797
5798 warn "Removing temporary VM config..\n";
5799 $run_locked->(sub {
5800 PVE::QemuServer::destroy_vm($state->{storecfg}, $state->{vmid}, 1);
5801 });
5802
5803 die "Exiting mtunnel\n";
5804 }
5805
5806 $state->{conn} = $conn;
5807
5808 my $reply_err = sub {
5809 my ($msg) = @_;
5810
5811 my $reply = JSON::encode_json({
5812 success => JSON::false,
5813 msg => $msg,
5814 });
5815 $conn->print("$reply\n");
5816 $conn->flush();
5817 };
5818
5819 my $reply_ok = sub {
5820 my ($res) = @_;
5821
5822 $res->{success} = JSON::true;
5823 my $reply = JSON::encode_json($res);
5824 $conn->print("$reply\n");
5825 $conn->flush();
5826 };
5827
5828 while (my $line = <$conn>) {
5829 chomp $line;
5830
5831 # untaint, we validate below if needed
5832 ($line) = $line =~ /^(.*)$/;
5833 my $parsed = eval { JSON::decode_json($line) };
5834 if ($@) {
5835 $reply_err->("failed to parse command - $@");
5836 next;
5837 }
5838
5839 my $cmd = delete $parsed->{cmd};
5840 if (!defined($cmd)) {
5841 $reply_err->("'cmd' missing");
5842 } elsif ($state->{exit}) {
5843 $reply_err->("tunnel is in exit-mode, processing '$cmd' cmd not possible");
5844 next;
5845 } elsif (my $handler = $cmd_handlers->{$cmd}) {
5846 print "received command '$cmd'\n";
5847 eval {
5848 if ($cmd_desc->{$cmd}) {
5849 PVE::JSONSchema::validate($parsed, $cmd_desc->{$cmd});
5850 } else {
5851 $parsed = {};
5852 }
5853 my $res = $run_locked->($handler, $parsed);
5854 $reply_ok->($res);
5855 };
5856 $reply_err->("failed to handle '$cmd' command - $@")
5857 if $@;
5858 } else {
5859 $reply_err->("unknown command '$cmd' given");
5860 }
5861 }
5862
5863 if ($state->{exit}) {
5864 print "mtunnel exited\n";
5865 } else {
5866 die "mtunnel exited unexpectedly\n";
5867 }
5868 };
5869
5870 my $socket_addr = "/run/qemu-server/$vmid.mtunnel";
5871 my $ticket = PVE::AccessControl::assemble_tunnel_ticket($authuser, "/socket/$socket_addr");
5872 my $upid = $rpcenv->fork_worker('qmtunnel', $vmid, $authuser, $realcmd);
5873
5874 return {
5875 ticket => $ticket,
5876 upid => $upid,
5877 socket => $socket_addr,
5878 };
5879 }});
5880
5881 __PACKAGE__->register_method({
5882 name => 'mtunnelwebsocket',
5883 path => '{vmid}/mtunnelwebsocket',
5884 method => 'GET',
5885 permissions => {
5886 description => "You need to pass a ticket valid for the selected socket. Tickets can be created via the mtunnel API call, which will check permissions accordingly.",
5887 user => 'all', # check inside
5888 },
5889 description => 'Migration tunnel endpoint for websocket upgrade - only for internal use by VM migration.',
5890 parameters => {
5891 additionalProperties => 0,
5892 properties => {
5893 node => get_standard_option('pve-node'),
5894 vmid => get_standard_option('pve-vmid'),
5895 socket => {
5896 type => "string",
5897 description => "unix socket to forward to",
5898 },
5899 ticket => {
5900 type => "string",
5901 description => "ticket return by initial 'mtunnel' API call, or retrieved via 'ticket' tunnel command",
5902 },
5903 },
5904 },
5905 returns => {
5906 type => "object",
5907 properties => {
5908 port => { type => 'string', optional => 1 },
5909 socket => { type => 'string', optional => 1 },
5910 },
5911 },
5912 code => sub {
5913 my ($param) = @_;
5914
5915 my $rpcenv = PVE::RPCEnvironment::get();
5916 my $authuser = $rpcenv->get_user();
5917
5918 my $nodename = PVE::INotify::nodename();
5919 my $node = extract_param($param, 'node');
5920
5921 raise_param_exc({ node => "node needs to be 'localhost' or local hostname '$nodename'" })
5922 if $node ne 'localhost' && $node ne $nodename;
5923
5924 my $vmid = $param->{vmid};
5925 # check VM exists
5926 PVE::QemuConfig->load_config($vmid);
5927
5928 my $socket = $param->{socket};
5929 PVE::AccessControl::verify_tunnel_ticket($param->{ticket}, $authuser, "/socket/$socket");
5930
5931 return { socket => $socket };
5932 }});
5933
5934 1;