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