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