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