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