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