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