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