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