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