]> git.proxmox.com Git - qemu-server.git/blame_incremental - PVE/API2/Qemu.pm
document for end users the differences between shutdown and stop
[qemu-server.git] / PVE / API2 / Qemu.pm
... / ...
CommitLineData
1package PVE::API2::Qemu;
2
3use strict;
4use warnings;
5use Cwd 'abs_path';
6use Net::SSLeay;
7use UUID;
8
9use PVE::Cluster qw (cfs_read_file cfs_write_file);;
10use PVE::SafeSyslog;
11use PVE::Tools qw(extract_param);
12use PVE::Exception qw(raise raise_param_exc raise_perm_exc);
13use PVE::Storage;
14use PVE::JSONSchema qw(get_standard_option);
15use PVE::RESTHandler;
16use PVE::QemuServer;
17use PVE::QemuMigrate;
18use PVE::RPCEnvironment;
19use PVE::AccessControl;
20use PVE::INotify;
21use PVE::Network;
22use PVE::Firewall;
23use PVE::API2::Firewall::VM;
24use PVE::HA::Env::PVE2;
25use PVE::HA::Config;
26
27use Data::Dumper; # fixme: remove
28
29use base qw(PVE::RESTHandler);
30
31my $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
33my $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
43my $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
67my $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.
106my $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
178my $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
208my $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
781my $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
1014my $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
1229my $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. The qemu process will exit immediatly. This" .
1627 "is akin to pulling the power plug of a running computer and may damage the VM data",
1628 permissions => {
1629 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1630 },
1631 parameters => {
1632 additionalProperties => 0,
1633 properties => {
1634 node => get_standard_option('pve-node'),
1635 vmid => get_standard_option('pve-vmid',
1636 { completion => \&PVE::QemuServer::complete_vmid_running }),
1637 skiplock => get_standard_option('skiplock'),
1638 migratedfrom => get_standard_option('pve-node', { optional => 1 }),
1639 timeout => {
1640 description => "Wait maximal timeout seconds.",
1641 type => 'integer',
1642 minimum => 0,
1643 optional => 1,
1644 },
1645 keepActive => {
1646 description => "Do not decativate storage volumes.",
1647 type => 'boolean',
1648 optional => 1,
1649 default => 0,
1650 }
1651 },
1652 },
1653 returns => {
1654 type => 'string',
1655 },
1656 code => sub {
1657 my ($param) = @_;
1658
1659 my $rpcenv = PVE::RPCEnvironment::get();
1660
1661 my $authuser = $rpcenv->get_user();
1662
1663 my $node = extract_param($param, 'node');
1664
1665 my $vmid = extract_param($param, 'vmid');
1666
1667 my $skiplock = extract_param($param, 'skiplock');
1668 raise_param_exc({ skiplock => "Only root may use this option." })
1669 if $skiplock && $authuser ne 'root@pam';
1670
1671 my $keepActive = extract_param($param, 'keepActive');
1672 raise_param_exc({ keepActive => "Only root may use this option." })
1673 if $keepActive && $authuser ne 'root@pam';
1674
1675 my $migratedfrom = extract_param($param, 'migratedfrom');
1676 raise_param_exc({ migratedfrom => "Only root may use this option." })
1677 if $migratedfrom && $authuser ne 'root@pam';
1678
1679
1680 my $storecfg = PVE::Storage::config();
1681
1682 if (PVE::HA::Config::vm_is_ha_managed($vmid) && ($rpcenv->{type} ne 'ha') && !defined($migratedfrom)) {
1683
1684 my $hacmd = sub {
1685 my $upid = shift;
1686
1687 my $service = "vm:$vmid";
1688
1689 my $cmd = ['ha-manager', 'disable', $service];
1690
1691 print "Executing HA stop for VM $vmid\n";
1692
1693 PVE::Tools::run_command($cmd);
1694
1695 return;
1696 };
1697
1698 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1699
1700 } else {
1701 my $realcmd = sub {
1702 my $upid = shift;
1703
1704 syslog('info', "stop VM $vmid: $upid\n");
1705
1706 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
1707 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
1708
1709 return;
1710 };
1711
1712 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1713 }
1714 }});
1715
1716__PACKAGE__->register_method({
1717 name => 'vm_reset',
1718 path => '{vmid}/status/reset',
1719 method => 'POST',
1720 protected => 1,
1721 proxyto => 'node',
1722 description => "Reset virtual machine.",
1723 permissions => {
1724 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1725 },
1726 parameters => {
1727 additionalProperties => 0,
1728 properties => {
1729 node => get_standard_option('pve-node'),
1730 vmid => get_standard_option('pve-vmid',
1731 { completion => \&PVE::QemuServer::complete_vmid_running }),
1732 skiplock => get_standard_option('skiplock'),
1733 },
1734 },
1735 returns => {
1736 type => 'string',
1737 },
1738 code => sub {
1739 my ($param) = @_;
1740
1741 my $rpcenv = PVE::RPCEnvironment::get();
1742
1743 my $authuser = $rpcenv->get_user();
1744
1745 my $node = extract_param($param, 'node');
1746
1747 my $vmid = extract_param($param, 'vmid');
1748
1749 my $skiplock = extract_param($param, 'skiplock');
1750 raise_param_exc({ skiplock => "Only root may use this option." })
1751 if $skiplock && $authuser ne 'root@pam';
1752
1753 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1754
1755 my $realcmd = sub {
1756 my $upid = shift;
1757
1758 PVE::QemuServer::vm_reset($vmid, $skiplock);
1759
1760 return;
1761 };
1762
1763 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
1764 }});
1765
1766__PACKAGE__->register_method({
1767 name => 'vm_shutdown',
1768 path => '{vmid}/status/shutdown',
1769 method => 'POST',
1770 protected => 1,
1771 proxyto => 'node',
1772 description => "Shutdown virtual machine. This is similar to pressing the power button on a physical machine." .
1773 "This will send an ACPI event for the guest OS, which should then proceed to a clean shutdown.",
1774 permissions => {
1775 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1776 },
1777 parameters => {
1778 additionalProperties => 0,
1779 properties => {
1780 node => get_standard_option('pve-node'),
1781 vmid => get_standard_option('pve-vmid',
1782 { completion => \&PVE::QemuServer::complete_vmid_running }),
1783 skiplock => get_standard_option('skiplock'),
1784 timeout => {
1785 description => "Wait maximal timeout seconds.",
1786 type => 'integer',
1787 minimum => 0,
1788 optional => 1,
1789 },
1790 forceStop => {
1791 description => "Make sure the VM stops.",
1792 type => 'boolean',
1793 optional => 1,
1794 default => 0,
1795 },
1796 keepActive => {
1797 description => "Do not decativate storage volumes.",
1798 type => 'boolean',
1799 optional => 1,
1800 default => 0,
1801 }
1802 },
1803 },
1804 returns => {
1805 type => 'string',
1806 },
1807 code => sub {
1808 my ($param) = @_;
1809
1810 my $rpcenv = PVE::RPCEnvironment::get();
1811
1812 my $authuser = $rpcenv->get_user();
1813
1814 my $node = extract_param($param, 'node');
1815
1816 my $vmid = extract_param($param, 'vmid');
1817
1818 my $skiplock = extract_param($param, 'skiplock');
1819 raise_param_exc({ skiplock => "Only root may use this option." })
1820 if $skiplock && $authuser ne 'root@pam';
1821
1822 my $keepActive = extract_param($param, 'keepActive');
1823 raise_param_exc({ keepActive => "Only root may use this option." })
1824 if $keepActive && $authuser ne 'root@pam';
1825
1826 my $storecfg = PVE::Storage::config();
1827
1828 my $realcmd = sub {
1829 my $upid = shift;
1830
1831 syslog('info', "shutdown VM $vmid: $upid\n");
1832
1833 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
1834 1, $param->{forceStop}, $keepActive);
1835
1836 return;
1837 };
1838
1839 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
1840 }});
1841
1842__PACKAGE__->register_method({
1843 name => 'vm_suspend',
1844 path => '{vmid}/status/suspend',
1845 method => 'POST',
1846 protected => 1,
1847 proxyto => 'node',
1848 description => "Suspend virtual machine.",
1849 permissions => {
1850 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1851 },
1852 parameters => {
1853 additionalProperties => 0,
1854 properties => {
1855 node => get_standard_option('pve-node'),
1856 vmid => get_standard_option('pve-vmid',
1857 { completion => \&PVE::QemuServer::complete_vmid_running }),
1858 skiplock => get_standard_option('skiplock'),
1859 },
1860 },
1861 returns => {
1862 type => 'string',
1863 },
1864 code => sub {
1865 my ($param) = @_;
1866
1867 my $rpcenv = PVE::RPCEnvironment::get();
1868
1869 my $authuser = $rpcenv->get_user();
1870
1871 my $node = extract_param($param, 'node');
1872
1873 my $vmid = extract_param($param, 'vmid');
1874
1875 my $skiplock = extract_param($param, 'skiplock');
1876 raise_param_exc({ skiplock => "Only root may use this option." })
1877 if $skiplock && $authuser ne 'root@pam';
1878
1879 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1880
1881 my $realcmd = sub {
1882 my $upid = shift;
1883
1884 syslog('info', "suspend VM $vmid: $upid\n");
1885
1886 PVE::QemuServer::vm_suspend($vmid, $skiplock);
1887
1888 return;
1889 };
1890
1891 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
1892 }});
1893
1894__PACKAGE__->register_method({
1895 name => 'vm_resume',
1896 path => '{vmid}/status/resume',
1897 method => 'POST',
1898 protected => 1,
1899 proxyto => 'node',
1900 description => "Resume virtual machine.",
1901 permissions => {
1902 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1903 },
1904 parameters => {
1905 additionalProperties => 0,
1906 properties => {
1907 node => get_standard_option('pve-node'),
1908 vmid => get_standard_option('pve-vmid',
1909 { completion => \&PVE::QemuServer::complete_vmid_running }),
1910 skiplock => get_standard_option('skiplock'),
1911 nocheck => { type => 'boolean', optional => 1 },
1912
1913 },
1914 },
1915 returns => {
1916 type => 'string',
1917 },
1918 code => sub {
1919 my ($param) = @_;
1920
1921 my $rpcenv = PVE::RPCEnvironment::get();
1922
1923 my $authuser = $rpcenv->get_user();
1924
1925 my $node = extract_param($param, 'node');
1926
1927 my $vmid = extract_param($param, 'vmid');
1928
1929 my $skiplock = extract_param($param, 'skiplock');
1930 raise_param_exc({ skiplock => "Only root may use this option." })
1931 if $skiplock && $authuser ne 'root@pam';
1932
1933 my $nocheck = extract_param($param, 'nocheck');
1934
1935 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid, $nocheck);
1936
1937 my $realcmd = sub {
1938 my $upid = shift;
1939
1940 syslog('info', "resume VM $vmid: $upid\n");
1941
1942 PVE::QemuServer::vm_resume($vmid, $skiplock, $nocheck);
1943
1944 return;
1945 };
1946
1947 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
1948 }});
1949
1950__PACKAGE__->register_method({
1951 name => 'vm_sendkey',
1952 path => '{vmid}/sendkey',
1953 method => 'PUT',
1954 protected => 1,
1955 proxyto => 'node',
1956 description => "Send key event to virtual machine.",
1957 permissions => {
1958 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1959 },
1960 parameters => {
1961 additionalProperties => 0,
1962 properties => {
1963 node => get_standard_option('pve-node'),
1964 vmid => get_standard_option('pve-vmid',
1965 { completion => \&PVE::QemuServer::complete_vmid_running }),
1966 skiplock => get_standard_option('skiplock'),
1967 key => {
1968 description => "The key (qemu monitor encoding).",
1969 type => 'string'
1970 }
1971 },
1972 },
1973 returns => { type => 'null'},
1974 code => sub {
1975 my ($param) = @_;
1976
1977 my $rpcenv = PVE::RPCEnvironment::get();
1978
1979 my $authuser = $rpcenv->get_user();
1980
1981 my $node = extract_param($param, 'node');
1982
1983 my $vmid = extract_param($param, 'vmid');
1984
1985 my $skiplock = extract_param($param, 'skiplock');
1986 raise_param_exc({ skiplock => "Only root may use this option." })
1987 if $skiplock && $authuser ne 'root@pam';
1988
1989 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1990
1991 return;
1992 }});
1993
1994__PACKAGE__->register_method({
1995 name => 'vm_feature',
1996 path => '{vmid}/feature',
1997 method => 'GET',
1998 proxyto => 'node',
1999 protected => 1,
2000 description => "Check if feature for virtual machine is available.",
2001 permissions => {
2002 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2003 },
2004 parameters => {
2005 additionalProperties => 0,
2006 properties => {
2007 node => get_standard_option('pve-node'),
2008 vmid => get_standard_option('pve-vmid'),
2009 feature => {
2010 description => "Feature to check.",
2011 type => 'string',
2012 enum => [ 'snapshot', 'clone', 'copy' ],
2013 },
2014 snapname => get_standard_option('pve-snapshot-name', {
2015 optional => 1,
2016 }),
2017 },
2018 },
2019 returns => {
2020 type => "object",
2021 properties => {
2022 hasFeature => { type => 'boolean' },
2023 nodes => {
2024 type => 'array',
2025 items => { type => 'string' },
2026 }
2027 },
2028 },
2029 code => sub {
2030 my ($param) = @_;
2031
2032 my $node = extract_param($param, 'node');
2033
2034 my $vmid = extract_param($param, 'vmid');
2035
2036 my $snapname = extract_param($param, 'snapname');
2037
2038 my $feature = extract_param($param, 'feature');
2039
2040 my $running = PVE::QemuServer::check_running($vmid);
2041
2042 my $conf = PVE::QemuServer::load_config($vmid);
2043
2044 if($snapname){
2045 my $snap = $conf->{snapshots}->{$snapname};
2046 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2047 $conf = $snap;
2048 }
2049 my $storecfg = PVE::Storage::config();
2050
2051 my $nodelist = PVE::QemuServer::shared_nodes($conf, $storecfg);
2052 my $hasFeature = PVE::QemuServer::has_feature($feature, $conf, $storecfg, $snapname, $running);
2053
2054 return {
2055 hasFeature => $hasFeature,
2056 nodes => [ keys %$nodelist ],
2057 };
2058 }});
2059
2060__PACKAGE__->register_method({
2061 name => 'clone_vm',
2062 path => '{vmid}/clone',
2063 method => 'POST',
2064 protected => 1,
2065 proxyto => 'node',
2066 description => "Create a copy of virtual machine/template.",
2067 permissions => {
2068 description => "You need 'VM.Clone' permissions on /vms/{vmid}, and 'VM.Allocate' permissions " .
2069 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
2070 "'Datastore.AllocateSpace' on any used storage.",
2071 check =>
2072 [ 'and',
2073 ['perm', '/vms/{vmid}', [ 'VM.Clone' ]],
2074 [ 'or',
2075 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
2076 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
2077 ],
2078 ]
2079 },
2080 parameters => {
2081 additionalProperties => 0,
2082 properties => {
2083 node => get_standard_option('pve-node'),
2084 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
2085 newid => get_standard_option('pve-vmid', { description => 'VMID for the clone.' }),
2086 name => {
2087 optional => 1,
2088 type => 'string', format => 'dns-name',
2089 description => "Set a name for the new VM.",
2090 },
2091 description => {
2092 optional => 1,
2093 type => 'string',
2094 description => "Description for the new VM.",
2095 },
2096 pool => {
2097 optional => 1,
2098 type => 'string', format => 'pve-poolid',
2099 description => "Add the new VM to the specified pool.",
2100 },
2101 snapname => get_standard_option('pve-snapshot-name', {
2102 optional => 1,
2103 }),
2104 storage => get_standard_option('pve-storage-id', {
2105 description => "Target storage for full clone.",
2106 requires => 'full',
2107 optional => 1,
2108 }),
2109 'format' => {
2110 description => "Target format for file storage.",
2111 requires => 'full',
2112 type => 'string',
2113 optional => 1,
2114 enum => [ 'raw', 'qcow2', 'vmdk'],
2115 },
2116 full => {
2117 optional => 1,
2118 type => 'boolean',
2119 description => "Create a full copy of all disk. This is always done when " .
2120 "you clone a normal VM. For VM templates, we try to create a linked clone by default.",
2121 default => 0,
2122 },
2123 target => get_standard_option('pve-node', {
2124 description => "Target node. Only allowed if the original VM is on shared storage.",
2125 optional => 1,
2126 }),
2127 },
2128 },
2129 returns => {
2130 type => 'string',
2131 },
2132 code => sub {
2133 my ($param) = @_;
2134
2135 my $rpcenv = PVE::RPCEnvironment::get();
2136
2137 my $authuser = $rpcenv->get_user();
2138
2139 my $node = extract_param($param, 'node');
2140
2141 my $vmid = extract_param($param, 'vmid');
2142
2143 my $newid = extract_param($param, 'newid');
2144
2145 my $pool = extract_param($param, 'pool');
2146
2147 if (defined($pool)) {
2148 $rpcenv->check_pool_exist($pool);
2149 }
2150
2151 my $snapname = extract_param($param, 'snapname');
2152
2153 my $storage = extract_param($param, 'storage');
2154
2155 my $format = extract_param($param, 'format');
2156
2157 my $target = extract_param($param, 'target');
2158
2159 my $localnode = PVE::INotify::nodename();
2160
2161 undef $target if $target && ($target eq $localnode || $target eq 'localhost');
2162
2163 PVE::Cluster::check_node_exists($target) if $target;
2164
2165 my $storecfg = PVE::Storage::config();
2166
2167 if ($storage) {
2168 # check if storage is enabled on local node
2169 PVE::Storage::storage_check_enabled($storecfg, $storage);
2170 if ($target) {
2171 # check if storage is available on target node
2172 PVE::Storage::storage_check_node($storecfg, $storage, $target);
2173 # clone only works if target storage is shared
2174 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
2175 die "can't clone to non-shared storage '$storage'\n" if !$scfg->{shared};
2176 }
2177 }
2178
2179 PVE::Cluster::check_cfs_quorum();
2180
2181 my $running = PVE::QemuServer::check_running($vmid) || 0;
2182
2183 # exclusive lock if VM is running - else shared lock is enough;
2184 my $shared_lock = $running ? 0 : 1;
2185
2186 my $clonefn = sub {
2187
2188 # do all tests after lock
2189 # we also try to do all tests before we fork the worker
2190
2191 my $conf = PVE::QemuServer::load_config($vmid);
2192
2193 PVE::QemuServer::check_lock($conf);
2194
2195 my $verify_running = PVE::QemuServer::check_running($vmid) || 0;
2196
2197 die "unexpected state change\n" if $verify_running != $running;
2198
2199 die "snapshot '$snapname' does not exist\n"
2200 if $snapname && !defined( $conf->{snapshots}->{$snapname});
2201
2202 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
2203
2204 my $sharedvm = &$check_storage_access_clone($rpcenv, $authuser, $storecfg, $oldconf, $storage);
2205
2206 die "can't clone VM to node '$target' (VM uses local storage)\n" if $target && !$sharedvm;
2207
2208 my $conffile = PVE::QemuServer::config_file($newid);
2209
2210 die "unable to create VM $newid: config file already exists\n"
2211 if -f $conffile;
2212
2213 my $newconf = { lock => 'clone' };
2214 my $drives = {};
2215 my $fullclone = {};
2216 my $vollist = [];
2217
2218 foreach my $opt (keys %$oldconf) {
2219 my $value = $oldconf->{$opt};
2220
2221 # do not copy snapshot related info
2222 next if $opt eq 'snapshots' || $opt eq 'parent' || $opt eq 'snaptime' ||
2223 $opt eq 'vmstate' || $opt eq 'snapstate';
2224
2225 # no need to copy unused images, because VMID(owner) changes anyways
2226 next if $opt =~ m/^unused\d+$/;
2227
2228 # always change MAC! address
2229 if ($opt =~ m/^net(\d+)$/) {
2230 my $net = PVE::QemuServer::parse_net($value);
2231 $net->{macaddr} = PVE::Tools::random_ether_addr();
2232 $newconf->{$opt} = PVE::QemuServer::print_net($net);
2233 } elsif (PVE::QemuServer::valid_drivename($opt)) {
2234 my $drive = PVE::QemuServer::parse_drive($opt, $value);
2235 die "unable to parse drive options for '$opt'\n" if !$drive;
2236 if (PVE::QemuServer::drive_is_cdrom($drive)) {
2237 $newconf->{$opt} = $value; # simply copy configuration
2238 } else {
2239 if ($param->{full}) {
2240 die "Full clone feature is not available"
2241 if !PVE::Storage::volume_has_feature($storecfg, 'copy', $drive->{file}, $snapname, $running);
2242 $fullclone->{$opt} = 1;
2243 } else {
2244 # not full means clone instead of copy
2245 die "Linked clone feature is not available"
2246 if !PVE::Storage::volume_has_feature($storecfg, 'clone', $drive->{file}, $snapname, $running);
2247 }
2248 $drives->{$opt} = $drive;
2249 push @$vollist, $drive->{file};
2250 }
2251 } else {
2252 # copy everything else
2253 $newconf->{$opt} = $value;
2254 }
2255 }
2256
2257 # auto generate a new uuid
2258 my ($uuid, $uuid_str);
2259 UUID::generate($uuid);
2260 UUID::unparse($uuid, $uuid_str);
2261 my $smbios1 = PVE::QemuServer::parse_smbios1($newconf->{smbios1} || '');
2262 $smbios1->{uuid} = $uuid_str;
2263 $newconf->{smbios1} = PVE::QemuServer::print_smbios1($smbios1);
2264
2265 delete $newconf->{template};
2266
2267 if ($param->{name}) {
2268 $newconf->{name} = $param->{name};
2269 } else {
2270 if ($oldconf->{name}) {
2271 $newconf->{name} = "Copy-of-$oldconf->{name}";
2272 } else {
2273 $newconf->{name} = "Copy-of-VM-$vmid";
2274 }
2275 }
2276
2277 if ($param->{description}) {
2278 $newconf->{description} = $param->{description};
2279 }
2280
2281 # create empty/temp config - this fails if VM already exists on other node
2282 PVE::Tools::file_set_contents($conffile, "# qmclone temporary file\nlock: clone\n");
2283
2284 my $realcmd = sub {
2285 my $upid = shift;
2286
2287 my $newvollist = [];
2288
2289 eval {
2290 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
2291
2292 PVE::Storage::activate_volumes($storecfg, $vollist, $snapname);
2293
2294 foreach my $opt (keys %$drives) {
2295 my $drive = $drives->{$opt};
2296
2297 my $newdrive = PVE::QemuServer::clone_disk($storecfg, $vmid, $running, $opt, $drive, $snapname,
2298 $newid, $storage, $format, $fullclone->{$opt}, $newvollist);
2299
2300 $newconf->{$opt} = PVE::QemuServer::print_drive($vmid, $newdrive);
2301
2302 PVE::QemuServer::write_config($newid, $newconf);
2303 }
2304
2305 delete $newconf->{lock};
2306 PVE::QemuServer::write_config($newid, $newconf);
2307
2308 if ($target) {
2309 # always deactivate volumes - avoid lvm LVs to be active on several nodes
2310 PVE::Storage::deactivate_volumes($storecfg, $vollist, $snapname) if !$running;
2311
2312 my $newconffile = PVE::QemuServer::config_file($newid, $target);
2313 die "Failed to move config to node '$target' - rename failed: $!\n"
2314 if !rename($conffile, $newconffile);
2315 }
2316
2317 PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
2318 };
2319 if (my $err = $@) {
2320 unlink $conffile;
2321
2322 sleep 1; # some storage like rbd need to wait before release volume - really?
2323
2324 foreach my $volid (@$newvollist) {
2325 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2326 warn $@ if $@;
2327 }
2328 die "clone failed: $err";
2329 }
2330
2331 return;
2332 };
2333
2334 PVE::Firewall::clone_vmfw_conf($vmid, $newid);
2335
2336 return $rpcenv->fork_worker('qmclone', $vmid, $authuser, $realcmd);
2337 };
2338
2339 return PVE::QemuServer::lock_config_mode($vmid, 1, $shared_lock, sub {
2340 # Aquire exclusive lock lock for $newid
2341 return PVE::QemuServer::lock_config_full($newid, 1, $clonefn);
2342 });
2343
2344 }});
2345
2346__PACKAGE__->register_method({
2347 name => 'move_vm_disk',
2348 path => '{vmid}/move_disk',
2349 method => 'POST',
2350 protected => 1,
2351 proxyto => 'node',
2352 description => "Move volume to different storage.",
2353 permissions => {
2354 description => "You need 'VM.Config.Disk' permissions on /vms/{vmid}, " .
2355 "and 'Datastore.AllocateSpace' permissions on the storage.",
2356 check =>
2357 [ 'and',
2358 ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
2359 ['perm', '/storage/{storage}', [ 'Datastore.AllocateSpace' ]],
2360 ],
2361 },
2362 parameters => {
2363 additionalProperties => 0,
2364 properties => {
2365 node => get_standard_option('pve-node'),
2366 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
2367 disk => {
2368 type => 'string',
2369 description => "The disk you want to move.",
2370 enum => [ PVE::QemuServer::disknames() ],
2371 },
2372 storage => get_standard_option('pve-storage-id', {
2373 description => "Target storage.",
2374 completion => \&PVE::QemuServer::complete_storage,
2375 }),
2376 'format' => {
2377 type => 'string',
2378 description => "Target Format.",
2379 enum => [ 'raw', 'qcow2', 'vmdk' ],
2380 optional => 1,
2381 },
2382 delete => {
2383 type => 'boolean',
2384 description => "Delete the original disk after successful copy. By default the original disk is kept as unused disk.",
2385 optional => 1,
2386 default => 0,
2387 },
2388 digest => {
2389 type => 'string',
2390 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2391 maxLength => 40,
2392 optional => 1,
2393 },
2394 },
2395 },
2396 returns => {
2397 type => 'string',
2398 description => "the task ID.",
2399 },
2400 code => sub {
2401 my ($param) = @_;
2402
2403 my $rpcenv = PVE::RPCEnvironment::get();
2404
2405 my $authuser = $rpcenv->get_user();
2406
2407 my $node = extract_param($param, 'node');
2408
2409 my $vmid = extract_param($param, 'vmid');
2410
2411 my $digest = extract_param($param, 'digest');
2412
2413 my $disk = extract_param($param, 'disk');
2414
2415 my $storeid = extract_param($param, 'storage');
2416
2417 my $format = extract_param($param, 'format');
2418
2419 my $storecfg = PVE::Storage::config();
2420
2421 my $updatefn = sub {
2422
2423 my $conf = PVE::QemuServer::load_config($vmid);
2424
2425 die "checksum missmatch (file change by other user?)\n"
2426 if $digest && $digest ne $conf->{digest};
2427
2428 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2429
2430 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2431
2432 my $old_volid = $drive->{file} || die "disk '$disk' has no associated volume\n";
2433
2434 die "you can't move a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2435
2436 my $oldfmt;
2437 my ($oldstoreid, $oldvolname) = PVE::Storage::parse_volume_id($old_volid);
2438 if ($oldvolname =~ m/\.(raw|qcow2|vmdk)$/){
2439 $oldfmt = $1;
2440 }
2441
2442 die "you can't move on the same storage with same format\n" if $oldstoreid eq $storeid &&
2443 (!$format || !$oldfmt || $oldfmt eq $format);
2444
2445 PVE::Cluster::log_msg('info', $authuser, "move disk VM $vmid: move --disk $disk --storage $storeid");
2446
2447 my $running = PVE::QemuServer::check_running($vmid);
2448
2449 PVE::Storage::activate_volumes($storecfg, [ $drive->{file} ]);
2450
2451 my $realcmd = sub {
2452
2453 my $newvollist = [];
2454
2455 eval {
2456 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
2457
2458 my $newdrive = PVE::QemuServer::clone_disk($storecfg, $vmid, $running, $disk, $drive, undef,
2459 $vmid, $storeid, $format, 1, $newvollist);
2460
2461 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $newdrive);
2462
2463 PVE::QemuServer::add_unused_volume($conf, $old_volid) if !$param->{delete};
2464
2465 PVE::QemuServer::write_config($vmid, $conf);
2466
2467 eval {
2468 # try to deactivate volumes - avoid lvm LVs to be active on several nodes
2469 PVE::Storage::deactivate_volumes($storecfg, [ $newdrive->{file} ])
2470 if !$running;
2471 };
2472 warn $@ if $@;
2473 };
2474 if (my $err = $@) {
2475
2476 foreach my $volid (@$newvollist) {
2477 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2478 warn $@ if $@;
2479 }
2480 die "storage migration failed: $err";
2481 }
2482
2483 if ($param->{delete}) {
2484 if (PVE::QemuServer::is_volume_in_use($storecfg, $conf, undef, $old_volid)) {
2485 warn "volume $old_volid still has snapshots, can't delete it\n";
2486 PVE::QemuServer::add_unused_volume($conf, $old_volid);
2487 PVE::QemuServer::write_config($vmid, $conf);
2488 } else {
2489 eval { PVE::Storage::vdisk_free($storecfg, $old_volid); };
2490 warn $@ if $@;
2491 }
2492 }
2493 };
2494
2495 return $rpcenv->fork_worker('qmmove', $vmid, $authuser, $realcmd);
2496 };
2497
2498 return PVE::QemuServer::lock_config($vmid, $updatefn);
2499 }});
2500
2501__PACKAGE__->register_method({
2502 name => 'migrate_vm',
2503 path => '{vmid}/migrate',
2504 method => 'POST',
2505 protected => 1,
2506 proxyto => 'node',
2507 description => "Migrate virtual machine. Creates a new migration task.",
2508 permissions => {
2509 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
2510 },
2511 parameters => {
2512 additionalProperties => 0,
2513 properties => {
2514 node => get_standard_option('pve-node'),
2515 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
2516 target => get_standard_option('pve-node', {
2517 description => "Target node.",
2518 completion => \&PVE::Cluster::complete_migration_target,
2519 }),
2520 online => {
2521 type => 'boolean',
2522 description => "Use online/live migration.",
2523 optional => 1,
2524 },
2525 force => {
2526 type => 'boolean',
2527 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
2528 optional => 1,
2529 },
2530 },
2531 },
2532 returns => {
2533 type => 'string',
2534 description => "the task ID.",
2535 },
2536 code => sub {
2537 my ($param) = @_;
2538
2539 my $rpcenv = PVE::RPCEnvironment::get();
2540
2541 my $authuser = $rpcenv->get_user();
2542
2543 my $target = extract_param($param, 'target');
2544
2545 my $localnode = PVE::INotify::nodename();
2546 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
2547
2548 PVE::Cluster::check_cfs_quorum();
2549
2550 PVE::Cluster::check_node_exists($target);
2551
2552 my $targetip = PVE::Cluster::remote_node_ip($target);
2553
2554 my $vmid = extract_param($param, 'vmid');
2555
2556 raise_param_exc({ force => "Only root may use this option." })
2557 if $param->{force} && $authuser ne 'root@pam';
2558
2559 # test if VM exists
2560 my $conf = PVE::QemuServer::load_config($vmid);
2561
2562 # try to detect errors early
2563
2564 PVE::QemuServer::check_lock($conf);
2565
2566 if (PVE::QemuServer::check_running($vmid)) {
2567 die "cant migrate running VM without --online\n"
2568 if !$param->{online};
2569 }
2570
2571 my $storecfg = PVE::Storage::config();
2572 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
2573
2574 if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
2575
2576 my $hacmd = sub {
2577 my $upid = shift;
2578
2579 my $service = "vm:$vmid";
2580
2581 my $cmd = ['ha-manager', 'migrate', $service, $target];
2582
2583 print "Executing HA migrate for VM $vmid to node $target\n";
2584
2585 PVE::Tools::run_command($cmd);
2586
2587 return;
2588 };
2589
2590 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
2591
2592 } else {
2593
2594 my $realcmd = sub {
2595 my $upid = shift;
2596
2597 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
2598 };
2599
2600 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
2601 }
2602
2603 }});
2604
2605__PACKAGE__->register_method({
2606 name => 'monitor',
2607 path => '{vmid}/monitor',
2608 method => 'POST',
2609 protected => 1,
2610 proxyto => 'node',
2611 description => "Execute Qemu monitor commands.",
2612 permissions => {
2613 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
2614 },
2615 parameters => {
2616 additionalProperties => 0,
2617 properties => {
2618 node => get_standard_option('pve-node'),
2619 vmid => get_standard_option('pve-vmid'),
2620 command => {
2621 type => 'string',
2622 description => "The monitor command.",
2623 }
2624 },
2625 },
2626 returns => { type => 'string'},
2627 code => sub {
2628 my ($param) = @_;
2629
2630 my $vmid = $param->{vmid};
2631
2632 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
2633
2634 my $res = '';
2635 eval {
2636 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
2637 };
2638 $res = "ERROR: $@" if $@;
2639
2640 return $res;
2641 }});
2642
2643__PACKAGE__->register_method({
2644 name => 'resize_vm',
2645 path => '{vmid}/resize',
2646 method => 'PUT',
2647 protected => 1,
2648 proxyto => 'node',
2649 description => "Extend volume size.",
2650 permissions => {
2651 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
2652 },
2653 parameters => {
2654 additionalProperties => 0,
2655 properties => {
2656 node => get_standard_option('pve-node'),
2657 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
2658 skiplock => get_standard_option('skiplock'),
2659 disk => {
2660 type => 'string',
2661 description => "The disk you want to resize.",
2662 enum => [PVE::QemuServer::disknames()],
2663 },
2664 size => {
2665 type => 'string',
2666 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2667 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.",
2668 },
2669 digest => {
2670 type => 'string',
2671 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2672 maxLength => 40,
2673 optional => 1,
2674 },
2675 },
2676 },
2677 returns => { type => 'null'},
2678 code => sub {
2679 my ($param) = @_;
2680
2681 my $rpcenv = PVE::RPCEnvironment::get();
2682
2683 my $authuser = $rpcenv->get_user();
2684
2685 my $node = extract_param($param, 'node');
2686
2687 my $vmid = extract_param($param, 'vmid');
2688
2689 my $digest = extract_param($param, 'digest');
2690
2691 my $disk = extract_param($param, 'disk');
2692
2693 my $sizestr = extract_param($param, 'size');
2694
2695 my $skiplock = extract_param($param, 'skiplock');
2696 raise_param_exc({ skiplock => "Only root may use this option." })
2697 if $skiplock && $authuser ne 'root@pam';
2698
2699 my $storecfg = PVE::Storage::config();
2700
2701 my $updatefn = sub {
2702
2703 my $conf = PVE::QemuServer::load_config($vmid);
2704
2705 die "checksum missmatch (file change by other user?)\n"
2706 if $digest && $digest ne $conf->{digest};
2707 PVE::QemuServer::check_lock($conf) if !$skiplock;
2708
2709 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2710
2711 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2712
2713 my (undef, undef, undef, undef, undef, undef, $format) =
2714 PVE::Storage::parse_volname($storecfg, $drive->{file});
2715
2716 die "can't resize volume: $disk if snapshot exists\n"
2717 if %{$conf->{snapshots}} && $format eq 'qcow2';
2718
2719 my $volid = $drive->{file};
2720
2721 die "disk '$disk' has no associated volume\n" if !$volid;
2722
2723 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2724
2725 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
2726
2727 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
2728
2729 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
2730
2731 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
2732 my ($ext, $newsize, $unit) = ($1, $2, $4);
2733 if ($unit) {
2734 if ($unit eq 'K') {
2735 $newsize = $newsize * 1024;
2736 } elsif ($unit eq 'M') {
2737 $newsize = $newsize * 1024 * 1024;
2738 } elsif ($unit eq 'G') {
2739 $newsize = $newsize * 1024 * 1024 * 1024;
2740 } elsif ($unit eq 'T') {
2741 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
2742 }
2743 }
2744 $newsize += $size if $ext;
2745 $newsize = int($newsize);
2746
2747 die "unable to skrink disk size\n" if $newsize < $size;
2748
2749 return if $size == $newsize;
2750
2751 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
2752
2753 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
2754
2755 $drive->{size} = $newsize;
2756 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
2757
2758 PVE::QemuServer::write_config($vmid, $conf);
2759 };
2760
2761 PVE::QemuServer::lock_config($vmid, $updatefn);
2762 return undef;
2763 }});
2764
2765__PACKAGE__->register_method({
2766 name => 'snapshot_list',
2767 path => '{vmid}/snapshot',
2768 method => 'GET',
2769 description => "List all snapshots.",
2770 permissions => {
2771 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2772 },
2773 proxyto => 'node',
2774 protected => 1, # qemu pid files are only readable by root
2775 parameters => {
2776 additionalProperties => 0,
2777 properties => {
2778 vmid => get_standard_option('pve-vmid'),
2779 node => get_standard_option('pve-node'),
2780 },
2781 },
2782 returns => {
2783 type => 'array',
2784 items => {
2785 type => "object",
2786 properties => {},
2787 },
2788 links => [ { rel => 'child', href => "{name}" } ],
2789 },
2790 code => sub {
2791 my ($param) = @_;
2792
2793 my $vmid = $param->{vmid};
2794
2795 my $conf = PVE::QemuServer::load_config($vmid);
2796 my $snaphash = $conf->{snapshots} || {};
2797
2798 my $res = [];
2799
2800 foreach my $name (keys %$snaphash) {
2801 my $d = $snaphash->{$name};
2802 my $item = {
2803 name => $name,
2804 snaptime => $d->{snaptime} || 0,
2805 vmstate => $d->{vmstate} ? 1 : 0,
2806 description => $d->{description} || '',
2807 };
2808 $item->{parent} = $d->{parent} if $d->{parent};
2809 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
2810 push @$res, $item;
2811 }
2812
2813 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
2814 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
2815 $current->{parent} = $conf->{parent} if $conf->{parent};
2816
2817 push @$res, $current;
2818
2819 return $res;
2820 }});
2821
2822__PACKAGE__->register_method({
2823 name => 'snapshot',
2824 path => '{vmid}/snapshot',
2825 method => 'POST',
2826 protected => 1,
2827 proxyto => 'node',
2828 description => "Snapshot a VM.",
2829 permissions => {
2830 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2831 },
2832 parameters => {
2833 additionalProperties => 0,
2834 properties => {
2835 node => get_standard_option('pve-node'),
2836 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
2837 snapname => get_standard_option('pve-snapshot-name'),
2838 vmstate => {
2839 optional => 1,
2840 type => 'boolean',
2841 description => "Save the vmstate",
2842 },
2843 description => {
2844 optional => 1,
2845 type => 'string',
2846 description => "A textual description or comment.",
2847 },
2848 },
2849 },
2850 returns => {
2851 type => 'string',
2852 description => "the task ID.",
2853 },
2854 code => sub {
2855 my ($param) = @_;
2856
2857 my $rpcenv = PVE::RPCEnvironment::get();
2858
2859 my $authuser = $rpcenv->get_user();
2860
2861 my $node = extract_param($param, 'node');
2862
2863 my $vmid = extract_param($param, 'vmid');
2864
2865 my $snapname = extract_param($param, 'snapname');
2866
2867 die "unable to use snapshot name 'current' (reserved name)\n"
2868 if $snapname eq 'current';
2869
2870 my $realcmd = sub {
2871 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
2872 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
2873 $param->{description});
2874 };
2875
2876 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2877 }});
2878
2879__PACKAGE__->register_method({
2880 name => 'snapshot_cmd_idx',
2881 path => '{vmid}/snapshot/{snapname}',
2882 description => '',
2883 method => 'GET',
2884 permissions => {
2885 user => 'all',
2886 },
2887 parameters => {
2888 additionalProperties => 0,
2889 properties => {
2890 vmid => get_standard_option('pve-vmid'),
2891 node => get_standard_option('pve-node'),
2892 snapname => get_standard_option('pve-snapshot-name'),
2893 },
2894 },
2895 returns => {
2896 type => 'array',
2897 items => {
2898 type => "object",
2899 properties => {},
2900 },
2901 links => [ { rel => 'child', href => "{cmd}" } ],
2902 },
2903 code => sub {
2904 my ($param) = @_;
2905
2906 my $res = [];
2907
2908 push @$res, { cmd => 'rollback' };
2909 push @$res, { cmd => 'config' };
2910
2911 return $res;
2912 }});
2913
2914__PACKAGE__->register_method({
2915 name => 'update_snapshot_config',
2916 path => '{vmid}/snapshot/{snapname}/config',
2917 method => 'PUT',
2918 protected => 1,
2919 proxyto => 'node',
2920 description => "Update snapshot metadata.",
2921 permissions => {
2922 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2923 },
2924 parameters => {
2925 additionalProperties => 0,
2926 properties => {
2927 node => get_standard_option('pve-node'),
2928 vmid => get_standard_option('pve-vmid'),
2929 snapname => get_standard_option('pve-snapshot-name'),
2930 description => {
2931 optional => 1,
2932 type => 'string',
2933 description => "A textual description or comment.",
2934 },
2935 },
2936 },
2937 returns => { type => 'null' },
2938 code => sub {
2939 my ($param) = @_;
2940
2941 my $rpcenv = PVE::RPCEnvironment::get();
2942
2943 my $authuser = $rpcenv->get_user();
2944
2945 my $vmid = extract_param($param, 'vmid');
2946
2947 my $snapname = extract_param($param, 'snapname');
2948
2949 return undef if !defined($param->{description});
2950
2951 my $updatefn = sub {
2952
2953 my $conf = PVE::QemuServer::load_config($vmid);
2954
2955 PVE::QemuServer::check_lock($conf);
2956
2957 my $snap = $conf->{snapshots}->{$snapname};
2958
2959 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2960
2961 $snap->{description} = $param->{description} if defined($param->{description});
2962
2963 PVE::QemuServer::write_config($vmid, $conf);
2964 };
2965
2966 PVE::QemuServer::lock_config($vmid, $updatefn);
2967
2968 return undef;
2969 }});
2970
2971__PACKAGE__->register_method({
2972 name => 'get_snapshot_config',
2973 path => '{vmid}/snapshot/{snapname}/config',
2974 method => 'GET',
2975 proxyto => 'node',
2976 description => "Get snapshot configuration",
2977 permissions => {
2978 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2979 },
2980 parameters => {
2981 additionalProperties => 0,
2982 properties => {
2983 node => get_standard_option('pve-node'),
2984 vmid => get_standard_option('pve-vmid'),
2985 snapname => get_standard_option('pve-snapshot-name'),
2986 },
2987 },
2988 returns => { type => "object" },
2989 code => sub {
2990 my ($param) = @_;
2991
2992 my $rpcenv = PVE::RPCEnvironment::get();
2993
2994 my $authuser = $rpcenv->get_user();
2995
2996 my $vmid = extract_param($param, 'vmid');
2997
2998 my $snapname = extract_param($param, 'snapname');
2999
3000 my $conf = PVE::QemuServer::load_config($vmid);
3001
3002 my $snap = $conf->{snapshots}->{$snapname};
3003
3004 die "snapshot '$snapname' does not exist\n" if !defined($snap);
3005
3006 return $snap;
3007 }});
3008
3009__PACKAGE__->register_method({
3010 name => 'rollback',
3011 path => '{vmid}/snapshot/{snapname}/rollback',
3012 method => 'POST',
3013 protected => 1,
3014 proxyto => 'node',
3015 description => "Rollback VM state to specified snapshot.",
3016 permissions => {
3017 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
3018 },
3019 parameters => {
3020 additionalProperties => 0,
3021 properties => {
3022 node => get_standard_option('pve-node'),
3023 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
3024 snapname => get_standard_option('pve-snapshot-name'),
3025 },
3026 },
3027 returns => {
3028 type => 'string',
3029 description => "the task ID.",
3030 },
3031 code => sub {
3032 my ($param) = @_;
3033
3034 my $rpcenv = PVE::RPCEnvironment::get();
3035
3036 my $authuser = $rpcenv->get_user();
3037
3038 my $node = extract_param($param, 'node');
3039
3040 my $vmid = extract_param($param, 'vmid');
3041
3042 my $snapname = extract_param($param, 'snapname');
3043
3044 my $realcmd = sub {
3045 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
3046 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
3047 };
3048
3049 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
3050 }});
3051
3052__PACKAGE__->register_method({
3053 name => 'delsnapshot',
3054 path => '{vmid}/snapshot/{snapname}',
3055 method => 'DELETE',
3056 protected => 1,
3057 proxyto => 'node',
3058 description => "Delete a VM snapshot.",
3059 permissions => {
3060 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
3061 },
3062 parameters => {
3063 additionalProperties => 0,
3064 properties => {
3065 node => get_standard_option('pve-node'),
3066 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
3067 snapname => get_standard_option('pve-snapshot-name'),
3068 force => {
3069 optional => 1,
3070 type => 'boolean',
3071 description => "For removal from config file, even if removing disk snapshots fails.",
3072 },
3073 },
3074 },
3075 returns => {
3076 type => 'string',
3077 description => "the task ID.",
3078 },
3079 code => sub {
3080 my ($param) = @_;
3081
3082 my $rpcenv = PVE::RPCEnvironment::get();
3083
3084 my $authuser = $rpcenv->get_user();
3085
3086 my $node = extract_param($param, 'node');
3087
3088 my $vmid = extract_param($param, 'vmid');
3089
3090 my $snapname = extract_param($param, 'snapname');
3091
3092 my $realcmd = sub {
3093 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
3094 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
3095 };
3096
3097 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
3098 }});
3099
3100__PACKAGE__->register_method({
3101 name => 'template',
3102 path => '{vmid}/template',
3103 method => 'POST',
3104 protected => 1,
3105 proxyto => 'node',
3106 description => "Create a Template.",
3107 permissions => {
3108 description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
3109 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
3110 },
3111 parameters => {
3112 additionalProperties => 0,
3113 properties => {
3114 node => get_standard_option('pve-node'),
3115 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_stopped }),
3116 disk => {
3117 optional => 1,
3118 type => 'string',
3119 description => "If you want to convert only 1 disk to base image.",
3120 enum => [PVE::QemuServer::disknames()],
3121 },
3122
3123 },
3124 },
3125 returns => { type => 'null'},
3126 code => sub {
3127 my ($param) = @_;
3128
3129 my $rpcenv = PVE::RPCEnvironment::get();
3130
3131 my $authuser = $rpcenv->get_user();
3132
3133 my $node = extract_param($param, 'node');
3134
3135 my $vmid = extract_param($param, 'vmid');
3136
3137 my $disk = extract_param($param, 'disk');
3138
3139 my $updatefn = sub {
3140
3141 my $conf = PVE::QemuServer::load_config($vmid);
3142
3143 PVE::QemuServer::check_lock($conf);
3144
3145 die "unable to create template, because VM contains snapshots\n"
3146 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
3147
3148 die "you can't convert a template to a template\n"
3149 if PVE::QemuServer::is_template($conf) && !$disk;
3150
3151 die "you can't convert a VM to template if VM is running\n"
3152 if PVE::QemuServer::check_running($vmid);
3153
3154 my $realcmd = sub {
3155 PVE::QemuServer::template_create($vmid, $conf, $disk);
3156 };
3157
3158 $conf->{template} = 1;
3159 PVE::QemuServer::write_config($vmid, $conf);
3160
3161 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
3162 };
3163
3164 PVE::QemuServer::lock_config($vmid, $updatefn);
3165 return undef;
3166 }});
3167
31681;