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