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