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