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