]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
fix assertion
[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);
10use PVE::Exception qw(raise raise_param_exc);
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
ae57f6b3
DM
62# Note: $pool is only needed when creating a VM, because pool permissions
63# are automatically inherited if VM already exists inside a pool.
64my $create_disks = sub {
65 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
a0d1b1a2
DM
66
67 my $vollist = [];
a0d1b1a2 68
ae57f6b3
DM
69 my $res = {};
70 PVE::QemuServer::foreach_drive($settings, sub {
71 my ($ds, $disk) = @_;
72
73 my $volid = $disk->{file};
74
f5782fd0 75 if (!$volid || $volid eq 'none' || $volid eq 'cdrom') {
628e9a2b
AD
76 delete $disk->{size};
77 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
09d0ee64 78 } elsif ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/) {
ae57f6b3
DM
79 my ($storeid, $size) = ($2 || $default_storage, $3);
80 die "no storage ID specified (and no default storage)\n" if !$storeid;
81 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
82 my $fmt = $disk->{format} || $defformat;
a0d1b1a2
DM
83 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid,
84 $fmt, undef, $size*1024*1024);
a0d1b1a2 85 $disk->{file} = $volid;
24afaca0 86 $disk->{size} = $size*1024*1024*1024;
a0d1b1a2 87 push @$vollist, $volid;
ae57f6b3
DM
88 delete $disk->{format}; # no longer needed
89 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
90 } else {
eabe0da0 91
ba68cf09 92 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $volid);
eabe0da0
DM
93
94 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
35cb731c 95
35cb731c
AD
96 my $foundvolid = undef;
97
eabe0da0
DM
98 if ($storeid) {
99 PVE::Storage::activate_volumes($storecfg, [ $volid ]);
100 my $dl = PVE::Storage::vdisk_list($storecfg, $storeid, undef);
101
102 PVE::Storage::foreach_volid($dl, sub {
103 my ($volumeid) = @_;
104 if($volumeid eq $volid) {
105 $foundvolid = 1;
106 return;
107 }
108 });
109 }
35cb731c
AD
110
111 die "image '$path' does not exists\n" if (!(-f $path || -b $path || $foundvolid));
24afaca0
DM
112
113 my ($size) = PVE::Storage::volume_size_info($storecfg, $volid, 1);
114 $disk->{size} = $size;
115 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
a0d1b1a2 116 }
ae57f6b3 117 });
a0d1b1a2
DM
118
119 # free allocated images on error
120 if (my $err = $@) {
121 syslog('err', "VM $vmid creating disks failed");
122 foreach my $volid (@$vollist) {
123 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
124 warn $@ if $@;
125 }
126 die $err;
127 }
128
129 # modify vm config if everything went well
ae57f6b3
DM
130 foreach my $ds (keys %$res) {
131 $conf->{$ds} = $res->{$ds};
a0d1b1a2
DM
132 }
133
134 return $vollist;
135};
136
137my $check_vm_modify_config_perm = sub {
ae57f6b3 138 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
a0d1b1a2 139
6e5c4da7 140 return 1 if $authuser eq 'root@pam';
a0d1b1a2 141
ae57f6b3 142 foreach my $opt (@$key_list) {
a0d1b1a2
DM
143 # disk checks need to be done somewhere else
144 next if PVE::QemuServer::valid_drivename($opt);
145
146 if ($opt eq 'sockets' || $opt eq 'cores' ||
147 $opt eq 'cpu' || $opt eq 'smp' ||
ab6b35df 148 $opt eq 'cpulimit' || $opt eq 'cpuunits') {
a0d1b1a2
DM
149 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
150 } elsif ($opt eq 'boot' || $opt eq 'bootdisk') {
151 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
ccd5438f 152 } elsif ($opt eq 'memory' || $opt eq 'balloon' || $opt eq 'shares') {
a0d1b1a2
DM
153 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
154 } elsif ($opt eq 'args' || $opt eq 'lock') {
155 die "only root can set '$opt' config\n";
156 } elsif ($opt eq 'cpu' || $opt eq 'kvm' || $opt eq 'acpi' ||
157 $opt eq 'vga' || $opt eq 'watchdog' || $opt eq 'tablet') {
158 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
159 } elsif ($opt =~ m/^net\d+$/) {
160 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
161 } else {
162 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
163 }
164 }
165
166 return 1;
167};
168
1e3baf05 169__PACKAGE__->register_method({
afdb31d5
DM
170 name => 'vmlist',
171 path => '',
1e3baf05
DM
172 method => 'GET',
173 description => "Virtual machine index (per node).",
a0d1b1a2
DM
174 permissions => {
175 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
176 user => 'all',
177 },
1e3baf05
DM
178 proxyto => 'node',
179 protected => 1, # qemu pid files are only readable by root
180 parameters => {
181 additionalProperties => 0,
182 properties => {
183 node => get_standard_option('pve-node'),
184 },
185 },
186 returns => {
187 type => 'array',
188 items => {
189 type => "object",
190 properties => {},
191 },
192 links => [ { rel => 'child', href => "{vmid}" } ],
193 },
194 code => sub {
195 my ($param) = @_;
196
a0d1b1a2
DM
197 my $rpcenv = PVE::RPCEnvironment::get();
198 my $authuser = $rpcenv->get_user();
199
1e3baf05
DM
200 my $vmstatus = PVE::QemuServer::vmstatus();
201
a0d1b1a2
DM
202 my $res = [];
203 foreach my $vmid (keys %$vmstatus) {
204 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
205
206 my $data = $vmstatus->{$vmid};
207 $data->{vmid} = $vmid;
208 push @$res, $data;
209 }
1e3baf05 210
a0d1b1a2 211 return $res;
1e3baf05
DM
212 }});
213
214__PACKAGE__->register_method({
afdb31d5
DM
215 name => 'create_vm',
216 path => '',
1e3baf05 217 method => 'POST',
3e16d5fc 218 description => "Create or restore a virtual machine.",
a0d1b1a2
DM
219 permissions => {
220 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. If you create disks you need 'Datastore.AllocateSpace' on any used storage.",
221 check => [ 'or',
222 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
223 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
224 ],
225 },
1e3baf05
DM
226 protected => 1,
227 proxyto => 'node',
228 parameters => {
229 additionalProperties => 0,
230 properties => PVE::QemuServer::json_config_properties(
231 {
232 node => get_standard_option('pve-node'),
233 vmid => get_standard_option('pve-vmid'),
3e16d5fc
DM
234 archive => {
235 description => "The backup file.",
236 type => 'string',
237 optional => 1,
238 maxLength => 255,
239 },
240 storage => get_standard_option('pve-storage-id', {
241 description => "Default storage.",
242 optional => 1,
243 }),
244 force => {
afdb31d5 245 optional => 1,
3e16d5fc
DM
246 type => 'boolean',
247 description => "Allow to overwrite existing VM.",
51586c3a
DM
248 requires => 'archive',
249 },
250 unique => {
afdb31d5 251 optional => 1,
51586c3a
DM
252 type => 'boolean',
253 description => "Assign a unique random ethernet address.",
254 requires => 'archive',
3e16d5fc 255 },
a0d1b1a2
DM
256 pool => {
257 optional => 1,
258 type => 'string', format => 'pve-poolid',
259 description => "Add the VM to the specified pool.",
260 },
1e3baf05
DM
261 }),
262 },
afdb31d5 263 returns => {
5fdbe4f0
DM
264 type => 'string',
265 },
1e3baf05
DM
266 code => sub {
267 my ($param) = @_;
268
5fdbe4f0
DM
269 my $rpcenv = PVE::RPCEnvironment::get();
270
a0d1b1a2 271 my $authuser = $rpcenv->get_user();
5fdbe4f0 272
1e3baf05
DM
273 my $node = extract_param($param, 'node');
274
1e3baf05
DM
275 my $vmid = extract_param($param, 'vmid');
276
3e16d5fc
DM
277 my $archive = extract_param($param, 'archive');
278
279 my $storage = extract_param($param, 'storage');
280
51586c3a
DM
281 my $force = extract_param($param, 'force');
282
283 my $unique = extract_param($param, 'unique');
a0d1b1a2
DM
284
285 my $pool = extract_param($param, 'pool');
51586c3a 286
1e3baf05 287 my $filename = PVE::QemuServer::config_file($vmid);
afdb31d5
DM
288
289 my $storecfg = PVE::Storage::config();
1e3baf05 290
3e16d5fc 291 PVE::Cluster::check_cfs_quorum();
1e3baf05 292
a0d1b1a2
DM
293 if (defined($pool)) {
294 $rpcenv->check_pool_exist($pool);
a0d1b1a2
DM
295 }
296
fcbb753e 297 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace'])
a0d1b1a2
DM
298 if defined($storage);
299
afdb31d5 300 if (!$archive) {
3e16d5fc 301 &$resolve_cdrom_alias($param);
1e3baf05 302
fcbb753e 303 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param, $storage);
ae57f6b3
DM
304
305 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
306
3e16d5fc
DM
307 foreach my $opt (keys %$param) {
308 if (PVE::QemuServer::valid_drivename($opt)) {
309 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
310 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
afdb31d5 311
3e16d5fc
DM
312 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
313 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
314 }
1e3baf05 315 }
3e16d5fc
DM
316
317 PVE::QemuServer::add_random_macs($param);
51586c3a
DM
318 } else {
319 my $keystr = join(' ', keys %$param);
bc4dcb99
DM
320 raise_param_exc({ archive => "option conflicts with other options ($keystr)"}) if $keystr;
321
5b9d692a 322 if ($archive eq '-') {
afdb31d5 323 die "pipe requires cli environment\n"
d7810bc1 324 if $rpcenv->{type} ne 'cli';
5b9d692a 325 } else {
ba68cf09 326 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $archive);
d7810bc1
DM
327
328 PVE::Storage::activate_volumes($storecfg, [ $archive ])
329 if PVE::Storage::parse_volume_id ($archive, 1);
330
971f27c4
DM
331 die "can't find archive file '$archive'\n" if !($path && -f $path);
332 $archive = $path;
333 }
1e3baf05
DM
334 }
335
502d18a2
DM
336 my $addVMtoPoolFn = sub {
337 my $usercfg = cfs_read_file("user.cfg");
338 if (my $data = $usercfg->{pools}->{$pool}) {
339 $data->{vms}->{$vmid} = 1;
340 $usercfg->{vms}->{$vmid} = $pool;
341 cfs_write_file("user.cfg", $usercfg);
342 }
343 };
344
3e16d5fc
DM
345 my $restorefn = sub {
346
347 if (-f $filename) {
afdb31d5 348 die "unable to restore vm $vmid: config file already exists\n"
51586c3a 349 if !$force;
3e16d5fc 350
afdb31d5 351 die "unable to restore vm $vmid: vm is running\n"
3e16d5fc
DM
352 if PVE::QemuServer::check_running($vmid);
353 }
354
355 my $realcmd = sub {
a0d1b1a2 356 PVE::QemuServer::restore_archive($archive, $vmid, $authuser, {
51586c3a 357 storage => $storage,
a0d1b1a2 358 pool => $pool,
51586c3a 359 unique => $unique });
502d18a2
DM
360
361 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
3e16d5fc
DM
362 };
363
a0d1b1a2 364 return $rpcenv->fork_worker('qmrestore', $vmid, $authuser, $realcmd);
3e16d5fc 365 };
1e3baf05 366
1e3baf05
DM
367 my $createfn = sub {
368
191435c6 369 # test after locking
afdb31d5 370 die "unable to create vm $vmid: config file already exists\n"
1e3baf05
DM
371 if -f $filename;
372
5fdbe4f0 373 my $realcmd = sub {
1e3baf05 374
5fdbe4f0 375 my $vollist = [];
1e3baf05 376
1858638f
DM
377 my $conf = $param;
378
5fdbe4f0 379 eval {
ae57f6b3 380
1858638f 381 $vollist = &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $param, $storage);
1e3baf05 382
5fdbe4f0
DM
383 # try to be smart about bootdisk
384 my @disks = PVE::QemuServer::disknames();
385 my $firstdisk;
386 foreach my $ds (reverse @disks) {
1858638f
DM
387 next if !$conf->{$ds};
388 my $disk = PVE::QemuServer::parse_drive($ds, $conf->{$ds});
5fdbe4f0
DM
389 next if PVE::QemuServer::drive_is_cdrom($disk);
390 $firstdisk = $ds;
391 }
1e3baf05 392
1858638f
DM
393 if (!$conf->{bootdisk} && $firstdisk) {
394 $conf->{bootdisk} = $firstdisk;
5fdbe4f0 395 }
1e3baf05 396
ae9ca91d
DM
397 PVE::QemuServer::update_config_nolock($vmid, $conf);
398
5fdbe4f0
DM
399 };
400 my $err = $@;
1e3baf05 401
5fdbe4f0
DM
402 if ($err) {
403 foreach my $volid (@$vollist) {
404 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
405 warn $@ if $@;
406 }
407 die "create failed - $err";
408 }
502d18a2
DM
409
410 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
5fdbe4f0
DM
411 };
412
a0d1b1a2 413 return $rpcenv->fork_worker('qmcreate', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
414 };
415
191435c6 416 return PVE::QemuServer::lock_config_full($vmid, 1, $archive ? $restorefn : $createfn);
1e3baf05
DM
417 }});
418
419__PACKAGE__->register_method({
420 name => 'vmdiridx',
afdb31d5 421 path => '{vmid}',
1e3baf05
DM
422 method => 'GET',
423 proxyto => 'node',
424 description => "Directory index",
a0d1b1a2
DM
425 permissions => {
426 user => 'all',
427 },
1e3baf05
DM
428 parameters => {
429 additionalProperties => 0,
430 properties => {
431 node => get_standard_option('pve-node'),
432 vmid => get_standard_option('pve-vmid'),
433 },
434 },
435 returns => {
436 type => 'array',
437 items => {
438 type => "object",
439 properties => {
440 subdir => { type => 'string' },
441 },
442 },
443 links => [ { rel => 'child', href => "{subdir}" } ],
444 },
445 code => sub {
446 my ($param) = @_;
447
448 my $res = [
449 { subdir => 'config' },
450 { subdir => 'status' },
451 { subdir => 'unlink' },
452 { subdir => 'vncproxy' },
3ea94c60 453 { subdir => 'migrate' },
2f48a4f5 454 { subdir => 'resize' },
1e3baf05
DM
455 { subdir => 'rrd' },
456 { subdir => 'rrddata' },
91c94f0a 457 { subdir => 'monitor' },
7e7d7b61 458 { subdir => 'snapshot' },
1e3baf05 459 ];
afdb31d5 460
1e3baf05
DM
461 return $res;
462 }});
463
464__PACKAGE__->register_method({
afdb31d5
DM
465 name => 'rrd',
466 path => '{vmid}/rrd',
1e3baf05
DM
467 method => 'GET',
468 protected => 1, # fixme: can we avoid that?
469 permissions => {
378b359e 470 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
471 },
472 description => "Read VM RRD statistics (returns PNG)",
473 parameters => {
474 additionalProperties => 0,
475 properties => {
476 node => get_standard_option('pve-node'),
477 vmid => get_standard_option('pve-vmid'),
478 timeframe => {
479 description => "Specify the time frame you are interested in.",
480 type => 'string',
481 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
482 },
483 ds => {
484 description => "The list of datasources you want to display.",
485 type => 'string', format => 'pve-configid-list',
486 },
487 cf => {
488 description => "The RRD consolidation function",
489 type => 'string',
490 enum => [ 'AVERAGE', 'MAX' ],
491 optional => 1,
492 },
493 },
494 },
495 returns => {
496 type => "object",
497 properties => {
498 filename => { type => 'string' },
499 },
500 },
501 code => sub {
502 my ($param) = @_;
503
504 return PVE::Cluster::create_rrd_graph(
afdb31d5 505 "pve2-vm/$param->{vmid}", $param->{timeframe},
1e3baf05 506 $param->{ds}, $param->{cf});
afdb31d5 507
1e3baf05
DM
508 }});
509
510__PACKAGE__->register_method({
afdb31d5
DM
511 name => 'rrddata',
512 path => '{vmid}/rrddata',
1e3baf05
DM
513 method => 'GET',
514 protected => 1, # fixme: can we avoid that?
515 permissions => {
378b359e 516 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
517 },
518 description => "Read VM RRD statistics",
519 parameters => {
520 additionalProperties => 0,
521 properties => {
522 node => get_standard_option('pve-node'),
523 vmid => get_standard_option('pve-vmid'),
524 timeframe => {
525 description => "Specify the time frame you are interested in.",
526 type => 'string',
527 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
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 => "array",
539 items => {
540 type => "object",
541 properties => {},
542 },
543 },
544 code => sub {
545 my ($param) = @_;
546
547 return PVE::Cluster::create_rrd_data(
548 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
549 }});
550
551
552__PACKAGE__->register_method({
afdb31d5
DM
553 name => 'vm_config',
554 path => '{vmid}/config',
1e3baf05
DM
555 method => 'GET',
556 proxyto => 'node',
557 description => "Get virtual machine configuration.",
a0d1b1a2
DM
558 permissions => {
559 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
560 },
1e3baf05
DM
561 parameters => {
562 additionalProperties => 0,
563 properties => {
564 node => get_standard_option('pve-node'),
565 vmid => get_standard_option('pve-vmid'),
566 },
567 },
afdb31d5 568 returns => {
1e3baf05 569 type => "object",
554ac7e7
DM
570 properties => {
571 digest => {
572 type => 'string',
573 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
574 }
575 },
1e3baf05
DM
576 },
577 code => sub {
578 my ($param) = @_;
579
580 my $conf = PVE::QemuServer::load_config($param->{vmid});
581
22c377f0
DM
582 delete $conf->{snapshots};
583
1e3baf05
DM
584 return $conf;
585 }});
586
ae57f6b3
DM
587my $vm_is_volid_owner = sub {
588 my ($storecfg, $vmid, $volid) =@_;
589
590 if ($volid !~ m|^/|) {
591 my ($path, $owner);
592 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
593 if ($owner && ($owner == $vmid)) {
594 return 1;
595 }
596 }
597
598 return undef;
599};
600
601my $test_deallocate_drive = sub {
602 my ($storecfg, $vmid, $key, $drive, $force) = @_;
603
604 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
605 my $volid = $drive->{file};
606 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
607 if ($force || $key =~ m/^unused/) {
608 my $sid = PVE::Storage::parse_volume_id($volid);
609 return $sid;
610 }
611 }
612 }
613
614 return undef;
615};
616
5d7a6767 617my $delete_drive = sub {
1858638f 618 my ($conf, $storecfg, $vmid, $key, $drive, $force) = @_;
5d7a6767
DM
619
620 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
621 my $volid = $drive->{file};
ae57f6b3
DM
622 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
623 if ($force || $key =~ m/^unused/) {
624 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
7e4e69a6 625 die $@ if $@;
ae57f6b3
DM
626 } else {
627 PVE::QemuServer::add_unused_volume($conf, $volid, $vmid);
5d7a6767 628 }
ae57f6b3
DM
629 }
630 }
49f9db93
DM
631
632 delete $conf->{$key};
ae57f6b3
DM
633};
634
635my $vmconfig_delete_option = sub {
636 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force) = @_;
637
638 return if !defined($conf->{$opt});
639
640 my $isDisk = PVE::QemuServer::valid_drivename($opt)|| ($opt =~ m/^unused/);
641
642 if ($isDisk) {
643 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
644
645 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
646 if (my $sid = &$test_deallocate_drive($storecfg, $vmid, $opt, $drive, $force)) {
fcbb753e 647 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.Allocate']);
5d7a6767 648 }
ae57f6b3 649 }
9a8d6b66
AD
650
651 my $unplugwarning = "";
652 if($conf->{ostype} && $conf->{ostype} eq 'l26'){
653 $unplugwarning = "<br>verify that you have acpiphp && pci_hotplug modules loaded in your guest VM";
654 }elsif($conf->{ostype} && $conf->{ostype} eq 'l24'){
655 $unplugwarning = "<br>kernel 2.4 don't support hotplug, please disable hotplug in options";
656 }elsif(!$conf->{ostype} || ($conf->{ostype} && $conf->{ostype} eq 'other')){
657 $unplugwarning = "<br>verify that your guest support acpi hotplug";
658 }
659
e8a7e9b4
AD
660 if($opt eq 'tablet'){
661 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt);
662 }else{
663 die "error hot-unplug $opt $unplugwarning" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
664 }
cd6ecb89 665
ae57f6b3
DM
666 if ($isDisk) {
667 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
668 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive, $force);
5d7a6767 669 } else {
ae57f6b3
DM
670 delete $conf->{$opt};
671 }
672
673 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
674};
675
9bf371a6 676my $safe_num_ne = sub {
93ae06e1
DM
677 my ($a, $b) = @_;
678
679 return 0 if !defined($a) && !defined($b);
680 return 1 if !defined($a);
681 return 1 if !defined($b);
682
683 return $a != $b;
684};
685
ae57f6b3
DM
686my $vmconfig_update_disk = sub {
687 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
5d7a6767 688
ae57f6b3
DM
689 my $drive = PVE::QemuServer::parse_drive($opt, $value);
690
691 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
692 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
693 } else {
694 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
695 }
696
697 if ($conf->{$opt}) {
698
699 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
700
701 my $media = $drive->{media} || 'disk';
702 my $oldmedia = $old_drive->{media} || 'disk';
703 die "unable to change media type\n" if $media ne $oldmedia;
704
705 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
706 ($drive->{file} ne $old_drive->{file})) { # delete old disks
707
708 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
709 $conf = PVE::QemuServer::load_config($vmid); # update/reload
710 }
0f56d571 711
9bf371a6
DM
712 if(&$safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
713 &$safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
714 &$safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
715 &$safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
716 &$safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
717 &$safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr})) {
718 PVE::QemuServer::qemu_block_set_io_throttle($vmid,"drive-$opt", $drive->{mbps}*1024*1024,
719 $drive->{mbps_rd}*1024*1024, $drive->{mbps_wr}*1024*1024,
720 $drive->{iops}, $drive->{iops_rd}, $drive->{iops_wr})
721 if !PVE::QemuServer::drive_is_cdrom($drive);
0f56d571 722 }
ae57f6b3
DM
723 }
724 }
725
726 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
727 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
728
729 $conf = PVE::QemuServer::load_config($vmid); # update/reload
730 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
731
732 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
733
734 if (PVE::QemuServer::check_running($vmid)) {
735 if ($drive->{file} eq 'none') {
ce156282 736 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
ae57f6b3
DM
737 } else {
738 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
ce156282
AD
739 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt"); #force eject if locked
740 PVE::QemuServer::vm_mon_cmd($vmid, "change",device => "drive-$opt",target => "$path") if $path;
ae57f6b3
DM
741 }
742 }
743
744 } else { # hotplug new disks
745
746 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
5d7a6767 747 }
5d7a6767
DM
748};
749
ae57f6b3
DM
750my $vmconfig_update_net = sub {
751 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
752
de8f60b2
AD
753 if ($conf->{$opt} && PVE::QemuServer::check_running($vmid)) {
754 my $oldnet = PVE::QemuServer::parse_net($conf->{$opt});
755 my $newnet = PVE::QemuServer::parse_net($value);
756
757 if($oldnet->{model} ne $newnet->{model}){
758 #if model change, we try to hot-unplug
759 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
760 }else{
761
762 if($newnet->{bridge} && $oldnet->{bridge}){
763 my $iface = "tap".$vmid."i".$1 if $opt =~ m/net(\d+)/;
ae57f6b3 764
de8f60b2
AD
765 if($newnet->{rate} ne $oldnet->{rate}){
766 PVE::Network::tap_rate_limit($iface, $newnet->{rate});
767 }
768
769 if(($newnet->{bridge} ne $oldnet->{bridge}) || ($newnet->{tag} ne $oldnet->{tag})){
770 eval{PVE::Network::tap_unplug($iface, $oldnet->{bridge}, $oldnet->{tag});};
771 PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag});
772 }
773
774 }else{
775 #if bridge/nat mode change, we try to hot-unplug
776 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
777 }
778 }
779
780 }
ae57f6b3
DM
781 $conf->{$opt} = $value;
782 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
783 $conf = PVE::QemuServer::load_config($vmid); # update/reload
784
785 my $net = PVE::QemuServer::parse_net($conf->{$opt});
786
787 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
788};
789
a0d1b1a2
DM
790my $vm_config_perm_list = [
791 'VM.Config.Disk',
792 'VM.Config.CDROM',
793 'VM.Config.CPU',
794 'VM.Config.Memory',
795 'VM.Config.Network',
796 'VM.Config.HWType',
797 'VM.Config.Options',
798 ];
799
1e3baf05 800__PACKAGE__->register_method({
afdb31d5
DM
801 name => 'update_vm',
802 path => '{vmid}/config',
1e3baf05
DM
803 method => 'PUT',
804 protected => 1,
805 proxyto => 'node',
806 description => "Set virtual machine options.",
a0d1b1a2
DM
807 permissions => {
808 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
809 },
1e3baf05
DM
810 parameters => {
811 additionalProperties => 0,
812 properties => PVE::QemuServer::json_config_properties(
813 {
814 node => get_standard_option('pve-node'),
815 vmid => get_standard_option('pve-vmid'),
3ea94c60 816 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
817 delete => {
818 type => 'string', format => 'pve-configid-list',
819 description => "A list of settings you want to delete.",
820 optional => 1,
821 },
822 force => {
823 type => 'boolean',
824 description => $opt_force_description,
825 optional => 1,
826 requires => 'delete',
827 },
554ac7e7
DM
828 digest => {
829 type => 'string',
830 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
831 maxLength => 40,
afdb31d5 832 optional => 1,
554ac7e7 833 }
1e3baf05
DM
834 }),
835 },
836 returns => { type => 'null'},
837 code => sub {
838 my ($param) = @_;
839
840 my $rpcenv = PVE::RPCEnvironment::get();
841
a0d1b1a2 842 my $authuser = $rpcenv->get_user();
1e3baf05
DM
843
844 my $node = extract_param($param, 'node');
845
1e3baf05
DM
846 my $vmid = extract_param($param, 'vmid');
847
5fdbe4f0
DM
848 my $digest = extract_param($param, 'digest');
849
850 my @paramarr = (); # used for log message
851 foreach my $key (keys %$param) {
852 push @paramarr, "-$key", $param->{$key};
853 }
854
1e3baf05 855 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 856 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 857 if $skiplock && $authuser ne 'root@pam';
1e3baf05 858
0532bc63
DM
859 my $delete_str = extract_param($param, 'delete');
860
1e3baf05
DM
861 my $force = extract_param($param, 'force');
862
0532bc63
DM
863 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
864
1e68cb19
DM
865 my $storecfg = PVE::Storage::config();
866
7bfdeb5f
DM
867 my $defaults = PVE::QemuServer::load_defaults();
868
1e68cb19
DM
869 &$resolve_cdrom_alias($param);
870
871 # now try to verify all parameters
872
0532bc63
DM
873 my @delete = ();
874 foreach my $opt (PVE::Tools::split_list($delete_str)) {
875 $opt = 'ide2' if $opt eq 'cdrom';
876 raise_param_exc({ delete => "you can't use '-$opt' and " .
877 "-delete $opt' at the same time" })
878 if defined($param->{$opt});
879
880 if (!PVE::QemuServer::option_exists($opt)) {
881 raise_param_exc({ delete => "unknown option '$opt'" });
882 }
ae57f6b3 883
0532bc63
DM
884 push @delete, $opt;
885 }
1e3baf05 886
1e68cb19
DM
887 foreach my $opt (keys %$param) {
888 if (PVE::QemuServer::valid_drivename($opt)) {
889 # cleanup drive path
890 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
891 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
892 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
1e68cb19
DM
893 } elsif ($opt =~ m/^net(\d+)$/) {
894 # add macaddr
895 my $net = PVE::QemuServer::parse_net($param->{$opt});
896 $param->{$opt} = PVE::QemuServer::print_net($net);
1e68cb19
DM
897 }
898 }
1e3baf05 899
ae57f6b3
DM
900 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
901
902 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
903
fcbb753e 904 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1e3baf05 905
5d39a182 906 my $updatefn = sub {
1e3baf05 907
5d39a182 908 my $conf = PVE::QemuServer::load_config($vmid);
1e3baf05 909
5d39a182
DM
910 die "checksum missmatch (file change by other user?)\n"
911 if $digest && $digest ne $conf->{digest};
1e3baf05 912
5d39a182 913 PVE::QemuServer::check_lock($conf) if !$skiplock;
1e3baf05 914
7bfdeb5f
DM
915 if ($param->{memory} || defined($param->{balloon})) {
916 my $maxmem = $param->{memory} || $conf->{memory} || $defaults->{memory};
917 my $balloon = defined($param->{balloon}) ? $param->{balloon} : $conf->{balloon};
918
919 die "balloon value too large (must be smaller than assigned memory)\n"
920 if $balloon > $maxmem;
921 }
922
a0d1b1a2 923 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
c2a64aa7 924
5d7a6767 925 foreach my $opt (@delete) { # delete
1e68cb19 926 $conf = PVE::QemuServer::load_config($vmid); # update/reload
ae57f6b3 927 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
5d39a182 928 }
1e3baf05 929
7bfdeb5f
DM
930 my $running = PVE::QemuServer::check_running($vmid);
931
5d7a6767 932 foreach my $opt (keys %$param) { # add/change
1e3baf05 933
1e68cb19 934 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1e3baf05 935
5d7a6767
DM
936 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
937
ae57f6b3 938 if (PVE::QemuServer::valid_drivename($opt)) {
5d7a6767 939
ae57f6b3
DM
940 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
941 $opt, $param->{$opt}, $force);
1e68cb19 942
ae57f6b3 943 } elsif ($opt =~ m/^net(\d+)$/) { #nics
1858638f 944
ae57f6b3
DM
945 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
946 $opt, $param->{$opt});
1e68cb19
DM
947
948 } else {
949
cd6ecb89
AD
950 if($opt eq 'tablet' && $param->{$opt} == 1){
951 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt);
952 }elsif($opt eq 'tablet' && $param->{$opt} == 0){
953 PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
954 }
955
1858638f
DM
956 $conf->{$opt} = $param->{$opt};
957 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3a1e36bb 958 }
5d39a182 959 }
7bfdeb5f
DM
960
961 # allow manual ballooning if shares is set to zero
962 if ($running && defined($param->{balloon}) &&
963 defined($conf->{shares}) && ($conf->{shares} == 0)) {
964 my $balloon = $param->{'balloon'} || $conf->{memory} || $defaults->{memory};
965 PVE::QemuServer::vm_mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
966 }
967
5d39a182
DM
968 };
969
970 PVE::QemuServer::lock_config($vmid, $updatefn);
fcdb0117 971
1e3baf05
DM
972 return undef;
973 }});
974
975
976__PACKAGE__->register_method({
afdb31d5
DM
977 name => 'destroy_vm',
978 path => '{vmid}',
1e3baf05
DM
979 method => 'DELETE',
980 protected => 1,
981 proxyto => 'node',
982 description => "Destroy the vm (also delete all used/owned volumes).",
a0d1b1a2
DM
983 permissions => {
984 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
985 },
1e3baf05
DM
986 parameters => {
987 additionalProperties => 0,
988 properties => {
989 node => get_standard_option('pve-node'),
990 vmid => get_standard_option('pve-vmid'),
3ea94c60 991 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
992 },
993 },
afdb31d5 994 returns => {
5fdbe4f0
DM
995 type => 'string',
996 },
1e3baf05
DM
997 code => sub {
998 my ($param) = @_;
999
1000 my $rpcenv = PVE::RPCEnvironment::get();
1001
a0d1b1a2 1002 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1003
1004 my $vmid = $param->{vmid};
1005
1006 my $skiplock = $param->{skiplock};
afdb31d5 1007 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1008 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1009
5fdbe4f0
DM
1010 # test if VM exists
1011 my $conf = PVE::QemuServer::load_config($vmid);
1012
afdb31d5 1013 my $storecfg = PVE::Storage::config();
1e3baf05 1014
502d18a2
DM
1015 my $delVMfromPoolFn = sub {
1016 my $usercfg = cfs_read_file("user.cfg");
5d0094ea
DM
1017 if (my $pool = $usercfg->{vms}->{$vmid}) {
1018 if (my $data = $usercfg->{pools}->{$pool}) {
1019 delete $data->{vms}->{$vmid};
1020 delete $usercfg->{vms}->{$vmid};
1021 cfs_write_file("user.cfg", $usercfg);
1022 }
502d18a2
DM
1023 }
1024 };
1025
5fdbe4f0 1026 my $realcmd = sub {
ff1a2432
DM
1027 my $upid = shift;
1028
1029 syslog('info', "destroy VM $vmid: $upid\n");
1030
5fdbe4f0 1031 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
502d18a2
DM
1032
1033 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
5fdbe4f0 1034 };
1e3baf05 1035
a0d1b1a2 1036 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1e3baf05
DM
1037 }});
1038
1039__PACKAGE__->register_method({
afdb31d5
DM
1040 name => 'unlink',
1041 path => '{vmid}/unlink',
1e3baf05
DM
1042 method => 'PUT',
1043 protected => 1,
1044 proxyto => 'node',
1045 description => "Unlink/delete disk images.",
a0d1b1a2
DM
1046 permissions => {
1047 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
1048 },
1e3baf05
DM
1049 parameters => {
1050 additionalProperties => 0,
1051 properties => {
1052 node => get_standard_option('pve-node'),
1053 vmid => get_standard_option('pve-vmid'),
1054 idlist => {
1055 type => 'string', format => 'pve-configid-list',
1056 description => "A list of disk IDs you want to delete.",
1057 },
1058 force => {
1059 type => 'boolean',
1060 description => $opt_force_description,
1061 optional => 1,
1062 },
1063 },
1064 },
1065 returns => { type => 'null'},
1066 code => sub {
1067 my ($param) = @_;
1068
1069 $param->{delete} = extract_param($param, 'idlist');
1070
1071 __PACKAGE__->update_vm($param);
1072
1073 return undef;
1074 }});
1075
1076my $sslcert;
1077
1078__PACKAGE__->register_method({
afdb31d5
DM
1079 name => 'vncproxy',
1080 path => '{vmid}/vncproxy',
1e3baf05
DM
1081 method => 'POST',
1082 protected => 1,
1083 permissions => {
378b359e 1084 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1e3baf05
DM
1085 },
1086 description => "Creates a TCP VNC proxy connections.",
1087 parameters => {
1088 additionalProperties => 0,
1089 properties => {
1090 node => get_standard_option('pve-node'),
1091 vmid => get_standard_option('pve-vmid'),
1092 },
1093 },
afdb31d5 1094 returns => {
1e3baf05
DM
1095 additionalProperties => 0,
1096 properties => {
1097 user => { type => 'string' },
1098 ticket => { type => 'string' },
1099 cert => { type => 'string' },
1100 port => { type => 'integer' },
1101 upid => { type => 'string' },
1102 },
1103 },
1104 code => sub {
1105 my ($param) = @_;
1106
1107 my $rpcenv = PVE::RPCEnvironment::get();
1108
a0d1b1a2 1109 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1110
1111 my $vmid = $param->{vmid};
1112 my $node = $param->{node};
1113
b6f39da2
DM
1114 my $authpath = "/vms/$vmid";
1115
a0d1b1a2 1116 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
b6f39da2 1117
1e3baf05
DM
1118 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1119 if !$sslcert;
1120
1121 my $port = PVE::Tools::next_vnc_port();
1122
1123 my $remip;
afdb31d5 1124
4f1be36c 1125 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1e3baf05
DM
1126 $remip = PVE::Cluster::remote_node_ip($node);
1127 }
1128
6bb726c9
SP
1129 # NOTE: kvm VNC traffic is already TLS encrypted
1130 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes', $remip] : [];
1e3baf05 1131
afdb31d5 1132 my $timeout = 10;
1e3baf05
DM
1133
1134 my $realcmd = sub {
1135 my $upid = shift;
1136
1137 syslog('info', "starting vnc proxy $upid\n");
1138
1139 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1140
1141 my $qmstr = join(' ', @$qmcmd);
1142
1143 # also redirect stderr (else we get RFB protocol errors)
be62c45c 1144 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1e3baf05 1145
be62c45c 1146 PVE::Tools::run_command($cmd);
1e3baf05
DM
1147
1148 return;
1149 };
1150
a0d1b1a2 1151 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1e3baf05 1152
3da85107
DM
1153 PVE::Tools::wait_for_vnc_port($port);
1154
1e3baf05 1155 return {
a0d1b1a2 1156 user => $authuser,
1e3baf05 1157 ticket => $ticket,
afdb31d5
DM
1158 port => $port,
1159 upid => $upid,
1160 cert => $sslcert,
1e3baf05
DM
1161 };
1162 }});
1163
5fdbe4f0
DM
1164__PACKAGE__->register_method({
1165 name => 'vmcmdidx',
afdb31d5 1166 path => '{vmid}/status',
5fdbe4f0
DM
1167 method => 'GET',
1168 proxyto => 'node',
1169 description => "Directory index",
a0d1b1a2
DM
1170 permissions => {
1171 user => 'all',
1172 },
5fdbe4f0
DM
1173 parameters => {
1174 additionalProperties => 0,
1175 properties => {
1176 node => get_standard_option('pve-node'),
1177 vmid => get_standard_option('pve-vmid'),
1178 },
1179 },
1180 returns => {
1181 type => 'array',
1182 items => {
1183 type => "object",
1184 properties => {
1185 subdir => { type => 'string' },
1186 },
1187 },
1188 links => [ { rel => 'child', href => "{subdir}" } ],
1189 },
1190 code => sub {
1191 my ($param) = @_;
1192
1193 # test if VM exists
1194 my $conf = PVE::QemuServer::load_config($param->{vmid});
1195
1196 my $res = [
1197 { subdir => 'current' },
1198 { subdir => 'start' },
1199 { subdir => 'stop' },
1200 ];
afdb31d5 1201
5fdbe4f0
DM
1202 return $res;
1203 }});
1204
88fc87b4
DM
1205my $vm_is_ha_managed = sub {
1206 my ($vmid) = @_;
1207
1208 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1209 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1210 return 1;
1211 }
1212 return 0;
1213};
1214
1e3baf05 1215__PACKAGE__->register_method({
afdb31d5 1216 name => 'vm_status',
5fdbe4f0 1217 path => '{vmid}/status/current',
1e3baf05
DM
1218 method => 'GET',
1219 proxyto => 'node',
1220 protected => 1, # qemu pid files are only readable by root
1221 description => "Get virtual machine status.",
a0d1b1a2
DM
1222 permissions => {
1223 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1224 },
1e3baf05
DM
1225 parameters => {
1226 additionalProperties => 0,
1227 properties => {
1228 node => get_standard_option('pve-node'),
1229 vmid => get_standard_option('pve-vmid'),
1230 },
1231 },
1232 returns => { type => 'object' },
1233 code => sub {
1234 my ($param) = @_;
1235
1236 # test if VM exists
1237 my $conf = PVE::QemuServer::load_config($param->{vmid});
1238
03a33f30 1239 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
8610701a 1240 my $status = $vmstatus->{$param->{vmid}};
1e3baf05 1241
88fc87b4 1242 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
8610701a
DM
1243
1244 return $status;
1e3baf05
DM
1245 }});
1246
1247__PACKAGE__->register_method({
afdb31d5 1248 name => 'vm_start',
5fdbe4f0
DM
1249 path => '{vmid}/status/start',
1250 method => 'POST',
1e3baf05
DM
1251 protected => 1,
1252 proxyto => 'node',
5fdbe4f0 1253 description => "Start virtual machine.",
a0d1b1a2
DM
1254 permissions => {
1255 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1256 },
1e3baf05
DM
1257 parameters => {
1258 additionalProperties => 0,
1259 properties => {
1260 node => get_standard_option('pve-node'),
1261 vmid => get_standard_option('pve-vmid'),
3ea94c60
DM
1262 skiplock => get_standard_option('skiplock'),
1263 stateuri => get_standard_option('pve-qm-stateuri'),
7e8dcf2c
AD
1264 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
1265
1e3baf05
DM
1266 },
1267 },
afdb31d5 1268 returns => {
5fdbe4f0
DM
1269 type => 'string',
1270 },
1e3baf05
DM
1271 code => sub {
1272 my ($param) = @_;
1273
1274 my $rpcenv = PVE::RPCEnvironment::get();
1275
a0d1b1a2 1276 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1277
1278 my $node = extract_param($param, 'node');
1279
1e3baf05
DM
1280 my $vmid = extract_param($param, 'vmid');
1281
3ea94c60 1282 my $stateuri = extract_param($param, 'stateuri');
afdb31d5 1283 raise_param_exc({ stateuri => "Only root may use this option." })
a0d1b1a2 1284 if $stateuri && $authuser ne 'root@pam';
3ea94c60 1285
1e3baf05 1286 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1287 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1288 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1289
7e8dcf2c
AD
1290 my $migratedfrom = extract_param($param, 'migratedfrom');
1291 raise_param_exc({ migratedfrom => "Only root may use this option." })
1292 if $migratedfrom && $authuser ne 'root@pam';
1293
afdb31d5 1294 my $storecfg = PVE::Storage::config();
5fdbe4f0 1295
cce37749
DM
1296 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1297 $rpcenv->{type} ne 'ha') {
5fdbe4f0 1298
88fc87b4
DM
1299 my $hacmd = sub {
1300 my $upid = shift;
5fdbe4f0 1301
88fc87b4 1302 my $service = "pvevm:$vmid";
5fdbe4f0 1303
88fc87b4
DM
1304 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1305
1306 print "Executing HA start for VM $vmid\n";
1307
1308 PVE::Tools::run_command($cmd);
1309
1310 return;
1311 };
1312
1313 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1314
1315 } else {
1316
1317 my $realcmd = sub {
1318 my $upid = shift;
1319
1320 syslog('info', "start VM $vmid: $upid\n");
1321
7e8dcf2c 1322 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock, $migratedfrom);
88fc87b4
DM
1323
1324 return;
1325 };
5fdbe4f0 1326
88fc87b4
DM
1327 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1328 }
5fdbe4f0
DM
1329 }});
1330
1331__PACKAGE__->register_method({
afdb31d5 1332 name => 'vm_stop',
5fdbe4f0
DM
1333 path => '{vmid}/status/stop',
1334 method => 'POST',
1335 protected => 1,
1336 proxyto => 'node',
1337 description => "Stop virtual machine.",
a0d1b1a2
DM
1338 permissions => {
1339 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1340 },
5fdbe4f0
DM
1341 parameters => {
1342 additionalProperties => 0,
1343 properties => {
1344 node => get_standard_option('pve-node'),
1345 vmid => get_standard_option('pve-vmid'),
1346 skiplock => get_standard_option('skiplock'),
af30308f 1347 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
c6bb9502
DM
1348 timeout => {
1349 description => "Wait maximal timeout seconds.",
1350 type => 'integer',
1351 minimum => 0,
1352 optional => 1,
254575e9
DM
1353 },
1354 keepActive => {
1355 description => "Do not decativate storage volumes.",
1356 type => 'boolean',
1357 optional => 1,
1358 default => 0,
c6bb9502 1359 }
5fdbe4f0
DM
1360 },
1361 },
afdb31d5 1362 returns => {
5fdbe4f0
DM
1363 type => 'string',
1364 },
1365 code => sub {
1366 my ($param) = @_;
1367
1368 my $rpcenv = PVE::RPCEnvironment::get();
1369
a0d1b1a2 1370 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1371
1372 my $node = extract_param($param, 'node');
1373
1374 my $vmid = extract_param($param, 'vmid');
1375
1376 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1377 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1378 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1379
254575e9 1380 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1381 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1382 if $keepActive && $authuser ne 'root@pam';
254575e9 1383
af30308f
DM
1384 my $migratedfrom = extract_param($param, 'migratedfrom');
1385 raise_param_exc({ migratedfrom => "Only root may use this option." })
1386 if $migratedfrom && $authuser ne 'root@pam';
1387
1388
ff1a2432
DM
1389 my $storecfg = PVE::Storage::config();
1390
3be30d63 1391 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
5fdbe4f0 1392
88fc87b4
DM
1393 my $hacmd = sub {
1394 my $upid = shift;
5fdbe4f0 1395
88fc87b4 1396 my $service = "pvevm:$vmid";
c6bb9502 1397
88fc87b4
DM
1398 my $cmd = ['clusvcadm', '-d', $service];
1399
1400 print "Executing HA stop for VM $vmid\n";
1401
1402 PVE::Tools::run_command($cmd);
5fdbe4f0 1403
88fc87b4
DM
1404 return;
1405 };
1406
1407 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1408
1409 } else {
1410 my $realcmd = sub {
1411 my $upid = shift;
1412
1413 syslog('info', "stop VM $vmid: $upid\n");
1414
1415 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
af30308f 1416 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
88fc87b4
DM
1417
1418 return;
1419 };
1420
1421 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1422 }
5fdbe4f0
DM
1423 }});
1424
1425__PACKAGE__->register_method({
afdb31d5 1426 name => 'vm_reset',
5fdbe4f0
DM
1427 path => '{vmid}/status/reset',
1428 method => 'POST',
1429 protected => 1,
1430 proxyto => 'node',
1431 description => "Reset virtual machine.",
a0d1b1a2
DM
1432 permissions => {
1433 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1434 },
5fdbe4f0
DM
1435 parameters => {
1436 additionalProperties => 0,
1437 properties => {
1438 node => get_standard_option('pve-node'),
1439 vmid => get_standard_option('pve-vmid'),
1440 skiplock => get_standard_option('skiplock'),
1441 },
1442 },
afdb31d5 1443 returns => {
5fdbe4f0
DM
1444 type => 'string',
1445 },
1446 code => sub {
1447 my ($param) = @_;
1448
1449 my $rpcenv = PVE::RPCEnvironment::get();
1450
a0d1b1a2 1451 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1452
1453 my $node = extract_param($param, 'node');
1454
1455 my $vmid = extract_param($param, 'vmid');
1456
1457 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1458 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1459 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1460
ff1a2432
DM
1461 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1462
5fdbe4f0
DM
1463 my $realcmd = sub {
1464 my $upid = shift;
1465
1e3baf05 1466 PVE::QemuServer::vm_reset($vmid, $skiplock);
5fdbe4f0
DM
1467
1468 return;
1469 };
1470
a0d1b1a2 1471 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1472 }});
1473
1474__PACKAGE__->register_method({
afdb31d5 1475 name => 'vm_shutdown',
5fdbe4f0
DM
1476 path => '{vmid}/status/shutdown',
1477 method => 'POST',
1478 protected => 1,
1479 proxyto => 'node',
1480 description => "Shutdown virtual machine.",
a0d1b1a2
DM
1481 permissions => {
1482 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1483 },
5fdbe4f0
DM
1484 parameters => {
1485 additionalProperties => 0,
1486 properties => {
1487 node => get_standard_option('pve-node'),
1488 vmid => get_standard_option('pve-vmid'),
1489 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1490 timeout => {
1491 description => "Wait maximal timeout seconds.",
1492 type => 'integer',
1493 minimum => 0,
1494 optional => 1,
9269013a
DM
1495 },
1496 forceStop => {
1497 description => "Make sure the VM stops.",
1498 type => 'boolean',
1499 optional => 1,
1500 default => 0,
254575e9
DM
1501 },
1502 keepActive => {
1503 description => "Do not decativate storage volumes.",
1504 type => 'boolean',
1505 optional => 1,
1506 default => 0,
c6bb9502 1507 }
5fdbe4f0
DM
1508 },
1509 },
afdb31d5 1510 returns => {
5fdbe4f0
DM
1511 type => 'string',
1512 },
1513 code => sub {
1514 my ($param) = @_;
1515
1516 my $rpcenv = PVE::RPCEnvironment::get();
1517
a0d1b1a2 1518 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1519
1520 my $node = extract_param($param, 'node');
1521
1522 my $vmid = extract_param($param, 'vmid');
1523
1524 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1525 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1526 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1527
254575e9 1528 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1529 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1530 if $keepActive && $authuser ne 'root@pam';
254575e9 1531
02d07cf5
DM
1532 my $storecfg = PVE::Storage::config();
1533
5fdbe4f0
DM
1534 my $realcmd = sub {
1535 my $upid = shift;
1536
1537 syslog('info', "shutdown VM $vmid: $upid\n");
1538
afdb31d5 1539 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
254575e9 1540 1, $param->{forceStop}, $keepActive);
c6bb9502 1541
5fdbe4f0
DM
1542 return;
1543 };
1544
a0d1b1a2 1545 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1546 }});
1547
1548__PACKAGE__->register_method({
afdb31d5 1549 name => 'vm_suspend',
5fdbe4f0
DM
1550 path => '{vmid}/status/suspend',
1551 method => 'POST',
1552 protected => 1,
1553 proxyto => 'node',
1554 description => "Suspend virtual machine.",
a0d1b1a2
DM
1555 permissions => {
1556 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1557 },
5fdbe4f0
DM
1558 parameters => {
1559 additionalProperties => 0,
1560 properties => {
1561 node => get_standard_option('pve-node'),
1562 vmid => get_standard_option('pve-vmid'),
1563 skiplock => get_standard_option('skiplock'),
1564 },
1565 },
afdb31d5 1566 returns => {
5fdbe4f0
DM
1567 type => 'string',
1568 },
1569 code => sub {
1570 my ($param) = @_;
1571
1572 my $rpcenv = PVE::RPCEnvironment::get();
1573
a0d1b1a2 1574 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1575
1576 my $node = extract_param($param, 'node');
1577
1578 my $vmid = extract_param($param, 'vmid');
1579
1580 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1581 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1582 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1583
ff1a2432
DM
1584 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1585
5fdbe4f0
DM
1586 my $realcmd = sub {
1587 my $upid = shift;
1588
1589 syslog('info', "suspend VM $vmid: $upid\n");
1590
1e3baf05 1591 PVE::QemuServer::vm_suspend($vmid, $skiplock);
5fdbe4f0
DM
1592
1593 return;
1594 };
1595
a0d1b1a2 1596 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1597 }});
1598
1599__PACKAGE__->register_method({
afdb31d5 1600 name => 'vm_resume',
5fdbe4f0
DM
1601 path => '{vmid}/status/resume',
1602 method => 'POST',
1603 protected => 1,
1604 proxyto => 'node',
1605 description => "Resume virtual machine.",
a0d1b1a2
DM
1606 permissions => {
1607 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1608 },
5fdbe4f0
DM
1609 parameters => {
1610 additionalProperties => 0,
1611 properties => {
1612 node => get_standard_option('pve-node'),
1613 vmid => get_standard_option('pve-vmid'),
1614 skiplock => get_standard_option('skiplock'),
1615 },
1616 },
afdb31d5 1617 returns => {
5fdbe4f0
DM
1618 type => 'string',
1619 },
1620 code => sub {
1621 my ($param) = @_;
1622
1623 my $rpcenv = PVE::RPCEnvironment::get();
1624
a0d1b1a2 1625 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1626
1627 my $node = extract_param($param, 'node');
1628
1629 my $vmid = extract_param($param, 'vmid');
1630
1631 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1632 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1633 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1634
b7eeab21 1635 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
ff1a2432 1636
5fdbe4f0
DM
1637 my $realcmd = sub {
1638 my $upid = shift;
1639
1640 syslog('info', "resume VM $vmid: $upid\n");
1641
1e3baf05 1642 PVE::QemuServer::vm_resume($vmid, $skiplock);
1e3baf05 1643
5fdbe4f0
DM
1644 return;
1645 };
1646
a0d1b1a2 1647 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1648 }});
1649
1650__PACKAGE__->register_method({
afdb31d5 1651 name => 'vm_sendkey',
5fdbe4f0
DM
1652 path => '{vmid}/sendkey',
1653 method => 'PUT',
1654 protected => 1,
1655 proxyto => 'node',
1656 description => "Send key event to virtual machine.",
a0d1b1a2
DM
1657 permissions => {
1658 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1659 },
5fdbe4f0
DM
1660 parameters => {
1661 additionalProperties => 0,
1662 properties => {
1663 node => get_standard_option('pve-node'),
1664 vmid => get_standard_option('pve-vmid'),
1665 skiplock => get_standard_option('skiplock'),
1666 key => {
1667 description => "The key (qemu monitor encoding).",
1668 type => 'string'
1669 }
1670 },
1671 },
1672 returns => { type => 'null'},
1673 code => sub {
1674 my ($param) = @_;
1675
1676 my $rpcenv = PVE::RPCEnvironment::get();
1677
a0d1b1a2 1678 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1679
1680 my $node = extract_param($param, 'node');
1681
1682 my $vmid = extract_param($param, 'vmid');
1683
1684 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1685 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1686 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0
DM
1687
1688 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1689
1690 return;
1e3baf05
DM
1691 }});
1692
1ac0d2ee
AD
1693__PACKAGE__->register_method({
1694 name => 'vm_feature',
1695 path => '{vmid}/feature',
1696 method => 'GET',
1697 proxyto => 'node',
1698 protected => 1,
1699 description => "Check if feature for virtual machine is available.",
1700 permissions => {
1701 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1702 },
1703 parameters => {
1704 additionalProperties => 0,
1705 properties => {
1706 node => get_standard_option('pve-node'),
1707 vmid => get_standard_option('pve-vmid'),
1708 feature => {
1709 description => "Feature to check.",
1710 type => 'string',
1711 enum => [ 'snapshot', 'clone' ],
1712 },
1713 snapname => get_standard_option('pve-snapshot-name', {
1714 optional => 1,
1715 }),
1716 },
1717
1718 },
1719 returns => {
1720 type => 'boolean'
1721 },
1722 code => sub {
1723 my ($param) = @_;
1724
1725 my $node = extract_param($param, 'node');
1726
1727 my $vmid = extract_param($param, 'vmid');
1728
1729 my $snapname = extract_param($param, 'snapname');
1730
1731 my $feature = extract_param($param, 'feature');
1732
1733 my $running = PVE::QemuServer::check_running($vmid);
1734
1735 my $conf = PVE::QemuServer::load_config($vmid);
1736
1737 if($snapname){
1738 my $snap = $conf->{snapshots}->{$snapname};
1739 die "snapshot '$snapname' does not exist\n" if !defined($snap);
1740 $conf = $snap;
1741 }
1742 my $storecfg = PVE::Storage::config();
1743
1744 my $hasfeature = PVE::QemuServer::has_feature($feature, $conf, $storecfg, $snapname, $running);
1745 my $res = $hasfeature ? 1 : 0 ;
1746 return $res;
1747 }});
1748
3ea94c60 1749__PACKAGE__->register_method({
afdb31d5 1750 name => 'migrate_vm',
3ea94c60
DM
1751 path => '{vmid}/migrate',
1752 method => 'POST',
1753 protected => 1,
1754 proxyto => 'node',
1755 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
1756 permissions => {
1757 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
1758 },
3ea94c60
DM
1759 parameters => {
1760 additionalProperties => 0,
1761 properties => {
1762 node => get_standard_option('pve-node'),
1763 vmid => get_standard_option('pve-vmid'),
1764 target => get_standard_option('pve-node', { description => "Target node." }),
1765 online => {
1766 type => 'boolean',
1767 description => "Use online/live migration.",
1768 optional => 1,
1769 },
1770 force => {
1771 type => 'boolean',
1772 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
1773 optional => 1,
1774 },
1775 },
1776 },
afdb31d5 1777 returns => {
3ea94c60
DM
1778 type => 'string',
1779 description => "the task ID.",
1780 },
1781 code => sub {
1782 my ($param) = @_;
1783
1784 my $rpcenv = PVE::RPCEnvironment::get();
1785
a0d1b1a2 1786 my $authuser = $rpcenv->get_user();
3ea94c60
DM
1787
1788 my $target = extract_param($param, 'target');
1789
1790 my $localnode = PVE::INotify::nodename();
1791 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
1792
1793 PVE::Cluster::check_cfs_quorum();
1794
1795 PVE::Cluster::check_node_exists($target);
1796
1797 my $targetip = PVE::Cluster::remote_node_ip($target);
1798
1799 my $vmid = extract_param($param, 'vmid');
1800
afdb31d5 1801 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 1802 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
1803
1804 # test if VM exists
a5ed42d3 1805 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
1806
1807 # try to detect errors early
a5ed42d3
DM
1808
1809 PVE::QemuServer::check_lock($conf);
1810
3ea94c60 1811 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 1812 die "cant migrate running VM without --online\n"
3ea94c60
DM
1813 if !$param->{online};
1814 }
1815
47152e2e 1816 my $storecfg = PVE::Storage::config();
22d646a7 1817 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
47152e2e 1818
3be30d63 1819 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3ea94c60 1820
88fc87b4
DM
1821 my $hacmd = sub {
1822 my $upid = shift;
3ea94c60 1823
88fc87b4
DM
1824 my $service = "pvevm:$vmid";
1825
1826 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
1827
1828 print "Executing HA migrate for VM $vmid to node $target\n";
1829
1830 PVE::Tools::run_command($cmd);
1831
1832 return;
1833 };
1834
1835 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
1836
1837 } else {
1838
1839 my $realcmd = sub {
1840 my $upid = shift;
1841
1842 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
1843 };
1844
1845 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
1846 }
3ea94c60 1847
3ea94c60 1848 }});
1e3baf05 1849
91c94f0a 1850__PACKAGE__->register_method({
afdb31d5
DM
1851 name => 'monitor',
1852 path => '{vmid}/monitor',
91c94f0a
DM
1853 method => 'POST',
1854 protected => 1,
1855 proxyto => 'node',
1856 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
1857 permissions => {
1858 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
1859 },
91c94f0a
DM
1860 parameters => {
1861 additionalProperties => 0,
1862 properties => {
1863 node => get_standard_option('pve-node'),
1864 vmid => get_standard_option('pve-vmid'),
1865 command => {
1866 type => 'string',
1867 description => "The monitor command.",
1868 }
1869 },
1870 },
1871 returns => { type => 'string'},
1872 code => sub {
1873 my ($param) = @_;
1874
1875 my $vmid = $param->{vmid};
1876
1877 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
1878
1879 my $res = '';
1880 eval {
7b7c6d1b 1881 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
91c94f0a
DM
1882 };
1883 $res = "ERROR: $@" if $@;
1884
1885 return $res;
1886 }});
1887
0d02881c
AD
1888__PACKAGE__->register_method({
1889 name => 'resize_vm',
614e3941 1890 path => '{vmid}/resize',
0d02881c
AD
1891 method => 'PUT',
1892 protected => 1,
1893 proxyto => 'node',
2f48a4f5 1894 description => "Extend volume size.",
0d02881c 1895 permissions => {
3b2773f6 1896 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
0d02881c
AD
1897 },
1898 parameters => {
1899 additionalProperties => 0,
2f48a4f5
DM
1900 properties => {
1901 node => get_standard_option('pve-node'),
1902 vmid => get_standard_option('pve-vmid'),
1903 skiplock => get_standard_option('skiplock'),
1904 disk => {
1905 type => 'string',
1906 description => "The disk you want to resize.",
1907 enum => [PVE::QemuServer::disknames()],
1908 },
1909 size => {
1910 type => 'string',
f91b2e45 1911 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2f48a4f5
DM
1912 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.",
1913 },
1914 digest => {
1915 type => 'string',
1916 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1917 maxLength => 40,
1918 optional => 1,
1919 },
1920 },
0d02881c
AD
1921 },
1922 returns => { type => 'null'},
1923 code => sub {
1924 my ($param) = @_;
1925
1926 my $rpcenv = PVE::RPCEnvironment::get();
1927
1928 my $authuser = $rpcenv->get_user();
1929
1930 my $node = extract_param($param, 'node');
1931
1932 my $vmid = extract_param($param, 'vmid');
1933
1934 my $digest = extract_param($param, 'digest');
1935
2f48a4f5
DM
1936 my $disk = extract_param($param, 'disk');
1937
1938 my $sizestr = extract_param($param, 'size');
0d02881c 1939
f91b2e45 1940 my $skiplock = extract_param($param, 'skiplock');
0d02881c
AD
1941 raise_param_exc({ skiplock => "Only root may use this option." })
1942 if $skiplock && $authuser ne 'root@pam';
1943
0d02881c
AD
1944 my $storecfg = PVE::Storage::config();
1945
0d02881c
AD
1946 my $updatefn = sub {
1947
1948 my $conf = PVE::QemuServer::load_config($vmid);
1949
1950 die "checksum missmatch (file change by other user?)\n"
1951 if $digest && $digest ne $conf->{digest};
1952 PVE::QemuServer::check_lock($conf) if !$skiplock;
1953
f91b2e45
DM
1954 die "disk '$disk' does not exist\n" if !$conf->{$disk};
1955
1956 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
1957
1958 my $volid = $drive->{file};
1959
1960 die "disk '$disk' has no associated volume\n" if !$volid;
1961
1962 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
1963
f2965e67
AD
1964 die "you can't online resize a virtio windows bootdisk\n"
1965 if PVE::QemuServer::check_running($vmid) && $conf->{bootdisk} eq $disk && $conf->{ostype} =~ m/^w/ && $disk =~ m/^virtio/;
1966
f91b2e45
DM
1967 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
1968
1969 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
1970
1971 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
1972
1973 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
1974 my ($ext, $newsize, $unit) = ($1, $2, $4);
1975 if ($unit) {
1976 if ($unit eq 'K') {
1977 $newsize = $newsize * 1024;
1978 } elsif ($unit eq 'M') {
1979 $newsize = $newsize * 1024 * 1024;
1980 } elsif ($unit eq 'G') {
1981 $newsize = $newsize * 1024 * 1024 * 1024;
1982 } elsif ($unit eq 'T') {
1983 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
1984 }
1985 }
1986 $newsize += $size if $ext;
1987 $newsize = int($newsize);
1988
1989 die "unable to skrink disk size\n" if $newsize < $size;
1990
1991 return if $size == $newsize;
1992
2f48a4f5 1993 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
0d02881c 1994
f91b2e45
DM
1995 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
1996
1997 $drive->{size} = $newsize;
1998 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
1999
2000 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2001 };
0d02881c
AD
2002
2003 PVE::QemuServer::lock_config($vmid, $updatefn);
2004 return undef;
2005 }});
2006
9dbd1ee4 2007__PACKAGE__->register_method({
7e7d7b61 2008 name => 'snapshot_list',
9dbd1ee4 2009 path => '{vmid}/snapshot',
7e7d7b61
DM
2010 method => 'GET',
2011 description => "List all snapshots.",
2012 permissions => {
2013 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2014 },
2015 proxyto => 'node',
2016 protected => 1, # qemu pid files are only readable by root
2017 parameters => {
2018 additionalProperties => 0,
2019 properties => {
2020 vmid => get_standard_option('pve-vmid'),
2021 node => get_standard_option('pve-node'),
2022 },
2023 },
2024 returns => {
2025 type => 'array',
2026 items => {
2027 type => "object",
2028 properties => {},
2029 },
2030 links => [ { rel => 'child', href => "{name}" } ],
2031 },
2032 code => sub {
2033 my ($param) = @_;
2034
6aa4651b
DM
2035 my $vmid = $param->{vmid};
2036
2037 my $conf = PVE::QemuServer::load_config($vmid);
7e7d7b61
DM
2038 my $snaphash = $conf->{snapshots} || {};
2039
2040 my $res = [];
2041
2042 foreach my $name (keys %$snaphash) {
0ea6bc69 2043 my $d = $snaphash->{$name};
982c7f12
DM
2044 my $item = {
2045 name => $name,
2046 snaptime => $d->{snaptime} || 0,
6aa4651b 2047 vmstate => $d->{vmstate} ? 1 : 0,
982c7f12
DM
2048 description => $d->{description} || '',
2049 };
0ea6bc69 2050 $item->{parent} = $d->{parent} if $d->{parent};
3ee28e38 2051 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
0ea6bc69
DM
2052 push @$res, $item;
2053 }
2054
6aa4651b
DM
2055 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
2056 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
d1914468
DM
2057 $current->{parent} = $conf->{parent} if $conf->{parent};
2058
2059 push @$res, $current;
7e7d7b61
DM
2060
2061 return $res;
2062 }});
2063
2064__PACKAGE__->register_method({
2065 name => 'snapshot',
2066 path => '{vmid}/snapshot',
2067 method => 'POST',
9dbd1ee4
AD
2068 protected => 1,
2069 proxyto => 'node',
2070 description => "Snapshot a VM.",
2071 permissions => {
f1baf1df 2072 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
9dbd1ee4
AD
2073 },
2074 parameters => {
2075 additionalProperties => 0,
2076 properties => {
2077 node => get_standard_option('pve-node'),
2078 vmid => get_standard_option('pve-vmid'),
8abd398b 2079 snapname => get_standard_option('pve-snapshot-name'),
9dbd1ee4
AD
2080 vmstate => {
2081 optional => 1,
2082 type => 'boolean',
2083 description => "Save the vmstate",
2084 },
2085 freezefs => {
2086 optional => 1,
2087 type => 'boolean',
2088 description => "Freeze the filesystem",
2089 },
782f4f75
DM
2090 description => {
2091 optional => 1,
2092 type => 'string',
2093 description => "A textual description or comment.",
2094 },
9dbd1ee4
AD
2095 },
2096 },
7e7d7b61
DM
2097 returns => {
2098 type => 'string',
2099 description => "the task ID.",
2100 },
9dbd1ee4
AD
2101 code => sub {
2102 my ($param) = @_;
2103
2104 my $rpcenv = PVE::RPCEnvironment::get();
2105
2106 my $authuser = $rpcenv->get_user();
2107
2108 my $node = extract_param($param, 'node');
2109
2110 my $vmid = extract_param($param, 'vmid');
2111
9dbd1ee4
AD
2112 my $snapname = extract_param($param, 'snapname');
2113
d1914468
DM
2114 die "unable to use snapshot name 'current' (reserved name)\n"
2115 if $snapname eq 'current';
2116
7e7d7b61 2117 my $realcmd = sub {
22c377f0 2118 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
782f4f75
DM
2119 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
2120 $param->{freezefs}, $param->{description});
7e7d7b61
DM
2121 };
2122
2123 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2124 }});
2125
154ccdcd
DM
2126__PACKAGE__->register_method({
2127 name => 'snapshot_cmd_idx',
2128 path => '{vmid}/snapshot/{snapname}',
2129 description => '',
2130 method => 'GET',
2131 permissions => {
2132 user => 'all',
2133 },
2134 parameters => {
2135 additionalProperties => 0,
2136 properties => {
2137 vmid => get_standard_option('pve-vmid'),
2138 node => get_standard_option('pve-node'),
8abd398b 2139 snapname => get_standard_option('pve-snapshot-name'),
154ccdcd
DM
2140 },
2141 },
2142 returns => {
2143 type => 'array',
2144 items => {
2145 type => "object",
2146 properties => {},
2147 },
2148 links => [ { rel => 'child', href => "{cmd}" } ],
2149 },
2150 code => sub {
2151 my ($param) = @_;
2152
2153 my $res = [];
2154
2155 push @$res, { cmd => 'rollback' };
d788cea6 2156 push @$res, { cmd => 'config' };
154ccdcd
DM
2157
2158 return $res;
2159 }});
2160
d788cea6
DM
2161__PACKAGE__->register_method({
2162 name => 'update_snapshot_config',
2163 path => '{vmid}/snapshot/{snapname}/config',
2164 method => 'PUT',
2165 protected => 1,
2166 proxyto => 'node',
2167 description => "Update snapshot metadata.",
2168 permissions => {
2169 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2170 },
2171 parameters => {
2172 additionalProperties => 0,
2173 properties => {
2174 node => get_standard_option('pve-node'),
2175 vmid => get_standard_option('pve-vmid'),
2176 snapname => get_standard_option('pve-snapshot-name'),
2177 description => {
2178 optional => 1,
2179 type => 'string',
2180 description => "A textual description or comment.",
2181 },
2182 },
2183 },
2184 returns => { type => 'null' },
2185 code => sub {
2186 my ($param) = @_;
2187
2188 my $rpcenv = PVE::RPCEnvironment::get();
2189
2190 my $authuser = $rpcenv->get_user();
2191
2192 my $vmid = extract_param($param, 'vmid');
2193
2194 my $snapname = extract_param($param, 'snapname');
2195
2196 return undef if !defined($param->{description});
2197
2198 my $updatefn = sub {
2199
2200 my $conf = PVE::QemuServer::load_config($vmid);
2201
2202 PVE::QemuServer::check_lock($conf);
2203
2204 my $snap = $conf->{snapshots}->{$snapname};
2205
2206 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2207
2208 $snap->{description} = $param->{description} if defined($param->{description});
2209
2210 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2211 };
2212
2213 PVE::QemuServer::lock_config($vmid, $updatefn);
2214
2215 return undef;
2216 }});
2217
2218__PACKAGE__->register_method({
2219 name => 'get_snapshot_config',
2220 path => '{vmid}/snapshot/{snapname}/config',
2221 method => 'GET',
2222 proxyto => 'node',
2223 description => "Get snapshot configuration",
2224 permissions => {
2225 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2226 },
2227 parameters => {
2228 additionalProperties => 0,
2229 properties => {
2230 node => get_standard_option('pve-node'),
2231 vmid => get_standard_option('pve-vmid'),
2232 snapname => get_standard_option('pve-snapshot-name'),
2233 },
2234 },
2235 returns => { type => "object" },
2236 code => sub {
2237 my ($param) = @_;
2238
2239 my $rpcenv = PVE::RPCEnvironment::get();
2240
2241 my $authuser = $rpcenv->get_user();
2242
2243 my $vmid = extract_param($param, 'vmid');
2244
2245 my $snapname = extract_param($param, 'snapname');
2246
2247 my $conf = PVE::QemuServer::load_config($vmid);
2248
2249 my $snap = $conf->{snapshots}->{$snapname};
2250
2251 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2252
2253 return $snap;
2254 }});
2255
7e7d7b61
DM
2256__PACKAGE__->register_method({
2257 name => 'rollback',
154ccdcd 2258 path => '{vmid}/snapshot/{snapname}/rollback',
7e7d7b61
DM
2259 method => 'POST',
2260 protected => 1,
2261 proxyto => 'node',
2262 description => "Rollback VM state to specified snapshot.",
2263 permissions => {
f1baf1df 2264 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2265 },
2266 parameters => {
2267 additionalProperties => 0,
2268 properties => {
2269 node => get_standard_option('pve-node'),
2270 vmid => get_standard_option('pve-vmid'),
8abd398b 2271 snapname => get_standard_option('pve-snapshot-name'),
7e7d7b61
DM
2272 },
2273 },
2274 returns => {
2275 type => 'string',
2276 description => "the task ID.",
2277 },
2278 code => sub {
2279 my ($param) = @_;
2280
2281 my $rpcenv = PVE::RPCEnvironment::get();
2282
2283 my $authuser = $rpcenv->get_user();
2284
2285 my $node = extract_param($param, 'node');
2286
2287 my $vmid = extract_param($param, 'vmid');
2288
2289 my $snapname = extract_param($param, 'snapname');
2290
7e7d7b61 2291 my $realcmd = sub {
22c377f0
DM
2292 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
2293 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
7e7d7b61
DM
2294 };
2295
2296 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
2297 }});
2298
2299__PACKAGE__->register_method({
2300 name => 'delsnapshot',
2301 path => '{vmid}/snapshot/{snapname}',
2302 method => 'DELETE',
2303 protected => 1,
2304 proxyto => 'node',
2305 description => "Delete a VM snapshot.",
2306 permissions => {
f1baf1df 2307 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2308 },
2309 parameters => {
2310 additionalProperties => 0,
2311 properties => {
2312 node => get_standard_option('pve-node'),
2313 vmid => get_standard_option('pve-vmid'),
8abd398b 2314 snapname => get_standard_option('pve-snapshot-name'),
3ee28e38
DM
2315 force => {
2316 optional => 1,
2317 type => 'boolean',
2318 description => "For removal from config file, even if removing disk snapshots fails.",
2319 },
7e7d7b61
DM
2320 },
2321 },
2322 returns => {
2323 type => 'string',
2324 description => "the task ID.",
2325 },
2326 code => sub {
2327 my ($param) = @_;
2328
2329 my $rpcenv = PVE::RPCEnvironment::get();
2330
2331 my $authuser = $rpcenv->get_user();
2332
2333 my $node = extract_param($param, 'node');
2334
2335 my $vmid = extract_param($param, 'vmid');
2336
2337 my $snapname = extract_param($param, 'snapname');
2338
7e7d7b61 2339 my $realcmd = sub {
22c377f0 2340 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
3ee28e38 2341 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
7e7d7b61 2342 };
9dbd1ee4 2343
7b2257a8 2344 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
9dbd1ee4
AD
2345 }});
2346
04a69bb4
AD
2347__PACKAGE__->register_method({
2348 name => 'template',
2349 path => '{vmid}/template',
2350 method => 'POST',
2351 protected => 1,
2352 proxyto => 'node',
2353 description => "Create a Template.",
b02691d8 2354 permissions => {
bef4463b 2355 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}.",
b02691d8
SP
2356 check => [ 'or',
2357 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
2358 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
2359 ],
2360 },
04a69bb4
AD
2361 parameters => {
2362 additionalProperties => 0,
2363 properties => {
2364 node => get_standard_option('pve-node'),
2365 vmid => get_standard_option('pve-vmid'),
2366 disk => {
2367 optional => 1,
2368 type => 'string',
2369 description => "If you want to convert only 1 disk to base image.",
2370 enum => [PVE::QemuServer::disknames()],
2371 },
2372
2373 },
2374 },
2375 returns => { type => 'null'},
2376 code => sub {
2377 my ($param) = @_;
2378
2379 my $rpcenv = PVE::RPCEnvironment::get();
2380
2381 my $authuser = $rpcenv->get_user();
2382
2383 my $node = extract_param($param, 'node');
2384
2385 my $vmid = extract_param($param, 'vmid');
2386
2387 my $disk = extract_param($param, 'disk');
2388
2389 my $updatefn = sub {
2390
2391 my $conf = PVE::QemuServer::load_config($vmid);
2392
2393 PVE::QemuServer::check_lock($conf);
2394
0402a80b 2395 die "unable to create template, because VM contains snapshots\n"
b91c2aae 2396 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
0402a80b
DM
2397
2398 die "you can't convert a template to a template\n"
03c2d0ad 2399 if PVE::QemuServer::is_template($conf) && !$disk;
0402a80b 2400
35c5fdef
DM
2401 die "you can't convert a VM to template if VM is running\n"
2402 if check_running($vmid);
2403
04a69bb4
AD
2404 my $realcmd = sub {
2405 PVE::QemuServer::template_create($vmid, $conf, $disk);
2406 };
04a69bb4 2407
75e7e997 2408 $conf->{template} = 1;
04a69bb4 2409 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
75e7e997
DM
2410
2411 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
04a69bb4
AD
2412 };
2413
2414 PVE::QemuServer::lock_config($vmid, $updatefn);
2415 return undef;
2416 }});
2417
2418
2419
1e3baf05 24201;