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