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