]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
use check() instead of check_storage_perm()
[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;
19
20use Data::Dumper; # fixme: remove
21
22use base qw(PVE::RESTHandler);
23
24my $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.";
25
26my $resolve_cdrom_alias = sub {
27 my $param = shift;
28
29 if (my $value = $param->{cdrom}) {
30 $value .= ",media=cdrom" if $value !~ m/media=/;
31 $param->{ide2} = $value;
32 delete $param->{cdrom};
33 }
34};
35
a0d1b1a2 36my $check_volume_access = sub {
fcbb753e 37 my ($rpcenv, $authuser, $storecfg, $vmid, $volid) = @_;
a0d1b1a2
DM
38
39 my $path;
40 if (my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1)) {
41 my ($ownervm, $vtype);
42 ($path, $ownervm, $vtype) = PVE::Storage::path($storecfg, $volid);
43 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
44 # we simply allow access
45 } elsif (!$ownervm || ($ownervm != $vmid)) {
46 # allow if we are Datastore administrator
fcbb753e 47 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.Allocate']);
a0d1b1a2
DM
48 }
49 } else {
50 die "Only root can pass arbitrary filesystem paths."
51 if $authuser ne 'root@pam';
52
53 $path = abs_path($volid);
54 }
55 return $path;
56};
57
ae57f6b3 58my $check_storage_access = sub {
fcbb753e 59 my ($rpcenv, $authuser, $storecfg, $vmid, $settings, $default_storage) = @_;
a0d1b1a2 60
ae57f6b3
DM
61 PVE::QemuServer::foreach_drive($settings, sub {
62 my ($ds, $drive) = @_;
a0d1b1a2 63
ae57f6b3 64 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
a0d1b1a2 65
ae57f6b3 66 my $volid = $drive->{file};
a0d1b1a2 67
09d0ee64
DM
68 if (!$volid || $volid eq 'none') {
69 # nothing to check
70 } elsif (!$isCDROM && ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/)) {
a0d1b1a2
DM
71 my ($storeid, $size) = ($2 || $default_storage, $3);
72 die "no storage ID specified (and no default storage)\n" if !$storeid;
fcbb753e 73 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
a0d1b1a2 74 } else {
fcbb753e 75 my $path = &$check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $volid);
a0d1b1a2
DM
76 die "image '$path' does not exists\n" if (!(-f $path || -b $path));
77 }
78 });
ae57f6b3 79};
a0d1b1a2 80
ae57f6b3
DM
81# Note: $pool is only needed when creating a VM, because pool permissions
82# are automatically inherited if VM already exists inside a pool.
83my $create_disks = sub {
84 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
a0d1b1a2
DM
85
86 my $vollist = [];
a0d1b1a2 87
ae57f6b3
DM
88 my $res = {};
89 PVE::QemuServer::foreach_drive($settings, sub {
90 my ($ds, $disk) = @_;
91
92 my $volid = $disk->{file};
93
09d0ee64
DM
94 if (!$volid || $volid eq 'none') {
95 $res->{$ds} = $settings->{$ds};
96 } elsif ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/) {
ae57f6b3
DM
97 my ($storeid, $size) = ($2 || $default_storage, $3);
98 die "no storage ID specified (and no default storage)\n" if !$storeid;
99 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
100 my $fmt = $disk->{format} || $defformat;
a0d1b1a2
DM
101 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid,
102 $fmt, undef, $size*1024*1024);
a0d1b1a2
DM
103 $disk->{file} = $volid;
104 push @$vollist, $volid;
ae57f6b3
DM
105 delete $disk->{format}; # no longer needed
106 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
107 } else {
fcbb753e 108 my $path = &$check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $volid);
ae57f6b3 109 die "image '$path' does not exists\n" if (!(-f $path || -b $path));
09d0ee64 110 $res->{$ds} = $settings->{$ds};
a0d1b1a2 111 }
ae57f6b3 112 });
a0d1b1a2
DM
113
114 # free allocated images on error
115 if (my $err = $@) {
116 syslog('err', "VM $vmid creating disks failed");
117 foreach my $volid (@$vollist) {
118 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
119 warn $@ if $@;
120 }
121 die $err;
122 }
123
124 # modify vm config if everything went well
ae57f6b3
DM
125 foreach my $ds (keys %$res) {
126 $conf->{$ds} = $res->{$ds};
a0d1b1a2
DM
127 }
128
129 return $vollist;
130};
131
132my $check_vm_modify_config_perm = sub {
ae57f6b3 133 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
a0d1b1a2
DM
134
135 return 1 if $authuser ne 'root@pam';
136
ae57f6b3 137 foreach my $opt (@$key_list) {
a0d1b1a2
DM
138 # disk checks need to be done somewhere else
139 next if PVE::QemuServer::valid_drivename($opt);
140
141 if ($opt eq 'sockets' || $opt eq 'cores' ||
142 $opt eq 'cpu' || $opt eq 'smp' ||
143 $opt eq 'cpuimit' || $opt eq 'cpuunits') {
144 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
145 } elsif ($opt eq 'boot' || $opt eq 'bootdisk') {
146 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
147 } elsif ($opt eq 'memory' || $opt eq 'balloon') {
148 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
149 } elsif ($opt eq 'args' || $opt eq 'lock') {
150 die "only root can set '$opt' config\n";
151 } elsif ($opt eq 'cpu' || $opt eq 'kvm' || $opt eq 'acpi' ||
152 $opt eq 'vga' || $opt eq 'watchdog' || $opt eq 'tablet') {
153 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
154 } elsif ($opt =~ m/^net\d+$/) {
155 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
156 } else {
157 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
158 }
159 }
160
161 return 1;
162};
163
1e3baf05 164__PACKAGE__->register_method({
afdb31d5
DM
165 name => 'vmlist',
166 path => '',
1e3baf05
DM
167 method => 'GET',
168 description => "Virtual machine index (per node).",
a0d1b1a2
DM
169 permissions => {
170 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
171 user => 'all',
172 },
1e3baf05
DM
173 proxyto => 'node',
174 protected => 1, # qemu pid files are only readable by root
175 parameters => {
176 additionalProperties => 0,
177 properties => {
178 node => get_standard_option('pve-node'),
179 },
180 },
181 returns => {
182 type => 'array',
183 items => {
184 type => "object",
185 properties => {},
186 },
187 links => [ { rel => 'child', href => "{vmid}" } ],
188 },
189 code => sub {
190 my ($param) = @_;
191
a0d1b1a2
DM
192 my $rpcenv = PVE::RPCEnvironment::get();
193 my $authuser = $rpcenv->get_user();
194
1e3baf05
DM
195 my $vmstatus = PVE::QemuServer::vmstatus();
196
a0d1b1a2
DM
197 my $res = [];
198 foreach my $vmid (keys %$vmstatus) {
199 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
200
201 my $data = $vmstatus->{$vmid};
202 $data->{vmid} = $vmid;
203 push @$res, $data;
204 }
1e3baf05 205
a0d1b1a2 206 return $res;
1e3baf05
DM
207 }});
208
209__PACKAGE__->register_method({
afdb31d5
DM
210 name => 'create_vm',
211 path => '',
1e3baf05 212 method => 'POST',
3e16d5fc 213 description => "Create or restore a virtual machine.",
a0d1b1a2
DM
214 permissions => {
215 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.",
216 check => [ 'or',
217 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
218 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
219 ],
220 },
1e3baf05
DM
221 protected => 1,
222 proxyto => 'node',
223 parameters => {
224 additionalProperties => 0,
225 properties => PVE::QemuServer::json_config_properties(
226 {
227 node => get_standard_option('pve-node'),
228 vmid => get_standard_option('pve-vmid'),
3e16d5fc
DM
229 archive => {
230 description => "The backup file.",
231 type => 'string',
232 optional => 1,
233 maxLength => 255,
234 },
235 storage => get_standard_option('pve-storage-id', {
236 description => "Default storage.",
237 optional => 1,
238 }),
239 force => {
afdb31d5 240 optional => 1,
3e16d5fc
DM
241 type => 'boolean',
242 description => "Allow to overwrite existing VM.",
51586c3a
DM
243 requires => 'archive',
244 },
245 unique => {
afdb31d5 246 optional => 1,
51586c3a
DM
247 type => 'boolean',
248 description => "Assign a unique random ethernet address.",
249 requires => 'archive',
3e16d5fc 250 },
a0d1b1a2
DM
251 pool => {
252 optional => 1,
253 type => 'string', format => 'pve-poolid',
254 description => "Add the VM to the specified pool.",
255 },
1e3baf05
DM
256 }),
257 },
afdb31d5 258 returns => {
5fdbe4f0
DM
259 type => 'string',
260 },
1e3baf05
DM
261 code => sub {
262 my ($param) = @_;
263
5fdbe4f0
DM
264 my $rpcenv = PVE::RPCEnvironment::get();
265
a0d1b1a2 266 my $authuser = $rpcenv->get_user();
5fdbe4f0 267
1e3baf05
DM
268 my $node = extract_param($param, 'node');
269
1e3baf05
DM
270 my $vmid = extract_param($param, 'vmid');
271
3e16d5fc
DM
272 my $archive = extract_param($param, 'archive');
273
274 my $storage = extract_param($param, 'storage');
275
51586c3a
DM
276 my $force = extract_param($param, 'force');
277
278 my $unique = extract_param($param, 'unique');
a0d1b1a2
DM
279
280 my $pool = extract_param($param, 'pool');
51586c3a 281
1e3baf05 282 my $filename = PVE::QemuServer::config_file($vmid);
afdb31d5
DM
283
284 my $storecfg = PVE::Storage::config();
1e3baf05 285
3e16d5fc 286 PVE::Cluster::check_cfs_quorum();
1e3baf05 287
a0d1b1a2
DM
288 if (defined($pool)) {
289 $rpcenv->check_pool_exist($pool);
290 $rpcenv->check_perm_modify($authuser, "/pool/$pool");
291 }
292
fcbb753e 293 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace'])
a0d1b1a2
DM
294 if defined($storage);
295
afdb31d5 296 if (!$archive) {
3e16d5fc 297 &$resolve_cdrom_alias($param);
1e3baf05 298
fcbb753e 299 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param, $storage);
ae57f6b3
DM
300
301 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
302
3e16d5fc
DM
303 foreach my $opt (keys %$param) {
304 if (PVE::QemuServer::valid_drivename($opt)) {
305 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
306 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
afdb31d5 307
3e16d5fc
DM
308 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
309 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
310 }
1e3baf05 311 }
3e16d5fc
DM
312
313 PVE::QemuServer::add_random_macs($param);
51586c3a
DM
314 } else {
315 my $keystr = join(' ', keys %$param);
bc4dcb99
DM
316 raise_param_exc({ archive => "option conflicts with other options ($keystr)"}) if $keystr;
317
5b9d692a 318 if ($archive eq '-') {
afdb31d5 319 die "pipe requires cli environment\n"
5b9d692a
DM
320 && $rpcenv->{type} ne 'cli';
321 } else {
fcbb753e 322 my $path = &$check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $archive);
971f27c4
DM
323 die "can't find archive file '$archive'\n" if !($path && -f $path);
324 $archive = $path;
325 }
1e3baf05
DM
326 }
327
502d18a2
DM
328 my $addVMtoPoolFn = sub {
329 my $usercfg = cfs_read_file("user.cfg");
330 if (my $data = $usercfg->{pools}->{$pool}) {
331 $data->{vms}->{$vmid} = 1;
332 $usercfg->{vms}->{$vmid} = $pool;
333 cfs_write_file("user.cfg", $usercfg);
334 }
335 };
336
3e16d5fc
DM
337 my $restorefn = sub {
338
339 if (-f $filename) {
afdb31d5 340 die "unable to restore vm $vmid: config file already exists\n"
51586c3a 341 if !$force;
3e16d5fc 342
afdb31d5 343 die "unable to restore vm $vmid: vm is running\n"
3e16d5fc 344 if PVE::QemuServer::check_running($vmid);
a6af7b3e
DM
345
346 # destroy existing data - keep empty config
347 PVE::QemuServer::destroy_vm($storecfg, $vmid, 1);
3e16d5fc
DM
348 }
349
350 my $realcmd = sub {
a0d1b1a2 351 PVE::QemuServer::restore_archive($archive, $vmid, $authuser, {
51586c3a 352 storage => $storage,
a0d1b1a2 353 pool => $pool,
51586c3a 354 unique => $unique });
502d18a2
DM
355
356 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
3e16d5fc
DM
357 };
358
a0d1b1a2 359 return $rpcenv->fork_worker('qmrestore', $vmid, $authuser, $realcmd);
3e16d5fc 360 };
1e3baf05 361
1e3baf05
DM
362 my $createfn = sub {
363
364 # second test (after locking test is accurate)
afdb31d5 365 die "unable to create vm $vmid: config file already exists\n"
1e3baf05
DM
366 if -f $filename;
367
5fdbe4f0 368 my $realcmd = sub {
1e3baf05 369
5fdbe4f0 370 my $vollist = [];
1e3baf05 371
1858638f
DM
372 my $conf = $param;
373
5fdbe4f0 374 eval {
ae57f6b3 375
1858638f 376 $vollist = &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $param, $storage);
1e3baf05 377
5fdbe4f0
DM
378 # try to be smart about bootdisk
379 my @disks = PVE::QemuServer::disknames();
380 my $firstdisk;
381 foreach my $ds (reverse @disks) {
1858638f
DM
382 next if !$conf->{$ds};
383 my $disk = PVE::QemuServer::parse_drive($ds, $conf->{$ds});
5fdbe4f0
DM
384 next if PVE::QemuServer::drive_is_cdrom($disk);
385 $firstdisk = $ds;
386 }
1e3baf05 387
1858638f
DM
388 if (!$conf->{bootdisk} && $firstdisk) {
389 $conf->{bootdisk} = $firstdisk;
5fdbe4f0 390 }
1e3baf05 391
ae9ca91d
DM
392 PVE::QemuServer::update_config_nolock($vmid, $conf);
393
5fdbe4f0
DM
394 };
395 my $err = $@;
1e3baf05 396
5fdbe4f0
DM
397 if ($err) {
398 foreach my $volid (@$vollist) {
399 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
400 warn $@ if $@;
401 }
402 die "create failed - $err";
403 }
502d18a2
DM
404
405 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
5fdbe4f0
DM
406 };
407
a0d1b1a2 408 return $rpcenv->fork_worker('qmcreate', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
409 };
410
3e16d5fc 411 return PVE::QemuServer::lock_config($vmid, $archive ? $restorefn : $createfn);
1e3baf05
DM
412 }});
413
414__PACKAGE__->register_method({
415 name => 'vmdiridx',
afdb31d5 416 path => '{vmid}',
1e3baf05
DM
417 method => 'GET',
418 proxyto => 'node',
419 description => "Directory index",
a0d1b1a2
DM
420 permissions => {
421 user => 'all',
422 },
1e3baf05
DM
423 parameters => {
424 additionalProperties => 0,
425 properties => {
426 node => get_standard_option('pve-node'),
427 vmid => get_standard_option('pve-vmid'),
428 },
429 },
430 returns => {
431 type => 'array',
432 items => {
433 type => "object",
434 properties => {
435 subdir => { type => 'string' },
436 },
437 },
438 links => [ { rel => 'child', href => "{subdir}" } ],
439 },
440 code => sub {
441 my ($param) = @_;
442
443 my $res = [
444 { subdir => 'config' },
445 { subdir => 'status' },
446 { subdir => 'unlink' },
447 { subdir => 'vncproxy' },
3ea94c60 448 { subdir => 'migrate' },
1e3baf05
DM
449 { subdir => 'rrd' },
450 { subdir => 'rrddata' },
91c94f0a 451 { subdir => 'monitor' },
1e3baf05 452 ];
afdb31d5 453
1e3baf05
DM
454 return $res;
455 }});
456
457__PACKAGE__->register_method({
afdb31d5
DM
458 name => 'rrd',
459 path => '{vmid}/rrd',
1e3baf05
DM
460 method => 'GET',
461 protected => 1, # fixme: can we avoid that?
462 permissions => {
378b359e 463 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
464 },
465 description => "Read VM RRD statistics (returns PNG)",
466 parameters => {
467 additionalProperties => 0,
468 properties => {
469 node => get_standard_option('pve-node'),
470 vmid => get_standard_option('pve-vmid'),
471 timeframe => {
472 description => "Specify the time frame you are interested in.",
473 type => 'string',
474 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
475 },
476 ds => {
477 description => "The list of datasources you want to display.",
478 type => 'string', format => 'pve-configid-list',
479 },
480 cf => {
481 description => "The RRD consolidation function",
482 type => 'string',
483 enum => [ 'AVERAGE', 'MAX' ],
484 optional => 1,
485 },
486 },
487 },
488 returns => {
489 type => "object",
490 properties => {
491 filename => { type => 'string' },
492 },
493 },
494 code => sub {
495 my ($param) = @_;
496
497 return PVE::Cluster::create_rrd_graph(
afdb31d5 498 "pve2-vm/$param->{vmid}", $param->{timeframe},
1e3baf05 499 $param->{ds}, $param->{cf});
afdb31d5 500
1e3baf05
DM
501 }});
502
503__PACKAGE__->register_method({
afdb31d5
DM
504 name => 'rrddata',
505 path => '{vmid}/rrddata',
1e3baf05
DM
506 method => 'GET',
507 protected => 1, # fixme: can we avoid that?
508 permissions => {
378b359e 509 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
510 },
511 description => "Read VM RRD statistics",
512 parameters => {
513 additionalProperties => 0,
514 properties => {
515 node => get_standard_option('pve-node'),
516 vmid => get_standard_option('pve-vmid'),
517 timeframe => {
518 description => "Specify the time frame you are interested in.",
519 type => 'string',
520 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
521 },
522 cf => {
523 description => "The RRD consolidation function",
524 type => 'string',
525 enum => [ 'AVERAGE', 'MAX' ],
526 optional => 1,
527 },
528 },
529 },
530 returns => {
531 type => "array",
532 items => {
533 type => "object",
534 properties => {},
535 },
536 },
537 code => sub {
538 my ($param) = @_;
539
540 return PVE::Cluster::create_rrd_data(
541 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
542 }});
543
544
545__PACKAGE__->register_method({
afdb31d5
DM
546 name => 'vm_config',
547 path => '{vmid}/config',
1e3baf05
DM
548 method => 'GET',
549 proxyto => 'node',
550 description => "Get virtual machine configuration.",
a0d1b1a2
DM
551 permissions => {
552 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
553 },
1e3baf05
DM
554 parameters => {
555 additionalProperties => 0,
556 properties => {
557 node => get_standard_option('pve-node'),
558 vmid => get_standard_option('pve-vmid'),
559 },
560 },
afdb31d5 561 returns => {
1e3baf05 562 type => "object",
554ac7e7
DM
563 properties => {
564 digest => {
565 type => 'string',
566 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
567 }
568 },
1e3baf05
DM
569 },
570 code => sub {
571 my ($param) = @_;
572
573 my $conf = PVE::QemuServer::load_config($param->{vmid});
574
575 return $conf;
576 }});
577
ae57f6b3
DM
578my $vm_is_volid_owner = sub {
579 my ($storecfg, $vmid, $volid) =@_;
580
581 if ($volid !~ m|^/|) {
582 my ($path, $owner);
583 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
584 if ($owner && ($owner == $vmid)) {
585 return 1;
586 }
587 }
588
589 return undef;
590};
591
592my $test_deallocate_drive = sub {
593 my ($storecfg, $vmid, $key, $drive, $force) = @_;
594
595 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
596 my $volid = $drive->{file};
597 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
598 if ($force || $key =~ m/^unused/) {
599 my $sid = PVE::Storage::parse_volume_id($volid);
600 return $sid;
601 }
602 }
603 }
604
605 return undef;
606};
607
5d7a6767 608my $delete_drive = sub {
1858638f 609 my ($conf, $storecfg, $vmid, $key, $drive, $force) = @_;
5d7a6767
DM
610
611 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
612 my $volid = $drive->{file};
ae57f6b3
DM
613 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
614 if ($force || $key =~ m/^unused/) {
615 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
616 warn $@ if $@;
617 } else {
618 PVE::QemuServer::add_unused_volume($conf, $volid, $vmid);
5d7a6767 619 }
ae57f6b3
DM
620 delete $conf->{$key};
621 }
622 }
623};
624
625my $vmconfig_delete_option = sub {
626 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force) = @_;
627
628 return if !defined($conf->{$opt});
629
630 my $isDisk = PVE::QemuServer::valid_drivename($opt)|| ($opt =~ m/^unused/);
631
632 if ($isDisk) {
633 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
634
635 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
636 if (my $sid = &$test_deallocate_drive($storecfg, $vmid, $opt, $drive, $force)) {
fcbb753e 637 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.Allocate']);
5d7a6767 638 }
ae57f6b3
DM
639 }
640
641 die "error hot-unplug $opt" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
642
643 if ($isDisk) {
644 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
645 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive, $force);
5d7a6767 646 } else {
ae57f6b3
DM
647 delete $conf->{$opt};
648 }
649
650 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
651};
652
653my $vmconfig_update_disk = sub {
654 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
5d7a6767 655
ae57f6b3
DM
656 my $drive = PVE::QemuServer::parse_drive($opt, $value);
657
658 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
659 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
660 } else {
661 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
662 }
663
664 if ($conf->{$opt}) {
665
666 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
667
668 my $media = $drive->{media} || 'disk';
669 my $oldmedia = $old_drive->{media} || 'disk';
670 die "unable to change media type\n" if $media ne $oldmedia;
671
672 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
673 ($drive->{file} ne $old_drive->{file})) { # delete old disks
674
675 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
676 $conf = PVE::QemuServer::load_config($vmid); # update/reload
677 }
678 }
679 }
680
681 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
682 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
683
684 $conf = PVE::QemuServer::load_config($vmid); # update/reload
685 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
686
687 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
688
689 if (PVE::QemuServer::check_running($vmid)) {
690 if ($drive->{file} eq 'none') {
691 PVE::QemuServer::vm_monitor_command($vmid, "eject -f drive-$opt", 0);
692 } else {
693 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
694 PVE::QemuServer::vm_monitor_command($vmid, "eject -f drive-$opt", 0); #force eject if locked
695 PVE::QemuServer::vm_monitor_command($vmid, "change drive-$opt \"$path\"", 0) if $path;
696 }
697 }
698
699 } else { # hotplug new disks
700
701 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
5d7a6767 702 }
5d7a6767
DM
703};
704
ae57f6b3
DM
705my $vmconfig_update_net = sub {
706 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
707
708 if ($conf->{$opt}) {
709 #if online update, then unplug first
710 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
711 }
712
713 $conf->{$opt} = $value;
714 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
715 $conf = PVE::QemuServer::load_config($vmid); # update/reload
716
717 my $net = PVE::QemuServer::parse_net($conf->{$opt});
718
719 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
720};
721
a0d1b1a2
DM
722my $vm_config_perm_list = [
723 'VM.Config.Disk',
724 'VM.Config.CDROM',
725 'VM.Config.CPU',
726 'VM.Config.Memory',
727 'VM.Config.Network',
728 'VM.Config.HWType',
729 'VM.Config.Options',
730 ];
731
1e3baf05 732__PACKAGE__->register_method({
afdb31d5
DM
733 name => 'update_vm',
734 path => '{vmid}/config',
1e3baf05
DM
735 method => 'PUT',
736 protected => 1,
737 proxyto => 'node',
738 description => "Set virtual machine options.",
a0d1b1a2
DM
739 permissions => {
740 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
741 },
1e3baf05
DM
742 parameters => {
743 additionalProperties => 0,
744 properties => PVE::QemuServer::json_config_properties(
745 {
746 node => get_standard_option('pve-node'),
747 vmid => get_standard_option('pve-vmid'),
3ea94c60 748 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
749 delete => {
750 type => 'string', format => 'pve-configid-list',
751 description => "A list of settings you want to delete.",
752 optional => 1,
753 },
754 force => {
755 type => 'boolean',
756 description => $opt_force_description,
757 optional => 1,
758 requires => 'delete',
759 },
554ac7e7
DM
760 digest => {
761 type => 'string',
762 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
763 maxLength => 40,
afdb31d5 764 optional => 1,
554ac7e7 765 }
1e3baf05
DM
766 }),
767 },
768 returns => { type => 'null'},
769 code => sub {
770 my ($param) = @_;
771
772 my $rpcenv = PVE::RPCEnvironment::get();
773
a0d1b1a2 774 my $authuser = $rpcenv->get_user();
1e3baf05
DM
775
776 my $node = extract_param($param, 'node');
777
1e3baf05
DM
778 my $vmid = extract_param($param, 'vmid');
779
5fdbe4f0
DM
780 my $digest = extract_param($param, 'digest');
781
782 my @paramarr = (); # used for log message
783 foreach my $key (keys %$param) {
784 push @paramarr, "-$key", $param->{$key};
785 }
786
1e3baf05 787 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 788 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 789 if $skiplock && $authuser ne 'root@pam';
1e3baf05 790
0532bc63
DM
791 my $delete_str = extract_param($param, 'delete');
792
1e3baf05
DM
793 my $force = extract_param($param, 'force');
794
0532bc63
DM
795 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
796
1e68cb19
DM
797 my $storecfg = PVE::Storage::config();
798
799 &$resolve_cdrom_alias($param);
800
801 # now try to verify all parameters
802
0532bc63
DM
803 my @delete = ();
804 foreach my $opt (PVE::Tools::split_list($delete_str)) {
805 $opt = 'ide2' if $opt eq 'cdrom';
806 raise_param_exc({ delete => "you can't use '-$opt' and " .
807 "-delete $opt' at the same time" })
808 if defined($param->{$opt});
809
810 if (!PVE::QemuServer::option_exists($opt)) {
811 raise_param_exc({ delete => "unknown option '$opt'" });
812 }
ae57f6b3 813
0532bc63
DM
814 push @delete, $opt;
815 }
1e3baf05 816
1e68cb19
DM
817 foreach my $opt (keys %$param) {
818 if (PVE::QemuServer::valid_drivename($opt)) {
819 # cleanup drive path
820 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
821 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
822 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
1e68cb19
DM
823 } elsif ($opt =~ m/^net(\d+)$/) {
824 # add macaddr
825 my $net = PVE::QemuServer::parse_net($param->{$opt});
826 $param->{$opt} = PVE::QemuServer::print_net($net);
1e68cb19
DM
827 }
828 }
1e3baf05 829
ae57f6b3
DM
830 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
831
832 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
833
fcbb753e 834 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1e3baf05 835
5d39a182 836 my $updatefn = sub {
1e3baf05 837
5d39a182 838 my $conf = PVE::QemuServer::load_config($vmid);
1e3baf05 839
5d39a182
DM
840 die "checksum missmatch (file change by other user?)\n"
841 if $digest && $digest ne $conf->{digest};
1e3baf05 842
5d39a182 843 PVE::QemuServer::check_lock($conf) if !$skiplock;
1e3baf05 844
a0d1b1a2 845 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
c2a64aa7 846
5d7a6767 847 foreach my $opt (@delete) { # delete
1e68cb19 848 $conf = PVE::QemuServer::load_config($vmid); # update/reload
ae57f6b3 849 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
5d39a182 850 }
1e3baf05 851
5d7a6767 852 foreach my $opt (keys %$param) { # add/change
1e3baf05 853
1e68cb19 854 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1e3baf05 855
5d7a6767
DM
856 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
857
ae57f6b3 858 if (PVE::QemuServer::valid_drivename($opt)) {
5d7a6767 859
ae57f6b3
DM
860 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
861 $opt, $param->{$opt}, $force);
1e68cb19 862
ae57f6b3 863 } elsif ($opt =~ m/^net(\d+)$/) { #nics
1858638f 864
ae57f6b3
DM
865 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
866 $opt, $param->{$opt});
1e68cb19
DM
867
868 } else {
869
1858638f
DM
870 $conf->{$opt} = $param->{$opt};
871 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3a1e36bb 872 }
5d39a182
DM
873 }
874 };
875
876 PVE::QemuServer::lock_config($vmid, $updatefn);
fcdb0117 877
1e3baf05
DM
878 return undef;
879 }});
880
881
882__PACKAGE__->register_method({
afdb31d5
DM
883 name => 'destroy_vm',
884 path => '{vmid}',
1e3baf05
DM
885 method => 'DELETE',
886 protected => 1,
887 proxyto => 'node',
888 description => "Destroy the vm (also delete all used/owned volumes).",
a0d1b1a2
DM
889 permissions => {
890 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
891 },
1e3baf05
DM
892 parameters => {
893 additionalProperties => 0,
894 properties => {
895 node => get_standard_option('pve-node'),
896 vmid => get_standard_option('pve-vmid'),
3ea94c60 897 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
898 },
899 },
afdb31d5 900 returns => {
5fdbe4f0
DM
901 type => 'string',
902 },
1e3baf05
DM
903 code => sub {
904 my ($param) = @_;
905
906 my $rpcenv = PVE::RPCEnvironment::get();
907
a0d1b1a2 908 my $authuser = $rpcenv->get_user();
1e3baf05
DM
909
910 my $vmid = $param->{vmid};
911
912 my $skiplock = $param->{skiplock};
afdb31d5 913 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 914 if $skiplock && $authuser ne 'root@pam';
1e3baf05 915
5fdbe4f0
DM
916 # test if VM exists
917 my $conf = PVE::QemuServer::load_config($vmid);
918
afdb31d5 919 my $storecfg = PVE::Storage::config();
1e3baf05 920
502d18a2
DM
921 my $delVMfromPoolFn = sub {
922 my $usercfg = cfs_read_file("user.cfg");
923 my $pool = $usercfg->{vms}->{$vmid};
924 if (my $data = $usercfg->{pools}->{$pool}) {
925 delete $data->{vms}->{$vmid};
926 delete $usercfg->{vms}->{$vmid};
927 cfs_write_file("user.cfg", $usercfg);
928 }
929 };
930
5fdbe4f0 931 my $realcmd = sub {
ff1a2432
DM
932 my $upid = shift;
933
934 syslog('info', "destroy VM $vmid: $upid\n");
935
5fdbe4f0 936 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
502d18a2
DM
937
938 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
5fdbe4f0 939 };
1e3baf05 940
a0d1b1a2 941 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1e3baf05
DM
942 }});
943
944__PACKAGE__->register_method({
afdb31d5
DM
945 name => 'unlink',
946 path => '{vmid}/unlink',
1e3baf05
DM
947 method => 'PUT',
948 protected => 1,
949 proxyto => 'node',
950 description => "Unlink/delete disk images.",
a0d1b1a2
DM
951 permissions => {
952 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
953 },
1e3baf05
DM
954 parameters => {
955 additionalProperties => 0,
956 properties => {
957 node => get_standard_option('pve-node'),
958 vmid => get_standard_option('pve-vmid'),
959 idlist => {
960 type => 'string', format => 'pve-configid-list',
961 description => "A list of disk IDs you want to delete.",
962 },
963 force => {
964 type => 'boolean',
965 description => $opt_force_description,
966 optional => 1,
967 },
968 },
969 },
970 returns => { type => 'null'},
971 code => sub {
972 my ($param) = @_;
973
974 $param->{delete} = extract_param($param, 'idlist');
975
976 __PACKAGE__->update_vm($param);
977
978 return undef;
979 }});
980
981my $sslcert;
982
983__PACKAGE__->register_method({
afdb31d5
DM
984 name => 'vncproxy',
985 path => '{vmid}/vncproxy',
1e3baf05
DM
986 method => 'POST',
987 protected => 1,
988 permissions => {
378b359e 989 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1e3baf05
DM
990 },
991 description => "Creates a TCP VNC proxy connections.",
992 parameters => {
993 additionalProperties => 0,
994 properties => {
995 node => get_standard_option('pve-node'),
996 vmid => get_standard_option('pve-vmid'),
997 },
998 },
afdb31d5 999 returns => {
1e3baf05
DM
1000 additionalProperties => 0,
1001 properties => {
1002 user => { type => 'string' },
1003 ticket => { type => 'string' },
1004 cert => { type => 'string' },
1005 port => { type => 'integer' },
1006 upid => { type => 'string' },
1007 },
1008 },
1009 code => sub {
1010 my ($param) = @_;
1011
1012 my $rpcenv = PVE::RPCEnvironment::get();
1013
a0d1b1a2 1014 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1015
1016 my $vmid = $param->{vmid};
1017 my $node = $param->{node};
1018
b6f39da2
DM
1019 my $authpath = "/vms/$vmid";
1020
a0d1b1a2 1021 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
b6f39da2 1022
1e3baf05
DM
1023 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1024 if !$sslcert;
1025
1026 my $port = PVE::Tools::next_vnc_port();
1027
1028 my $remip;
afdb31d5 1029
4f1be36c 1030 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1e3baf05
DM
1031 $remip = PVE::Cluster::remote_node_ip($node);
1032 }
1033
1034 # NOTE: kvm VNC traffic is already TLS encrypted,
1035 # so we select the fastest chipher here (or 'none'?)
1036 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes',
1037 '-c', 'blowfish-cbc', $remip] : [];
1038
afdb31d5 1039 my $timeout = 10;
1e3baf05
DM
1040
1041 my $realcmd = sub {
1042 my $upid = shift;
1043
1044 syslog('info', "starting vnc proxy $upid\n");
1045
1046 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1047
1048 my $qmstr = join(' ', @$qmcmd);
1049
1050 # also redirect stderr (else we get RFB protocol errors)
be62c45c 1051 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1e3baf05 1052
be62c45c 1053 PVE::Tools::run_command($cmd);
1e3baf05
DM
1054
1055 return;
1056 };
1057
a0d1b1a2 1058 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1e3baf05
DM
1059
1060 return {
a0d1b1a2 1061 user => $authuser,
1e3baf05 1062 ticket => $ticket,
afdb31d5
DM
1063 port => $port,
1064 upid => $upid,
1065 cert => $sslcert,
1e3baf05
DM
1066 };
1067 }});
1068
5fdbe4f0
DM
1069__PACKAGE__->register_method({
1070 name => 'vmcmdidx',
afdb31d5 1071 path => '{vmid}/status',
5fdbe4f0
DM
1072 method => 'GET',
1073 proxyto => 'node',
1074 description => "Directory index",
a0d1b1a2
DM
1075 permissions => {
1076 user => 'all',
1077 },
5fdbe4f0
DM
1078 parameters => {
1079 additionalProperties => 0,
1080 properties => {
1081 node => get_standard_option('pve-node'),
1082 vmid => get_standard_option('pve-vmid'),
1083 },
1084 },
1085 returns => {
1086 type => 'array',
1087 items => {
1088 type => "object",
1089 properties => {
1090 subdir => { type => 'string' },
1091 },
1092 },
1093 links => [ { rel => 'child', href => "{subdir}" } ],
1094 },
1095 code => sub {
1096 my ($param) = @_;
1097
1098 # test if VM exists
1099 my $conf = PVE::QemuServer::load_config($param->{vmid});
1100
1101 my $res = [
1102 { subdir => 'current' },
1103 { subdir => 'start' },
1104 { subdir => 'stop' },
1105 ];
afdb31d5 1106
5fdbe4f0
DM
1107 return $res;
1108 }});
1109
1e3baf05 1110__PACKAGE__->register_method({
afdb31d5 1111 name => 'vm_status',
5fdbe4f0 1112 path => '{vmid}/status/current',
1e3baf05
DM
1113 method => 'GET',
1114 proxyto => 'node',
1115 protected => 1, # qemu pid files are only readable by root
1116 description => "Get virtual machine status.",
a0d1b1a2
DM
1117 permissions => {
1118 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1119 },
1e3baf05
DM
1120 parameters => {
1121 additionalProperties => 0,
1122 properties => {
1123 node => get_standard_option('pve-node'),
1124 vmid => get_standard_option('pve-vmid'),
1125 },
1126 },
1127 returns => { type => 'object' },
1128 code => sub {
1129 my ($param) = @_;
1130
1131 # test if VM exists
1132 my $conf = PVE::QemuServer::load_config($param->{vmid});
1133
ff1a2432 1134 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid});
8610701a 1135 my $status = $vmstatus->{$param->{vmid}};
1e3baf05 1136
8610701a
DM
1137 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1138 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $param->{vmid}, 1)) {
1139 $status->{ha} = 1;
1140 } else {
1141 $status->{ha} = 0;
1142 }
1143
1144 return $status;
1e3baf05
DM
1145 }});
1146
1147__PACKAGE__->register_method({
afdb31d5 1148 name => 'vm_start',
5fdbe4f0
DM
1149 path => '{vmid}/status/start',
1150 method => 'POST',
1e3baf05
DM
1151 protected => 1,
1152 proxyto => 'node',
5fdbe4f0 1153 description => "Start virtual machine.",
a0d1b1a2
DM
1154 permissions => {
1155 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1156 },
1e3baf05
DM
1157 parameters => {
1158 additionalProperties => 0,
1159 properties => {
1160 node => get_standard_option('pve-node'),
1161 vmid => get_standard_option('pve-vmid'),
3ea94c60
DM
1162 skiplock => get_standard_option('skiplock'),
1163 stateuri => get_standard_option('pve-qm-stateuri'),
1e3baf05
DM
1164 },
1165 },
afdb31d5 1166 returns => {
5fdbe4f0
DM
1167 type => 'string',
1168 },
1e3baf05
DM
1169 code => sub {
1170 my ($param) = @_;
1171
1172 my $rpcenv = PVE::RPCEnvironment::get();
1173
a0d1b1a2 1174 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1175
1176 my $node = extract_param($param, 'node');
1177
1e3baf05
DM
1178 my $vmid = extract_param($param, 'vmid');
1179
3ea94c60 1180 my $stateuri = extract_param($param, 'stateuri');
afdb31d5 1181 raise_param_exc({ stateuri => "Only root may use this option." })
a0d1b1a2 1182 if $stateuri && $authuser ne 'root@pam';
3ea94c60 1183
1e3baf05 1184 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1185 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1186 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1187
afdb31d5 1188 my $storecfg = PVE::Storage::config();
5fdbe4f0
DM
1189
1190 my $realcmd = sub {
1191 my $upid = shift;
1192
1193 syslog('info', "start VM $vmid: $upid\n");
1194
3ea94c60 1195 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock);
5fdbe4f0
DM
1196
1197 return;
1198 };
1199
a0d1b1a2 1200 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1201 }});
1202
1203__PACKAGE__->register_method({
afdb31d5 1204 name => 'vm_stop',
5fdbe4f0
DM
1205 path => '{vmid}/status/stop',
1206 method => 'POST',
1207 protected => 1,
1208 proxyto => 'node',
1209 description => "Stop virtual machine.",
a0d1b1a2
DM
1210 permissions => {
1211 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1212 },
5fdbe4f0
DM
1213 parameters => {
1214 additionalProperties => 0,
1215 properties => {
1216 node => get_standard_option('pve-node'),
1217 vmid => get_standard_option('pve-vmid'),
1218 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1219 timeout => {
1220 description => "Wait maximal timeout seconds.",
1221 type => 'integer',
1222 minimum => 0,
1223 optional => 1,
254575e9
DM
1224 },
1225 keepActive => {
1226 description => "Do not decativate storage volumes.",
1227 type => 'boolean',
1228 optional => 1,
1229 default => 0,
c6bb9502 1230 }
5fdbe4f0
DM
1231 },
1232 },
afdb31d5 1233 returns => {
5fdbe4f0
DM
1234 type => 'string',
1235 },
1236 code => sub {
1237 my ($param) = @_;
1238
1239 my $rpcenv = PVE::RPCEnvironment::get();
1240
a0d1b1a2 1241 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1242
1243 my $node = extract_param($param, 'node');
1244
1245 my $vmid = extract_param($param, 'vmid');
1246
1247 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1248 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1249 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1250
254575e9 1251 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1252 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1253 if $keepActive && $authuser ne 'root@pam';
254575e9 1254
ff1a2432
DM
1255 my $storecfg = PVE::Storage::config();
1256
5fdbe4f0
DM
1257 my $realcmd = sub {
1258 my $upid = shift;
1259
1260 syslog('info', "stop VM $vmid: $upid\n");
1261
afdb31d5 1262 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
254575e9 1263 $param->{timeout}, 0, 1, $keepActive);
c6bb9502 1264
5fdbe4f0
DM
1265 return;
1266 };
1267
a0d1b1a2 1268 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1269 }});
1270
1271__PACKAGE__->register_method({
afdb31d5 1272 name => 'vm_reset',
5fdbe4f0
DM
1273 path => '{vmid}/status/reset',
1274 method => 'POST',
1275 protected => 1,
1276 proxyto => 'node',
1277 description => "Reset virtual machine.",
a0d1b1a2
DM
1278 permissions => {
1279 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1280 },
5fdbe4f0
DM
1281 parameters => {
1282 additionalProperties => 0,
1283 properties => {
1284 node => get_standard_option('pve-node'),
1285 vmid => get_standard_option('pve-vmid'),
1286 skiplock => get_standard_option('skiplock'),
1287 },
1288 },
afdb31d5 1289 returns => {
5fdbe4f0
DM
1290 type => 'string',
1291 },
1292 code => sub {
1293 my ($param) = @_;
1294
1295 my $rpcenv = PVE::RPCEnvironment::get();
1296
a0d1b1a2 1297 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1298
1299 my $node = extract_param($param, 'node');
1300
1301 my $vmid = extract_param($param, 'vmid');
1302
1303 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1304 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1305 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1306
ff1a2432
DM
1307 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1308
5fdbe4f0
DM
1309 my $realcmd = sub {
1310 my $upid = shift;
1311
1e3baf05 1312 PVE::QemuServer::vm_reset($vmid, $skiplock);
5fdbe4f0
DM
1313
1314 return;
1315 };
1316
a0d1b1a2 1317 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1318 }});
1319
1320__PACKAGE__->register_method({
afdb31d5 1321 name => 'vm_shutdown',
5fdbe4f0
DM
1322 path => '{vmid}/status/shutdown',
1323 method => 'POST',
1324 protected => 1,
1325 proxyto => 'node',
1326 description => "Shutdown virtual machine.",
a0d1b1a2
DM
1327 permissions => {
1328 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
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 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1336 timeout => {
1337 description => "Wait maximal timeout seconds.",
1338 type => 'integer',
1339 minimum => 0,
1340 optional => 1,
9269013a
DM
1341 },
1342 forceStop => {
1343 description => "Make sure the VM stops.",
1344 type => 'boolean',
1345 optional => 1,
1346 default => 0,
254575e9
DM
1347 },
1348 keepActive => {
1349 description => "Do not decativate storage volumes.",
1350 type => 'boolean',
1351 optional => 1,
1352 default => 0,
c6bb9502 1353 }
5fdbe4f0
DM
1354 },
1355 },
afdb31d5 1356 returns => {
5fdbe4f0
DM
1357 type => 'string',
1358 },
1359 code => sub {
1360 my ($param) = @_;
1361
1362 my $rpcenv = PVE::RPCEnvironment::get();
1363
a0d1b1a2 1364 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1365
1366 my $node = extract_param($param, 'node');
1367
1368 my $vmid = extract_param($param, 'vmid');
1369
1370 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1371 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1372 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1373
254575e9 1374 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1375 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1376 if $keepActive && $authuser ne 'root@pam';
254575e9 1377
02d07cf5
DM
1378 my $storecfg = PVE::Storage::config();
1379
5fdbe4f0
DM
1380 my $realcmd = sub {
1381 my $upid = shift;
1382
1383 syslog('info', "shutdown VM $vmid: $upid\n");
1384
afdb31d5 1385 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
254575e9 1386 1, $param->{forceStop}, $keepActive);
c6bb9502 1387
5fdbe4f0
DM
1388 return;
1389 };
1390
a0d1b1a2 1391 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1392 }});
1393
1394__PACKAGE__->register_method({
afdb31d5 1395 name => 'vm_suspend',
5fdbe4f0
DM
1396 path => '{vmid}/status/suspend',
1397 method => 'POST',
1398 protected => 1,
1399 proxyto => 'node',
1400 description => "Suspend virtual machine.",
a0d1b1a2
DM
1401 permissions => {
1402 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1403 },
5fdbe4f0
DM
1404 parameters => {
1405 additionalProperties => 0,
1406 properties => {
1407 node => get_standard_option('pve-node'),
1408 vmid => get_standard_option('pve-vmid'),
1409 skiplock => get_standard_option('skiplock'),
1410 },
1411 },
afdb31d5 1412 returns => {
5fdbe4f0
DM
1413 type => 'string',
1414 },
1415 code => sub {
1416 my ($param) = @_;
1417
1418 my $rpcenv = PVE::RPCEnvironment::get();
1419
a0d1b1a2 1420 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1421
1422 my $node = extract_param($param, 'node');
1423
1424 my $vmid = extract_param($param, 'vmid');
1425
1426 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1427 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1428 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1429
ff1a2432
DM
1430 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1431
5fdbe4f0
DM
1432 my $realcmd = sub {
1433 my $upid = shift;
1434
1435 syslog('info', "suspend VM $vmid: $upid\n");
1436
1e3baf05 1437 PVE::QemuServer::vm_suspend($vmid, $skiplock);
5fdbe4f0
DM
1438
1439 return;
1440 };
1441
a0d1b1a2 1442 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1443 }});
1444
1445__PACKAGE__->register_method({
afdb31d5 1446 name => 'vm_resume',
5fdbe4f0
DM
1447 path => '{vmid}/status/resume',
1448 method => 'POST',
1449 protected => 1,
1450 proxyto => 'node',
1451 description => "Resume virtual machine.",
a0d1b1a2
DM
1452 permissions => {
1453 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1454 },
5fdbe4f0
DM
1455 parameters => {
1456 additionalProperties => 0,
1457 properties => {
1458 node => get_standard_option('pve-node'),
1459 vmid => get_standard_option('pve-vmid'),
1460 skiplock => get_standard_option('skiplock'),
1461 },
1462 },
afdb31d5 1463 returns => {
5fdbe4f0
DM
1464 type => 'string',
1465 },
1466 code => sub {
1467 my ($param) = @_;
1468
1469 my $rpcenv = PVE::RPCEnvironment::get();
1470
a0d1b1a2 1471 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1472
1473 my $node = extract_param($param, 'node');
1474
1475 my $vmid = extract_param($param, 'vmid');
1476
1477 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1478 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1479 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1480
b7eeab21 1481 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
ff1a2432 1482
5fdbe4f0
DM
1483 my $realcmd = sub {
1484 my $upid = shift;
1485
1486 syslog('info', "resume VM $vmid: $upid\n");
1487
1e3baf05 1488 PVE::QemuServer::vm_resume($vmid, $skiplock);
1e3baf05 1489
5fdbe4f0
DM
1490 return;
1491 };
1492
a0d1b1a2 1493 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1494 }});
1495
1496__PACKAGE__->register_method({
afdb31d5 1497 name => 'vm_sendkey',
5fdbe4f0
DM
1498 path => '{vmid}/sendkey',
1499 method => 'PUT',
1500 protected => 1,
1501 proxyto => 'node',
1502 description => "Send key event to virtual machine.",
a0d1b1a2
DM
1503 permissions => {
1504 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1505 },
5fdbe4f0
DM
1506 parameters => {
1507 additionalProperties => 0,
1508 properties => {
1509 node => get_standard_option('pve-node'),
1510 vmid => get_standard_option('pve-vmid'),
1511 skiplock => get_standard_option('skiplock'),
1512 key => {
1513 description => "The key (qemu monitor encoding).",
1514 type => 'string'
1515 }
1516 },
1517 },
1518 returns => { type => 'null'},
1519 code => sub {
1520 my ($param) = @_;
1521
1522 my $rpcenv = PVE::RPCEnvironment::get();
1523
a0d1b1a2 1524 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1525
1526 my $node = extract_param($param, 'node');
1527
1528 my $vmid = extract_param($param, 'vmid');
1529
1530 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1531 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1532 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0
DM
1533
1534 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1535
1536 return;
1e3baf05
DM
1537 }});
1538
3ea94c60 1539__PACKAGE__->register_method({
afdb31d5 1540 name => 'migrate_vm',
3ea94c60
DM
1541 path => '{vmid}/migrate',
1542 method => 'POST',
1543 protected => 1,
1544 proxyto => 'node',
1545 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
1546 permissions => {
1547 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
1548 },
3ea94c60
DM
1549 parameters => {
1550 additionalProperties => 0,
1551 properties => {
1552 node => get_standard_option('pve-node'),
1553 vmid => get_standard_option('pve-vmid'),
1554 target => get_standard_option('pve-node', { description => "Target node." }),
1555 online => {
1556 type => 'boolean',
1557 description => "Use online/live migration.",
1558 optional => 1,
1559 },
1560 force => {
1561 type => 'boolean',
1562 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
1563 optional => 1,
1564 },
1565 },
1566 },
afdb31d5 1567 returns => {
3ea94c60
DM
1568 type => 'string',
1569 description => "the task ID.",
1570 },
1571 code => sub {
1572 my ($param) = @_;
1573
1574 my $rpcenv = PVE::RPCEnvironment::get();
1575
a0d1b1a2 1576 my $authuser = $rpcenv->get_user();
3ea94c60
DM
1577
1578 my $target = extract_param($param, 'target');
1579
1580 my $localnode = PVE::INotify::nodename();
1581 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
1582
1583 PVE::Cluster::check_cfs_quorum();
1584
1585 PVE::Cluster::check_node_exists($target);
1586
1587 my $targetip = PVE::Cluster::remote_node_ip($target);
1588
1589 my $vmid = extract_param($param, 'vmid');
1590
afdb31d5 1591 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 1592 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
1593
1594 # test if VM exists
a5ed42d3 1595 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
1596
1597 # try to detect errors early
a5ed42d3
DM
1598
1599 PVE::QemuServer::check_lock($conf);
1600
3ea94c60 1601 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 1602 die "cant migrate running VM without --online\n"
3ea94c60
DM
1603 if !$param->{online};
1604 }
1605
1606 my $realcmd = sub {
1607 my $upid = shift;
1608
16e903f2 1609 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
3ea94c60
DM
1610 };
1611
a0d1b1a2 1612 my $upid = $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
3ea94c60
DM
1613
1614 return $upid;
1615 }});
1e3baf05 1616
91c94f0a 1617__PACKAGE__->register_method({
afdb31d5
DM
1618 name => 'monitor',
1619 path => '{vmid}/monitor',
91c94f0a
DM
1620 method => 'POST',
1621 protected => 1,
1622 proxyto => 'node',
1623 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
1624 permissions => {
1625 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
1626 },
91c94f0a
DM
1627 parameters => {
1628 additionalProperties => 0,
1629 properties => {
1630 node => get_standard_option('pve-node'),
1631 vmid => get_standard_option('pve-vmid'),
1632 command => {
1633 type => 'string',
1634 description => "The monitor command.",
1635 }
1636 },
1637 },
1638 returns => { type => 'string'},
1639 code => sub {
1640 my ($param) = @_;
1641
1642 my $vmid = $param->{vmid};
1643
1644 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
1645
1646 my $res = '';
1647 eval {
1648 $res = PVE::QemuServer::vm_monitor_command($vmid, $param->{command});
1649 };
1650 $res = "ERROR: $@" if $@;
1651
1652 return $res;
1653 }});
1654
1e3baf05 16551;