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