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