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