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