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