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