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