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