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