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