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