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