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