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