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