Qemu-Server: fix wrong quotation
[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 my $check_storage_access_migrate = sub {
139 my ($rpcenv, $authuser, $storecfg, $storage, $node) = @_;
140
141 PVE::Storage::storage_check_enabled($storecfg, $storage, $node);
142
143 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace']);
144
145 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
146 die "storage '$storage' does not support vm images\n"
147 if !$scfg->{content}->{images};
148 };
149
150 # Note: $pool is only needed when creating a VM, because pool permissions
151 # are automatically inherited if VM already exists inside a pool.
152 my $create_disks = sub {
153 my ($rpcenv, $authuser, $conf, $arch, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
154
155 my $vollist = [];
156
157 my $res = {};
158
159 my $code = sub {
160 my ($ds, $disk) = @_;
161
162 my $volid = $disk->{file};
163 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
164
165 if (!$volid || $volid eq 'none' || $volid eq 'cdrom') {
166 delete $disk->{size};
167 $res->{$ds} = PVE::QemuServer::print_drive($disk);
168 } elsif (defined($volname) && $volname eq 'cloudinit') {
169 $storeid = $storeid // $default_storage;
170 die "no storage ID specified (and no default storage)\n" if !$storeid;
171 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
172 my $name = "vm-$vmid-cloudinit";
173
174 my $fmt = undef;
175 if ($scfg->{path}) {
176 $fmt = $disk->{format} // "qcow2";
177 $name .= ".$fmt";
178 } else {
179 $fmt = $disk->{format} // "raw";
180 }
181
182 # Initial disk created with 4 MB and aligned to 4MB on regeneration
183 my $ci_size = PVE::QemuServer::Cloudinit::CLOUDINIT_DISK_SIZE;
184 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $fmt, $name, $ci_size/1024);
185 $disk->{file} = $volid;
186 $disk->{media} = 'cdrom';
187 push @$vollist, $volid;
188 delete $disk->{format}; # no longer needed
189 $res->{$ds} = PVE::QemuServer::print_drive($disk);
190 } elsif ($volid =~ $NEW_DISK_RE) {
191 my ($storeid, $size) = ($2 || $default_storage, $3);
192 die "no storage ID specified (and no default storage)\n" if !$storeid;
193 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
194 my $fmt = $disk->{format} || $defformat;
195
196 $size = PVE::Tools::convert_size($size, 'gb' => 'kb'); # vdisk_alloc uses kb
197
198 my $volid;
199 if ($ds eq 'efidisk0') {
200 my $smm = PVE::QemuServer::Machine::machine_type_is_q35($conf);
201 ($volid, $size) = PVE::QemuServer::create_efidisk(
202 $storecfg, $storeid, $vmid, $fmt, $arch, $disk, $smm);
203 } elsif ($ds eq 'tpmstate0') {
204 # swtpm can only use raw volumes, and uses a fixed size
205 $size = PVE::Tools::convert_size(PVE::QemuServer::Drive::TPMSTATE_DISK_SIZE, 'b' => 'kb');
206 $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, "raw", undef, $size);
207 } else {
208 $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $fmt, undef, $size);
209 }
210 push @$vollist, $volid;
211 $disk->{file} = $volid;
212 $disk->{size} = PVE::Tools::convert_size($size, 'kb' => 'b');
213 delete $disk->{format}; # no longer needed
214 $res->{$ds} = PVE::QemuServer::print_drive($disk);
215 } else {
216
217 PVE::Storage::check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $volid);
218
219 my $volid_is_new = 1;
220
221 if ($conf->{$ds}) {
222 my $olddrive = PVE::QemuServer::parse_drive($ds, $conf->{$ds});
223 $volid_is_new = undef if $olddrive->{file} && $olddrive->{file} eq $volid;
224 }
225
226 if ($volid_is_new) {
227
228 PVE::Storage::activate_volumes($storecfg, [ $volid ]) if $storeid;
229
230 my $size = PVE::Storage::volume_size_info($storecfg, $volid);
231
232 die "volume $volid does not exist\n" if !$size;
233
234 $disk->{size} = $size;
235 }
236
237 $res->{$ds} = PVE::QemuServer::print_drive($disk);
238 }
239 };
240
241 eval { PVE::QemuConfig->foreach_volume($settings, $code); };
242
243 # free allocated images on error
244 if (my $err = $@) {
245 syslog('err', "VM $vmid creating disks failed");
246 foreach my $volid (@$vollist) {
247 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
248 warn $@ if $@;
249 }
250 die $err;
251 }
252
253 # modify vm config if everything went well
254 foreach my $ds (keys %$res) {
255 $conf->{$ds} = $res->{$ds};
256 }
257
258 return $vollist;
259 };
260
261 my $check_cpu_model_access = sub {
262 my ($rpcenv, $authuser, $new, $existing) = @_;
263
264 return if !defined($new->{cpu});
265
266 my $cpu = PVE::JSONSchema::check_format('pve-vm-cpu-conf', $new->{cpu});
267 return if !$cpu || !$cpu->{cputype}; # always allow default
268 my $cputype = $cpu->{cputype};
269
270 if ($existing && $existing->{cpu}) {
271 # changing only other settings doesn't require permissions for CPU model
272 my $existingCpu = PVE::JSONSchema::check_format('pve-vm-cpu-conf', $existing->{cpu});
273 return if $existingCpu->{cputype} eq $cputype;
274 }
275
276 if (PVE::QemuServer::CPUConfig::is_custom_model($cputype)) {
277 $rpcenv->check($authuser, "/nodes", ['Sys.Audit']);
278 }
279 };
280
281 my $cpuoptions = {
282 'cores' => 1,
283 'cpu' => 1,
284 'cpulimit' => 1,
285 'cpuunits' => 1,
286 'numa' => 1,
287 'smp' => 1,
288 'sockets' => 1,
289 'vcpus' => 1,
290 };
291
292 my $memoryoptions = {
293 'memory' => 1,
294 'balloon' => 1,
295 'shares' => 1,
296 };
297
298 my $hwtypeoptions = {
299 'acpi' => 1,
300 'hotplug' => 1,
301 'kvm' => 1,
302 'machine' => 1,
303 'scsihw' => 1,
304 'smbios1' => 1,
305 'tablet' => 1,
306 'vga' => 1,
307 'watchdog' => 1,
308 'audio0' => 1,
309 };
310
311 my $generaloptions = {
312 'agent' => 1,
313 'autostart' => 1,
314 'bios' => 1,
315 'description' => 1,
316 'keyboard' => 1,
317 'localtime' => 1,
318 'migrate_downtime' => 1,
319 'migrate_speed' => 1,
320 'name' => 1,
321 'onboot' => 1,
322 'ostype' => 1,
323 'protection' => 1,
324 'reboot' => 1,
325 'startdate' => 1,
326 'startup' => 1,
327 'tdf' => 1,
328 'template' => 1,
329 'tags' => 1,
330 };
331
332 my $vmpoweroptions = {
333 'freeze' => 1,
334 };
335
336 my $diskoptions = {
337 'boot' => 1,
338 'bootdisk' => 1,
339 'vmstatestorage' => 1,
340 };
341
342 my $cloudinitoptions = {
343 cicustom => 1,
344 cipassword => 1,
345 citype => 1,
346 ciuser => 1,
347 nameserver => 1,
348 searchdomain => 1,
349 sshkeys => 1,
350 };
351
352 my $check_vm_create_serial_perm = sub {
353 my ($rpcenv, $authuser, $vmid, $pool, $param) = @_;
354
355 return 1 if $authuser eq 'root@pam';
356
357 foreach my $opt (keys %{$param}) {
358 next if $opt !~ m/^serial\d+$/;
359
360 if ($param->{$opt} eq 'socket') {
361 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
362 } else {
363 die "only root can set '$opt' config for real devices\n";
364 }
365 }
366
367 return 1;
368 };
369
370 my $check_vm_create_usb_perm = sub {
371 my ($rpcenv, $authuser, $vmid, $pool, $param) = @_;
372
373 return 1 if $authuser eq 'root@pam';
374
375 foreach my $opt (keys %{$param}) {
376 next if $opt !~ m/^usb\d+$/;
377
378 if ($param->{$opt} =~ m/spice/) {
379 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
380 } else {
381 die "only root can set '$opt' config for real devices\n";
382 }
383 }
384
385 return 1;
386 };
387
388 my $check_vm_modify_config_perm = sub {
389 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
390
391 return 1 if $authuser eq 'root@pam';
392
393 foreach my $opt (@$key_list) {
394 # some checks (e.g., disk, serial port, usb) need to be done somewhere
395 # else, as there the permission can be value dependend
396 next if PVE::QemuServer::is_valid_drivename($opt);
397 next if $opt eq 'cdrom';
398 next if $opt =~ m/^(?:unused|serial|usb)\d+$/;
399
400
401 if ($cpuoptions->{$opt} || $opt =~ m/^numa\d+$/) {
402 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
403 } elsif ($memoryoptions->{$opt}) {
404 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
405 } elsif ($hwtypeoptions->{$opt}) {
406 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
407 } elsif ($generaloptions->{$opt}) {
408 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
409 # special case for startup since it changes host behaviour
410 if ($opt eq 'startup') {
411 $rpcenv->check_full($authuser, "/", ['Sys.Modify']);
412 }
413 } elsif ($vmpoweroptions->{$opt}) {
414 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.PowerMgmt']);
415 } elsif ($diskoptions->{$opt}) {
416 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
417 } elsif ($opt =~ m/^(?:net|ipconfig)\d+$/) {
418 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
419 } elsif ($cloudinitoptions->{$opt}) {
420 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Cloudinit', 'VM.Config.Network'], 1);
421 } elsif ($opt eq 'vmstate') {
422 # the user needs Disk and PowerMgmt privileges to change the vmstate
423 # also needs privileges on the storage, that will be checked later
424 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk', 'VM.PowerMgmt' ]);
425 } else {
426 # catches hostpci\d+, args, lock, etc.
427 # new options will be checked here
428 die "only root can set '$opt' config\n";
429 }
430 }
431
432 return 1;
433 };
434
435 __PACKAGE__->register_method({
436 name => 'vmlist',
437 path => '',
438 method => 'GET',
439 description => "Virtual machine index (per node).",
440 permissions => {
441 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
442 user => 'all',
443 },
444 proxyto => 'node',
445 protected => 1, # qemu pid files are only readable by root
446 parameters => {
447 additionalProperties => 0,
448 properties => {
449 node => get_standard_option('pve-node'),
450 full => {
451 type => 'boolean',
452 optional => 1,
453 description => "Determine the full status of active VMs.",
454 },
455 },
456 },
457 returns => {
458 type => 'array',
459 items => {
460 type => "object",
461 properties => $PVE::QemuServer::vmstatus_return_properties,
462 },
463 links => [ { rel => 'child', href => "{vmid}" } ],
464 },
465 code => sub {
466 my ($param) = @_;
467
468 my $rpcenv = PVE::RPCEnvironment::get();
469 my $authuser = $rpcenv->get_user();
470
471 my $vmstatus = PVE::QemuServer::vmstatus(undef, $param->{full});
472
473 my $res = [];
474 foreach my $vmid (keys %$vmstatus) {
475 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
476
477 my $data = $vmstatus->{$vmid};
478 push @$res, $data;
479 }
480
481 return $res;
482 }});
483
484 my $parse_restore_archive = sub {
485 my ($storecfg, $archive) = @_;
486
487 my ($archive_storeid, $archive_volname) = PVE::Storage::parse_volume_id($archive, 1);
488
489 if (defined($archive_storeid)) {
490 my $scfg = PVE::Storage::storage_config($storecfg, $archive_storeid);
491 if ($scfg->{type} eq 'pbs') {
492 return {
493 type => 'pbs',
494 volid => $archive,
495 };
496 }
497 }
498 my $path = PVE::Storage::abs_filesystem_path($storecfg, $archive);
499 return {
500 type => 'file',
501 path => $path,
502 };
503 };
504
505
506 __PACKAGE__->register_method({
507 name => 'create_vm',
508 path => '',
509 method => 'POST',
510 description => "Create or restore a virtual machine.",
511 permissions => {
512 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. " .
513 "For restore (option 'archive'), it is enough if the user has 'VM.Backup' permission and the VM already exists. " .
514 "If you create disks you need 'Datastore.AllocateSpace' on any used storage.",
515 user => 'all', # check inside
516 },
517 protected => 1,
518 proxyto => 'node',
519 parameters => {
520 additionalProperties => 0,
521 properties => PVE::QemuServer::json_config_properties(
522 {
523 node => get_standard_option('pve-node'),
524 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
525 archive => {
526 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.",
527 type => 'string',
528 optional => 1,
529 maxLength => 255,
530 completion => \&PVE::QemuServer::complete_backup_archives,
531 },
532 storage => get_standard_option('pve-storage-id', {
533 description => "Default storage.",
534 optional => 1,
535 completion => \&PVE::QemuServer::complete_storage,
536 }),
537 force => {
538 optional => 1,
539 type => 'boolean',
540 description => "Allow to overwrite existing VM.",
541 requires => 'archive',
542 },
543 unique => {
544 optional => 1,
545 type => 'boolean',
546 description => "Assign a unique random ethernet address.",
547 requires => 'archive',
548 },
549 'live-restore' => {
550 optional => 1,
551 type => 'boolean',
552 description => "Start the VM immediately from the backup and restore in background. PBS only.",
553 requires => 'archive',
554 },
555 pool => {
556 optional => 1,
557 type => 'string', format => 'pve-poolid',
558 description => "Add the VM to the specified pool.",
559 },
560 bwlimit => {
561 description => "Override I/O bandwidth limit (in KiB/s).",
562 optional => 1,
563 type => 'integer',
564 minimum => '0',
565 default => 'restore limit from datacenter or storage config',
566 },
567 start => {
568 optional => 1,
569 type => 'boolean',
570 default => 0,
571 description => "Start VM after it was created successfully.",
572 },
573 }),
574 },
575 returns => {
576 type => 'string',
577 },
578 code => sub {
579 my ($param) = @_;
580
581 my $rpcenv = PVE::RPCEnvironment::get();
582 my $authuser = $rpcenv->get_user();
583
584 my $node = extract_param($param, 'node');
585 my $vmid = extract_param($param, 'vmid');
586
587 my $archive = extract_param($param, 'archive');
588 my $is_restore = !!$archive;
589
590 my $bwlimit = extract_param($param, 'bwlimit');
591 my $force = extract_param($param, 'force');
592 my $pool = extract_param($param, 'pool');
593 my $start_after_create = extract_param($param, 'start');
594 my $storage = extract_param($param, 'storage');
595 my $unique = extract_param($param, 'unique');
596 my $live_restore = extract_param($param, 'live-restore');
597
598 if (defined(my $ssh_keys = $param->{sshkeys})) {
599 $ssh_keys = URI::Escape::uri_unescape($ssh_keys);
600 PVE::Tools::validate_ssh_public_keys($ssh_keys);
601 }
602
603 PVE::Cluster::check_cfs_quorum();
604
605 my $filename = PVE::QemuConfig->config_file($vmid);
606 my $storecfg = PVE::Storage::config();
607
608 if (defined($pool)) {
609 $rpcenv->check_pool_exist($pool);
610 }
611
612 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace'])
613 if defined($storage);
614
615 if ($rpcenv->check($authuser, "/vms/$vmid", ['VM.Allocate'], 1)) {
616 # OK
617 } elsif ($pool && $rpcenv->check($authuser, "/pool/$pool", ['VM.Allocate'], 1)) {
618 # OK
619 } elsif ($archive && $force && (-f $filename) &&
620 $rpcenv->check($authuser, "/vms/$vmid", ['VM.Backup'], 1)) {
621 # OK: user has VM.Backup permissions, and want to restore an existing VM
622 } else {
623 raise_perm_exc();
624 }
625
626 if (!$archive) {
627 &$resolve_cdrom_alias($param);
628
629 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param, $storage);
630
631 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
632
633 &$check_vm_create_serial_perm($rpcenv, $authuser, $vmid, $pool, $param);
634 &$check_vm_create_usb_perm($rpcenv, $authuser, $vmid, $pool, $param);
635
636 &$check_cpu_model_access($rpcenv, $authuser, $param);
637
638 foreach my $opt (keys %$param) {
639 if (PVE::QemuServer::is_valid_drivename($opt)) {
640 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
641 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
642
643 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
644 $param->{$opt} = PVE::QemuServer::print_drive($drive);
645 }
646 }
647
648 PVE::QemuServer::add_random_macs($param);
649 } else {
650 my $keystr = join(' ', keys %$param);
651 raise_param_exc({ archive => "option conflicts with other options ($keystr)"}) if $keystr;
652
653 if ($archive eq '-') {
654 die "pipe requires cli environment\n" if $rpcenv->{type} ne 'cli';
655 $archive = { type => 'pipe' };
656 } else {
657 PVE::Storage::check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $archive);
658
659 $archive = $parse_restore_archive->($storecfg, $archive);
660 }
661 }
662
663 my $emsg = $is_restore ? "unable to restore VM $vmid -" : "unable to create VM $vmid -";
664
665 eval { PVE::QemuConfig->create_and_lock_config($vmid, $force) };
666 die "$emsg $@" if $@;
667
668 my $restored_data = 0;
669 my $restorefn = sub {
670 my $conf = PVE::QemuConfig->load_config($vmid);
671
672 PVE::QemuConfig->check_protection($conf, $emsg);
673
674 die "$emsg vm is running\n" if PVE::QemuServer::check_running($vmid);
675
676 my $realcmd = sub {
677 my $restore_options = {
678 storage => $storage,
679 pool => $pool,
680 unique => $unique,
681 bwlimit => $bwlimit,
682 live => $live_restore,
683 };
684 if ($archive->{type} eq 'file' || $archive->{type} eq 'pipe') {
685 die "live-restore is only compatible with backup images from a Proxmox Backup Server\n"
686 if $live_restore;
687 PVE::QemuServer::restore_file_archive($archive->{path} // '-', $vmid, $authuser, $restore_options);
688 } elsif ($archive->{type} eq 'pbs') {
689 PVE::QemuServer::restore_proxmox_backup_archive($archive->{volid}, $vmid, $authuser, $restore_options);
690 } else {
691 die "unknown backup archive type\n";
692 }
693 $restored_data = 1;
694
695 my $restored_conf = PVE::QemuConfig->load_config($vmid);
696 # Convert restored VM to template if backup was VM template
697 if (PVE::QemuConfig->is_template($restored_conf)) {
698 warn "Convert to template.\n";
699 eval { PVE::QemuServer::template_create($vmid, $restored_conf) };
700 warn $@ if $@;
701 }
702 };
703
704 # ensure no old replication state are exists
705 PVE::ReplicationState::delete_guest_states($vmid);
706
707 PVE::QemuConfig->lock_config_full($vmid, 1, $realcmd);
708
709 if ($start_after_create && !$live_restore) {
710 print "Execute autostart\n";
711 eval { PVE::API2::Qemu->vm_start({ vmid => $vmid, node => $node }) };
712 warn $@ if $@;
713 }
714 };
715
716 my $createfn = sub {
717 # ensure no old replication state are exists
718 PVE::ReplicationState::delete_guest_states($vmid);
719
720 my $realcmd = sub {
721 my $conf = $param;
722 my $arch = PVE::QemuServer::get_vm_arch($conf);
723
724 $conf->{meta} = PVE::QemuServer::new_meta_info_string();
725
726 my $vollist = [];
727 eval {
728 $vollist = &$create_disks($rpcenv, $authuser, $conf, $arch, $storecfg, $vmid, $pool, $param, $storage);
729
730 if (!$conf->{boot}) {
731 my $devs = PVE::QemuServer::get_default_bootdevices($conf);
732 $conf->{boot} = PVE::QemuServer::print_bootorder($devs);
733 }
734
735 # auto generate uuid if user did not specify smbios1 option
736 if (!$conf->{smbios1}) {
737 $conf->{smbios1} = PVE::QemuServer::generate_smbios1_uuid();
738 }
739
740 if ((!defined($conf->{vmgenid}) || $conf->{vmgenid} eq '1') && $arch ne 'aarch64') {
741 $conf->{vmgenid} = PVE::QemuServer::generate_uuid();
742 }
743
744 my $machine = $conf->{machine};
745 if (!$machine || $machine =~ m/^(?:pc|q35|virt)$/) {
746 # always pin Windows' machine version on create, they get to easily confused
747 if (PVE::QemuServer::windows_version($conf->{ostype})) {
748 $conf->{machine} = PVE::QemuServer::windows_get_pinned_machine_version($machine);
749 }
750 }
751
752 PVE::QemuConfig->write_config($vmid, $conf);
753
754 };
755 my $err = $@;
756
757 if ($err) {
758 foreach my $volid (@$vollist) {
759 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
760 warn $@ if $@;
761 }
762 die "$emsg $err";
763 }
764
765 PVE::AccessControl::add_vm_to_pool($vmid, $pool) if $pool;
766 };
767
768 PVE::QemuConfig->lock_config_full($vmid, 1, $realcmd);
769
770 if ($start_after_create) {
771 print "Execute autostart\n";
772 eval { PVE::API2::Qemu->vm_start({vmid => $vmid, node => $node}) };
773 warn $@ if $@;
774 }
775 };
776
777 my ($code, $worker_name);
778 if ($is_restore) {
779 $worker_name = 'qmrestore';
780 $code = sub {
781 eval { $restorefn->() };
782 if (my $err = $@) {
783 eval { PVE::QemuConfig->remove_lock($vmid, 'create') };
784 warn $@ if $@;
785 if ($restored_data) {
786 warn "error after data was restored, VM disks should be OK but config may "
787 ."require adaptions. VM $vmid state is NOT cleaned up.\n";
788 } else {
789 warn "error before or during data restore, some or all disks were not "
790 ."completely restored. VM $vmid state is NOT cleaned up.\n";
791 }
792 die $err;
793 }
794 };
795 } else {
796 $worker_name = 'qmcreate';
797 $code = sub {
798 eval { $createfn->() };
799 if (my $err = $@) {
800 eval {
801 my $conffile = PVE::QemuConfig->config_file($vmid);
802 unlink($conffile) or die "failed to remove config file: $!\n";
803 };
804 warn $@ if $@;
805 die $err;
806 }
807 };
808 }
809
810 return $rpcenv->fork_worker($worker_name, $vmid, $authuser, $code);
811 }});
812
813 __PACKAGE__->register_method({
814 name => 'vmdiridx',
815 path => '{vmid}',
816 method => 'GET',
817 proxyto => 'node',
818 description => "Directory index",
819 permissions => {
820 user => 'all',
821 },
822 parameters => {
823 additionalProperties => 0,
824 properties => {
825 node => get_standard_option('pve-node'),
826 vmid => get_standard_option('pve-vmid'),
827 },
828 },
829 returns => {
830 type => 'array',
831 items => {
832 type => "object",
833 properties => {
834 subdir => { type => 'string' },
835 },
836 },
837 links => [ { rel => 'child', href => "{subdir}" } ],
838 },
839 code => sub {
840 my ($param) = @_;
841
842 my $res = [
843 { subdir => 'config' },
844 { subdir => 'pending' },
845 { subdir => 'status' },
846 { subdir => 'unlink' },
847 { subdir => 'vncproxy' },
848 { subdir => 'termproxy' },
849 { subdir => 'migrate' },
850 { subdir => 'resize' },
851 { subdir => 'move' },
852 { subdir => 'rrd' },
853 { subdir => 'rrddata' },
854 { subdir => 'monitor' },
855 { subdir => 'agent' },
856 { subdir => 'snapshot' },
857 { subdir => 'spiceproxy' },
858 { subdir => 'sendkey' },
859 { subdir => 'firewall' },
860 ];
861
862 return $res;
863 }});
864
865 __PACKAGE__->register_method ({
866 subclass => "PVE::API2::Firewall::VM",
867 path => '{vmid}/firewall',
868 });
869
870 __PACKAGE__->register_method ({
871 subclass => "PVE::API2::Qemu::Agent",
872 path => '{vmid}/agent',
873 });
874
875 __PACKAGE__->register_method({
876 name => 'rrd',
877 path => '{vmid}/rrd',
878 method => 'GET',
879 protected => 1, # fixme: can we avoid that?
880 permissions => {
881 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
882 },
883 description => "Read VM RRD statistics (returns PNG)",
884 parameters => {
885 additionalProperties => 0,
886 properties => {
887 node => get_standard_option('pve-node'),
888 vmid => get_standard_option('pve-vmid'),
889 timeframe => {
890 description => "Specify the time frame you are interested in.",
891 type => 'string',
892 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
893 },
894 ds => {
895 description => "The list of datasources you want to display.",
896 type => 'string', format => 'pve-configid-list',
897 },
898 cf => {
899 description => "The RRD consolidation function",
900 type => 'string',
901 enum => [ 'AVERAGE', 'MAX' ],
902 optional => 1,
903 },
904 },
905 },
906 returns => {
907 type => "object",
908 properties => {
909 filename => { type => 'string' },
910 },
911 },
912 code => sub {
913 my ($param) = @_;
914
915 return PVE::RRD::create_rrd_graph(
916 "pve2-vm/$param->{vmid}", $param->{timeframe},
917 $param->{ds}, $param->{cf});
918
919 }});
920
921 __PACKAGE__->register_method({
922 name => 'rrddata',
923 path => '{vmid}/rrddata',
924 method => 'GET',
925 protected => 1, # fixme: can we avoid that?
926 permissions => {
927 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
928 },
929 description => "Read VM RRD statistics",
930 parameters => {
931 additionalProperties => 0,
932 properties => {
933 node => get_standard_option('pve-node'),
934 vmid => get_standard_option('pve-vmid'),
935 timeframe => {
936 description => "Specify the time frame you are interested in.",
937 type => 'string',
938 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
939 },
940 cf => {
941 description => "The RRD consolidation function",
942 type => 'string',
943 enum => [ 'AVERAGE', 'MAX' ],
944 optional => 1,
945 },
946 },
947 },
948 returns => {
949 type => "array",
950 items => {
951 type => "object",
952 properties => {},
953 },
954 },
955 code => sub {
956 my ($param) = @_;
957
958 return PVE::RRD::create_rrd_data(
959 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
960 }});
961
962
963 __PACKAGE__->register_method({
964 name => 'vm_config',
965 path => '{vmid}/config',
966 method => 'GET',
967 proxyto => 'node',
968 description => "Get the virtual machine configuration with pending configuration " .
969 "changes applied. Set the 'current' parameter to get the current configuration instead.",
970 permissions => {
971 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
972 },
973 parameters => {
974 additionalProperties => 0,
975 properties => {
976 node => get_standard_option('pve-node'),
977 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
978 current => {
979 description => "Get current values (instead of pending values).",
980 optional => 1,
981 default => 0,
982 type => 'boolean',
983 },
984 snapshot => get_standard_option('pve-snapshot-name', {
985 description => "Fetch config values from given snapshot.",
986 optional => 1,
987 completion => sub {
988 my ($cmd, $pname, $cur, $args) = @_;
989 PVE::QemuConfig->snapshot_list($args->[0]);
990 },
991 }),
992 },
993 },
994 returns => {
995 description => "The VM configuration.",
996 type => "object",
997 properties => PVE::QemuServer::json_config_properties({
998 digest => {
999 type => 'string',
1000 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
1001 }
1002 }),
1003 },
1004 code => sub {
1005 my ($param) = @_;
1006
1007 raise_param_exc({ snapshot => "cannot use 'snapshot' parameter with 'current'",
1008 current => "cannot use 'snapshot' parameter with 'current'"})
1009 if ($param->{snapshot} && $param->{current});
1010
1011 my $conf;
1012 if ($param->{snapshot}) {
1013 $conf = PVE::QemuConfig->load_snapshot_config($param->{vmid}, $param->{snapshot});
1014 } else {
1015 $conf = PVE::QemuConfig->load_current_config($param->{vmid}, $param->{current});
1016 }
1017 $conf->{cipassword} = '**********' if $conf->{cipassword};
1018 return $conf;
1019
1020 }});
1021
1022 __PACKAGE__->register_method({
1023 name => 'vm_pending',
1024 path => '{vmid}/pending',
1025 method => 'GET',
1026 proxyto => 'node',
1027 description => "Get the virtual machine configuration with both current and pending values.",
1028 permissions => {
1029 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1030 },
1031 parameters => {
1032 additionalProperties => 0,
1033 properties => {
1034 node => get_standard_option('pve-node'),
1035 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
1036 },
1037 },
1038 returns => {
1039 type => "array",
1040 items => {
1041 type => "object",
1042 properties => {
1043 key => {
1044 description => "Configuration option name.",
1045 type => 'string',
1046 },
1047 value => {
1048 description => "Current value.",
1049 type => 'string',
1050 optional => 1,
1051 },
1052 pending => {
1053 description => "Pending value.",
1054 type => 'string',
1055 optional => 1,
1056 },
1057 delete => {
1058 description => "Indicates a pending delete request if present and not 0. " .
1059 "The value 2 indicates a force-delete request.",
1060 type => 'integer',
1061 minimum => 0,
1062 maximum => 2,
1063 optional => 1,
1064 },
1065 },
1066 },
1067 },
1068 code => sub {
1069 my ($param) = @_;
1070
1071 my $conf = PVE::QemuConfig->load_config($param->{vmid});
1072
1073 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
1074
1075 $conf->{cipassword} = '**********' if defined($conf->{cipassword});
1076 $conf->{pending}->{cipassword} = '********** ' if defined($conf->{pending}->{cipassword});
1077
1078 return PVE::GuestHelpers::config_with_pending_array($conf, $pending_delete_hash);
1079 }});
1080
1081 # POST/PUT {vmid}/config implementation
1082 #
1083 # The original API used PUT (idempotent) an we assumed that all operations
1084 # are fast. But it turned out that almost any configuration change can
1085 # involve hot-plug actions, or disk alloc/free. Such actions can take long
1086 # time to complete and have side effects (not idempotent).
1087 #
1088 # The new implementation uses POST and forks a worker process. We added
1089 # a new option 'background_delay'. If specified we wait up to
1090 # 'background_delay' second for the worker task to complete. It returns null
1091 # if the task is finished within that time, else we return the UPID.
1092
1093 my $update_vm_api = sub {
1094 my ($param, $sync) = @_;
1095
1096 my $rpcenv = PVE::RPCEnvironment::get();
1097
1098 my $authuser = $rpcenv->get_user();
1099
1100 my $node = extract_param($param, 'node');
1101
1102 my $vmid = extract_param($param, 'vmid');
1103
1104 my $digest = extract_param($param, 'digest');
1105
1106 my $background_delay = extract_param($param, 'background_delay');
1107
1108 if (defined(my $cipassword = $param->{cipassword})) {
1109 # Same logic as in cloud-init (but with the regex fixed...)
1110 $param->{cipassword} = PVE::Tools::encrypt_pw($cipassword)
1111 if $cipassword !~ /^\$(?:[156]|2[ay])(\$.+){2}/;
1112 }
1113
1114 my @paramarr = (); # used for log message
1115 foreach my $key (sort keys %$param) {
1116 my $value = $key eq 'cipassword' ? '<hidden>' : $param->{$key};
1117 push @paramarr, "-$key", $value;
1118 }
1119
1120 my $skiplock = extract_param($param, 'skiplock');
1121 raise_param_exc({ skiplock => "Only root may use this option." })
1122 if $skiplock && $authuser ne 'root@pam';
1123
1124 my $delete_str = extract_param($param, 'delete');
1125
1126 my $revert_str = extract_param($param, 'revert');
1127
1128 my $force = extract_param($param, 'force');
1129
1130 if (defined(my $ssh_keys = $param->{sshkeys})) {
1131 $ssh_keys = URI::Escape::uri_unescape($ssh_keys);
1132 PVE::Tools::validate_ssh_public_keys($ssh_keys);
1133 }
1134
1135 die "no options specified\n" if !$delete_str && !$revert_str && !scalar(keys %$param);
1136
1137 my $storecfg = PVE::Storage::config();
1138
1139 my $defaults = PVE::QemuServer::load_defaults();
1140
1141 &$resolve_cdrom_alias($param);
1142
1143 # now try to verify all parameters
1144
1145 my $revert = {};
1146 foreach my $opt (PVE::Tools::split_list($revert_str)) {
1147 if (!PVE::QemuServer::option_exists($opt)) {
1148 raise_param_exc({ revert => "unknown option '$opt'" });
1149 }
1150
1151 raise_param_exc({ delete => "you can't use '-$opt' and " .
1152 "-revert $opt' at the same time" })
1153 if defined($param->{$opt});
1154
1155 $revert->{$opt} = 1;
1156 }
1157
1158 my @delete = ();
1159 foreach my $opt (PVE::Tools::split_list($delete_str)) {
1160 $opt = 'ide2' if $opt eq 'cdrom';
1161
1162 raise_param_exc({ delete => "you can't use '-$opt' and " .
1163 "-delete $opt' at the same time" })
1164 if defined($param->{$opt});
1165
1166 raise_param_exc({ revert => "you can't use '-delete $opt' and " .
1167 "-revert $opt' at the same time" })
1168 if $revert->{$opt};
1169
1170 if (!PVE::QemuServer::option_exists($opt)) {
1171 raise_param_exc({ delete => "unknown option '$opt'" });
1172 }
1173
1174 push @delete, $opt;
1175 }
1176
1177 my $repl_conf = PVE::ReplicationConfig->new();
1178 my $is_replicated = $repl_conf->check_for_existing_jobs($vmid, 1);
1179 my $check_replication = sub {
1180 my ($drive) = @_;
1181 return if !$is_replicated;
1182 my $volid = $drive->{file};
1183 return if !$volid || !($drive->{replicate}//1);
1184 return if PVE::QemuServer::drive_is_cdrom($drive);
1185
1186 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1187 die "cannot add non-managed/pass-through volume to a replicated VM\n"
1188 if !defined($storeid);
1189
1190 return if defined($volname) && $volname eq 'cloudinit';
1191
1192 my $format;
1193 if ($volid =~ $NEW_DISK_RE) {
1194 $storeid = $2;
1195 $format = $drive->{format} || PVE::Storage::storage_default_format($storecfg, $storeid);
1196 } else {
1197 $format = (PVE::Storage::parse_volname($storecfg, $volid))[6];
1198 }
1199 return if PVE::Storage::storage_can_replicate($storecfg, $storeid, $format);
1200 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
1201 return if $scfg->{shared};
1202 die "cannot add non-replicatable volume to a replicated VM\n";
1203 };
1204
1205 foreach my $opt (keys %$param) {
1206 if (PVE::QemuServer::is_valid_drivename($opt)) {
1207 # cleanup drive path
1208 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
1209 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
1210 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
1211 $check_replication->($drive);
1212 $param->{$opt} = PVE::QemuServer::print_drive($drive);
1213 } elsif ($opt =~ m/^net(\d+)$/) {
1214 # add macaddr
1215 my $net = PVE::QemuServer::parse_net($param->{$opt});
1216 $param->{$opt} = PVE::QemuServer::print_net($net);
1217 } elsif ($opt eq 'vmgenid') {
1218 if ($param->{$opt} eq '1') {
1219 $param->{$opt} = PVE::QemuServer::generate_uuid();
1220 }
1221 } elsif ($opt eq 'hookscript') {
1222 eval { PVE::GuestHelpers::check_hookscript($param->{$opt}, $storecfg); };
1223 raise_param_exc({ $opt => $@ }) if $@;
1224 }
1225 }
1226
1227 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
1228
1229 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
1230
1231 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1232
1233 my $updatefn = sub {
1234
1235 my $conf = PVE::QemuConfig->load_config($vmid);
1236
1237 die "checksum missmatch (file change by other user?)\n"
1238 if $digest && $digest ne $conf->{digest};
1239
1240 &$check_cpu_model_access($rpcenv, $authuser, $param, $conf);
1241
1242 # FIXME: 'suspended' lock should probabyl be a state or "weak" lock?!
1243 if (scalar(@delete) && grep { $_ eq 'vmstate'} @delete) {
1244 if (defined($conf->{lock}) && $conf->{lock} eq 'suspended') {
1245 delete $conf->{lock}; # for check lock check, not written out
1246 push @delete, 'lock'; # this is the real deal to write it out
1247 }
1248 push @delete, 'runningmachine' if $conf->{runningmachine};
1249 push @delete, 'runningcpu' if $conf->{runningcpu};
1250 }
1251
1252 PVE::QemuConfig->check_lock($conf) if !$skiplock;
1253
1254 foreach my $opt (keys %$revert) {
1255 if (defined($conf->{$opt})) {
1256 $param->{$opt} = $conf->{$opt};
1257 } elsif (defined($conf->{pending}->{$opt})) {
1258 push @delete, $opt;
1259 }
1260 }
1261
1262 if ($param->{memory} || defined($param->{balloon})) {
1263 my $maxmem = $param->{memory} || $conf->{pending}->{memory} || $conf->{memory} || $defaults->{memory};
1264 my $balloon = defined($param->{balloon}) ? $param->{balloon} : $conf->{pending}->{balloon} || $conf->{balloon};
1265
1266 die "balloon value too large (must be smaller than assigned memory)\n"
1267 if $balloon && $balloon > $maxmem;
1268 }
1269
1270 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
1271
1272 my $worker = sub {
1273
1274 print "update VM $vmid: " . join (' ', @paramarr) . "\n";
1275
1276 # write updates to pending section
1277
1278 my $modified = {}; # record what $option we modify
1279
1280 my @bootorder;
1281 if (my $boot = $conf->{boot}) {
1282 my $bootcfg = PVE::JSONSchema::parse_property_string('pve-qm-boot', $boot);
1283 @bootorder = PVE::Tools::split_list($bootcfg->{order}) if $bootcfg && $bootcfg->{order};
1284 }
1285 my $bootorder_deleted = grep {$_ eq 'bootorder'} @delete;
1286
1287 my $check_drive_perms = sub {
1288 my ($opt, $val) = @_;
1289 my $drive = PVE::QemuServer::parse_drive($opt, $val);
1290 # FIXME: cloudinit: CDROM or Disk?
1291 if (PVE::QemuServer::drive_is_cdrom($drive)) { # CDROM
1292 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
1293 } else {
1294 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
1295 }
1296 };
1297
1298 foreach my $opt (@delete) {
1299 $modified->{$opt} = 1;
1300 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
1301
1302 # value of what we want to delete, independent if pending or not
1303 my $val = $conf->{$opt} // $conf->{pending}->{$opt};
1304 if (!defined($val)) {
1305 warn "cannot delete '$opt' - not set in current configuration!\n";
1306 $modified->{$opt} = 0;
1307 next;
1308 }
1309 my $is_pending_val = defined($conf->{pending}->{$opt});
1310 delete $conf->{pending}->{$opt};
1311
1312 # remove from bootorder if necessary
1313 if (!$bootorder_deleted && @bootorder && grep {$_ eq $opt} @bootorder) {
1314 @bootorder = grep {$_ ne $opt} @bootorder;
1315 $conf->{pending}->{boot} = PVE::QemuServer::print_bootorder(\@bootorder);
1316 $modified->{boot} = 1;
1317 }
1318
1319 if ($opt =~ m/^unused/) {
1320 my $drive = PVE::QemuServer::parse_drive($opt, $val);
1321 PVE::QemuConfig->check_protection($conf, "can't remove unused disk '$drive->{file}'");
1322 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
1323 if (PVE::QemuServer::try_deallocate_drive($storecfg, $vmid, $conf, $opt, $drive, $rpcenv, $authuser)) {
1324 delete $conf->{$opt};
1325 PVE::QemuConfig->write_config($vmid, $conf);
1326 }
1327 } elsif ($opt eq 'vmstate') {
1328 PVE::QemuConfig->check_protection($conf, "can't remove vmstate '$val'");
1329 if (PVE::QemuServer::try_deallocate_drive($storecfg, $vmid, $conf, $opt, { file => $val }, $rpcenv, $authuser, 1)) {
1330 delete $conf->{$opt};
1331 PVE::QemuConfig->write_config($vmid, $conf);
1332 }
1333 } elsif (PVE::QemuServer::is_valid_drivename($opt)) {
1334 PVE::QemuConfig->check_protection($conf, "can't remove drive '$opt'");
1335 $check_drive_perms->($opt, $val);
1336 PVE::QemuServer::vmconfig_register_unused_drive($storecfg, $vmid, $conf, PVE::QemuServer::parse_drive($opt, $val))
1337 if $is_pending_val;
1338 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1339 PVE::QemuConfig->write_config($vmid, $conf);
1340 } elsif ($opt =~ m/^serial\d+$/) {
1341 if ($val eq 'socket') {
1342 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.HWType']);
1343 } elsif ($authuser ne 'root@pam') {
1344 die "only root can delete '$opt' config for real devices\n";
1345 }
1346 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1347 PVE::QemuConfig->write_config($vmid, $conf);
1348 } elsif ($opt =~ m/^usb\d+$/) {
1349 if ($val =~ m/spice/) {
1350 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.HWType']);
1351 } elsif ($authuser ne 'root@pam') {
1352 die "only root can delete '$opt' config for real devices\n";
1353 }
1354 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1355 PVE::QemuConfig->write_config($vmid, $conf);
1356 } else {
1357 PVE::QemuConfig->add_to_pending_delete($conf, $opt, $force);
1358 PVE::QemuConfig->write_config($vmid, $conf);
1359 }
1360 }
1361
1362 foreach my $opt (keys %$param) { # add/change
1363 $modified->{$opt} = 1;
1364 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
1365 next if defined($conf->{pending}->{$opt}) && ($param->{$opt} eq $conf->{pending}->{$opt}); # skip if nothing changed
1366
1367 my $arch = PVE::QemuServer::get_vm_arch($conf);
1368
1369 if (PVE::QemuServer::is_valid_drivename($opt)) {
1370 # old drive
1371 if ($conf->{$opt}) {
1372 $check_drive_perms->($opt, $conf->{$opt});
1373 }
1374
1375 # new drive
1376 $check_drive_perms->($opt, $param->{$opt});
1377 PVE::QemuServer::vmconfig_register_unused_drive($storecfg, $vmid, $conf, PVE::QemuServer::parse_drive($opt, $conf->{pending}->{$opt}))
1378 if defined($conf->{pending}->{$opt});
1379
1380 &$create_disks($rpcenv, $authuser, $conf->{pending}, $arch, $storecfg, $vmid, undef, {$opt => $param->{$opt}});
1381
1382 # default legacy boot order implies all cdroms anyway
1383 if (@bootorder) {
1384 # append new CD drives to bootorder to mark them bootable
1385 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
1386 if (PVE::QemuServer::drive_is_cdrom($drive, 1) && !grep(/^$opt$/, @bootorder)) {
1387 push @bootorder, $opt;
1388 $conf->{pending}->{boot} = PVE::QemuServer::print_bootorder(\@bootorder);
1389 $modified->{boot} = 1;
1390 }
1391 }
1392 } elsif ($opt =~ m/^serial\d+/) {
1393 if ((!defined($conf->{$opt}) || $conf->{$opt} eq 'socket') && $param->{$opt} eq 'socket') {
1394 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.HWType']);
1395 } elsif ($authuser ne 'root@pam') {
1396 die "only root can modify '$opt' config for real devices\n";
1397 }
1398 $conf->{pending}->{$opt} = $param->{$opt};
1399 } elsif ($opt =~ m/^usb\d+/) {
1400 if ((!defined($conf->{$opt}) || $conf->{$opt} =~ m/spice/) && $param->{$opt} =~ m/spice/) {
1401 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.HWType']);
1402 } elsif ($authuser ne 'root@pam') {
1403 die "only root can modify '$opt' config for real devices\n";
1404 }
1405 $conf->{pending}->{$opt} = $param->{$opt};
1406 } else {
1407 $conf->{pending}->{$opt} = $param->{$opt};
1408
1409 if ($opt eq 'boot') {
1410 my $new_bootcfg = PVE::JSONSchema::parse_property_string('pve-qm-boot', $param->{$opt});
1411 if ($new_bootcfg->{order}) {
1412 my @devs = PVE::Tools::split_list($new_bootcfg->{order});
1413 for my $dev (@devs) {
1414 my $exists = $conf->{$dev} || $conf->{pending}->{$dev};
1415 my $deleted = grep {$_ eq $dev} @delete;
1416 die "invalid bootorder: device '$dev' does not exist'\n"
1417 if !$exists || $deleted;
1418 }
1419
1420 # remove legacy boot order settings if new one set
1421 $conf->{pending}->{$opt} = PVE::QemuServer::print_bootorder(\@devs);
1422 PVE::QemuConfig->add_to_pending_delete($conf, "bootdisk")
1423 if $conf->{bootdisk};
1424 }
1425 }
1426 }
1427 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
1428 PVE::QemuConfig->write_config($vmid, $conf);
1429 }
1430
1431 # remove pending changes when nothing changed
1432 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
1433 my $changes = PVE::QemuConfig->cleanup_pending($conf);
1434 PVE::QemuConfig->write_config($vmid, $conf) if $changes;
1435
1436 return if !scalar(keys %{$conf->{pending}});
1437
1438 my $running = PVE::QemuServer::check_running($vmid);
1439
1440 # apply pending changes
1441
1442 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
1443
1444 my $errors = {};
1445 if ($running) {
1446 PVE::QemuServer::vmconfig_hotplug_pending($vmid, $conf, $storecfg, $modified, $errors);
1447 } else {
1448 PVE::QemuServer::vmconfig_apply_pending($vmid, $conf, $storecfg, $errors);
1449 }
1450 raise_param_exc($errors) if scalar(keys %$errors);
1451
1452 return;
1453 };
1454
1455 if ($sync) {
1456 &$worker();
1457 return;
1458 } else {
1459 my $upid = $rpcenv->fork_worker('qmconfig', $vmid, $authuser, $worker);
1460
1461 if ($background_delay) {
1462
1463 # Note: It would be better to do that in the Event based HTTPServer
1464 # to avoid blocking call to sleep.
1465
1466 my $end_time = time() + $background_delay;
1467
1468 my $task = PVE::Tools::upid_decode($upid);
1469
1470 my $running = 1;
1471 while (time() < $end_time) {
1472 $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
1473 last if !$running;
1474 sleep(1); # this gets interrupted when child process ends
1475 }
1476
1477 if (!$running) {
1478 my $status = PVE::Tools::upid_read_status($upid);
1479 return if !PVE::Tools::upid_status_is_error($status);
1480 die "failed to update VM $vmid: $status\n";
1481 }
1482 }
1483
1484 return $upid;
1485 }
1486 };
1487
1488 return PVE::QemuConfig->lock_config($vmid, $updatefn);
1489 };
1490
1491 my $vm_config_perm_list = [
1492 'VM.Config.Disk',
1493 'VM.Config.CDROM',
1494 'VM.Config.CPU',
1495 'VM.Config.Memory',
1496 'VM.Config.Network',
1497 'VM.Config.HWType',
1498 'VM.Config.Options',
1499 'VM.Config.Cloudinit',
1500 ];
1501
1502 __PACKAGE__->register_method({
1503 name => 'update_vm_async',
1504 path => '{vmid}/config',
1505 method => 'POST',
1506 protected => 1,
1507 proxyto => 'node',
1508 description => "Set virtual machine options (asynchrounous API).",
1509 permissions => {
1510 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
1511 },
1512 parameters => {
1513 additionalProperties => 0,
1514 properties => PVE::QemuServer::json_config_properties(
1515 {
1516 node => get_standard_option('pve-node'),
1517 vmid => get_standard_option('pve-vmid'),
1518 skiplock => get_standard_option('skiplock'),
1519 delete => {
1520 type => 'string', format => 'pve-configid-list',
1521 description => "A list of settings you want to delete.",
1522 optional => 1,
1523 },
1524 revert => {
1525 type => 'string', format => 'pve-configid-list',
1526 description => "Revert a pending change.",
1527 optional => 1,
1528 },
1529 force => {
1530 type => 'boolean',
1531 description => $opt_force_description,
1532 optional => 1,
1533 requires => 'delete',
1534 },
1535 digest => {
1536 type => 'string',
1537 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1538 maxLength => 40,
1539 optional => 1,
1540 },
1541 background_delay => {
1542 type => 'integer',
1543 description => "Time to wait for the task to finish. We return 'null' if the task finish within that time.",
1544 minimum => 1,
1545 maximum => 30,
1546 optional => 1,
1547 },
1548 }),
1549 },
1550 returns => {
1551 type => 'string',
1552 optional => 1,
1553 },
1554 code => $update_vm_api,
1555 });
1556
1557 __PACKAGE__->register_method({
1558 name => 'update_vm',
1559 path => '{vmid}/config',
1560 method => 'PUT',
1561 protected => 1,
1562 proxyto => 'node',
1563 description => "Set virtual machine options (synchrounous API) - You should consider using the POST method instead for any actions involving hotplug or storage allocation.",
1564 permissions => {
1565 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
1566 },
1567 parameters => {
1568 additionalProperties => 0,
1569 properties => PVE::QemuServer::json_config_properties(
1570 {
1571 node => get_standard_option('pve-node'),
1572 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
1573 skiplock => get_standard_option('skiplock'),
1574 delete => {
1575 type => 'string', format => 'pve-configid-list',
1576 description => "A list of settings you want to delete.",
1577 optional => 1,
1578 },
1579 revert => {
1580 type => 'string', format => 'pve-configid-list',
1581 description => "Revert a pending change.",
1582 optional => 1,
1583 },
1584 force => {
1585 type => 'boolean',
1586 description => $opt_force_description,
1587 optional => 1,
1588 requires => 'delete',
1589 },
1590 digest => {
1591 type => 'string',
1592 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1593 maxLength => 40,
1594 optional => 1,
1595 },
1596 }),
1597 },
1598 returns => { type => 'null' },
1599 code => sub {
1600 my ($param) = @_;
1601 &$update_vm_api($param, 1);
1602 return;
1603 }
1604 });
1605
1606 __PACKAGE__->register_method({
1607 name => 'destroy_vm',
1608 path => '{vmid}',
1609 method => 'DELETE',
1610 protected => 1,
1611 proxyto => 'node',
1612 description => "Destroy the VM and all used/owned volumes. Removes any VM specific permissions"
1613 ." and firewall rules",
1614 permissions => {
1615 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
1616 },
1617 parameters => {
1618 additionalProperties => 0,
1619 properties => {
1620 node => get_standard_option('pve-node'),
1621 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_stopped }),
1622 skiplock => get_standard_option('skiplock'),
1623 purge => {
1624 type => 'boolean',
1625 description => "Remove VMID from configurations, like backup & replication jobs and HA.",
1626 optional => 1,
1627 },
1628 'destroy-unreferenced-disks' => {
1629 type => 'boolean',
1630 description => "If set, destroy additionally all disks not referenced in the config"
1631 ." but with a matching VMID from all enabled storages.",
1632 optional => 1,
1633 default => 0,
1634 },
1635 },
1636 },
1637 returns => {
1638 type => 'string',
1639 },
1640 code => sub {
1641 my ($param) = @_;
1642
1643 my $rpcenv = PVE::RPCEnvironment::get();
1644 my $authuser = $rpcenv->get_user();
1645 my $vmid = $param->{vmid};
1646
1647 my $skiplock = $param->{skiplock};
1648 raise_param_exc({ skiplock => "Only root may use this option." })
1649 if $skiplock && $authuser ne 'root@pam';
1650
1651 my $early_checks = sub {
1652 # test if VM exists
1653 my $conf = PVE::QemuConfig->load_config($vmid);
1654 PVE::QemuConfig->check_protection($conf, "can't remove VM $vmid");
1655
1656 my $ha_managed = PVE::HA::Config::service_is_configured("vm:$vmid");
1657
1658 if (!$param->{purge}) {
1659 die "unable to remove VM $vmid - used in HA resources and purge parameter not set.\n"
1660 if $ha_managed;
1661 # don't allow destroy if with replication jobs but no purge param
1662 my $repl_conf = PVE::ReplicationConfig->new();
1663 $repl_conf->check_for_existing_jobs($vmid);
1664 }
1665
1666 die "VM $vmid is running - destroy failed\n"
1667 if PVE::QemuServer::check_running($vmid);
1668
1669 return $ha_managed;
1670 };
1671
1672 $early_checks->();
1673
1674 my $realcmd = sub {
1675 my $upid = shift;
1676
1677 my $storecfg = PVE::Storage::config();
1678
1679 syslog('info', "destroy VM $vmid: $upid\n");
1680 PVE::QemuConfig->lock_config($vmid, sub {
1681 # repeat, config might have changed
1682 my $ha_managed = $early_checks->();
1683
1684 my $purge_unreferenced = $param->{'destroy-unreferenced-disks'};
1685
1686 PVE::QemuServer::destroy_vm(
1687 $storecfg,
1688 $vmid,
1689 $skiplock, { lock => 'destroyed' },
1690 $purge_unreferenced,
1691 );
1692
1693 PVE::AccessControl::remove_vm_access($vmid);
1694 PVE::Firewall::remove_vmfw_conf($vmid);
1695 if ($param->{purge}) {
1696 print "purging VM $vmid from related configurations..\n";
1697 PVE::ReplicationConfig::remove_vmid_jobs($vmid);
1698 PVE::VZDump::Plugin::remove_vmid_from_backup_jobs($vmid);
1699
1700 if ($ha_managed) {
1701 PVE::HA::Config::delete_service_from_config("vm:$vmid");
1702 print "NOTE: removed VM $vmid from HA resource configuration.\n";
1703 }
1704 }
1705
1706 # only now remove the zombie config, else we can have reuse race
1707 PVE::QemuConfig->destroy_config($vmid);
1708 });
1709 };
1710
1711 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1712 }});
1713
1714 __PACKAGE__->register_method({
1715 name => 'unlink',
1716 path => '{vmid}/unlink',
1717 method => 'PUT',
1718 protected => 1,
1719 proxyto => 'node',
1720 description => "Unlink/delete disk images.",
1721 permissions => {
1722 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
1723 },
1724 parameters => {
1725 additionalProperties => 0,
1726 properties => {
1727 node => get_standard_option('pve-node'),
1728 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
1729 idlist => {
1730 type => 'string', format => 'pve-configid-list',
1731 description => "A list of disk IDs you want to delete.",
1732 },
1733 force => {
1734 type => 'boolean',
1735 description => $opt_force_description,
1736 optional => 1,
1737 },
1738 },
1739 },
1740 returns => { type => 'null'},
1741 code => sub {
1742 my ($param) = @_;
1743
1744 $param->{delete} = extract_param($param, 'idlist');
1745
1746 __PACKAGE__->update_vm($param);
1747
1748 return;
1749 }});
1750
1751 # uses good entropy, each char is limited to 6 bit to get printable chars simply
1752 my $gen_rand_chars = sub {
1753 my ($length) = @_;
1754
1755 die "invalid length $length" if $length < 1;
1756
1757 my $min = ord('!'); # first printable ascii
1758
1759 my $rand_bytes = Crypt::OpenSSL::Random::random_bytes($length);
1760 die "failed to generate random bytes!\n"
1761 if !$rand_bytes;
1762
1763 my $str = join('', map { chr((ord($_) & 0x3F) + $min) } split('', $rand_bytes));
1764
1765 return $str;
1766 };
1767
1768 my $sslcert;
1769
1770 __PACKAGE__->register_method({
1771 name => 'vncproxy',
1772 path => '{vmid}/vncproxy',
1773 method => 'POST',
1774 protected => 1,
1775 permissions => {
1776 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1777 },
1778 description => "Creates a TCP VNC proxy connections.",
1779 parameters => {
1780 additionalProperties => 0,
1781 properties => {
1782 node => get_standard_option('pve-node'),
1783 vmid => get_standard_option('pve-vmid'),
1784 websocket => {
1785 optional => 1,
1786 type => 'boolean',
1787 description => "starts websockify instead of vncproxy",
1788 },
1789 'generate-password' => {
1790 optional => 1,
1791 type => 'boolean',
1792 default => 0,
1793 description => "Generates a random password to be used as ticket instead of the API ticket.",
1794 },
1795 },
1796 },
1797 returns => {
1798 additionalProperties => 0,
1799 properties => {
1800 user => { type => 'string' },
1801 ticket => { type => 'string' },
1802 password => {
1803 optional => 1,
1804 description => "Returned if requested with 'generate-password' param."
1805 ." Consists of printable ASCII characters ('!' .. '~').",
1806 type => 'string',
1807 },
1808 cert => { type => 'string' },
1809 port => { type => 'integer' },
1810 upid => { type => 'string' },
1811 },
1812 },
1813 code => sub {
1814 my ($param) = @_;
1815
1816 my $rpcenv = PVE::RPCEnvironment::get();
1817
1818 my $authuser = $rpcenv->get_user();
1819
1820 my $vmid = $param->{vmid};
1821 my $node = $param->{node};
1822 my $websocket = $param->{websocket};
1823
1824 my $conf = PVE::QemuConfig->load_config($vmid, $node); # check if VM exists
1825
1826 my $serial;
1827 if ($conf->{vga}) {
1828 my $vga = PVE::QemuServer::parse_vga($conf->{vga});
1829 $serial = $vga->{type} if $vga->{type} =~ m/^serial\d+$/;
1830 }
1831
1832 my $authpath = "/vms/$vmid";
1833
1834 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
1835 my $password = $ticket;
1836 if ($param->{'generate-password'}) {
1837 $password = $gen_rand_chars->(8);
1838 }
1839
1840 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1841 if !$sslcert;
1842
1843 my $family;
1844 my $remcmd = [];
1845
1846 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1847 (undef, $family) = PVE::Cluster::remote_node_ip($node);
1848 my $sshinfo = PVE::SSHInfo::get_ssh_info($node);
1849 # NOTE: kvm VNC traffic is already TLS encrypted or is known unsecure
1850 $remcmd = PVE::SSHInfo::ssh_info_to_command($sshinfo, defined($serial) ? '-t' : '-T');
1851 } else {
1852 $family = PVE::Tools::get_host_address_family($node);
1853 }
1854
1855 my $port = PVE::Tools::next_vnc_port($family);
1856
1857 my $timeout = 10;
1858
1859 my $realcmd = sub {
1860 my $upid = shift;
1861
1862 syslog('info', "starting vnc proxy $upid\n");
1863
1864 my $cmd;
1865
1866 if (defined($serial)) {
1867
1868 my $termcmd = [ '/usr/sbin/qm', 'terminal', $vmid, '-iface', $serial, '-escape', '0' ];
1869
1870 $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
1871 '-timeout', $timeout, '-authpath', $authpath,
1872 '-perm', 'Sys.Console'];
1873
1874 if ($param->{websocket}) {
1875 $ENV{PVE_VNC_TICKET} = $password; # pass ticket to vncterm
1876 push @$cmd, '-notls', '-listen', 'localhost';
1877 }
1878
1879 push @$cmd, '-c', @$remcmd, @$termcmd;
1880
1881 PVE::Tools::run_command($cmd);
1882
1883 } else {
1884
1885 $ENV{LC_PVE_TICKET} = $password if $websocket; # set ticket with "qm vncproxy"
1886
1887 $cmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1888
1889 my $sock = IO::Socket::IP->new(
1890 ReuseAddr => 1,
1891 Listen => 1,
1892 LocalPort => $port,
1893 Proto => 'tcp',
1894 GetAddrInfoFlags => 0,
1895 ) or die "failed to create socket: $!\n";
1896 # Inside the worker we shouldn't have any previous alarms
1897 # running anyway...:
1898 alarm(0);
1899 local $SIG{ALRM} = sub { die "connection timed out\n" };
1900 alarm $timeout;
1901 accept(my $cli, $sock) or die "connection failed: $!\n";
1902 alarm(0);
1903 close($sock);
1904 if (PVE::Tools::run_command($cmd,
1905 output => '>&'.fileno($cli),
1906 input => '<&'.fileno($cli),
1907 noerr => 1) != 0)
1908 {
1909 die "Failed to run vncproxy.\n";
1910 }
1911 }
1912
1913 return;
1914 };
1915
1916 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd, 1);
1917
1918 PVE::Tools::wait_for_vnc_port($port);
1919
1920 my $res = {
1921 user => $authuser,
1922 ticket => $ticket,
1923 port => $port,
1924 upid => $upid,
1925 cert => $sslcert,
1926 };
1927 $res->{password} = $password if $param->{'generate-password'};
1928
1929 return $res;
1930 }});
1931
1932 __PACKAGE__->register_method({
1933 name => 'termproxy',
1934 path => '{vmid}/termproxy',
1935 method => 'POST',
1936 protected => 1,
1937 permissions => {
1938 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1939 },
1940 description => "Creates a TCP proxy connections.",
1941 parameters => {
1942 additionalProperties => 0,
1943 properties => {
1944 node => get_standard_option('pve-node'),
1945 vmid => get_standard_option('pve-vmid'),
1946 serial=> {
1947 optional => 1,
1948 type => 'string',
1949 enum => [qw(serial0 serial1 serial2 serial3)],
1950 description => "opens a serial terminal (defaults to display)",
1951 },
1952 },
1953 },
1954 returns => {
1955 additionalProperties => 0,
1956 properties => {
1957 user => { type => 'string' },
1958 ticket => { type => 'string' },
1959 port => { type => 'integer' },
1960 upid => { type => 'string' },
1961 },
1962 },
1963 code => sub {
1964 my ($param) = @_;
1965
1966 my $rpcenv = PVE::RPCEnvironment::get();
1967
1968 my $authuser = $rpcenv->get_user();
1969
1970 my $vmid = $param->{vmid};
1971 my $node = $param->{node};
1972 my $serial = $param->{serial};
1973
1974 my $conf = PVE::QemuConfig->load_config($vmid, $node); # check if VM exists
1975
1976 if (!defined($serial)) {
1977 if ($conf->{vga}) {
1978 my $vga = PVE::QemuServer::parse_vga($conf->{vga});
1979 $serial = $vga->{type} if $vga->{type} =~ m/^serial\d+$/;
1980 }
1981 }
1982
1983 my $authpath = "/vms/$vmid";
1984
1985 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
1986
1987 my $family;
1988 my $remcmd = [];
1989
1990 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1991 (undef, $family) = PVE::Cluster::remote_node_ip($node);
1992 my $sshinfo = PVE::SSHInfo::get_ssh_info($node);
1993 $remcmd = PVE::SSHInfo::ssh_info_to_command($sshinfo, '-t');
1994 push @$remcmd, '--';
1995 } else {
1996 $family = PVE::Tools::get_host_address_family($node);
1997 }
1998
1999 my $port = PVE::Tools::next_vnc_port($family);
2000
2001 my $termcmd = [ '/usr/sbin/qm', 'terminal', $vmid, '-escape', '0'];
2002 push @$termcmd, '-iface', $serial if $serial;
2003
2004 my $realcmd = sub {
2005 my $upid = shift;
2006
2007 syslog('info', "starting qemu termproxy $upid\n");
2008
2009 my $cmd = ['/usr/bin/termproxy', $port, '--path', $authpath,
2010 '--perm', 'VM.Console', '--'];
2011 push @$cmd, @$remcmd, @$termcmd;
2012
2013 PVE::Tools::run_command($cmd);
2014 };
2015
2016 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd, 1);
2017
2018 PVE::Tools::wait_for_vnc_port($port);
2019
2020 return {
2021 user => $authuser,
2022 ticket => $ticket,
2023 port => $port,
2024 upid => $upid,
2025 };
2026 }});
2027
2028 __PACKAGE__->register_method({
2029 name => 'vncwebsocket',
2030 path => '{vmid}/vncwebsocket',
2031 method => 'GET',
2032 permissions => {
2033 description => "You also need to pass a valid ticket (vncticket).",
2034 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
2035 },
2036 description => "Opens a weksocket for VNC traffic.",
2037 parameters => {
2038 additionalProperties => 0,
2039 properties => {
2040 node => get_standard_option('pve-node'),
2041 vmid => get_standard_option('pve-vmid'),
2042 vncticket => {
2043 description => "Ticket from previous call to vncproxy.",
2044 type => 'string',
2045 maxLength => 512,
2046 },
2047 port => {
2048 description => "Port number returned by previous vncproxy call.",
2049 type => 'integer',
2050 minimum => 5900,
2051 maximum => 5999,
2052 },
2053 },
2054 },
2055 returns => {
2056 type => "object",
2057 properties => {
2058 port => { type => 'string' },
2059 },
2060 },
2061 code => sub {
2062 my ($param) = @_;
2063
2064 my $rpcenv = PVE::RPCEnvironment::get();
2065
2066 my $authuser = $rpcenv->get_user();
2067
2068 my $vmid = $param->{vmid};
2069 my $node = $param->{node};
2070
2071 my $authpath = "/vms/$vmid";
2072
2073 PVE::AccessControl::verify_vnc_ticket($param->{vncticket}, $authuser, $authpath);
2074
2075 my $conf = PVE::QemuConfig->load_config($vmid, $node); # VM exists ?
2076
2077 # Note: VNC ports are acessible from outside, so we do not gain any
2078 # security if we verify that $param->{port} belongs to VM $vmid. This
2079 # check is done by verifying the VNC ticket (inside VNC protocol).
2080
2081 my $port = $param->{port};
2082
2083 return { port => $port };
2084 }});
2085
2086 __PACKAGE__->register_method({
2087 name => 'spiceproxy',
2088 path => '{vmid}/spiceproxy',
2089 method => 'POST',
2090 protected => 1,
2091 proxyto => 'node',
2092 permissions => {
2093 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
2094 },
2095 description => "Returns a SPICE configuration to connect to the VM.",
2096 parameters => {
2097 additionalProperties => 0,
2098 properties => {
2099 node => get_standard_option('pve-node'),
2100 vmid => get_standard_option('pve-vmid'),
2101 proxy => get_standard_option('spice-proxy', { optional => 1 }),
2102 },
2103 },
2104 returns => get_standard_option('remote-viewer-config'),
2105 code => sub {
2106 my ($param) = @_;
2107
2108 my $rpcenv = PVE::RPCEnvironment::get();
2109
2110 my $authuser = $rpcenv->get_user();
2111
2112 my $vmid = $param->{vmid};
2113 my $node = $param->{node};
2114 my $proxy = $param->{proxy};
2115
2116 my $conf = PVE::QemuConfig->load_config($vmid, $node);
2117 my $title = "VM $vmid";
2118 $title .= " - ". $conf->{name} if $conf->{name};
2119
2120 my $port = PVE::QemuServer::spice_port($vmid);
2121
2122 my ($ticket, undef, $remote_viewer_config) =
2123 PVE::AccessControl::remote_viewer_config($authuser, $vmid, $node, $proxy, $title, $port);
2124
2125 mon_cmd($vmid, "set_password", protocol => 'spice', password => $ticket);
2126 mon_cmd($vmid, "expire_password", protocol => 'spice', time => "+30");
2127
2128 return $remote_viewer_config;
2129 }});
2130
2131 __PACKAGE__->register_method({
2132 name => 'vmcmdidx',
2133 path => '{vmid}/status',
2134 method => 'GET',
2135 proxyto => 'node',
2136 description => "Directory index",
2137 permissions => {
2138 user => 'all',
2139 },
2140 parameters => {
2141 additionalProperties => 0,
2142 properties => {
2143 node => get_standard_option('pve-node'),
2144 vmid => get_standard_option('pve-vmid'),
2145 },
2146 },
2147 returns => {
2148 type => 'array',
2149 items => {
2150 type => "object",
2151 properties => {
2152 subdir => { type => 'string' },
2153 },
2154 },
2155 links => [ { rel => 'child', href => "{subdir}" } ],
2156 },
2157 code => sub {
2158 my ($param) = @_;
2159
2160 # test if VM exists
2161 my $conf = PVE::QemuConfig->load_config($param->{vmid});
2162
2163 my $res = [
2164 { subdir => 'current' },
2165 { subdir => 'start' },
2166 { subdir => 'stop' },
2167 { subdir => 'reset' },
2168 { subdir => 'shutdown' },
2169 { subdir => 'suspend' },
2170 { subdir => 'reboot' },
2171 ];
2172
2173 return $res;
2174 }});
2175
2176 __PACKAGE__->register_method({
2177 name => 'vm_status',
2178 path => '{vmid}/status/current',
2179 method => 'GET',
2180 proxyto => 'node',
2181 protected => 1, # qemu pid files are only readable by root
2182 description => "Get virtual machine status.",
2183 permissions => {
2184 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2185 },
2186 parameters => {
2187 additionalProperties => 0,
2188 properties => {
2189 node => get_standard_option('pve-node'),
2190 vmid => get_standard_option('pve-vmid'),
2191 },
2192 },
2193 returns => {
2194 type => 'object',
2195 properties => {
2196 %$PVE::QemuServer::vmstatus_return_properties,
2197 ha => {
2198 description => "HA manager service status.",
2199 type => 'object',
2200 },
2201 spice => {
2202 description => "Qemu VGA configuration supports spice.",
2203 type => 'boolean',
2204 optional => 1,
2205 },
2206 agent => {
2207 description => "Qemu GuestAgent enabled in config.",
2208 type => 'boolean',
2209 optional => 1,
2210 },
2211 },
2212 },
2213 code => sub {
2214 my ($param) = @_;
2215
2216 # test if VM exists
2217 my $conf = PVE::QemuConfig->load_config($param->{vmid});
2218
2219 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
2220 my $status = $vmstatus->{$param->{vmid}};
2221
2222 $status->{ha} = PVE::HA::Config::get_service_status("vm:$param->{vmid}");
2223
2224 $status->{spice} = 1 if PVE::QemuServer::vga_conf_has_spice($conf->{vga});
2225 $status->{agent} = 1 if PVE::QemuServer::get_qga_key($conf, 'enabled');
2226
2227 return $status;
2228 }});
2229
2230 __PACKAGE__->register_method({
2231 name => 'vm_start',
2232 path => '{vmid}/status/start',
2233 method => 'POST',
2234 protected => 1,
2235 proxyto => 'node',
2236 description => "Start virtual machine.",
2237 permissions => {
2238 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2239 },
2240 parameters => {
2241 additionalProperties => 0,
2242 properties => {
2243 node => get_standard_option('pve-node'),
2244 vmid => get_standard_option('pve-vmid',
2245 { completion => \&PVE::QemuServer::complete_vmid_stopped }),
2246 skiplock => get_standard_option('skiplock'),
2247 stateuri => get_standard_option('pve-qm-stateuri'),
2248 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
2249 migration_type => {
2250 type => 'string',
2251 enum => ['secure', 'insecure'],
2252 description => "Migration traffic is encrypted using an SSH " .
2253 "tunnel by default. On secure, completely private networks " .
2254 "this can be disabled to increase performance.",
2255 optional => 1,
2256 },
2257 migration_network => {
2258 type => 'string', format => 'CIDR',
2259 description => "CIDR of the (sub) network that is used for migration.",
2260 optional => 1,
2261 },
2262 machine => get_standard_option('pve-qemu-machine'),
2263 'force-cpu' => {
2264 description => "Override QEMU's -cpu argument with the given string.",
2265 type => 'string',
2266 optional => 1,
2267 },
2268 targetstorage => get_standard_option('pve-targetstorage'),
2269 timeout => {
2270 description => "Wait maximal timeout seconds.",
2271 type => 'integer',
2272 minimum => 0,
2273 default => 'max(30, vm memory in GiB)',
2274 optional => 1,
2275 },
2276 },
2277 },
2278 returns => {
2279 type => 'string',
2280 },
2281 code => sub {
2282 my ($param) = @_;
2283
2284 my $rpcenv = PVE::RPCEnvironment::get();
2285 my $authuser = $rpcenv->get_user();
2286
2287 my $node = extract_param($param, 'node');
2288 my $vmid = extract_param($param, 'vmid');
2289 my $timeout = extract_param($param, 'timeout');
2290
2291 my $machine = extract_param($param, 'machine');
2292 my $force_cpu = extract_param($param, 'force-cpu');
2293
2294 my $get_root_param = sub {
2295 my $value = extract_param($param, $_[0]);
2296 raise_param_exc({ "$_[0]" => "Only root may use this option." })
2297 if $value && $authuser ne 'root@pam';
2298 return $value;
2299 };
2300
2301 my $stateuri = $get_root_param->('stateuri');
2302 my $skiplock = $get_root_param->('skiplock');
2303 my $migratedfrom = $get_root_param->('migratedfrom');
2304 my $migration_type = $get_root_param->('migration_type');
2305 my $migration_network = $get_root_param->('migration_network');
2306 my $targetstorage = $get_root_param->('targetstorage');
2307
2308 my $storagemap;
2309
2310 if ($targetstorage) {
2311 raise_param_exc({ targetstorage => "targetstorage can only by used with migratedfrom." })
2312 if !$migratedfrom;
2313 $storagemap = eval { PVE::JSONSchema::parse_idmap($targetstorage, 'pve-storage-id') };
2314 raise_param_exc({ targetstorage => "failed to parse storage map: $@" })
2315 if $@;
2316 }
2317
2318 # read spice ticket from STDIN
2319 my $spice_ticket;
2320 my $nbd_protocol_version = 0;
2321 my $replicated_volumes = {};
2322 my $tpmstate_vol;
2323 if ($stateuri && ($stateuri eq 'tcp' || $stateuri eq 'unix') && $migratedfrom && ($rpcenv->{type} eq 'cli')) {
2324 while (defined(my $line = <STDIN>)) {
2325 chomp $line;
2326 if ($line =~ m/^spice_ticket: (.+)$/) {
2327 $spice_ticket = $1;
2328 } elsif ($line =~ m/^nbd_protocol_version: (\d+)$/) {
2329 $nbd_protocol_version = $1;
2330 } elsif ($line =~ m/^replicated_volume: (.*)$/) {
2331 $replicated_volumes->{$1} = 1;
2332 } elsif ($line =~ m/^tpmstate0: (.*)$/) {
2333 $tpmstate_vol = $1;
2334 } elsif (!$spice_ticket) {
2335 # fallback for old source node
2336 $spice_ticket = $line;
2337 } else {
2338 warn "unknown 'start' parameter on STDIN: '$line'\n";
2339 }
2340 }
2341 }
2342
2343 PVE::Cluster::check_cfs_quorum();
2344
2345 my $storecfg = PVE::Storage::config();
2346
2347 if (PVE::HA::Config::vm_is_ha_managed($vmid) && !$stateuri && $rpcenv->{type} ne 'ha') {
2348 my $hacmd = sub {
2349 my $upid = shift;
2350
2351 print "Requesting HA start for VM $vmid\n";
2352
2353 my $cmd = ['ha-manager', 'set', "vm:$vmid", '--state', 'started'];
2354 PVE::Tools::run_command($cmd);
2355 return;
2356 };
2357
2358 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
2359
2360 } else {
2361
2362 my $realcmd = sub {
2363 my $upid = shift;
2364
2365 syslog('info', "start VM $vmid: $upid\n");
2366
2367 my $migrate_opts = {
2368 migratedfrom => $migratedfrom,
2369 spice_ticket => $spice_ticket,
2370 network => $migration_network,
2371 type => $migration_type,
2372 storagemap => $storagemap,
2373 nbd_proto_version => $nbd_protocol_version,
2374 replicated_volumes => $replicated_volumes,
2375 tpmstate_vol => $tpmstate_vol,
2376 };
2377
2378 my $params = {
2379 statefile => $stateuri,
2380 skiplock => $skiplock,
2381 forcemachine => $machine,
2382 timeout => $timeout,
2383 forcecpu => $force_cpu,
2384 };
2385
2386 PVE::QemuServer::vm_start($storecfg, $vmid, $params, $migrate_opts);
2387 return;
2388 };
2389
2390 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
2391 }
2392 }});
2393
2394 __PACKAGE__->register_method({
2395 name => 'vm_stop',
2396 path => '{vmid}/status/stop',
2397 method => 'POST',
2398 protected => 1,
2399 proxyto => 'node',
2400 description => "Stop virtual machine. The qemu process will exit immediately. This" .
2401 "is akin to pulling the power plug of a running computer and may damage the VM data",
2402 permissions => {
2403 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2404 },
2405 parameters => {
2406 additionalProperties => 0,
2407 properties => {
2408 node => get_standard_option('pve-node'),
2409 vmid => get_standard_option('pve-vmid',
2410 { completion => \&PVE::QemuServer::complete_vmid_running }),
2411 skiplock => get_standard_option('skiplock'),
2412 migratedfrom => get_standard_option('pve-node', { optional => 1 }),
2413 timeout => {
2414 description => "Wait maximal timeout seconds.",
2415 type => 'integer',
2416 minimum => 0,
2417 optional => 1,
2418 },
2419 keepActive => {
2420 description => "Do not deactivate storage volumes.",
2421 type => 'boolean',
2422 optional => 1,
2423 default => 0,
2424 }
2425 },
2426 },
2427 returns => {
2428 type => 'string',
2429 },
2430 code => sub {
2431 my ($param) = @_;
2432
2433 my $rpcenv = PVE::RPCEnvironment::get();
2434 my $authuser = $rpcenv->get_user();
2435
2436 my $node = extract_param($param, 'node');
2437 my $vmid = extract_param($param, 'vmid');
2438
2439 my $skiplock = extract_param($param, 'skiplock');
2440 raise_param_exc({ skiplock => "Only root may use this option." })
2441 if $skiplock && $authuser ne 'root@pam';
2442
2443 my $keepActive = extract_param($param, 'keepActive');
2444 raise_param_exc({ keepActive => "Only root may use this option." })
2445 if $keepActive && $authuser ne 'root@pam';
2446
2447 my $migratedfrom = extract_param($param, 'migratedfrom');
2448 raise_param_exc({ migratedfrom => "Only root may use this option." })
2449 if $migratedfrom && $authuser ne 'root@pam';
2450
2451
2452 my $storecfg = PVE::Storage::config();
2453
2454 if (PVE::HA::Config::vm_is_ha_managed($vmid) && ($rpcenv->{type} ne 'ha') && !defined($migratedfrom)) {
2455
2456 my $hacmd = sub {
2457 my $upid = shift;
2458
2459 print "Requesting HA stop for VM $vmid\n";
2460
2461 my $cmd = ['ha-manager', 'crm-command', 'stop', "vm:$vmid", '0'];
2462 PVE::Tools::run_command($cmd);
2463 return;
2464 };
2465
2466 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
2467
2468 } else {
2469 my $realcmd = sub {
2470 my $upid = shift;
2471
2472 syslog('info', "stop VM $vmid: $upid\n");
2473
2474 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
2475 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
2476 return;
2477 };
2478
2479 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
2480 }
2481 }});
2482
2483 __PACKAGE__->register_method({
2484 name => 'vm_reset',
2485 path => '{vmid}/status/reset',
2486 method => 'POST',
2487 protected => 1,
2488 proxyto => 'node',
2489 description => "Reset virtual machine.",
2490 permissions => {
2491 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2492 },
2493 parameters => {
2494 additionalProperties => 0,
2495 properties => {
2496 node => get_standard_option('pve-node'),
2497 vmid => get_standard_option('pve-vmid',
2498 { completion => \&PVE::QemuServer::complete_vmid_running }),
2499 skiplock => get_standard_option('skiplock'),
2500 },
2501 },
2502 returns => {
2503 type => 'string',
2504 },
2505 code => sub {
2506 my ($param) = @_;
2507
2508 my $rpcenv = PVE::RPCEnvironment::get();
2509
2510 my $authuser = $rpcenv->get_user();
2511
2512 my $node = extract_param($param, 'node');
2513
2514 my $vmid = extract_param($param, 'vmid');
2515
2516 my $skiplock = extract_param($param, 'skiplock');
2517 raise_param_exc({ skiplock => "Only root may use this option." })
2518 if $skiplock && $authuser ne 'root@pam';
2519
2520 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
2521
2522 my $realcmd = sub {
2523 my $upid = shift;
2524
2525 PVE::QemuServer::vm_reset($vmid, $skiplock);
2526
2527 return;
2528 };
2529
2530 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
2531 }});
2532
2533 __PACKAGE__->register_method({
2534 name => 'vm_shutdown',
2535 path => '{vmid}/status/shutdown',
2536 method => 'POST',
2537 protected => 1,
2538 proxyto => 'node',
2539 description => "Shutdown virtual machine. This is similar to pressing the power button on a physical machine." .
2540 "This will send an ACPI event for the guest OS, which should then proceed to a clean shutdown.",
2541 permissions => {
2542 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2543 },
2544 parameters => {
2545 additionalProperties => 0,
2546 properties => {
2547 node => get_standard_option('pve-node'),
2548 vmid => get_standard_option('pve-vmid',
2549 { completion => \&PVE::QemuServer::complete_vmid_running }),
2550 skiplock => get_standard_option('skiplock'),
2551 timeout => {
2552 description => "Wait maximal timeout seconds.",
2553 type => 'integer',
2554 minimum => 0,
2555 optional => 1,
2556 },
2557 forceStop => {
2558 description => "Make sure the VM stops.",
2559 type => 'boolean',
2560 optional => 1,
2561 default => 0,
2562 },
2563 keepActive => {
2564 description => "Do not deactivate storage volumes.",
2565 type => 'boolean',
2566 optional => 1,
2567 default => 0,
2568 }
2569 },
2570 },
2571 returns => {
2572 type => 'string',
2573 },
2574 code => sub {
2575 my ($param) = @_;
2576
2577 my $rpcenv = PVE::RPCEnvironment::get();
2578 my $authuser = $rpcenv->get_user();
2579
2580 my $node = extract_param($param, 'node');
2581 my $vmid = extract_param($param, 'vmid');
2582
2583 my $skiplock = extract_param($param, 'skiplock');
2584 raise_param_exc({ skiplock => "Only root may use this option." })
2585 if $skiplock && $authuser ne 'root@pam';
2586
2587 my $keepActive = extract_param($param, 'keepActive');
2588 raise_param_exc({ keepActive => "Only root may use this option." })
2589 if $keepActive && $authuser ne 'root@pam';
2590
2591 my $storecfg = PVE::Storage::config();
2592
2593 my $shutdown = 1;
2594
2595 # if vm is paused, do not shutdown (but stop if forceStop = 1)
2596 # otherwise, we will infer a shutdown command, but run into the timeout,
2597 # then when the vm is resumed, it will instantly shutdown
2598 #
2599 # checking the qmp status here to get feedback to the gui/cli/api
2600 # and the status query should not take too long
2601 if (PVE::QemuServer::vm_is_paused($vmid)) {
2602 if ($param->{forceStop}) {
2603 warn "VM is paused - stop instead of shutdown\n";
2604 $shutdown = 0;
2605 } else {
2606 die "VM is paused - cannot shutdown\n";
2607 }
2608 }
2609
2610 if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
2611
2612 my $timeout = $param->{timeout} // 60;
2613 my $hacmd = sub {
2614 my $upid = shift;
2615
2616 print "Requesting HA stop for VM $vmid\n";
2617
2618 my $cmd = ['ha-manager', 'crm-command', 'stop', "vm:$vmid", "$timeout"];
2619 PVE::Tools::run_command($cmd);
2620 return;
2621 };
2622
2623 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
2624
2625 } else {
2626
2627 my $realcmd = sub {
2628 my $upid = shift;
2629
2630 syslog('info', "shutdown VM $vmid: $upid\n");
2631
2632 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
2633 $shutdown, $param->{forceStop}, $keepActive);
2634 return;
2635 };
2636
2637 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
2638 }
2639 }});
2640
2641 __PACKAGE__->register_method({
2642 name => 'vm_reboot',
2643 path => '{vmid}/status/reboot',
2644 method => 'POST',
2645 protected => 1,
2646 proxyto => 'node',
2647 description => "Reboot the VM by shutting it down, and starting it again. Applies pending changes.",
2648 permissions => {
2649 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2650 },
2651 parameters => {
2652 additionalProperties => 0,
2653 properties => {
2654 node => get_standard_option('pve-node'),
2655 vmid => get_standard_option('pve-vmid',
2656 { completion => \&PVE::QemuServer::complete_vmid_running }),
2657 timeout => {
2658 description => "Wait maximal timeout seconds for the shutdown.",
2659 type => 'integer',
2660 minimum => 0,
2661 optional => 1,
2662 },
2663 },
2664 },
2665 returns => {
2666 type => 'string',
2667 },
2668 code => sub {
2669 my ($param) = @_;
2670
2671 my $rpcenv = PVE::RPCEnvironment::get();
2672 my $authuser = $rpcenv->get_user();
2673
2674 my $node = extract_param($param, 'node');
2675 my $vmid = extract_param($param, 'vmid');
2676
2677 die "VM is paused - cannot shutdown\n" if PVE::QemuServer::vm_is_paused($vmid);
2678
2679 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
2680
2681 my $realcmd = sub {
2682 my $upid = shift;
2683
2684 syslog('info', "requesting reboot of VM $vmid: $upid\n");
2685 PVE::QemuServer::vm_reboot($vmid, $param->{timeout});
2686 return;
2687 };
2688
2689 return $rpcenv->fork_worker('qmreboot', $vmid, $authuser, $realcmd);
2690 }});
2691
2692 __PACKAGE__->register_method({
2693 name => 'vm_suspend',
2694 path => '{vmid}/status/suspend',
2695 method => 'POST',
2696 protected => 1,
2697 proxyto => 'node',
2698 description => "Suspend virtual machine.",
2699 permissions => {
2700 description => "You need 'VM.PowerMgmt' on /vms/{vmid}, and if you have set 'todisk',".
2701 " you need also 'VM.Config.Disk' on /vms/{vmid} and 'Datastore.AllocateSpace'".
2702 " on the storage for the vmstate.",
2703 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2704 },
2705 parameters => {
2706 additionalProperties => 0,
2707 properties => {
2708 node => get_standard_option('pve-node'),
2709 vmid => get_standard_option('pve-vmid',
2710 { completion => \&PVE::QemuServer::complete_vmid_running }),
2711 skiplock => get_standard_option('skiplock'),
2712 todisk => {
2713 type => 'boolean',
2714 default => 0,
2715 optional => 1,
2716 description => 'If set, suspends the VM to disk. Will be resumed on next VM start.',
2717 },
2718 statestorage => get_standard_option('pve-storage-id', {
2719 description => "The storage for the VM state",
2720 requires => 'todisk',
2721 optional => 1,
2722 completion => \&PVE::Storage::complete_storage_enabled,
2723 }),
2724 },
2725 },
2726 returns => {
2727 type => 'string',
2728 },
2729 code => sub {
2730 my ($param) = @_;
2731
2732 my $rpcenv = PVE::RPCEnvironment::get();
2733 my $authuser = $rpcenv->get_user();
2734
2735 my $node = extract_param($param, 'node');
2736 my $vmid = extract_param($param, 'vmid');
2737
2738 my $todisk = extract_param($param, 'todisk') // 0;
2739
2740 my $statestorage = extract_param($param, 'statestorage');
2741
2742 my $skiplock = extract_param($param, 'skiplock');
2743 raise_param_exc({ skiplock => "Only root may use this option." })
2744 if $skiplock && $authuser ne 'root@pam';
2745
2746 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
2747
2748 die "Cannot suspend HA managed VM to disk\n"
2749 if $todisk && PVE::HA::Config::vm_is_ha_managed($vmid);
2750
2751 # early check for storage permission, for better user feedback
2752 if ($todisk) {
2753 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
2754
2755 if (!$statestorage) {
2756 # get statestorage from config if none is given
2757 my $conf = PVE::QemuConfig->load_config($vmid);
2758 my $storecfg = PVE::Storage::config();
2759 $statestorage = PVE::QemuServer::find_vmstate_storage($conf, $storecfg);
2760 }
2761
2762 $rpcenv->check($authuser, "/storage/$statestorage", ['Datastore.AllocateSpace']);
2763 }
2764
2765 my $realcmd = sub {
2766 my $upid = shift;
2767
2768 syslog('info', "suspend VM $vmid: $upid\n");
2769
2770 PVE::QemuServer::vm_suspend($vmid, $skiplock, $todisk, $statestorage);
2771
2772 return;
2773 };
2774
2775 my $taskname = $todisk ? 'qmsuspend' : 'qmpause';
2776 return $rpcenv->fork_worker($taskname, $vmid, $authuser, $realcmd);
2777 }});
2778
2779 __PACKAGE__->register_method({
2780 name => 'vm_resume',
2781 path => '{vmid}/status/resume',
2782 method => 'POST',
2783 protected => 1,
2784 proxyto => 'node',
2785 description => "Resume virtual machine.",
2786 permissions => {
2787 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
2788 },
2789 parameters => {
2790 additionalProperties => 0,
2791 properties => {
2792 node => get_standard_option('pve-node'),
2793 vmid => get_standard_option('pve-vmid',
2794 { completion => \&PVE::QemuServer::complete_vmid_running }),
2795 skiplock => get_standard_option('skiplock'),
2796 nocheck => { type => 'boolean', optional => 1 },
2797
2798 },
2799 },
2800 returns => {
2801 type => 'string',
2802 },
2803 code => sub {
2804 my ($param) = @_;
2805
2806 my $rpcenv = PVE::RPCEnvironment::get();
2807
2808 my $authuser = $rpcenv->get_user();
2809
2810 my $node = extract_param($param, 'node');
2811
2812 my $vmid = extract_param($param, 'vmid');
2813
2814 my $skiplock = extract_param($param, 'skiplock');
2815 raise_param_exc({ skiplock => "Only root may use this option." })
2816 if $skiplock && $authuser ne 'root@pam';
2817
2818 my $nocheck = extract_param($param, 'nocheck');
2819 raise_param_exc({ nocheck => "Only root may use this option." })
2820 if $nocheck && $authuser ne 'root@pam';
2821
2822 my $to_disk_suspended;
2823 eval {
2824 PVE::QemuConfig->lock_config($vmid, sub {
2825 my $conf = PVE::QemuConfig->load_config($vmid);
2826 $to_disk_suspended = PVE::QemuConfig->has_lock($conf, 'suspended');
2827 });
2828 };
2829
2830 die "VM $vmid not running\n"
2831 if !$to_disk_suspended && !PVE::QemuServer::check_running($vmid, $nocheck);
2832
2833 my $realcmd = sub {
2834 my $upid = shift;
2835
2836 syslog('info', "resume VM $vmid: $upid\n");
2837
2838 if (!$to_disk_suspended) {
2839 PVE::QemuServer::vm_resume($vmid, $skiplock, $nocheck);
2840 } else {
2841 my $storecfg = PVE::Storage::config();
2842 PVE::QemuServer::vm_start($storecfg, $vmid, { skiplock => $skiplock });
2843 }
2844
2845 return;
2846 };
2847
2848 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
2849 }});
2850
2851 __PACKAGE__->register_method({
2852 name => 'vm_sendkey',
2853 path => '{vmid}/sendkey',
2854 method => 'PUT',
2855 protected => 1,
2856 proxyto => 'node',
2857 description => "Send key event to virtual machine.",
2858 permissions => {
2859 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
2860 },
2861 parameters => {
2862 additionalProperties => 0,
2863 properties => {
2864 node => get_standard_option('pve-node'),
2865 vmid => get_standard_option('pve-vmid',
2866 { completion => \&PVE::QemuServer::complete_vmid_running }),
2867 skiplock => get_standard_option('skiplock'),
2868 key => {
2869 description => "The key (qemu monitor encoding).",
2870 type => 'string'
2871 }
2872 },
2873 },
2874 returns => { type => 'null'},
2875 code => sub {
2876 my ($param) = @_;
2877
2878 my $rpcenv = PVE::RPCEnvironment::get();
2879
2880 my $authuser = $rpcenv->get_user();
2881
2882 my $node = extract_param($param, 'node');
2883
2884 my $vmid = extract_param($param, 'vmid');
2885
2886 my $skiplock = extract_param($param, 'skiplock');
2887 raise_param_exc({ skiplock => "Only root may use this option." })
2888 if $skiplock && $authuser ne 'root@pam';
2889
2890 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
2891
2892 return;
2893 }});
2894
2895 __PACKAGE__->register_method({
2896 name => 'vm_feature',
2897 path => '{vmid}/feature',
2898 method => 'GET',
2899 proxyto => 'node',
2900 protected => 1,
2901 description => "Check if feature for virtual machine is available.",
2902 permissions => {
2903 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2904 },
2905 parameters => {
2906 additionalProperties => 0,
2907 properties => {
2908 node => get_standard_option('pve-node'),
2909 vmid => get_standard_option('pve-vmid'),
2910 feature => {
2911 description => "Feature to check.",
2912 type => 'string',
2913 enum => [ 'snapshot', 'clone', 'copy' ],
2914 },
2915 snapname => get_standard_option('pve-snapshot-name', {
2916 optional => 1,
2917 }),
2918 },
2919 },
2920 returns => {
2921 type => "object",
2922 properties => {
2923 hasFeature => { type => 'boolean' },
2924 nodes => {
2925 type => 'array',
2926 items => { type => 'string' },
2927 }
2928 },
2929 },
2930 code => sub {
2931 my ($param) = @_;
2932
2933 my $node = extract_param($param, 'node');
2934
2935 my $vmid = extract_param($param, 'vmid');
2936
2937 my $snapname = extract_param($param, 'snapname');
2938
2939 my $feature = extract_param($param, 'feature');
2940
2941 my $running = PVE::QemuServer::check_running($vmid);
2942
2943 my $conf = PVE::QemuConfig->load_config($vmid);
2944
2945 if($snapname){
2946 my $snap = $conf->{snapshots}->{$snapname};
2947 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2948 $conf = $snap;
2949 }
2950 my $storecfg = PVE::Storage::config();
2951
2952 my $nodelist = PVE::QemuServer::shared_nodes($conf, $storecfg);
2953 my $hasFeature = PVE::QemuConfig->has_feature($feature, $conf, $storecfg, $snapname, $running);
2954
2955 return {
2956 hasFeature => $hasFeature,
2957 nodes => [ keys %$nodelist ],
2958 };
2959 }});
2960
2961 __PACKAGE__->register_method({
2962 name => 'clone_vm',
2963 path => '{vmid}/clone',
2964 method => 'POST',
2965 protected => 1,
2966 proxyto => 'node',
2967 description => "Create a copy of virtual machine/template.",
2968 permissions => {
2969 description => "You need 'VM.Clone' permissions on /vms/{vmid}, and 'VM.Allocate' permissions " .
2970 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
2971 "'Datastore.AllocateSpace' on any used storage.",
2972 check =>
2973 [ 'and',
2974 ['perm', '/vms/{vmid}', [ 'VM.Clone' ]],
2975 [ 'or',
2976 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
2977 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
2978 ],
2979 ]
2980 },
2981 parameters => {
2982 additionalProperties => 0,
2983 properties => {
2984 node => get_standard_option('pve-node'),
2985 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
2986 newid => get_standard_option('pve-vmid', {
2987 completion => \&PVE::Cluster::complete_next_vmid,
2988 description => 'VMID for the clone.' }),
2989 name => {
2990 optional => 1,
2991 type => 'string', format => 'dns-name',
2992 description => "Set a name for the new VM.",
2993 },
2994 description => {
2995 optional => 1,
2996 type => 'string',
2997 description => "Description for the new VM.",
2998 },
2999 pool => {
3000 optional => 1,
3001 type => 'string', format => 'pve-poolid',
3002 description => "Add the new VM to the specified pool.",
3003 },
3004 snapname => get_standard_option('pve-snapshot-name', {
3005 optional => 1,
3006 }),
3007 storage => get_standard_option('pve-storage-id', {
3008 description => "Target storage for full clone.",
3009 optional => 1,
3010 }),
3011 'format' => {
3012 description => "Target format for file storage. Only valid for full clone.",
3013 type => 'string',
3014 optional => 1,
3015 enum => [ 'raw', 'qcow2', 'vmdk'],
3016 },
3017 full => {
3018 optional => 1,
3019 type => 'boolean',
3020 description => "Create a full copy of all disks. This is always done when " .
3021 "you clone a normal VM. For VM templates, we try to create a linked clone by default.",
3022 },
3023 target => get_standard_option('pve-node', {
3024 description => "Target node. Only allowed if the original VM is on shared storage.",
3025 optional => 1,
3026 }),
3027 bwlimit => {
3028 description => "Override I/O bandwidth limit (in KiB/s).",
3029 optional => 1,
3030 type => 'integer',
3031 minimum => '0',
3032 default => 'clone limit from datacenter or storage config',
3033 },
3034 },
3035 },
3036 returns => {
3037 type => 'string',
3038 },
3039 code => sub {
3040 my ($param) = @_;
3041
3042 my $rpcenv = PVE::RPCEnvironment::get();
3043 my $authuser = $rpcenv->get_user();
3044
3045 my $node = extract_param($param, 'node');
3046 my $vmid = extract_param($param, 'vmid');
3047 my $newid = extract_param($param, 'newid');
3048 my $pool = extract_param($param, 'pool');
3049 $rpcenv->check_pool_exist($pool) if defined($pool);
3050
3051 my $snapname = extract_param($param, 'snapname');
3052 my $storage = extract_param($param, 'storage');
3053 my $format = extract_param($param, 'format');
3054 my $target = extract_param($param, 'target');
3055
3056 my $localnode = PVE::INotify::nodename();
3057
3058 if ($target && ($target eq $localnode || $target eq 'localhost')) {
3059 undef $target;
3060 }
3061
3062 PVE::Cluster::check_node_exists($target) if $target;
3063
3064 my $storecfg = PVE::Storage::config();
3065
3066 if ($storage) {
3067 # check if storage is enabled on local node
3068 PVE::Storage::storage_check_enabled($storecfg, $storage);
3069 if ($target) {
3070 # check if storage is available on target node
3071 PVE::Storage::storage_check_enabled($storecfg, $storage, $target);
3072 # clone only works if target storage is shared
3073 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
3074 die "can't clone to non-shared storage '$storage'\n" if !$scfg->{shared};
3075 }
3076 }
3077
3078 PVE::Cluster::check_cfs_quorum();
3079
3080 my $running = PVE::QemuServer::check_running($vmid) || 0;
3081
3082 my $clonefn = sub {
3083 # do all tests after lock but before forking worker - if possible
3084
3085 my $conf = PVE::QemuConfig->load_config($vmid);
3086 PVE::QemuConfig->check_lock($conf);
3087
3088 my $verify_running = PVE::QemuServer::check_running($vmid) || 0;
3089 die "unexpected state change\n" if $verify_running != $running;
3090
3091 die "snapshot '$snapname' does not exist\n"
3092 if $snapname && !defined( $conf->{snapshots}->{$snapname});
3093
3094 my $full = extract_param($param, 'full') // !PVE::QemuConfig->is_template($conf);
3095
3096 die "parameter 'storage' not allowed for linked clones\n"
3097 if defined($storage) && !$full;
3098
3099 die "parameter 'format' not allowed for linked clones\n"
3100 if defined($format) && !$full;
3101
3102 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
3103
3104 my $sharedvm = &$check_storage_access_clone($rpcenv, $authuser, $storecfg, $oldconf, $storage);
3105
3106 die "can't clone VM to node '$target' (VM uses local storage)\n"
3107 if $target && !$sharedvm;
3108
3109 my $conffile = PVE::QemuConfig->config_file($newid);
3110 die "unable to create VM $newid: config file already exists\n"
3111 if -f $conffile;
3112
3113 my $newconf = { lock => 'clone' };
3114 my $drives = {};
3115 my $fullclone = {};
3116 my $vollist = [];
3117
3118 foreach my $opt (keys %$oldconf) {
3119 my $value = $oldconf->{$opt};
3120
3121 # do not copy snapshot related info
3122 next if $opt eq 'snapshots' || $opt eq 'parent' || $opt eq 'snaptime' ||
3123 $opt eq 'vmstate' || $opt eq 'snapstate';
3124
3125 # no need to copy unused images, because VMID(owner) changes anyways
3126 next if $opt =~ m/^unused\d+$/;
3127
3128 # always change MAC! address
3129 if ($opt =~ m/^net(\d+)$/) {
3130 my $net = PVE::QemuServer::parse_net($value);
3131 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
3132 $net->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
3133 $newconf->{$opt} = PVE::QemuServer::print_net($net);
3134 } elsif (PVE::QemuServer::is_valid_drivename($opt)) {
3135 my $drive = PVE::QemuServer::parse_drive($opt, $value);
3136 die "unable to parse drive options for '$opt'\n" if !$drive;
3137 if (PVE::QemuServer::drive_is_cdrom($drive, 1)) {
3138 $newconf->{$opt} = $value; # simply copy configuration
3139 } else {
3140 if ($full || PVE::QemuServer::drive_is_cloudinit($drive)) {
3141 die "Full clone feature is not supported for drive '$opt'\n"
3142 if !PVE::Storage::volume_has_feature($storecfg, 'copy', $drive->{file}, $snapname, $running);
3143 $fullclone->{$opt} = 1;
3144 } else {
3145 # not full means clone instead of copy
3146 die "Linked clone feature is not supported for drive '$opt'\n"
3147 if !PVE::Storage::volume_has_feature($storecfg, 'clone', $drive->{file}, $snapname, $running);
3148 }
3149 $drives->{$opt} = $drive;
3150 next if PVE::QemuServer::drive_is_cloudinit($drive);
3151 push @$vollist, $drive->{file};
3152 }
3153 } else {
3154 # copy everything else
3155 $newconf->{$opt} = $value;
3156 }
3157 }
3158
3159 # auto generate a new uuid
3160 my $smbios1 = PVE::QemuServer::parse_smbios1($newconf->{smbios1} || '');
3161 $smbios1->{uuid} = PVE::QemuServer::generate_uuid();
3162 $newconf->{smbios1} = PVE::QemuServer::print_smbios1($smbios1);
3163 # auto generate a new vmgenid only if the option was set for template
3164 if ($newconf->{vmgenid}) {
3165 $newconf->{vmgenid} = PVE::QemuServer::generate_uuid();
3166 }
3167
3168 delete $newconf->{template};
3169
3170 if ($param->{name}) {
3171 $newconf->{name} = $param->{name};
3172 } else {
3173 $newconf->{name} = "Copy-of-VM-" . ($oldconf->{name} // $vmid);
3174 }
3175
3176 if ($param->{description}) {
3177 $newconf->{description} = $param->{description};
3178 }
3179
3180 # create empty/temp config - this fails if VM already exists on other node
3181 # FIXME use PVE::QemuConfig->create_and_lock_config and adapt code
3182 PVE::Tools::file_set_contents($conffile, "# qmclone temporary file\nlock: clone\n");
3183
3184 my $realcmd = sub {
3185 my $upid = shift;
3186
3187 my $newvollist = [];
3188 my $jobs = {};
3189
3190 eval {
3191 local $SIG{INT} =
3192 local $SIG{TERM} =
3193 local $SIG{QUIT} =
3194 local $SIG{HUP} = sub { die "interrupted by signal\n"; };
3195
3196 PVE::Storage::activate_volumes($storecfg, $vollist, $snapname);
3197
3198 my $bwlimit = extract_param($param, 'bwlimit');
3199
3200 my $total_jobs = scalar(keys %{$drives});
3201 my $i = 1;
3202
3203 foreach my $opt (sort keys %$drives) {
3204 my $drive = $drives->{$opt};
3205 my $skipcomplete = ($total_jobs != $i); # finish after last drive
3206 my $completion = $skipcomplete ? 'skip' : 'complete';
3207
3208 my $src_sid = PVE::Storage::parse_volume_id($drive->{file});
3209 my $storage_list = [ $src_sid ];
3210 push @$storage_list, $storage if defined($storage);
3211 my $clonelimit = PVE::Storage::get_bandwidth_limit('clone', $storage_list, $bwlimit);
3212
3213 my $newdrive = PVE::QemuServer::clone_disk(
3214 $storecfg,
3215 $vmid,
3216 $running,
3217 $opt,
3218 $drive,
3219 $snapname,
3220 $newid,
3221 $storage,
3222 $format,
3223 $fullclone->{$opt},
3224 $newvollist,
3225 $jobs,
3226 $completion,
3227 $oldconf->{agent},
3228 $clonelimit,
3229 $oldconf
3230 );
3231
3232 $newconf->{$opt} = PVE::QemuServer::print_drive($newdrive);
3233
3234 PVE::QemuConfig->write_config($newid, $newconf);
3235 $i++;
3236 }
3237
3238 delete $newconf->{lock};
3239
3240 # do not write pending changes
3241 if (my @changes = keys %{$newconf->{pending}}) {
3242 my $pending = join(',', @changes);
3243 warn "found pending changes for '$pending', discarding for clone\n";
3244 delete $newconf->{pending};
3245 }
3246
3247 PVE::QemuConfig->write_config($newid, $newconf);
3248
3249 if ($target) {
3250 # always deactivate volumes - avoid lvm LVs to be active on several nodes
3251 PVE::Storage::deactivate_volumes($storecfg, $vollist, $snapname) if !$running;
3252 PVE::Storage::deactivate_volumes($storecfg, $newvollist);
3253
3254 my $newconffile = PVE::QemuConfig->config_file($newid, $target);
3255 die "Failed to move config to node '$target' - rename failed: $!\n"
3256 if !rename($conffile, $newconffile);
3257 }
3258
3259 PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
3260 };
3261 if (my $err = $@) {
3262 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs) };
3263 sleep 1; # some storage like rbd need to wait before release volume - really?
3264
3265 foreach my $volid (@$newvollist) {
3266 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
3267 warn $@ if $@;
3268 }
3269
3270 PVE::Firewall::remove_vmfw_conf($newid);
3271
3272 unlink $conffile; # avoid races -> last thing before die
3273
3274 die "clone failed: $err";
3275 }
3276
3277 return;
3278 };
3279
3280 PVE::Firewall::clone_vmfw_conf($vmid, $newid);
3281
3282 return $rpcenv->fork_worker('qmclone', $vmid, $authuser, $realcmd);
3283 };
3284
3285 # Aquire exclusive lock lock for $newid
3286 my $lock_target_vm = sub {
3287 return PVE::QemuConfig->lock_config_full($newid, 1, $clonefn);
3288 };
3289
3290 # exclusive lock if VM is running - else shared lock is enough;
3291 if ($running) {
3292 return PVE::QemuConfig->lock_config_full($vmid, 1, $lock_target_vm);
3293 } else {
3294 return PVE::QemuConfig->lock_config_shared($vmid, 1, $lock_target_vm);
3295 }
3296 }});
3297
3298 __PACKAGE__->register_method({
3299 name => 'move_vm_disk',
3300 path => '{vmid}/move_disk',
3301 method => 'POST',
3302 protected => 1,
3303 proxyto => 'node',
3304 description => "Move volume to different storage or to a different VM.",
3305 permissions => {
3306 description => "You need 'VM.Config.Disk' permissions on /vms/{vmid}, " .
3307 "and 'Datastore.AllocateSpace' permissions on the storage. To move ".
3308 "a disk to another VM, you need the permissions on the target VM as well.",
3309 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
3310 },
3311 parameters => {
3312 additionalProperties => 0,
3313 properties => {
3314 node => get_standard_option('pve-node'),
3315 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
3316 'target-vmid' => get_standard_option('pve-vmid', {
3317 completion => \&PVE::QemuServer::complete_vmid,
3318 optional => 1,
3319 }),
3320 disk => {
3321 type => 'string',
3322 description => "The disk you want to move.",
3323 enum => [PVE::QemuServer::Drive::valid_drive_names_with_unused()],
3324 },
3325 storage => get_standard_option('pve-storage-id', {
3326 description => "Target storage.",
3327 completion => \&PVE::QemuServer::complete_storage,
3328 optional => 1,
3329 }),
3330 'format' => {
3331 type => 'string',
3332 description => "Target Format.",
3333 enum => [ 'raw', 'qcow2', 'vmdk' ],
3334 optional => 1,
3335 },
3336 delete => {
3337 type => 'boolean',
3338 description => "Delete the original disk after successful copy. By default the"
3339 ." original disk is kept as unused disk.",
3340 optional => 1,
3341 default => 0