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