]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
add spice proxy API
[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',
1328 method => 'GET', # fixme: should be POST, but howto handle that in the HTML client
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' },
1347 host => { type => 'string' },
1348 port => { type => 'integer' },
1349 },
1350 },
1351 code => sub {
1352 my ($param) = @_;
1353
1354 my $rpcenv = PVE::RPCEnvironment::get();
1355
1356 my $authuser = $rpcenv->get_user();
1357
1358 my $vmid = $param->{vmid};
1359 my $node = $param->{node};
1360
1361 my $port = PVE::Tools::next_vnc_port();
1362
1363 my $remip;
1364
1365 # Note: we currectly use "proxyto => 'node'", so this code will never trigger
1366 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1367 $remip = PVE::Cluster::remote_node_ip($node);
1368 }
1369
1370 my $authpath = "/vms/$vmid";
1371
1372 my $ticket = PVE::AccessControl::assemble_spice_ticket($authuser, $authpath);
1373
1374 my $timeout = 10;
1375
1376 # Note: this only works if VM is on local node
1377 PVE::QemuServer::vm_mon_cmd($vmid, "set_password", protocol => 'spice', password => $ticket);
1378 PVE::QemuServer::vm_mon_cmd($vmid, "expire_password", protocol => 'spice', time => "+30");
1379
1380 my $remcmd = []; #fixme
1381
1382 my $realcmd = sub {
1383 my $upid = shift;
1384
1385 syslog('info', "starting spice proxy $upid\n");
1386
1387 my $socket = PVE::QemuServer::spice_socket($vmid);
1388
1389 my $cmd = ['/usr/bin/socat', '-d', '-d',
1390 "TCP-LISTEN:$port,reuseaddr,fork" ];
1391
1392 if ($remip) {
1393 push @$cmd, "EXEC:'ssh root@$remip socat STDIO UNIX-CONNECT:$socket";
1394 } else {
1395 push @$cmd, "UNIX-CONNECT:$socket";
1396 }
1397
1398 my $conn_count = 0;
1399
1400 my $parser = sub {
1401 my $line = shift;
1402 print "$line\n";
1403 if ($line =~ /successfully connected from/) {
1404 $conn_count++;
1405 } elsif ($line =~ /exiting with status/) {
1406 $conn_count--;
1407 # Note: counting connections seems unreliable here
1408 die "client exit\n"; # if $conn_count <= 0;
1409 }
1410 };
1411
1412 eval { PVE::Tools::run_command($cmd, errfunc => $parser, outfunc => sub{}); };
1413 if (my $err = $@) {
1414 die $err if $err !~ m/client exit$/;
1415 }
1416
1417 return;
1418 };
1419
1420 my $upid = $rpcenv->fork_worker('spiceproxy', $vmid, $authuser, $realcmd);
1421
1422 PVE::Tools::wait_for_vnc_port($port);
1423
1424 # fimxe: ??
1425 my $host = `hostname -f` || PVE::INotify::nodename();
1426 chomp $host;
1427
1428 return {
1429 type => 'spice',
1430 host => $host,
1431 port => $port,
1432 password => $ticket,
1433 upid => $upid,
1434 };
1435 }});
1436
5fdbe4f0
DM
1437__PACKAGE__->register_method({
1438 name => 'vmcmdidx',
afdb31d5 1439 path => '{vmid}/status',
5fdbe4f0
DM
1440 method => 'GET',
1441 proxyto => 'node',
1442 description => "Directory index",
a0d1b1a2
DM
1443 permissions => {
1444 user => 'all',
1445 },
5fdbe4f0
DM
1446 parameters => {
1447 additionalProperties => 0,
1448 properties => {
1449 node => get_standard_option('pve-node'),
1450 vmid => get_standard_option('pve-vmid'),
1451 },
1452 },
1453 returns => {
1454 type => 'array',
1455 items => {
1456 type => "object",
1457 properties => {
1458 subdir => { type => 'string' },
1459 },
1460 },
1461 links => [ { rel => 'child', href => "{subdir}" } ],
1462 },
1463 code => sub {
1464 my ($param) = @_;
1465
1466 # test if VM exists
1467 my $conf = PVE::QemuServer::load_config($param->{vmid});
1468
1469 my $res = [
1470 { subdir => 'current' },
1471 { subdir => 'start' },
1472 { subdir => 'stop' },
1473 ];
afdb31d5 1474
5fdbe4f0
DM
1475 return $res;
1476 }});
1477
88fc87b4
DM
1478my $vm_is_ha_managed = sub {
1479 my ($vmid) = @_;
1480
1481 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1482 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1483 return 1;
75466c4f 1484 }
88fc87b4
DM
1485 return 0;
1486};
1487
1e3baf05 1488__PACKAGE__->register_method({
afdb31d5 1489 name => 'vm_status',
5fdbe4f0 1490 path => '{vmid}/status/current',
1e3baf05
DM
1491 method => 'GET',
1492 proxyto => 'node',
1493 protected => 1, # qemu pid files are only readable by root
1494 description => "Get virtual machine status.",
a0d1b1a2
DM
1495 permissions => {
1496 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1497 },
1e3baf05
DM
1498 parameters => {
1499 additionalProperties => 0,
1500 properties => {
1501 node => get_standard_option('pve-node'),
1502 vmid => get_standard_option('pve-vmid'),
1503 },
1504 },
1505 returns => { type => 'object' },
1506 code => sub {
1507 my ($param) = @_;
1508
1509 # test if VM exists
1510 my $conf = PVE::QemuServer::load_config($param->{vmid});
1511
03a33f30 1512 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
8610701a 1513 my $status = $vmstatus->{$param->{vmid}};
1e3baf05 1514
88fc87b4 1515 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
8610701a
DM
1516
1517 return $status;
1e3baf05
DM
1518 }});
1519
1520__PACKAGE__->register_method({
afdb31d5 1521 name => 'vm_start',
5fdbe4f0
DM
1522 path => '{vmid}/status/start',
1523 method => 'POST',
1e3baf05
DM
1524 protected => 1,
1525 proxyto => 'node',
5fdbe4f0 1526 description => "Start virtual machine.",
a0d1b1a2
DM
1527 permissions => {
1528 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1529 },
1e3baf05
DM
1530 parameters => {
1531 additionalProperties => 0,
1532 properties => {
1533 node => get_standard_option('pve-node'),
1534 vmid => get_standard_option('pve-vmid'),
3ea94c60
DM
1535 skiplock => get_standard_option('skiplock'),
1536 stateuri => get_standard_option('pve-qm-stateuri'),
7e8dcf2c 1537 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
952958bc 1538 machine => get_standard_option('pve-qm-machine'),
1e3baf05
DM
1539 },
1540 },
afdb31d5 1541 returns => {
5fdbe4f0
DM
1542 type => 'string',
1543 },
1e3baf05
DM
1544 code => sub {
1545 my ($param) = @_;
1546
1547 my $rpcenv = PVE::RPCEnvironment::get();
1548
a0d1b1a2 1549 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1550
1551 my $node = extract_param($param, 'node');
1552
1e3baf05
DM
1553 my $vmid = extract_param($param, 'vmid');
1554
952958bc
DM
1555 my $machine = extract_param($param, 'machine');
1556
3ea94c60 1557 my $stateuri = extract_param($param, 'stateuri');
afdb31d5 1558 raise_param_exc({ stateuri => "Only root may use this option." })
a0d1b1a2 1559 if $stateuri && $authuser ne 'root@pam';
3ea94c60 1560
1e3baf05 1561 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1562 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1563 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1564
7e8dcf2c
AD
1565 my $migratedfrom = extract_param($param, 'migratedfrom');
1566 raise_param_exc({ migratedfrom => "Only root may use this option." })
1567 if $migratedfrom && $authuser ne 'root@pam';
1568
afdb31d5 1569 my $storecfg = PVE::Storage::config();
5fdbe4f0 1570
cce37749
DM
1571 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1572 $rpcenv->{type} ne 'ha') {
5fdbe4f0 1573
88fc87b4
DM
1574 my $hacmd = sub {
1575 my $upid = shift;
5fdbe4f0 1576
88fc87b4 1577 my $service = "pvevm:$vmid";
5fdbe4f0 1578
88fc87b4
DM
1579 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1580
1581 print "Executing HA start for VM $vmid\n";
1582
1583 PVE::Tools::run_command($cmd);
1584
1585 return;
1586 };
1587
1588 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1589
1590 } else {
1591
1592 my $realcmd = sub {
1593 my $upid = shift;
1594
1595 syslog('info', "start VM $vmid: $upid\n");
1596
952958bc 1597 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock, $migratedfrom, undef, $machine);
88fc87b4
DM
1598
1599 return;
1600 };
5fdbe4f0 1601
88fc87b4
DM
1602 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1603 }
5fdbe4f0
DM
1604 }});
1605
1606__PACKAGE__->register_method({
afdb31d5 1607 name => 'vm_stop',
5fdbe4f0
DM
1608 path => '{vmid}/status/stop',
1609 method => 'POST',
1610 protected => 1,
1611 proxyto => 'node',
1612 description => "Stop virtual machine.",
a0d1b1a2
DM
1613 permissions => {
1614 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1615 },
5fdbe4f0
DM
1616 parameters => {
1617 additionalProperties => 0,
1618 properties => {
1619 node => get_standard_option('pve-node'),
1620 vmid => get_standard_option('pve-vmid'),
1621 skiplock => get_standard_option('skiplock'),
af30308f 1622 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
c6bb9502
DM
1623 timeout => {
1624 description => "Wait maximal timeout seconds.",
1625 type => 'integer',
1626 minimum => 0,
1627 optional => 1,
254575e9
DM
1628 },
1629 keepActive => {
1630 description => "Do not decativate storage volumes.",
1631 type => 'boolean',
1632 optional => 1,
1633 default => 0,
c6bb9502 1634 }
5fdbe4f0
DM
1635 },
1636 },
afdb31d5 1637 returns => {
5fdbe4f0
DM
1638 type => 'string',
1639 },
1640 code => sub {
1641 my ($param) = @_;
1642
1643 my $rpcenv = PVE::RPCEnvironment::get();
1644
a0d1b1a2 1645 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1646
1647 my $node = extract_param($param, 'node');
1648
1649 my $vmid = extract_param($param, 'vmid');
1650
1651 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1652 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1653 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1654
254575e9 1655 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1656 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1657 if $keepActive && $authuser ne 'root@pam';
254575e9 1658
af30308f
DM
1659 my $migratedfrom = extract_param($param, 'migratedfrom');
1660 raise_param_exc({ migratedfrom => "Only root may use this option." })
1661 if $migratedfrom && $authuser ne 'root@pam';
1662
1663
ff1a2432
DM
1664 my $storecfg = PVE::Storage::config();
1665
3be30d63 1666 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
5fdbe4f0 1667
88fc87b4
DM
1668 my $hacmd = sub {
1669 my $upid = shift;
5fdbe4f0 1670
88fc87b4 1671 my $service = "pvevm:$vmid";
c6bb9502 1672
88fc87b4
DM
1673 my $cmd = ['clusvcadm', '-d', $service];
1674
1675 print "Executing HA stop for VM $vmid\n";
1676
1677 PVE::Tools::run_command($cmd);
5fdbe4f0 1678
88fc87b4
DM
1679 return;
1680 };
1681
1682 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1683
1684 } else {
1685 my $realcmd = sub {
1686 my $upid = shift;
1687
1688 syslog('info', "stop VM $vmid: $upid\n");
1689
1690 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
af30308f 1691 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
88fc87b4
DM
1692
1693 return;
1694 };
1695
1696 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1697 }
5fdbe4f0
DM
1698 }});
1699
1700__PACKAGE__->register_method({
afdb31d5 1701 name => 'vm_reset',
5fdbe4f0
DM
1702 path => '{vmid}/status/reset',
1703 method => 'POST',
1704 protected => 1,
1705 proxyto => 'node',
1706 description => "Reset virtual machine.",
a0d1b1a2
DM
1707 permissions => {
1708 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1709 },
5fdbe4f0
DM
1710 parameters => {
1711 additionalProperties => 0,
1712 properties => {
1713 node => get_standard_option('pve-node'),
1714 vmid => get_standard_option('pve-vmid'),
1715 skiplock => get_standard_option('skiplock'),
1716 },
1717 },
afdb31d5 1718 returns => {
5fdbe4f0
DM
1719 type => 'string',
1720 },
1721 code => sub {
1722 my ($param) = @_;
1723
1724 my $rpcenv = PVE::RPCEnvironment::get();
1725
a0d1b1a2 1726 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1727
1728 my $node = extract_param($param, 'node');
1729
1730 my $vmid = extract_param($param, 'vmid');
1731
1732 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1733 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1734 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1735
ff1a2432
DM
1736 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1737
5fdbe4f0
DM
1738 my $realcmd = sub {
1739 my $upid = shift;
1740
1e3baf05 1741 PVE::QemuServer::vm_reset($vmid, $skiplock);
5fdbe4f0
DM
1742
1743 return;
1744 };
1745
a0d1b1a2 1746 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1747 }});
1748
1749__PACKAGE__->register_method({
afdb31d5 1750 name => 'vm_shutdown',
5fdbe4f0
DM
1751 path => '{vmid}/status/shutdown',
1752 method => 'POST',
1753 protected => 1,
1754 proxyto => 'node',
1755 description => "Shutdown virtual machine.",
a0d1b1a2
DM
1756 permissions => {
1757 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1758 },
5fdbe4f0
DM
1759 parameters => {
1760 additionalProperties => 0,
1761 properties => {
1762 node => get_standard_option('pve-node'),
1763 vmid => get_standard_option('pve-vmid'),
1764 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1765 timeout => {
1766 description => "Wait maximal timeout seconds.",
1767 type => 'integer',
1768 minimum => 0,
1769 optional => 1,
9269013a
DM
1770 },
1771 forceStop => {
1772 description => "Make sure the VM stops.",
1773 type => 'boolean',
1774 optional => 1,
1775 default => 0,
254575e9
DM
1776 },
1777 keepActive => {
1778 description => "Do not decativate storage volumes.",
1779 type => 'boolean',
1780 optional => 1,
1781 default => 0,
c6bb9502 1782 }
5fdbe4f0
DM
1783 },
1784 },
afdb31d5 1785 returns => {
5fdbe4f0
DM
1786 type => 'string',
1787 },
1788 code => sub {
1789 my ($param) = @_;
1790
1791 my $rpcenv = PVE::RPCEnvironment::get();
1792
a0d1b1a2 1793 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1794
1795 my $node = extract_param($param, 'node');
1796
1797 my $vmid = extract_param($param, 'vmid');
1798
1799 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1800 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1801 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1802
254575e9 1803 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1804 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1805 if $keepActive && $authuser ne 'root@pam';
254575e9 1806
02d07cf5
DM
1807 my $storecfg = PVE::Storage::config();
1808
5fdbe4f0
DM
1809 my $realcmd = sub {
1810 my $upid = shift;
1811
1812 syslog('info', "shutdown VM $vmid: $upid\n");
1813
afdb31d5 1814 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
254575e9 1815 1, $param->{forceStop}, $keepActive);
c6bb9502 1816
5fdbe4f0
DM
1817 return;
1818 };
1819
a0d1b1a2 1820 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1821 }});
1822
1823__PACKAGE__->register_method({
afdb31d5 1824 name => 'vm_suspend',
5fdbe4f0
DM
1825 path => '{vmid}/status/suspend',
1826 method => 'POST',
1827 protected => 1,
1828 proxyto => 'node',
1829 description => "Suspend virtual machine.",
a0d1b1a2
DM
1830 permissions => {
1831 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1832 },
5fdbe4f0
DM
1833 parameters => {
1834 additionalProperties => 0,
1835 properties => {
1836 node => get_standard_option('pve-node'),
1837 vmid => get_standard_option('pve-vmid'),
1838 skiplock => get_standard_option('skiplock'),
1839 },
1840 },
afdb31d5 1841 returns => {
5fdbe4f0
DM
1842 type => 'string',
1843 },
1844 code => sub {
1845 my ($param) = @_;
1846
1847 my $rpcenv = PVE::RPCEnvironment::get();
1848
a0d1b1a2 1849 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1850
1851 my $node = extract_param($param, 'node');
1852
1853 my $vmid = extract_param($param, 'vmid');
1854
1855 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1856 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1857 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1858
ff1a2432
DM
1859 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1860
5fdbe4f0
DM
1861 my $realcmd = sub {
1862 my $upid = shift;
1863
1864 syslog('info', "suspend VM $vmid: $upid\n");
1865
1e3baf05 1866 PVE::QemuServer::vm_suspend($vmid, $skiplock);
5fdbe4f0
DM
1867
1868 return;
1869 };
1870
a0d1b1a2 1871 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1872 }});
1873
1874__PACKAGE__->register_method({
afdb31d5 1875 name => 'vm_resume',
5fdbe4f0
DM
1876 path => '{vmid}/status/resume',
1877 method => 'POST',
1878 protected => 1,
1879 proxyto => 'node',
1880 description => "Resume virtual machine.",
a0d1b1a2
DM
1881 permissions => {
1882 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1883 },
5fdbe4f0
DM
1884 parameters => {
1885 additionalProperties => 0,
1886 properties => {
1887 node => get_standard_option('pve-node'),
1888 vmid => get_standard_option('pve-vmid'),
1889 skiplock => get_standard_option('skiplock'),
1890 },
1891 },
afdb31d5 1892 returns => {
5fdbe4f0
DM
1893 type => 'string',
1894 },
1895 code => sub {
1896 my ($param) = @_;
1897
1898 my $rpcenv = PVE::RPCEnvironment::get();
1899
a0d1b1a2 1900 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1901
1902 my $node = extract_param($param, 'node');
1903
1904 my $vmid = extract_param($param, 'vmid');
1905
1906 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1907 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1908 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1909
b7eeab21 1910 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
ff1a2432 1911
5fdbe4f0
DM
1912 my $realcmd = sub {
1913 my $upid = shift;
1914
1915 syslog('info', "resume VM $vmid: $upid\n");
1916
1e3baf05 1917 PVE::QemuServer::vm_resume($vmid, $skiplock);
1e3baf05 1918
5fdbe4f0
DM
1919 return;
1920 };
1921
a0d1b1a2 1922 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1923 }});
1924
1925__PACKAGE__->register_method({
afdb31d5 1926 name => 'vm_sendkey',
5fdbe4f0
DM
1927 path => '{vmid}/sendkey',
1928 method => 'PUT',
1929 protected => 1,
1930 proxyto => 'node',
1931 description => "Send key event to virtual machine.",
a0d1b1a2
DM
1932 permissions => {
1933 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1934 },
5fdbe4f0
DM
1935 parameters => {
1936 additionalProperties => 0,
1937 properties => {
1938 node => get_standard_option('pve-node'),
1939 vmid => get_standard_option('pve-vmid'),
1940 skiplock => get_standard_option('skiplock'),
1941 key => {
1942 description => "The key (qemu monitor encoding).",
1943 type => 'string'
1944 }
1945 },
1946 },
1947 returns => { type => 'null'},
1948 code => sub {
1949 my ($param) = @_;
1950
1951 my $rpcenv = PVE::RPCEnvironment::get();
1952
a0d1b1a2 1953 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1954
1955 my $node = extract_param($param, 'node');
1956
1957 my $vmid = extract_param($param, 'vmid');
1958
1959 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1960 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1961 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0
DM
1962
1963 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1964
1965 return;
1e3baf05
DM
1966 }});
1967
1ac0d2ee
AD
1968__PACKAGE__->register_method({
1969 name => 'vm_feature',
1970 path => '{vmid}/feature',
1971 method => 'GET',
1972 proxyto => 'node',
75466c4f 1973 protected => 1,
1ac0d2ee
AD
1974 description => "Check if feature for virtual machine is available.",
1975 permissions => {
1976 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1977 },
1978 parameters => {
1979 additionalProperties => 0,
1980 properties => {
1981 node => get_standard_option('pve-node'),
1982 vmid => get_standard_option('pve-vmid'),
1983 feature => {
1984 description => "Feature to check.",
1985 type => 'string',
7758ce86 1986 enum => [ 'snapshot', 'clone', 'copy' ],
1ac0d2ee
AD
1987 },
1988 snapname => get_standard_option('pve-snapshot-name', {
1989 optional => 1,
1990 }),
1991 },
1ac0d2ee
AD
1992 },
1993 returns => {
719893a9
DM
1994 type => "object",
1995 properties => {
1996 hasFeature => { type => 'boolean' },
7043d946 1997 nodes => {
719893a9
DM
1998 type => 'array',
1999 items => { type => 'string' },
2000 }
2001 },
1ac0d2ee
AD
2002 },
2003 code => sub {
2004 my ($param) = @_;
2005
2006 my $node = extract_param($param, 'node');
2007
2008 my $vmid = extract_param($param, 'vmid');
2009
2010 my $snapname = extract_param($param, 'snapname');
2011
2012 my $feature = extract_param($param, 'feature');
2013
2014 my $running = PVE::QemuServer::check_running($vmid);
2015
2016 my $conf = PVE::QemuServer::load_config($vmid);
2017
2018 if($snapname){
2019 my $snap = $conf->{snapshots}->{$snapname};
2020 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2021 $conf = $snap;
2022 }
2023 my $storecfg = PVE::Storage::config();
2024
719893a9
DM
2025 my $nodelist = PVE::QemuServer::shared_nodes($conf, $storecfg);
2026 my $hasFeature = PVE::QemuServer::has_feature($feature, $conf, $storecfg, $snapname, $running);
7043d946 2027
719893a9
DM
2028 return {
2029 hasFeature => $hasFeature,
2030 nodes => [ keys %$nodelist ],
7043d946 2031 };
1ac0d2ee
AD
2032 }});
2033
6116f729 2034__PACKAGE__->register_method({
9418baad
DM
2035 name => 'clone_vm',
2036 path => '{vmid}/clone',
6116f729
DM
2037 method => 'POST',
2038 protected => 1,
2039 proxyto => 'node',
37329185 2040 description => "Create a copy of virtual machine/template.",
6116f729 2041 permissions => {
9418baad 2042 description => "You need 'VM.Clone' permissions on /vms/{vmid}, and 'VM.Allocate' permissions " .
6116f729
DM
2043 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
2044 "'Datastore.AllocateSpace' on any used storage.",
75466c4f
DM
2045 check =>
2046 [ 'and',
9418baad 2047 ['perm', '/vms/{vmid}', [ 'VM.Clone' ]],
75466c4f 2048 [ 'or',
6116f729
DM
2049 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
2050 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
2051 ],
2052 ]
2053 },
2054 parameters => {
2055 additionalProperties => 0,
2056 properties => {
6116f729
DM
2057 node => get_standard_option('pve-node'),
2058 vmid => get_standard_option('pve-vmid'),
9418baad 2059 newid => get_standard_option('pve-vmid', { description => 'VMID for the clone.' }),
a60ab1a6
DM
2060 name => {
2061 optional => 1,
2062 type => 'string', format => 'dns-name',
2063 description => "Set a name for the new VM.",
2064 },
2065 description => {
2066 optional => 1,
2067 type => 'string',
2068 description => "Description for the new VM.",
2069 },
75466c4f 2070 pool => {
6116f729
DM
2071 optional => 1,
2072 type => 'string', format => 'pve-poolid',
2073 description => "Add the new VM to the specified pool.",
2074 },
9076d880
DM
2075 snapname => get_standard_option('pve-snapshot-name', {
2076 requires => 'full',
2077 optional => 1,
2078 }),
81f043eb 2079 storage => get_standard_option('pve-storage-id', {
9418baad 2080 description => "Target storage for full clone.",
4e4f83fe 2081 requires => 'full',
81f043eb
AD
2082 optional => 1,
2083 }),
55173c6b 2084 'format' => {
42a19c87
AD
2085 description => "Target format for file storage.",
2086 requires => 'full',
2087 type => 'string',
2088 optional => 1,
55173c6b 2089 enum => [ 'raw', 'qcow2', 'vmdk'],
42a19c87 2090 },
6116f729
DM
2091 full => {
2092 optional => 1,
55173c6b
DM
2093 type => 'boolean',
2094 description => "Create a full copy of all disk. This is always done when " .
9418baad 2095 "you clone a normal VM. For VM templates, we try to create a linked clone by default.",
6116f729
DM
2096 default => 0,
2097 },
75466c4f 2098 target => get_standard_option('pve-node', {
55173c6b
DM
2099 description => "Target node. Only allowed if the original VM is on shared storage.",
2100 optional => 1,
2101 }),
2102 },
6116f729
DM
2103 },
2104 returns => {
2105 type => 'string',
2106 },
2107 code => sub {
2108 my ($param) = @_;
2109
2110 my $rpcenv = PVE::RPCEnvironment::get();
2111
55173c6b 2112 my $authuser = $rpcenv->get_user();
6116f729
DM
2113
2114 my $node = extract_param($param, 'node');
2115
2116 my $vmid = extract_param($param, 'vmid');
2117
2118 my $newid = extract_param($param, 'newid');
2119
6116f729
DM
2120 my $pool = extract_param($param, 'pool');
2121
2122 if (defined($pool)) {
2123 $rpcenv->check_pool_exist($pool);
2124 }
2125
55173c6b 2126 my $snapname = extract_param($param, 'snapname');
9076d880 2127
81f043eb
AD
2128 my $storage = extract_param($param, 'storage');
2129
42a19c87
AD
2130 my $format = extract_param($param, 'format');
2131
55173c6b
DM
2132 my $target = extract_param($param, 'target');
2133
2134 my $localnode = PVE::INotify::nodename();
2135
751cc556 2136 undef $target if $target && ($target eq $localnode || $target eq 'localhost');
55173c6b
DM
2137
2138 PVE::Cluster::check_node_exists($target) if $target;
2139
6116f729
DM
2140 my $storecfg = PVE::Storage::config();
2141
4a5a2590
DM
2142 if ($storage) {
2143 # check if storage is enabled on local node
2144 PVE::Storage::storage_check_enabled($storecfg, $storage);
2145 if ($target) {
2146 # check if storage is available on target node
2147 PVE::Storage::storage_check_node($storecfg, $storage, $target);
2148 # clone only works if target storage is shared
2149 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
2150 die "can't clone to non-shared storage '$storage'\n" if !$scfg->{shared};
2151 }
2152 }
2153
55173c6b 2154 PVE::Cluster::check_cfs_quorum();
6116f729 2155
4e4f83fe
DM
2156 my $running = PVE::QemuServer::check_running($vmid) || 0;
2157
4e4f83fe
DM
2158 # exclusive lock if VM is running - else shared lock is enough;
2159 my $shared_lock = $running ? 0 : 1;
2160
9418baad 2161 my $clonefn = sub {
6116f729 2162
829967a9
DM
2163 # do all tests after lock
2164 # we also try to do all tests before we fork the worker
2165
6116f729
DM
2166 my $conf = PVE::QemuServer::load_config($vmid);
2167
2168 PVE::QemuServer::check_lock($conf);
2169
4e4f83fe 2170 my $verify_running = PVE::QemuServer::check_running($vmid) || 0;
6116f729 2171
4e4f83fe 2172 die "unexpected state change\n" if $verify_running != $running;
6116f729 2173
75466c4f
DM
2174 die "snapshot '$snapname' does not exist\n"
2175 if $snapname && !defined( $conf->{snapshots}->{$snapname});
6116f729 2176
75466c4f 2177 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
9076d880 2178
9418baad 2179 my $sharedvm = &$check_storage_access_clone($rpcenv, $authuser, $storecfg, $oldconf, $storage);
6116f729 2180
9418baad 2181 die "can't clone VM to node '$target' (VM uses local storage)\n" if $target && !$sharedvm;
75466c4f 2182
6116f729
DM
2183 my $conffile = PVE::QemuServer::config_file($newid);
2184
2185 die "unable to create VM $newid: config file already exists\n"
2186 if -f $conffile;
2187
9418baad 2188 my $newconf = { lock => 'clone' };
829967a9
DM
2189 my $drives = {};
2190 my $vollist = [];
2191
2192 foreach my $opt (keys %$oldconf) {
2193 my $value = $oldconf->{$opt};
2194
2195 # do not copy snapshot related info
2196 next if $opt eq 'snapshots' || $opt eq 'parent' || $opt eq 'snaptime' ||
2197 $opt eq 'vmstate' || $opt eq 'snapstate';
2198
2199 # always change MAC! address
2200 if ($opt =~ m/^net(\d+)$/) {
2201 my $net = PVE::QemuServer::parse_net($value);
2202 $net->{macaddr} = PVE::Tools::random_ether_addr();
2203 $newconf->{$opt} = PVE::QemuServer::print_net($net);
2204 } elsif (my $drive = PVE::QemuServer::parse_drive($opt, $value)) {
2205 if (PVE::QemuServer::drive_is_cdrom($drive)) {
2206 $newconf->{$opt} = $value; # simply copy configuration
2207 } else {
dba198b0 2208 if ($param->{full} || !PVE::Storage::volume_is_base($storecfg, $drive->{file})) {
2dd53043 2209 die "Full clone feature is not available"
dba198b0 2210 if !PVE::Storage::volume_has_feature($storecfg, 'copy', $drive->{file}, $snapname, $running);
2dd53043 2211 $drive->{full} = 1;
dba198b0 2212 }
829967a9
DM
2213 $drives->{$opt} = $drive;
2214 push @$vollist, $drive->{file};
2215 }
2216 } else {
2217 # copy everything else
2218 $newconf->{$opt} = $value;
2219 }
2220 }
2221
2222 delete $newconf->{template};
2223
2224 if ($param->{name}) {
2225 $newconf->{name} = $param->{name};
2226 } else {
c55fee03
DM
2227 if ($oldconf->{name}) {
2228 $newconf->{name} = "Copy-of-$oldconf->{name}";
2229 } else {
2230 $newconf->{name} = "Copy-of-VM-$vmid";
2231 }
829967a9 2232 }
2dd53043 2233
829967a9
DM
2234 if ($param->{description}) {
2235 $newconf->{description} = $param->{description};
2236 }
2237
6116f729 2238 # create empty/temp config - this fails if VM already exists on other node
9418baad 2239 PVE::Tools::file_set_contents($conffile, "# qmclone temporary file\nlock: clone\n");
6116f729
DM
2240
2241 my $realcmd = sub {
2242 my $upid = shift;
2243
b83e0181 2244 my $newvollist = [];
6116f729 2245
b83e0181 2246 eval {
829967a9 2247 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
75466c4f 2248
6116f729
DM
2249 PVE::Storage::activate_volumes($storecfg, $vollist);
2250
829967a9
DM
2251 foreach my $opt (keys %$drives) {
2252 my $drive = $drives->{$opt};
2dd53043 2253
152fe752
DM
2254 my $newdrive = PVE::QemuServer::clone_disk($storecfg, $vmid, $running, $opt, $drive, $snapname,
2255 $newid, $storage, $format, $drive->{full}, $newvollist);
00b095ca 2256
152fe752 2257 $newconf->{$opt} = PVE::QemuServer::print_drive($vmid, $newdrive);
2dd53043 2258
829967a9
DM
2259 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
2260 }
b83e0181
DM
2261
2262 delete $newconf->{lock};
2263 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
55173c6b
DM
2264
2265 if ($target) {
2266 my $newconffile = PVE::QemuServer::config_file($newid, $target);
2267 die "Failed to move config to node '$target' - rename failed: $!\n"
2268 if !rename($conffile, $newconffile);
2269 }
d703d4c0 2270
be517049 2271 PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
6116f729 2272 };
75466c4f 2273 if (my $err = $@) {
6116f729
DM
2274 unlink $conffile;
2275
b83e0181
DM
2276 sleep 1; # some storage like rbd need to wait before release volume - really?
2277
2278 foreach my $volid (@$newvollist) {
2279 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2280 warn $@ if $@;
2281 }
9418baad 2282 die "clone failed: $err";
6116f729
DM
2283 }
2284
2285 return;
2286 };
2287
9418baad 2288 return $rpcenv->fork_worker('qmclone', $vmid, $authuser, $realcmd);
6116f729
DM
2289 };
2290
4e4f83fe 2291 return PVE::QemuServer::lock_config_mode($vmid, 1, $shared_lock, sub {
6116f729 2292 # Aquire exclusive lock lock for $newid
9418baad 2293 return PVE::QemuServer::lock_config_full($newid, 1, $clonefn);
6116f729
DM
2294 });
2295
2296 }});
2297
586bfa78 2298__PACKAGE__->register_method({
43bc02a9
DM
2299 name => 'move_vm_disk',
2300 path => '{vmid}/move_disk',
e2cd75fa 2301 method => 'POST',
586bfa78
AD
2302 protected => 1,
2303 proxyto => 'node',
2304 description => "Move volume to different storage.",
2305 permissions => {
e2cd75fa
DM
2306 description => "You need 'VM.Config.Disk' permissions on /vms/{vmid}, " .
2307 "and 'Datastore.AllocateSpace' permissions on the storage.",
7043d946 2308 check =>
e2cd75fa
DM
2309 [ 'and',
2310 ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
2311 ['perm', '/storage/{storage}', [ 'Datastore.AllocateSpace' ]],
2312 ],
586bfa78
AD
2313 },
2314 parameters => {
2315 additionalProperties => 0,
2316 properties => {
2317 node => get_standard_option('pve-node'),
2318 vmid => get_standard_option('pve-vmid'),
586bfa78
AD
2319 disk => {
2320 type => 'string',
2321 description => "The disk you want to move.",
e2cd75fa 2322 enum => [ PVE::QemuServer::disknames() ],
586bfa78 2323 },
e2cd75fa 2324 storage => get_standard_option('pve-storage-id', { description => "Target Storage." }),
635c3c44 2325 'format' => {
586bfa78
AD
2326 type => 'string',
2327 description => "Target Format.",
2328 enum => [ 'raw', 'qcow2', 'vmdk' ],
2329 optional => 1,
2330 },
70d45e33
DM
2331 delete => {
2332 type => 'boolean',
2333 description => "Delete the original disk after successful copy. By default the original disk is kept as unused disk.",
2334 optional => 1,
2335 default => 0,
2336 },
586bfa78
AD
2337 digest => {
2338 type => 'string',
2339 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2340 maxLength => 40,
2341 optional => 1,
2342 },
2343 },
2344 },
e2cd75fa
DM
2345 returns => {
2346 type => 'string',
2347 description => "the task ID.",
2348 },
586bfa78
AD
2349 code => sub {
2350 my ($param) = @_;
2351
2352 my $rpcenv = PVE::RPCEnvironment::get();
2353
2354 my $authuser = $rpcenv->get_user();
2355
2356 my $node = extract_param($param, 'node');
2357
2358 my $vmid = extract_param($param, 'vmid');
2359
2360 my $digest = extract_param($param, 'digest');
2361
2362 my $disk = extract_param($param, 'disk');
2363
2364 my $storeid = extract_param($param, 'storage');
2365
2366 my $format = extract_param($param, 'format');
2367
586bfa78
AD
2368 my $storecfg = PVE::Storage::config();
2369
2370 my $updatefn = sub {
2371
2372 my $conf = PVE::QemuServer::load_config($vmid);
2373
2374 die "checksum missmatch (file change by other user?)\n"
2375 if $digest && $digest ne $conf->{digest};
586bfa78
AD
2376
2377 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2378
2379 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2380
70d45e33 2381 my $old_volid = $drive->{file} || die "disk '$disk' has no associated volume\n";
586bfa78
AD
2382
2383 die "you can't move a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2384
e2cd75fa 2385 my $oldfmt;
70d45e33 2386 my ($oldstoreid, $oldvolname) = PVE::Storage::parse_volume_id($old_volid);
586bfa78
AD
2387 if ($oldvolname =~ m/\.(raw|qcow2|vmdk)$/){
2388 $oldfmt = $1;
2389 }
2390
7043d946 2391 die "you can't move on the same storage with same format\n" if $oldstoreid eq $storeid &&
e2cd75fa 2392 (!$format || !$oldfmt || $oldfmt eq $format);
586bfa78
AD
2393
2394 PVE::Cluster::log_msg('info', $authuser, "move disk VM $vmid: move --disk $disk --storage $storeid");
2395
2396 my $running = PVE::QemuServer::check_running($vmid);
e2cd75fa
DM
2397
2398 PVE::Storage::activate_volumes($storecfg, [ $drive->{file} ]);
2399
586bfa78
AD
2400 my $realcmd = sub {
2401
2402 my $newvollist = [];
2403
2404 eval {
2405 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
2406
e2cd75fa
DM
2407 my $newdrive = PVE::QemuServer::clone_disk($storecfg, $vmid, $running, $disk, $drive, undef,
2408 $vmid, $storeid, $format, 1, $newvollist);
2409
2410 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $newdrive);
2411
70d45e33 2412 PVE::QemuServer::add_unused_volume($conf, $old_volid) if !$param->{delete};
7043d946 2413
e2cd75fa 2414 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
586bfa78
AD
2415 };
2416 if (my $err = $@) {
2417
2418 foreach my $volid (@$newvollist) {
2419 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2420 warn $@ if $@;
2421 }
2422 die "storage migration failed: $err";
2423 }
70d45e33
DM
2424
2425 if ($param->{delete}) {
2426 eval { PVE::Storage::vdisk_free($storecfg, $old_volid); };
2427 warn $@ if $@;
2428 }
586bfa78
AD
2429 };
2430
2431 return $rpcenv->fork_worker('qmmove', $vmid, $authuser, $realcmd);
2432 };
e2cd75fa
DM
2433
2434 return PVE::QemuServer::lock_config($vmid, $updatefn);
586bfa78
AD
2435 }});
2436
3ea94c60 2437__PACKAGE__->register_method({
afdb31d5 2438 name => 'migrate_vm',
3ea94c60
DM
2439 path => '{vmid}/migrate',
2440 method => 'POST',
2441 protected => 1,
2442 proxyto => 'node',
2443 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
2444 permissions => {
2445 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
2446 },
3ea94c60
DM
2447 parameters => {
2448 additionalProperties => 0,
2449 properties => {
2450 node => get_standard_option('pve-node'),
2451 vmid => get_standard_option('pve-vmid'),
2452 target => get_standard_option('pve-node', { description => "Target node." }),
2453 online => {
2454 type => 'boolean',
2455 description => "Use online/live migration.",
2456 optional => 1,
2457 },
2458 force => {
2459 type => 'boolean',
2460 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
2461 optional => 1,
2462 },
2463 },
2464 },
afdb31d5 2465 returns => {
3ea94c60
DM
2466 type => 'string',
2467 description => "the task ID.",
2468 },
2469 code => sub {
2470 my ($param) = @_;
2471
2472 my $rpcenv = PVE::RPCEnvironment::get();
2473
a0d1b1a2 2474 my $authuser = $rpcenv->get_user();
3ea94c60
DM
2475
2476 my $target = extract_param($param, 'target');
2477
2478 my $localnode = PVE::INotify::nodename();
2479 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
2480
2481 PVE::Cluster::check_cfs_quorum();
2482
2483 PVE::Cluster::check_node_exists($target);
2484
2485 my $targetip = PVE::Cluster::remote_node_ip($target);
2486
2487 my $vmid = extract_param($param, 'vmid');
2488
afdb31d5 2489 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 2490 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
2491
2492 # test if VM exists
a5ed42d3 2493 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
2494
2495 # try to detect errors early
a5ed42d3
DM
2496
2497 PVE::QemuServer::check_lock($conf);
2498
3ea94c60 2499 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 2500 die "cant migrate running VM without --online\n"
3ea94c60
DM
2501 if !$param->{online};
2502 }
2503
47152e2e 2504 my $storecfg = PVE::Storage::config();
22d646a7 2505 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
47152e2e 2506
3be30d63 2507 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3ea94c60 2508
88fc87b4
DM
2509 my $hacmd = sub {
2510 my $upid = shift;
3ea94c60 2511
88fc87b4
DM
2512 my $service = "pvevm:$vmid";
2513
2514 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
2515
2516 print "Executing HA migrate for VM $vmid to node $target\n";
2517
2518 PVE::Tools::run_command($cmd);
2519
2520 return;
2521 };
2522
2523 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
2524
2525 } else {
2526
2527 my $realcmd = sub {
2528 my $upid = shift;
2529
2530 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
2531 };
2532
2533 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
2534 }
3ea94c60 2535
3ea94c60 2536 }});
1e3baf05 2537
91c94f0a 2538__PACKAGE__->register_method({
afdb31d5
DM
2539 name => 'monitor',
2540 path => '{vmid}/monitor',
91c94f0a
DM
2541 method => 'POST',
2542 protected => 1,
2543 proxyto => 'node',
2544 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
2545 permissions => {
2546 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
2547 },
91c94f0a
DM
2548 parameters => {
2549 additionalProperties => 0,
2550 properties => {
2551 node => get_standard_option('pve-node'),
2552 vmid => get_standard_option('pve-vmid'),
2553 command => {
2554 type => 'string',
2555 description => "The monitor command.",
2556 }
2557 },
2558 },
2559 returns => { type => 'string'},
2560 code => sub {
2561 my ($param) = @_;
2562
2563 my $vmid = $param->{vmid};
2564
2565 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
2566
2567 my $res = '';
2568 eval {
7b7c6d1b 2569 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
91c94f0a
DM
2570 };
2571 $res = "ERROR: $@" if $@;
2572
2573 return $res;
2574 }});
2575
0d02881c
AD
2576__PACKAGE__->register_method({
2577 name => 'resize_vm',
614e3941 2578 path => '{vmid}/resize',
0d02881c
AD
2579 method => 'PUT',
2580 protected => 1,
2581 proxyto => 'node',
2f48a4f5 2582 description => "Extend volume size.",
0d02881c 2583 permissions => {
3b2773f6 2584 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
0d02881c
AD
2585 },
2586 parameters => {
2587 additionalProperties => 0,
2f48a4f5
DM
2588 properties => {
2589 node => get_standard_option('pve-node'),
2590 vmid => get_standard_option('pve-vmid'),
2591 skiplock => get_standard_option('skiplock'),
2592 disk => {
2593 type => 'string',
2594 description => "The disk you want to resize.",
2595 enum => [PVE::QemuServer::disknames()],
2596 },
2597 size => {
2598 type => 'string',
f91b2e45 2599 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2f48a4f5
DM
2600 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.",
2601 },
2602 digest => {
2603 type => 'string',
2604 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2605 maxLength => 40,
2606 optional => 1,
2607 },
2608 },
0d02881c
AD
2609 },
2610 returns => { type => 'null'},
2611 code => sub {
2612 my ($param) = @_;
2613
2614 my $rpcenv = PVE::RPCEnvironment::get();
2615
2616 my $authuser = $rpcenv->get_user();
2617
2618 my $node = extract_param($param, 'node');
2619
2620 my $vmid = extract_param($param, 'vmid');
2621
2622 my $digest = extract_param($param, 'digest');
2623
2f48a4f5 2624 my $disk = extract_param($param, 'disk');
75466c4f 2625
2f48a4f5 2626 my $sizestr = extract_param($param, 'size');
0d02881c 2627
f91b2e45 2628 my $skiplock = extract_param($param, 'skiplock');
0d02881c
AD
2629 raise_param_exc({ skiplock => "Only root may use this option." })
2630 if $skiplock && $authuser ne 'root@pam';
2631
0d02881c
AD
2632 my $storecfg = PVE::Storage::config();
2633
0d02881c
AD
2634 my $updatefn = sub {
2635
2636 my $conf = PVE::QemuServer::load_config($vmid);
2637
2638 die "checksum missmatch (file change by other user?)\n"
2639 if $digest && $digest ne $conf->{digest};
2640 PVE::QemuServer::check_lock($conf) if !$skiplock;
2641
f91b2e45
DM
2642 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2643
2644 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2645
2646 my $volid = $drive->{file};
2647
2648 die "disk '$disk' has no associated volume\n" if !$volid;
2649
2650 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2651
75466c4f 2652 die "you can't online resize a virtio windows bootdisk\n"
f2965e67
AD
2653 if PVE::QemuServer::check_running($vmid) && $conf->{bootdisk} eq $disk && $conf->{ostype} =~ m/^w/ && $disk =~ m/^virtio/;
2654
f91b2e45
DM
2655 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
2656
2657 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
2658
2659 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
2660
2661 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
2662 my ($ext, $newsize, $unit) = ($1, $2, $4);
2663 if ($unit) {
2664 if ($unit eq 'K') {
2665 $newsize = $newsize * 1024;
2666 } elsif ($unit eq 'M') {
2667 $newsize = $newsize * 1024 * 1024;
2668 } elsif ($unit eq 'G') {
2669 $newsize = $newsize * 1024 * 1024 * 1024;
2670 } elsif ($unit eq 'T') {
2671 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
2672 }
2673 }
2674 $newsize += $size if $ext;
2675 $newsize = int($newsize);
2676
2677 die "unable to skrink disk size\n" if $newsize < $size;
2678
2679 return if $size == $newsize;
2680
2f48a4f5 2681 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
0d02881c 2682
f91b2e45 2683 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
75466c4f 2684
f91b2e45
DM
2685 $drive->{size} = $newsize;
2686 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
2687
2688 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2689 };
0d02881c
AD
2690
2691 PVE::QemuServer::lock_config($vmid, $updatefn);
2692 return undef;
2693 }});
2694
9dbd1ee4 2695__PACKAGE__->register_method({
7e7d7b61 2696 name => 'snapshot_list',
9dbd1ee4 2697 path => '{vmid}/snapshot',
7e7d7b61
DM
2698 method => 'GET',
2699 description => "List all snapshots.",
2700 permissions => {
2701 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2702 },
2703 proxyto => 'node',
2704 protected => 1, # qemu pid files are only readable by root
2705 parameters => {
2706 additionalProperties => 0,
2707 properties => {
2708 vmid => get_standard_option('pve-vmid'),
2709 node => get_standard_option('pve-node'),
2710 },
2711 },
2712 returns => {
2713 type => 'array',
2714 items => {
2715 type => "object",
2716 properties => {},
2717 },
2718 links => [ { rel => 'child', href => "{name}" } ],
2719 },
2720 code => sub {
2721 my ($param) = @_;
2722
6aa4651b
DM
2723 my $vmid = $param->{vmid};
2724
2725 my $conf = PVE::QemuServer::load_config($vmid);
7e7d7b61
DM
2726 my $snaphash = $conf->{snapshots} || {};
2727
2728 my $res = [];
2729
2730 foreach my $name (keys %$snaphash) {
0ea6bc69 2731 my $d = $snaphash->{$name};
75466c4f
DM
2732 my $item = {
2733 name => $name,
2734 snaptime => $d->{snaptime} || 0,
6aa4651b 2735 vmstate => $d->{vmstate} ? 1 : 0,
982c7f12
DM
2736 description => $d->{description} || '',
2737 };
0ea6bc69 2738 $item->{parent} = $d->{parent} if $d->{parent};
3ee28e38 2739 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
0ea6bc69
DM
2740 push @$res, $item;
2741 }
2742
6aa4651b
DM
2743 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
2744 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
d1914468
DM
2745 $current->{parent} = $conf->{parent} if $conf->{parent};
2746
2747 push @$res, $current;
7e7d7b61
DM
2748
2749 return $res;
2750 }});
2751
2752__PACKAGE__->register_method({
2753 name => 'snapshot',
2754 path => '{vmid}/snapshot',
2755 method => 'POST',
9dbd1ee4
AD
2756 protected => 1,
2757 proxyto => 'node',
2758 description => "Snapshot a VM.",
2759 permissions => {
f1baf1df 2760 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
9dbd1ee4
AD
2761 },
2762 parameters => {
2763 additionalProperties => 0,
2764 properties => {
2765 node => get_standard_option('pve-node'),
2766 vmid => get_standard_option('pve-vmid'),
8abd398b 2767 snapname => get_standard_option('pve-snapshot-name'),
9dbd1ee4
AD
2768 vmstate => {
2769 optional => 1,
2770 type => 'boolean',
2771 description => "Save the vmstate",
2772 },
2773 freezefs => {
2774 optional => 1,
2775 type => 'boolean',
2776 description => "Freeze the filesystem",
2777 },
782f4f75
DM
2778 description => {
2779 optional => 1,
2780 type => 'string',
2781 description => "A textual description or comment.",
2782 },
9dbd1ee4
AD
2783 },
2784 },
7e7d7b61
DM
2785 returns => {
2786 type => 'string',
2787 description => "the task ID.",
2788 },
9dbd1ee4
AD
2789 code => sub {
2790 my ($param) = @_;
2791
2792 my $rpcenv = PVE::RPCEnvironment::get();
2793
2794 my $authuser = $rpcenv->get_user();
2795
2796 my $node = extract_param($param, 'node');
2797
2798 my $vmid = extract_param($param, 'vmid');
2799
9dbd1ee4
AD
2800 my $snapname = extract_param($param, 'snapname');
2801
d1914468
DM
2802 die "unable to use snapshot name 'current' (reserved name)\n"
2803 if $snapname eq 'current';
2804
7e7d7b61 2805 my $realcmd = sub {
22c377f0 2806 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
75466c4f 2807 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
782f4f75 2808 $param->{freezefs}, $param->{description});
7e7d7b61
DM
2809 };
2810
2811 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2812 }});
2813
154ccdcd
DM
2814__PACKAGE__->register_method({
2815 name => 'snapshot_cmd_idx',
2816 path => '{vmid}/snapshot/{snapname}',
2817 description => '',
2818 method => 'GET',
2819 permissions => {
2820 user => 'all',
2821 },
2822 parameters => {
2823 additionalProperties => 0,
2824 properties => {
2825 vmid => get_standard_option('pve-vmid'),
2826 node => get_standard_option('pve-node'),
8abd398b 2827 snapname => get_standard_option('pve-snapshot-name'),
154ccdcd
DM
2828 },
2829 },
2830 returns => {
2831 type => 'array',
2832 items => {
2833 type => "object",
2834 properties => {},
2835 },
2836 links => [ { rel => 'child', href => "{cmd}" } ],
2837 },
2838 code => sub {
2839 my ($param) = @_;
2840
2841 my $res = [];
2842
2843 push @$res, { cmd => 'rollback' };
d788cea6 2844 push @$res, { cmd => 'config' };
154ccdcd
DM
2845
2846 return $res;
2847 }});
2848
d788cea6
DM
2849__PACKAGE__->register_method({
2850 name => 'update_snapshot_config',
2851 path => '{vmid}/snapshot/{snapname}/config',
2852 method => 'PUT',
2853 protected => 1,
2854 proxyto => 'node',
2855 description => "Update snapshot metadata.",
2856 permissions => {
2857 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2858 },
2859 parameters => {
2860 additionalProperties => 0,
2861 properties => {
2862 node => get_standard_option('pve-node'),
2863 vmid => get_standard_option('pve-vmid'),
2864 snapname => get_standard_option('pve-snapshot-name'),
2865 description => {
2866 optional => 1,
2867 type => 'string',
2868 description => "A textual description or comment.",
2869 },
2870 },
2871 },
2872 returns => { type => 'null' },
2873 code => sub {
2874 my ($param) = @_;
2875
2876 my $rpcenv = PVE::RPCEnvironment::get();
2877
2878 my $authuser = $rpcenv->get_user();
2879
2880 my $vmid = extract_param($param, 'vmid');
2881
2882 my $snapname = extract_param($param, 'snapname');
2883
2884 return undef if !defined($param->{description});
2885
2886 my $updatefn = sub {
2887
2888 my $conf = PVE::QemuServer::load_config($vmid);
2889
2890 PVE::QemuServer::check_lock($conf);
2891
2892 my $snap = $conf->{snapshots}->{$snapname};
2893
75466c4f
DM
2894 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2895
d788cea6
DM
2896 $snap->{description} = $param->{description} if defined($param->{description});
2897
2898 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2899 };
2900
2901 PVE::QemuServer::lock_config($vmid, $updatefn);
2902
2903 return undef;
2904 }});
2905
2906__PACKAGE__->register_method({
2907 name => 'get_snapshot_config',
2908 path => '{vmid}/snapshot/{snapname}/config',
2909 method => 'GET',
2910 proxyto => 'node',
2911 description => "Get snapshot configuration",
2912 permissions => {
2913 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2914 },
2915 parameters => {
2916 additionalProperties => 0,
2917 properties => {
2918 node => get_standard_option('pve-node'),
2919 vmid => get_standard_option('pve-vmid'),
2920 snapname => get_standard_option('pve-snapshot-name'),
2921 },
2922 },
2923 returns => { type => "object" },
2924 code => sub {
2925 my ($param) = @_;
2926
2927 my $rpcenv = PVE::RPCEnvironment::get();
2928
2929 my $authuser = $rpcenv->get_user();
2930
2931 my $vmid = extract_param($param, 'vmid');
2932
2933 my $snapname = extract_param($param, 'snapname');
2934
2935 my $conf = PVE::QemuServer::load_config($vmid);
2936
2937 my $snap = $conf->{snapshots}->{$snapname};
2938
75466c4f
DM
2939 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2940
d788cea6
DM
2941 return $snap;
2942 }});
2943
7e7d7b61
DM
2944__PACKAGE__->register_method({
2945 name => 'rollback',
154ccdcd 2946 path => '{vmid}/snapshot/{snapname}/rollback',
7e7d7b61
DM
2947 method => 'POST',
2948 protected => 1,
2949 proxyto => 'node',
2950 description => "Rollback VM state to specified snapshot.",
2951 permissions => {
f1baf1df 2952 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2953 },
2954 parameters => {
2955 additionalProperties => 0,
2956 properties => {
2957 node => get_standard_option('pve-node'),
2958 vmid => get_standard_option('pve-vmid'),
8abd398b 2959 snapname => get_standard_option('pve-snapshot-name'),
7e7d7b61
DM
2960 },
2961 },
2962 returns => {
2963 type => 'string',
2964 description => "the task ID.",
2965 },
2966 code => sub {
2967 my ($param) = @_;
2968
2969 my $rpcenv = PVE::RPCEnvironment::get();
2970
2971 my $authuser = $rpcenv->get_user();
2972
2973 my $node = extract_param($param, 'node');
2974
2975 my $vmid = extract_param($param, 'vmid');
2976
2977 my $snapname = extract_param($param, 'snapname');
2978
7e7d7b61 2979 my $realcmd = sub {
22c377f0
DM
2980 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
2981 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
7e7d7b61
DM
2982 };
2983
2984 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
2985 }});
2986
2987__PACKAGE__->register_method({
2988 name => 'delsnapshot',
2989 path => '{vmid}/snapshot/{snapname}',
2990 method => 'DELETE',
2991 protected => 1,
2992 proxyto => 'node',
2993 description => "Delete a VM snapshot.",
2994 permissions => {
f1baf1df 2995 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2996 },
2997 parameters => {
2998 additionalProperties => 0,
2999 properties => {
3000 node => get_standard_option('pve-node'),
3001 vmid => get_standard_option('pve-vmid'),
8abd398b 3002 snapname => get_standard_option('pve-snapshot-name'),
3ee28e38
DM
3003 force => {
3004 optional => 1,
3005 type => 'boolean',
3006 description => "For removal from config file, even if removing disk snapshots fails.",
3007 },
7e7d7b61
DM
3008 },
3009 },
3010 returns => {
3011 type => 'string',
3012 description => "the task ID.",
3013 },
3014 code => sub {
3015 my ($param) = @_;
3016
3017 my $rpcenv = PVE::RPCEnvironment::get();
3018
3019 my $authuser = $rpcenv->get_user();
3020
3021 my $node = extract_param($param, 'node');
3022
3023 my $vmid = extract_param($param, 'vmid');
3024
3025 my $snapname = extract_param($param, 'snapname');
3026
7e7d7b61 3027 my $realcmd = sub {
22c377f0 3028 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
3ee28e38 3029 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
7e7d7b61 3030 };
9dbd1ee4 3031
7b2257a8 3032 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
9dbd1ee4
AD
3033 }});
3034
04a69bb4
AD
3035__PACKAGE__->register_method({
3036 name => 'template',
3037 path => '{vmid}/template',
3038 method => 'POST',
3039 protected => 1,
3040 proxyto => 'node',
3041 description => "Create a Template.",
b02691d8 3042 permissions => {
7af0a6c8
DM
3043 description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
3044 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
b02691d8 3045 },
04a69bb4
AD
3046 parameters => {
3047 additionalProperties => 0,
3048 properties => {
3049 node => get_standard_option('pve-node'),
3050 vmid => get_standard_option('pve-vmid'),
3051 disk => {
3052 optional => 1,
3053 type => 'string',
3054 description => "If you want to convert only 1 disk to base image.",
3055 enum => [PVE::QemuServer::disknames()],
3056 },
3057
3058 },
3059 },
3060 returns => { type => 'null'},
3061 code => sub {
3062 my ($param) = @_;
3063
3064 my $rpcenv = PVE::RPCEnvironment::get();
3065
3066 my $authuser = $rpcenv->get_user();
3067
3068 my $node = extract_param($param, 'node');
3069
3070 my $vmid = extract_param($param, 'vmid');
3071
3072 my $disk = extract_param($param, 'disk');
3073
3074 my $updatefn = sub {
3075
3076 my $conf = PVE::QemuServer::load_config($vmid);
3077
3078 PVE::QemuServer::check_lock($conf);
3079
75466c4f 3080 die "unable to create template, because VM contains snapshots\n"
b91c2aae 3081 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
0402a80b 3082
75466c4f 3083 die "you can't convert a template to a template\n"
03c2d0ad 3084 if PVE::QemuServer::is_template($conf) && !$disk;
0402a80b 3085
75466c4f 3086 die "you can't convert a VM to template if VM is running\n"
218cab9a 3087 if PVE::QemuServer::check_running($vmid);
35c5fdef 3088
04a69bb4
AD
3089 my $realcmd = sub {
3090 PVE::QemuServer::template_create($vmid, $conf, $disk);
3091 };
04a69bb4 3092
75e7e997 3093 $conf->{template} = 1;
04a69bb4 3094 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
75e7e997
DM
3095
3096 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
04a69bb4
AD
3097 };
3098
3099 PVE::QemuServer::lock_config($vmid, $updatefn);
3100 return undef;
3101 }});
3102
1e3baf05 31031;