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