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