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