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