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