]> git.proxmox.com Git - qemu-server.git/blob - PVE/API2/Qemu.pm
correctly add/remove VMs to pool
[qemu-server.git] / PVE / API2 / Qemu.pm
1 package PVE::API2::Qemu;
2
3 use strict;
4 use warnings;
5 use Cwd 'abs_path';
6
7 use PVE::Cluster qw (cfs_read_file cfs_write_file);;
8 use PVE::SafeSyslog;
9 use PVE::Tools qw(extract_param);
10 use PVE::Exception qw(raise raise_param_exc);
11 use PVE::Storage;
12 use PVE::JSONSchema qw(get_standard_option);
13 use PVE::RESTHandler;
14 use PVE::QemuServer;
15 use PVE::QemuMigrate;
16 use PVE::RPCEnvironment;
17 use PVE::AccessControl;
18 use PVE::INotify;
19
20 use Data::Dumper; # fixme: remove
21
22 use base qw(PVE::RESTHandler);
23
24 my $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
26 my $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
36 my $check_volume_access = sub {
37 my ($rpcenv, $authuser, $storecfg, $vmid, $volid, $pool) = @_;
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
47 $rpcenv->check_storage_perm($authuser, $vmid, $pool, $sid, [ 'Datastore.Allocate' ]);
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
58 my $check_storage_access = sub {
59 my ($rpcenv, $authuser, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
60
61 PVE::QemuServer::foreach_drive($settings, sub {
62 my ($ds, $drive) = @_;
63
64 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
65
66 my $volid = $drive->{file};
67
68 if (!$volid || $volid eq 'none') {
69 # nothing to check
70 } elsif (!$isCDROM && ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/)) {
71 my ($storeid, $size) = ($2 || $default_storage, $3);
72 die "no storage ID specified (and no default storage)\n" if !$storeid;
73 $rpcenv->check_storage_perm($authuser, $vmid, $pool, $storeid, [ 'Datastore.AllocateSpace' ]);
74 } else {
75 my $path = &$check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $volid, $pool);
76 die "image '$path' does not exists\n" if (!(-f $path || -b $path));
77 }
78 });
79 };
80
81 # Note: $pool is only needed when creating a VM, because pool permissions
82 # are automatically inherited if VM already exists inside a pool.
83 my $create_disks = sub {
84 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
85
86 my $vollist = [];
87
88 my $res = {};
89 PVE::QemuServer::foreach_drive($settings, sub {
90 my ($ds, $disk) = @_;
91
92 my $volid = $disk->{file};
93
94 if (!$volid || $volid eq 'none') {
95 $res->{$ds} = $settings->{$ds};
96 } elsif ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/) {
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;
101 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid,
102 $fmt, undef, $size*1024*1024);
103 $disk->{file} = $volid;
104 push @$vollist, $volid;
105 delete $disk->{format}; # no longer needed
106 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
107 } else {
108 my $path = &$check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $volid, $pool);
109 die "image '$path' does not exists\n" if (!(-f $path || -b $path));
110 $res->{$ds} = $settings->{$ds};
111 }
112 });
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
125 foreach my $ds (keys %$res) {
126 $conf->{$ds} = $res->{$ds};
127 }
128
129 return $vollist;
130 };
131
132 my $check_vm_modify_config_perm = sub {
133 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
134
135 return 1 if $authuser ne 'root@pam';
136
137 foreach my $opt (@$key_list) {
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
164 __PACKAGE__->register_method({
165 name => 'vmlist',
166 path => '',
167 method => 'GET',
168 description => "Virtual machine index (per node).",
169 permissions => {
170 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
171 user => 'all',
172 },
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
192 my $rpcenv = PVE::RPCEnvironment::get();
193 my $authuser = $rpcenv->get_user();
194
195 my $vmstatus = PVE::QemuServer::vmstatus();
196
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 }
205
206 return $res;
207 }});
208
209 __PACKAGE__->register_method({
210 name => 'create_vm',
211 path => '',
212 method => 'POST',
213 description => "Create or restore a virtual machine.",
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 },
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'),
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 => {
240 optional => 1,
241 type => 'boolean',
242 description => "Allow to overwrite existing VM.",
243 requires => 'archive',
244 },
245 unique => {
246 optional => 1,
247 type => 'boolean',
248 description => "Assign a unique random ethernet address.",
249 requires => 'archive',
250 },
251 pool => {
252 optional => 1,
253 type => 'string', format => 'pve-poolid',
254 description => "Add the VM to the specified pool.",
255 },
256 }),
257 },
258 returns => {
259 type => 'string',
260 },
261 code => sub {
262 my ($param) = @_;
263
264 my $rpcenv = PVE::RPCEnvironment::get();
265
266 my $authuser = $rpcenv->get_user();
267
268 my $node = extract_param($param, 'node');
269
270 my $vmid = extract_param($param, 'vmid');
271
272 my $archive = extract_param($param, 'archive');
273
274 my $storage = extract_param($param, 'storage');
275
276 my $force = extract_param($param, 'force');
277
278 my $unique = extract_param($param, 'unique');
279
280 my $pool = extract_param($param, 'pool');
281
282 my $filename = PVE::QemuServer::config_file($vmid);
283
284 my $storecfg = PVE::Storage::config();
285
286 PVE::Cluster::check_cfs_quorum();
287
288 if (defined($pool)) {
289 $rpcenv->check_pool_exist($pool);
290 $rpcenv->check_perm_modify($authuser, "/pool/$pool");
291 }
292
293 $rpcenv->check_storage_perm($authuser, $vmid, $pool, $storage, [ 'Datastore.AllocateSpace' ])
294 if defined($storage);
295
296 if (!$archive) {
297 &$resolve_cdrom_alias($param);
298
299 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $pool, $param, $storage);
300
301 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
302
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;
307
308 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
309 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
310 }
311 }
312
313 PVE::QemuServer::add_random_macs($param);
314 } else {
315 my $keystr = join(' ', keys %$param);
316 raise_param_exc({ archive => "option conflicts with other options ($keystr)"}) if $keystr;
317
318 if ($archive eq '-') {
319 die "pipe requires cli environment\n"
320 && $rpcenv->{type} ne 'cli';
321 } else {
322 my $path = &$check_volume_access($rpcenv, $authuser, $storecfg, $vmid, $archive, $pool);
323 die "can't find archive file '$archive'\n" if !($path && -f $path);
324 $archive = $path;
325 }
326 }
327
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
337 my $restorefn = sub {
338
339 if (-f $filename) {
340 die "unable to restore vm $vmid: config file already exists\n"
341 if !$force;
342
343 die "unable to restore vm $vmid: vm is running\n"
344 if PVE::QemuServer::check_running($vmid);
345
346 # destroy existing data - keep empty config
347 PVE::QemuServer::destroy_vm($storecfg, $vmid, 1);
348 }
349
350 my $realcmd = sub {
351 PVE::QemuServer::restore_archive($archive, $vmid, $authuser, {
352 storage => $storage,
353 pool => $pool,
354 unique => $unique });
355
356 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
357 };
358
359 return $rpcenv->fork_worker('qmrestore', $vmid, $authuser, $realcmd);
360 };
361
362 my $createfn = sub {
363
364 # second test (after locking test is accurate)
365 die "unable to create vm $vmid: config file already exists\n"
366 if -f $filename;
367
368 my $realcmd = sub {
369
370 my $vollist = [];
371
372 my $conf = $param;
373
374 eval {
375
376 $vollist = &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $param, $storage);
377
378 # try to be smart about bootdisk
379 my @disks = PVE::QemuServer::disknames();
380 my $firstdisk;
381 foreach my $ds (reverse @disks) {
382 next if !$conf->{$ds};
383 my $disk = PVE::QemuServer::parse_drive($ds, $conf->{$ds});
384 next if PVE::QemuServer::drive_is_cdrom($disk);
385 $firstdisk = $ds;
386 }
387
388 if (!$conf->{bootdisk} && $firstdisk) {
389 $conf->{bootdisk} = $firstdisk;
390 }
391
392 PVE::QemuServer::update_config_nolock($vmid, $conf);
393
394 };
395 my $err = $@;
396
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 }
404
405 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
406 };
407
408 return $rpcenv->fork_worker('qmcreate', $vmid, $authuser, $realcmd);
409 };
410
411 return PVE::QemuServer::lock_config($vmid, $archive ? $restorefn : $createfn);
412 }});
413
414 __PACKAGE__->register_method({
415 name => 'vmdiridx',
416 path => '{vmid}',
417 method => 'GET',
418 proxyto => 'node',
419 description => "Directory index",
420 permissions => {
421 user => 'all',
422 },
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' },
448 { subdir => 'migrate' },
449 { subdir => 'rrd' },
450 { subdir => 'rrddata' },
451 { subdir => 'monitor' },
452 ];
453
454 return $res;
455 }});
456
457 __PACKAGE__->register_method({
458 name => 'rrd',
459 path => '{vmid}/rrd',
460 method => 'GET',
461 protected => 1, # fixme: can we avoid that?
462 permissions => {
463 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
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(
498 "pve2-vm/$param->{vmid}", $param->{timeframe},
499 $param->{ds}, $param->{cf});
500
501 }});
502
503 __PACKAGE__->register_method({
504 name => 'rrddata',
505 path => '{vmid}/rrddata',
506 method => 'GET',
507 protected => 1, # fixme: can we avoid that?
508 permissions => {
509 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
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({
546 name => 'vm_config',
547 path => '{vmid}/config',
548 method => 'GET',
549 proxyto => 'node',
550 description => "Get virtual machine configuration.",
551 permissions => {
552 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
553 },
554 parameters => {
555 additionalProperties => 0,
556 properties => {
557 node => get_standard_option('pve-node'),
558 vmid => get_standard_option('pve-vmid'),
559 },
560 },
561 returns => {
562 type => "object",
563 properties => {
564 digest => {
565 type => 'string',
566 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
567 }
568 },
569 },
570 code => sub {
571 my ($param) = @_;
572
573 my $conf = PVE::QemuServer::load_config($param->{vmid});
574
575 return $conf;
576 }});
577
578 my $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
592 my $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
608 my $delete_drive = sub {
609 my ($conf, $storecfg, $vmid, $key, $drive, $force) = @_;
610
611 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
612 my $volid = $drive->{file};
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);
619 }
620 delete $conf->{$key};
621 }
622 }
623 };
624
625 my $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)) {
637 $rpcenv->check_storage_perm($authuser, $vmid, undef, $sid, [ 'Datastore.Allocate' ]);
638 }
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);
646 } else {
647 delete $conf->{$opt};
648 }
649
650 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
651 };
652
653 my $vmconfig_update_disk = sub {
654 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
655
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);
702 }
703 };
704
705 my $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
722 my $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
732 __PACKAGE__->register_method({
733 name => 'update_vm',
734 path => '{vmid}/config',
735 method => 'PUT',
736 protected => 1,
737 proxyto => 'node',
738 description => "Set virtual machine options.",
739 permissions => {
740 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
741 },
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'),
748 skiplock => get_standard_option('skiplock'),
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 },
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,
764 optional => 1,
765 }
766 }),
767 },
768 returns => { type => 'null'},
769 code => sub {
770 my ($param) = @_;
771
772 my $rpcenv = PVE::RPCEnvironment::get();
773
774 my $authuser = $rpcenv->get_user();
775
776 my $node = extract_param($param, 'node');
777
778 my $vmid = extract_param($param, 'vmid');
779
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
787 my $skiplock = extract_param($param, 'skiplock');
788 raise_param_exc({ skiplock => "Only root may use this option." })
789 if $skiplock && $authuser ne 'root@pam';
790
791 my $delete_str = extract_param($param, 'delete');
792
793 my $force = extract_param($param, 'force');
794
795 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
796
797 my $storecfg = PVE::Storage::config();
798
799 &$resolve_cdrom_alias($param);
800
801 # now try to verify all parameters
802
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 }
813
814 push @delete, $opt;
815 }
816
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);
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);
827 }
828 }
829
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
834 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, undef, $param);
835
836 my $updatefn = sub {
837
838 my $conf = PVE::QemuServer::load_config($vmid);
839
840 die "checksum missmatch (file change by other user?)\n"
841 if $digest && $digest ne $conf->{digest};
842
843 PVE::QemuServer::check_lock($conf) if !$skiplock;
844
845 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
846
847 foreach my $opt (@delete) { # delete
848 $conf = PVE::QemuServer::load_config($vmid); # update/reload
849 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
850 }
851
852 foreach my $opt (keys %$param) { # add/change
853
854 $conf = PVE::QemuServer::load_config($vmid); # update/reload
855
856 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
857
858 if (PVE::QemuServer::valid_drivename($opt)) {
859
860 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
861 $opt, $param->{$opt}, $force);
862
863 } elsif ($opt =~ m/^net(\d+)$/) { #nics
864
865 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
866 $opt, $param->{$opt});
867
868 } else {
869
870 $conf->{$opt} = $param->{$opt};
871 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
872 }
873 }
874 };
875
876 PVE::QemuServer::lock_config($vmid, $updatefn);
877
878 return undef;
879 }});
880
881
882 __PACKAGE__->register_method({
883 name => 'destroy_vm',
884 path => '{vmid}',
885 method => 'DELETE',
886 protected => 1,
887 proxyto => 'node',
888 description => "Destroy the vm (also delete all used/owned volumes).",
889 permissions => {
890 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
891 },
892 parameters => {
893 additionalProperties => 0,
894 properties => {
895 node => get_standard_option('pve-node'),
896 vmid => get_standard_option('pve-vmid'),
897 skiplock => get_standard_option('skiplock'),
898 },
899 },
900 returns => {
901 type => 'string',
902 },
903 code => sub {
904 my ($param) = @_;
905
906 my $rpcenv = PVE::RPCEnvironment::get();
907
908 my $authuser = $rpcenv->get_user();
909
910 my $vmid = $param->{vmid};
911
912 my $skiplock = $param->{skiplock};
913 raise_param_exc({ skiplock => "Only root may use this option." })
914 if $skiplock && $authuser ne 'root@pam';
915
916 # test if VM exists
917 my $conf = PVE::QemuServer::load_config($vmid);
918
919 my $storecfg = PVE::Storage::config();
920
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
931 my $realcmd = sub {
932 my $upid = shift;
933
934 syslog('info', "destroy VM $vmid: $upid\n");
935
936 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
937
938 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
939 };
940
941 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
942 }});
943
944 __PACKAGE__->register_method({
945 name => 'unlink',
946 path => '{vmid}/unlink',
947 method => 'PUT',
948 protected => 1,
949 proxyto => 'node',
950 description => "Unlink/delete disk images.",
951 permissions => {
952 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
953 },
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
981 my $sslcert;
982
983 __PACKAGE__->register_method({
984 name => 'vncproxy',
985 path => '{vmid}/vncproxy',
986 method => 'POST',
987 protected => 1,
988 permissions => {
989 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
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 },
999 returns => {
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
1014 my $authuser = $rpcenv->get_user();
1015
1016 my $vmid = $param->{vmid};
1017 my $node = $param->{node};
1018
1019 my $authpath = "/vms/$vmid";
1020
1021 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
1022
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;
1029
1030 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
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
1039 my $timeout = 10;
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)
1051 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1052
1053 PVE::Tools::run_command($cmd);
1054
1055 return;
1056 };
1057
1058 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1059
1060 return {
1061 user => $authuser,
1062 ticket => $ticket,
1063 port => $port,
1064 upid => $upid,
1065 cert => $sslcert,
1066 };
1067 }});
1068
1069 __PACKAGE__->register_method({
1070 name => 'vmcmdidx',
1071 path => '{vmid}/status',
1072 method => 'GET',
1073 proxyto => 'node',
1074 description => "Directory index",
1075 permissions => {
1076 user => 'all',
1077 },
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 ];
1106
1107 return $res;
1108 }});
1109
1110 __PACKAGE__->register_method({
1111 name => 'vm_status',
1112 path => '{vmid}/status/current',
1113 method => 'GET',
1114 proxyto => 'node',
1115 protected => 1, # qemu pid files are only readable by root
1116 description => "Get virtual machine status.",
1117 permissions => {
1118 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1119 },
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
1134 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid});
1135 my $status = $vmstatus->{$param->{vmid}};
1136
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;
1145 }});
1146
1147 __PACKAGE__->register_method({
1148 name => 'vm_start',
1149 path => '{vmid}/status/start',
1150 method => 'POST',
1151 protected => 1,
1152 proxyto => 'node',
1153 description => "Start virtual machine.",
1154 permissions => {
1155 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1156 },
1157 parameters => {
1158 additionalProperties => 0,
1159 properties => {
1160 node => get_standard_option('pve-node'),
1161 vmid => get_standard_option('pve-vmid'),
1162 skiplock => get_standard_option('skiplock'),
1163 stateuri => get_standard_option('pve-qm-stateuri'),
1164 },
1165 },
1166 returns => {
1167 type => 'string',
1168 },
1169 code => sub {
1170 my ($param) = @_;
1171
1172 my $rpcenv = PVE::RPCEnvironment::get();
1173
1174 my $authuser = $rpcenv->get_user();
1175
1176 my $node = extract_param($param, 'node');
1177
1178 my $vmid = extract_param($param, 'vmid');
1179
1180 my $stateuri = extract_param($param, 'stateuri');
1181 raise_param_exc({ stateuri => "Only root may use this option." })
1182 if $stateuri && $authuser ne 'root@pam';
1183
1184 my $skiplock = extract_param($param, 'skiplock');
1185 raise_param_exc({ skiplock => "Only root may use this option." })
1186 if $skiplock && $authuser ne 'root@pam';
1187
1188 my $storecfg = PVE::Storage::config();
1189
1190 my $realcmd = sub {
1191 my $upid = shift;
1192
1193 syslog('info', "start VM $vmid: $upid\n");
1194
1195 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock);
1196
1197 return;
1198 };
1199
1200 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1201 }});
1202
1203 __PACKAGE__->register_method({
1204 name => 'vm_stop',
1205 path => '{vmid}/status/stop',
1206 method => 'POST',
1207 protected => 1,
1208 proxyto => 'node',
1209 description => "Stop virtual machine.",
1210 permissions => {
1211 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1212 },
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'),
1219 timeout => {
1220 description => "Wait maximal timeout seconds.",
1221 type => 'integer',
1222 minimum => 0,
1223 optional => 1,
1224 },
1225 keepActive => {
1226 description => "Do not decativate storage volumes.",
1227 type => 'boolean',
1228 optional => 1,
1229 default => 0,
1230 }
1231 },
1232 },
1233 returns => {
1234 type => 'string',
1235 },
1236 code => sub {
1237 my ($param) = @_;
1238
1239 my $rpcenv = PVE::RPCEnvironment::get();
1240
1241 my $authuser = $rpcenv->get_user();
1242
1243 my $node = extract_param($param, 'node');
1244
1245 my $vmid = extract_param($param, 'vmid');
1246
1247 my $skiplock = extract_param($param, 'skiplock');
1248 raise_param_exc({ skiplock => "Only root may use this option." })
1249 if $skiplock && $authuser ne 'root@pam';
1250
1251 my $keepActive = extract_param($param, 'keepActive');
1252 raise_param_exc({ keepActive => "Only root may use this option." })
1253 if $keepActive && $authuser ne 'root@pam';
1254
1255 my $storecfg = PVE::Storage::config();
1256
1257 my $realcmd = sub {
1258 my $upid = shift;
1259
1260 syslog('info', "stop VM $vmid: $upid\n");
1261
1262 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
1263 $param->{timeout}, 0, 1, $keepActive);
1264
1265 return;
1266 };
1267
1268 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1269 }});
1270
1271 __PACKAGE__->register_method({
1272 name => 'vm_reset',
1273 path => '{vmid}/status/reset',
1274 method => 'POST',
1275 protected => 1,
1276 proxyto => 'node',
1277 description => "Reset virtual machine.",
1278 permissions => {
1279 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1280 },
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 },
1289 returns => {
1290 type => 'string',
1291 },
1292 code => sub {
1293 my ($param) = @_;
1294
1295 my $rpcenv = PVE::RPCEnvironment::get();
1296
1297 my $authuser = $rpcenv->get_user();
1298
1299 my $node = extract_param($param, 'node');
1300
1301 my $vmid = extract_param($param, 'vmid');
1302
1303 my $skiplock = extract_param($param, 'skiplock');
1304 raise_param_exc({ skiplock => "Only root may use this option." })
1305 if $skiplock && $authuser ne 'root@pam';
1306
1307 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1308
1309 my $realcmd = sub {
1310 my $upid = shift;
1311
1312 PVE::QemuServer::vm_reset($vmid, $skiplock);
1313
1314 return;
1315 };
1316
1317 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
1318 }});
1319
1320 __PACKAGE__->register_method({
1321 name => 'vm_shutdown',
1322 path => '{vmid}/status/shutdown',
1323 method => 'POST',
1324 protected => 1,
1325 proxyto => 'node',
1326 description => "Shutdown virtual machine.",
1327 permissions => {
1328 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1329 },
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'),
1336 timeout => {
1337 description => "Wait maximal timeout seconds.",
1338 type => 'integer',
1339 minimum => 0,
1340 optional => 1,
1341 },
1342 forceStop => {
1343 description => "Make sure the VM stops.",
1344 type => 'boolean',
1345 optional => 1,
1346 default => 0,
1347 },
1348 keepActive => {
1349 description => "Do not decativate storage volumes.",
1350 type => 'boolean',
1351 optional => 1,
1352 default => 0,
1353 }
1354 },
1355 },
1356 returns => {
1357 type => 'string',
1358 },
1359 code => sub {
1360 my ($param) = @_;
1361
1362 my $rpcenv = PVE::RPCEnvironment::get();
1363
1364 my $authuser = $rpcenv->get_user();
1365
1366 my $node = extract_param($param, 'node');
1367
1368 my $vmid = extract_param($param, 'vmid');
1369
1370 my $skiplock = extract_param($param, 'skiplock');
1371 raise_param_exc({ skiplock => "Only root may use this option." })
1372 if $skiplock && $authuser ne 'root@pam';
1373
1374 my $keepActive = extract_param($param, 'keepActive');
1375 raise_param_exc({ keepActive => "Only root may use this option." })
1376 if $keepActive && $authuser ne 'root@pam';
1377
1378 my $storecfg = PVE::Storage::config();
1379
1380 my $realcmd = sub {
1381 my $upid = shift;
1382
1383 syslog('info', "shutdown VM $vmid: $upid\n");
1384
1385 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
1386 1, $param->{forceStop}, $keepActive);
1387
1388 return;
1389 };
1390
1391 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
1392 }});
1393
1394 __PACKAGE__->register_method({
1395 name => 'vm_suspend',
1396 path => '{vmid}/status/suspend',
1397 method => 'POST',
1398 protected => 1,
1399 proxyto => 'node',
1400 description => "Suspend virtual machine.",
1401 permissions => {
1402 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1403 },
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 },
1412 returns => {
1413 type => 'string',
1414 },
1415 code => sub {
1416 my ($param) = @_;
1417
1418 my $rpcenv = PVE::RPCEnvironment::get();
1419
1420 my $authuser = $rpcenv->get_user();
1421
1422 my $node = extract_param($param, 'node');
1423
1424 my $vmid = extract_param($param, 'vmid');
1425
1426 my $skiplock = extract_param($param, 'skiplock');
1427 raise_param_exc({ skiplock => "Only root may use this option." })
1428 if $skiplock && $authuser ne 'root@pam';
1429
1430 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1431
1432 my $realcmd = sub {
1433 my $upid = shift;
1434
1435 syslog('info', "suspend VM $vmid: $upid\n");
1436
1437 PVE::QemuServer::vm_suspend($vmid, $skiplock);
1438
1439 return;
1440 };
1441
1442 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
1443 }});
1444
1445 __PACKAGE__->register_method({
1446 name => 'vm_resume',
1447 path => '{vmid}/status/resume',
1448 method => 'POST',
1449 protected => 1,
1450 proxyto => 'node',
1451 description => "Resume virtual machine.",
1452 permissions => {
1453 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1454 },
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 },
1463 returns => {
1464 type => 'string',
1465 },
1466 code => sub {
1467 my ($param) = @_;
1468
1469 my $rpcenv = PVE::RPCEnvironment::get();
1470
1471 my $authuser = $rpcenv->get_user();
1472
1473 my $node = extract_param($param, 'node');
1474
1475 my $vmid = extract_param($param, 'vmid');
1476
1477 my $skiplock = extract_param($param, 'skiplock');
1478 raise_param_exc({ skiplock => "Only root may use this option." })
1479 if $skiplock && $authuser ne 'root@pam';
1480
1481 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1482
1483 my $realcmd = sub {
1484 my $upid = shift;
1485
1486 syslog('info', "resume VM $vmid: $upid\n");
1487
1488 PVE::QemuServer::vm_resume($vmid, $skiplock);
1489
1490 return;
1491 };
1492
1493 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
1494 }});
1495
1496 __PACKAGE__->register_method({
1497 name => 'vm_sendkey',
1498 path => '{vmid}/sendkey',
1499 method => 'PUT',
1500 protected => 1,
1501 proxyto => 'node',
1502 description => "Send key event to virtual machine.",
1503 permissions => {
1504 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1505 },
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
1524 my $authuser = $rpcenv->get_user();
1525
1526 my $node = extract_param($param, 'node');
1527
1528 my $vmid = extract_param($param, 'vmid');
1529
1530 my $skiplock = extract_param($param, 'skiplock');
1531 raise_param_exc({ skiplock => "Only root may use this option." })
1532 if $skiplock && $authuser ne 'root@pam';
1533
1534 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1535
1536 return;
1537 }});
1538
1539 __PACKAGE__->register_method({
1540 name => 'migrate_vm',
1541 path => '{vmid}/migrate',
1542 method => 'POST',
1543 protected => 1,
1544 proxyto => 'node',
1545 description => "Migrate virtual machine. Creates a new migration task.",
1546 permissions => {
1547 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
1548 },
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 },
1567 returns => {
1568 type => 'string',
1569 description => "the task ID.",
1570 },
1571 code => sub {
1572 my ($param) = @_;
1573
1574 my $rpcenv = PVE::RPCEnvironment::get();
1575
1576 my $authuser = $rpcenv->get_user();
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
1591 raise_param_exc({ force => "Only root may use this option." })
1592 if $param->{force} && $authuser ne 'root@pam';
1593
1594 # test if VM exists
1595 my $conf = PVE::QemuServer::load_config($vmid);
1596
1597 # try to detect errors early
1598
1599 PVE::QemuServer::check_lock($conf);
1600
1601 if (PVE::QemuServer::check_running($vmid)) {
1602 die "cant migrate running VM without --online\n"
1603 if !$param->{online};
1604 }
1605
1606 my $realcmd = sub {
1607 my $upid = shift;
1608
1609 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
1610 };
1611
1612 my $upid = $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
1613
1614 return $upid;
1615 }});
1616
1617 __PACKAGE__->register_method({
1618 name => 'monitor',
1619 path => '{vmid}/monitor',
1620 method => 'POST',
1621 protected => 1,
1622 proxyto => 'node',
1623 description => "Execute Qemu monitor commands.",
1624 permissions => {
1625 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
1626 },
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
1655 1;