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