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