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