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