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