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