]> git.proxmox.com Git - qemu-server.git/blob - PVE/API2/Qemu.pm
qm : add resize
[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 => 'rrd' },
456 { subdir => 'rrddata' },
457 { subdir => 'monitor' },
458 ];
459
460 return $res;
461 }});
462
463 __PACKAGE__->register_method({
464 name => 'rrd',
465 path => '{vmid}/rrd',
466 method => 'GET',
467 protected => 1, # fixme: can we avoid that?
468 permissions => {
469 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
470 },
471 description => "Read VM RRD statistics (returns PNG)",
472 parameters => {
473 additionalProperties => 0,
474 properties => {
475 node => get_standard_option('pve-node'),
476 vmid => get_standard_option('pve-vmid'),
477 timeframe => {
478 description => "Specify the time frame you are interested in.",
479 type => 'string',
480 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
481 },
482 ds => {
483 description => "The list of datasources you want to display.",
484 type => 'string', format => 'pve-configid-list',
485 },
486 cf => {
487 description => "The RRD consolidation function",
488 type => 'string',
489 enum => [ 'AVERAGE', 'MAX' ],
490 optional => 1,
491 },
492 },
493 },
494 returns => {
495 type => "object",
496 properties => {
497 filename => { type => 'string' },
498 },
499 },
500 code => sub {
501 my ($param) = @_;
502
503 return PVE::Cluster::create_rrd_graph(
504 "pve2-vm/$param->{vmid}", $param->{timeframe},
505 $param->{ds}, $param->{cf});
506
507 }});
508
509 __PACKAGE__->register_method({
510 name => 'rrddata',
511 path => '{vmid}/rrddata',
512 method => 'GET',
513 protected => 1, # fixme: can we avoid that?
514 permissions => {
515 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
516 },
517 description => "Read VM RRD statistics",
518 parameters => {
519 additionalProperties => 0,
520 properties => {
521 node => get_standard_option('pve-node'),
522 vmid => get_standard_option('pve-vmid'),
523 timeframe => {
524 description => "Specify the time frame you are interested in.",
525 type => 'string',
526 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
527 },
528 cf => {
529 description => "The RRD consolidation function",
530 type => 'string',
531 enum => [ 'AVERAGE', 'MAX' ],
532 optional => 1,
533 },
534 },
535 },
536 returns => {
537 type => "array",
538 items => {
539 type => "object",
540 properties => {},
541 },
542 },
543 code => sub {
544 my ($param) = @_;
545
546 return PVE::Cluster::create_rrd_data(
547 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
548 }});
549
550
551 __PACKAGE__->register_method({
552 name => 'vm_config',
553 path => '{vmid}/config',
554 method => 'GET',
555 proxyto => 'node',
556 description => "Get virtual machine configuration.",
557 permissions => {
558 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
559 },
560 parameters => {
561 additionalProperties => 0,
562 properties => {
563 node => get_standard_option('pve-node'),
564 vmid => get_standard_option('pve-vmid'),
565 },
566 },
567 returns => {
568 type => "object",
569 properties => {
570 digest => {
571 type => 'string',
572 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
573 }
574 },
575 },
576 code => sub {
577 my ($param) = @_;
578
579 my $conf = PVE::QemuServer::load_config($param->{vmid});
580
581 return $conf;
582 }});
583
584 my $vm_is_volid_owner = sub {
585 my ($storecfg, $vmid, $volid) =@_;
586
587 if ($volid !~ m|^/|) {
588 my ($path, $owner);
589 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
590 if ($owner && ($owner == $vmid)) {
591 return 1;
592 }
593 }
594
595 return undef;
596 };
597
598 my $test_deallocate_drive = sub {
599 my ($storecfg, $vmid, $key, $drive, $force) = @_;
600
601 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
602 my $volid = $drive->{file};
603 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
604 if ($force || $key =~ m/^unused/) {
605 my $sid = PVE::Storage::parse_volume_id($volid);
606 return $sid;
607 }
608 }
609 }
610
611 return undef;
612 };
613
614 my $delete_drive = sub {
615 my ($conf, $storecfg, $vmid, $key, $drive, $force) = @_;
616
617 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
618 my $volid = $drive->{file};
619 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
620 if ($force || $key =~ m/^unused/) {
621 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
622 die $@ if $@;
623 } else {
624 PVE::QemuServer::add_unused_volume($conf, $volid, $vmid);
625 }
626 }
627 }
628
629 delete $conf->{$key};
630 };
631
632 my $vmconfig_delete_option = sub {
633 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force) = @_;
634
635 return if !defined($conf->{$opt});
636
637 my $isDisk = PVE::QemuServer::valid_drivename($opt)|| ($opt =~ m/^unused/);
638
639 if ($isDisk) {
640 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
641
642 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
643 if (my $sid = &$test_deallocate_drive($storecfg, $vmid, $opt, $drive, $force)) {
644 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.Allocate']);
645 }
646 }
647
648 die "error hot-unplug $opt" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
649
650 if ($isDisk) {
651 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
652 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive, $force);
653 } else {
654 delete $conf->{$opt};
655 }
656
657 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
658 };
659
660 my $safe_int_ne = sub {
661 my ($a, $b) = @_;
662
663 return 0 if !defined($a) && !defined($b);
664 return 1 if !defined($a);
665 return 1 if !defined($b);
666
667 return $a != $b;
668 };
669
670 my $vmconfig_update_disk = sub {
671 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
672
673 my $drive = PVE::QemuServer::parse_drive($opt, $value);
674
675 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
676 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
677 } else {
678 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
679 }
680
681 if ($conf->{$opt}) {
682
683 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
684
685 my $media = $drive->{media} || 'disk';
686 my $oldmedia = $old_drive->{media} || 'disk';
687 die "unable to change media type\n" if $media ne $oldmedia;
688
689 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
690 ($drive->{file} ne $old_drive->{file})) { # delete old disks
691
692 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
693 $conf = PVE::QemuServer::load_config($vmid); # update/reload
694 }
695
696 if(&$safe_int_ne($drive->{bps}, $old_drive->{bps}) ||
697 &$safe_int_ne($drive->{bps_rd}, $old_drive->{bps_rd}) ||
698 &$safe_int_ne($drive->{bps_wr}, $old_drive->{bps_wr}) ||
699 &$safe_int_ne($drive->{iops}, $old_drive->{iops}) ||
700 &$safe_int_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
701 &$safe_int_ne($drive->{iops_wr}, $old_drive->{iops_wr})) {
702 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);
703 }
704 }
705 }
706
707 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
708 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
709
710 $conf = PVE::QemuServer::load_config($vmid); # update/reload
711 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
712
713 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
714
715 if (PVE::QemuServer::check_running($vmid)) {
716 if ($drive->{file} eq 'none') {
717 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
718 } else {
719 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
720 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt"); #force eject if locked
721 PVE::QemuServer::vm_mon_cmd($vmid, "change",device => "drive-$opt",target => "$path") if $path;
722 }
723 }
724
725 } else { # hotplug new disks
726
727 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
728 }
729 };
730
731 my $vmconfig_resize_disk = sub {
732 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
733
734 my $drive = PVE::QemuServer::parse_drive($opt, $value);
735
736 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
737 die "you can't resize a cdrom";
738 } else {
739 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
740 }
741
742 if ($conf->{$opt}) {
743
744 if (my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
745 my $volid = $drive->{file};
746 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 1);
747 if ($value =~ m/^\+([1-9]\d*(\.\d+)?)([KMG])?$/){
748 my ($sizeextent, $unit) = ($1, $3);
749 if ($unit) {
750 if ($unit eq 'K') {
751 $sizeextent = $sizeextent * 1024;
752 } elsif ($unit eq 'M') {
753 $sizeextent = $sizeextent * 1024 * 1024;
754 } elsif ($unit eq 'G') {
755 $sizeextent = $sizeextent * 1024 * 1024 * 1024;
756 }
757 }
758
759 my $targetsize = $size + int($sizeextent);
760 PVE::QemuServer::qemu_block_resize($vmid, "drive-$opt", $storecfg, $drive->{file}, $targetsize);
761 my $newsize = PVE::Storage::volume_size_info($storecfg, $volid, 1);
762 $drive->{size} = $newsize;
763 $conf->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
764
765 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
766 }
767 }
768 }
769
770 };
771
772 my $vmconfig_update_net = sub {
773 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
774
775 if ($conf->{$opt}) {
776 #if online update, then unplug first
777 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
778 }
779
780 $conf->{$opt} = $value;
781 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
782 $conf = PVE::QemuServer::load_config($vmid); # update/reload
783
784 my $net = PVE::QemuServer::parse_net($conf->{$opt});
785
786 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
787 };
788
789 my $vm_config_perm_list = [
790 'VM.Config.Disk',
791 'VM.Config.CDROM',
792 'VM.Config.CPU',
793 'VM.Config.Memory',
794 'VM.Config.Network',
795 'VM.Config.HWType',
796 'VM.Config.Options',
797 ];
798
799 __PACKAGE__->register_method({
800 name => 'update_vm',
801 path => '{vmid}/config',
802 method => 'PUT',
803 protected => 1,
804 proxyto => 'node',
805 description => "Set virtual machine options.",
806 permissions => {
807 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
808 },
809 parameters => {
810 additionalProperties => 0,
811 properties => PVE::QemuServer::json_config_properties(
812 {
813 node => get_standard_option('pve-node'),
814 vmid => get_standard_option('pve-vmid'),
815 skiplock => get_standard_option('skiplock'),
816 delete => {
817 type => 'string', format => 'pve-configid-list',
818 description => "A list of settings you want to delete.",
819 optional => 1,
820 },
821 force => {
822 type => 'boolean',
823 description => $opt_force_description,
824 optional => 1,
825 requires => 'delete',
826 },
827 digest => {
828 type => 'string',
829 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
830 maxLength => 40,
831 optional => 1,
832 }
833 }),
834 },
835 returns => { type => 'null'},
836 code => sub {
837 my ($param) = @_;
838
839 my $rpcenv = PVE::RPCEnvironment::get();
840
841 my $authuser = $rpcenv->get_user();
842
843 my $node = extract_param($param, 'node');
844
845 my $vmid = extract_param($param, 'vmid');
846
847 my $digest = extract_param($param, 'digest');
848
849 my @paramarr = (); # used for log message
850 foreach my $key (keys %$param) {
851 push @paramarr, "-$key", $param->{$key};
852 }
853
854 my $skiplock = extract_param($param, 'skiplock');
855 raise_param_exc({ skiplock => "Only root may use this option." })
856 if $skiplock && $authuser ne 'root@pam';
857
858 my $delete_str = extract_param($param, 'delete');
859
860 my $force = extract_param($param, 'force');
861
862 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
863
864 my $storecfg = PVE::Storage::config();
865
866 &$resolve_cdrom_alias($param);
867
868 # now try to verify all parameters
869
870 my @delete = ();
871 foreach my $opt (PVE::Tools::split_list($delete_str)) {
872 $opt = 'ide2' if $opt eq 'cdrom';
873 raise_param_exc({ delete => "you can't use '-$opt' and " .
874 "-delete $opt' at the same time" })
875 if defined($param->{$opt});
876
877 if (!PVE::QemuServer::option_exists($opt)) {
878 raise_param_exc({ delete => "unknown option '$opt'" });
879 }
880
881 push @delete, $opt;
882 }
883
884 foreach my $opt (keys %$param) {
885 if (PVE::QemuServer::valid_drivename($opt)) {
886 # cleanup drive path
887 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
888 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
889 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
890 } elsif ($opt =~ m/^net(\d+)$/) {
891 # add macaddr
892 my $net = PVE::QemuServer::parse_net($param->{$opt});
893 $param->{$opt} = PVE::QemuServer::print_net($net);
894 }
895 }
896
897 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
898
899 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
900
901 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
902
903 my $updatefn = sub {
904
905 my $conf = PVE::QemuServer::load_config($vmid);
906
907 die "checksum missmatch (file change by other user?)\n"
908 if $digest && $digest ne $conf->{digest};
909
910 PVE::QemuServer::check_lock($conf) if !$skiplock;
911
912 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
913
914 foreach my $opt (@delete) { # delete
915 $conf = PVE::QemuServer::load_config($vmid); # update/reload
916 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
917 }
918
919 foreach my $opt (keys %$param) { # add/change
920
921 $conf = PVE::QemuServer::load_config($vmid); # update/reload
922
923 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
924
925 if (PVE::QemuServer::valid_drivename($opt)) {
926
927 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
928 $opt, $param->{$opt}, $force);
929
930 } elsif ($opt =~ m/^net(\d+)$/) { #nics
931
932 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
933 $opt, $param->{$opt});
934
935 } else {
936
937 $conf->{$opt} = $param->{$opt};
938 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
939 }
940 }
941 };
942
943 PVE::QemuServer::lock_config($vmid, $updatefn);
944
945 return undef;
946 }});
947
948
949 __PACKAGE__->register_method({
950 name => 'destroy_vm',
951 path => '{vmid}',
952 method => 'DELETE',
953 protected => 1,
954 proxyto => 'node',
955 description => "Destroy the vm (also delete all used/owned volumes).",
956 permissions => {
957 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
958 },
959 parameters => {
960 additionalProperties => 0,
961 properties => {
962 node => get_standard_option('pve-node'),
963 vmid => get_standard_option('pve-vmid'),
964 skiplock => get_standard_option('skiplock'),
965 },
966 },
967 returns => {
968 type => 'string',
969 },
970 code => sub {
971 my ($param) = @_;
972
973 my $rpcenv = PVE::RPCEnvironment::get();
974
975 my $authuser = $rpcenv->get_user();
976
977 my $vmid = $param->{vmid};
978
979 my $skiplock = $param->{skiplock};
980 raise_param_exc({ skiplock => "Only root may use this option." })
981 if $skiplock && $authuser ne 'root@pam';
982
983 # test if VM exists
984 my $conf = PVE::QemuServer::load_config($vmid);
985
986 my $storecfg = PVE::Storage::config();
987
988 my $delVMfromPoolFn = sub {
989 my $usercfg = cfs_read_file("user.cfg");
990 if (my $pool = $usercfg->{vms}->{$vmid}) {
991 if (my $data = $usercfg->{pools}->{$pool}) {
992 delete $data->{vms}->{$vmid};
993 delete $usercfg->{vms}->{$vmid};
994 cfs_write_file("user.cfg", $usercfg);
995 }
996 }
997 };
998
999 my $realcmd = sub {
1000 my $upid = shift;
1001
1002 syslog('info', "destroy VM $vmid: $upid\n");
1003
1004 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
1005
1006 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
1007 };
1008
1009 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1010 }});
1011
1012 __PACKAGE__->register_method({
1013 name => 'unlink',
1014 path => '{vmid}/unlink',
1015 method => 'PUT',
1016 protected => 1,
1017 proxyto => 'node',
1018 description => "Unlink/delete disk images.",
1019 permissions => {
1020 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
1021 },
1022 parameters => {
1023 additionalProperties => 0,
1024 properties => {
1025 node => get_standard_option('pve-node'),
1026 vmid => get_standard_option('pve-vmid'),
1027 idlist => {
1028 type => 'string', format => 'pve-configid-list',
1029 description => "A list of disk IDs you want to delete.",
1030 },
1031 force => {
1032 type => 'boolean',
1033 description => $opt_force_description,
1034 optional => 1,
1035 },
1036 },
1037 },
1038 returns => { type => 'null'},
1039 code => sub {
1040 my ($param) = @_;
1041
1042 $param->{delete} = extract_param($param, 'idlist');
1043
1044 __PACKAGE__->update_vm($param);
1045
1046 return undef;
1047 }});
1048
1049 my $sslcert;
1050
1051 __PACKAGE__->register_method({
1052 name => 'vncproxy',
1053 path => '{vmid}/vncproxy',
1054 method => 'POST',
1055 protected => 1,
1056 permissions => {
1057 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1058 },
1059 description => "Creates a TCP VNC proxy connections.",
1060 parameters => {
1061 additionalProperties => 0,
1062 properties => {
1063 node => get_standard_option('pve-node'),
1064 vmid => get_standard_option('pve-vmid'),
1065 },
1066 },
1067 returns => {
1068 additionalProperties => 0,
1069 properties => {
1070 user => { type => 'string' },
1071 ticket => { type => 'string' },
1072 cert => { type => 'string' },
1073 port => { type => 'integer' },
1074 upid => { type => 'string' },
1075 },
1076 },
1077 code => sub {
1078 my ($param) = @_;
1079
1080 my $rpcenv = PVE::RPCEnvironment::get();
1081
1082 my $authuser = $rpcenv->get_user();
1083
1084 my $vmid = $param->{vmid};
1085 my $node = $param->{node};
1086
1087 my $authpath = "/vms/$vmid";
1088
1089 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
1090
1091 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1092 if !$sslcert;
1093
1094 my $port = PVE::Tools::next_vnc_port();
1095
1096 my $remip;
1097
1098 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1099 $remip = PVE::Cluster::remote_node_ip($node);
1100 }
1101
1102 # NOTE: kvm VNC traffic is already TLS encrypted,
1103 # so we select the fastest chipher here (or 'none'?)
1104 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes',
1105 '-c', 'blowfish-cbc', $remip] : [];
1106
1107 my $timeout = 10;
1108
1109 my $realcmd = sub {
1110 my $upid = shift;
1111
1112 syslog('info', "starting vnc proxy $upid\n");
1113
1114 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1115
1116 my $qmstr = join(' ', @$qmcmd);
1117
1118 # also redirect stderr (else we get RFB protocol errors)
1119 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1120
1121 PVE::Tools::run_command($cmd);
1122
1123 return;
1124 };
1125
1126 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1127
1128 return {
1129 user => $authuser,
1130 ticket => $ticket,
1131 port => $port,
1132 upid => $upid,
1133 cert => $sslcert,
1134 };
1135 }});
1136
1137 __PACKAGE__->register_method({
1138 name => 'vmcmdidx',
1139 path => '{vmid}/status',
1140 method => 'GET',
1141 proxyto => 'node',
1142 description => "Directory index",
1143 permissions => {
1144 user => 'all',
1145 },
1146 parameters => {
1147 additionalProperties => 0,
1148 properties => {
1149 node => get_standard_option('pve-node'),
1150 vmid => get_standard_option('pve-vmid'),
1151 },
1152 },
1153 returns => {
1154 type => 'array',
1155 items => {
1156 type => "object",
1157 properties => {
1158 subdir => { type => 'string' },
1159 },
1160 },
1161 links => [ { rel => 'child', href => "{subdir}" } ],
1162 },
1163 code => sub {
1164 my ($param) = @_;
1165
1166 # test if VM exists
1167 my $conf = PVE::QemuServer::load_config($param->{vmid});
1168
1169 my $res = [
1170 { subdir => 'current' },
1171 { subdir => 'start' },
1172 { subdir => 'stop' },
1173 ];
1174
1175 return $res;
1176 }});
1177
1178 my $vm_is_ha_managed = sub {
1179 my ($vmid) = @_;
1180
1181 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1182 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1183 return 1;
1184 }
1185 return 0;
1186 };
1187
1188 __PACKAGE__->register_method({
1189 name => 'vm_status',
1190 path => '{vmid}/status/current',
1191 method => 'GET',
1192 proxyto => 'node',
1193 protected => 1, # qemu pid files are only readable by root
1194 description => "Get virtual machine status.",
1195 permissions => {
1196 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1197 },
1198 parameters => {
1199 additionalProperties => 0,
1200 properties => {
1201 node => get_standard_option('pve-node'),
1202 vmid => get_standard_option('pve-vmid'),
1203 },
1204 },
1205 returns => { type => 'object' },
1206 code => sub {
1207 my ($param) = @_;
1208
1209 # test if VM exists
1210 my $conf = PVE::QemuServer::load_config($param->{vmid});
1211
1212 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
1213 my $status = $vmstatus->{$param->{vmid}};
1214
1215 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
1216
1217 return $status;
1218 }});
1219
1220 __PACKAGE__->register_method({
1221 name => 'vm_start',
1222 path => '{vmid}/status/start',
1223 method => 'POST',
1224 protected => 1,
1225 proxyto => 'node',
1226 description => "Start virtual machine.",
1227 permissions => {
1228 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1229 },
1230 parameters => {
1231 additionalProperties => 0,
1232 properties => {
1233 node => get_standard_option('pve-node'),
1234 vmid => get_standard_option('pve-vmid'),
1235 skiplock => get_standard_option('skiplock'),
1236 stateuri => get_standard_option('pve-qm-stateuri'),
1237 },
1238 },
1239 returns => {
1240 type => 'string',
1241 },
1242 code => sub {
1243 my ($param) = @_;
1244
1245 my $rpcenv = PVE::RPCEnvironment::get();
1246
1247 my $authuser = $rpcenv->get_user();
1248
1249 my $node = extract_param($param, 'node');
1250
1251 my $vmid = extract_param($param, 'vmid');
1252
1253 my $stateuri = extract_param($param, 'stateuri');
1254 raise_param_exc({ stateuri => "Only root may use this option." })
1255 if $stateuri && $authuser ne 'root@pam';
1256
1257 my $skiplock = extract_param($param, 'skiplock');
1258 raise_param_exc({ skiplock => "Only root may use this option." })
1259 if $skiplock && $authuser ne 'root@pam';
1260
1261 my $storecfg = PVE::Storage::config();
1262
1263 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1264 $rpcenv->{type} ne 'ha') {
1265
1266 my $hacmd = sub {
1267 my $upid = shift;
1268
1269 my $service = "pvevm:$vmid";
1270
1271 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1272
1273 print "Executing HA start for VM $vmid\n";
1274
1275 PVE::Tools::run_command($cmd);
1276
1277 return;
1278 };
1279
1280 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1281
1282 } else {
1283
1284 my $realcmd = sub {
1285 my $upid = shift;
1286
1287 syslog('info', "start VM $vmid: $upid\n");
1288
1289 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock);
1290
1291 return;
1292 };
1293
1294 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1295 }
1296 }});
1297
1298 __PACKAGE__->register_method({
1299 name => 'vm_stop',
1300 path => '{vmid}/status/stop',
1301 method => 'POST',
1302 protected => 1,
1303 proxyto => 'node',
1304 description => "Stop virtual machine.",
1305 permissions => {
1306 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1307 },
1308 parameters => {
1309 additionalProperties => 0,
1310 properties => {
1311 node => get_standard_option('pve-node'),
1312 vmid => get_standard_option('pve-vmid'),
1313 skiplock => get_standard_option('skiplock'),
1314 timeout => {
1315 description => "Wait maximal timeout seconds.",
1316 type => 'integer',
1317 minimum => 0,
1318 optional => 1,
1319 },
1320 keepActive => {
1321 description => "Do not decativate storage volumes.",
1322 type => 'boolean',
1323 optional => 1,
1324 default => 0,
1325 }
1326 },
1327 },
1328 returns => {
1329 type => 'string',
1330 },
1331 code => sub {
1332 my ($param) = @_;
1333
1334 my $rpcenv = PVE::RPCEnvironment::get();
1335
1336 my $authuser = $rpcenv->get_user();
1337
1338 my $node = extract_param($param, 'node');
1339
1340 my $vmid = extract_param($param, 'vmid');
1341
1342 my $skiplock = extract_param($param, 'skiplock');
1343 raise_param_exc({ skiplock => "Only root may use this option." })
1344 if $skiplock && $authuser ne 'root@pam';
1345
1346 my $keepActive = extract_param($param, 'keepActive');
1347 raise_param_exc({ keepActive => "Only root may use this option." })
1348 if $keepActive && $authuser ne 'root@pam';
1349
1350 my $storecfg = PVE::Storage::config();
1351
1352 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
1353
1354 my $hacmd = sub {
1355 my $upid = shift;
1356
1357 my $service = "pvevm:$vmid";
1358
1359 my $cmd = ['clusvcadm', '-d', $service];
1360
1361 print "Executing HA stop for VM $vmid\n";
1362
1363 PVE::Tools::run_command($cmd);
1364
1365 return;
1366 };
1367
1368 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1369
1370 } else {
1371 my $realcmd = sub {
1372 my $upid = shift;
1373
1374 syslog('info', "stop VM $vmid: $upid\n");
1375
1376 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
1377 $param->{timeout}, 0, 1, $keepActive);
1378
1379 return;
1380 };
1381
1382 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1383 }
1384 }});
1385
1386 __PACKAGE__->register_method({
1387 name => 'vm_reset',
1388 path => '{vmid}/status/reset',
1389 method => 'POST',
1390 protected => 1,
1391 proxyto => 'node',
1392 description => "Reset virtual machine.",
1393 permissions => {
1394 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1395 },
1396 parameters => {
1397 additionalProperties => 0,
1398 properties => {
1399 node => get_standard_option('pve-node'),
1400 vmid => get_standard_option('pve-vmid'),
1401 skiplock => get_standard_option('skiplock'),
1402 },
1403 },
1404 returns => {
1405 type => 'string',
1406 },
1407 code => sub {
1408 my ($param) = @_;
1409
1410 my $rpcenv = PVE::RPCEnvironment::get();
1411
1412 my $authuser = $rpcenv->get_user();
1413
1414 my $node = extract_param($param, 'node');
1415
1416 my $vmid = extract_param($param, 'vmid');
1417
1418 my $skiplock = extract_param($param, 'skiplock');
1419 raise_param_exc({ skiplock => "Only root may use this option." })
1420 if $skiplock && $authuser ne 'root@pam';
1421
1422 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1423
1424 my $realcmd = sub {
1425 my $upid = shift;
1426
1427 PVE::QemuServer::vm_reset($vmid, $skiplock);
1428
1429 return;
1430 };
1431
1432 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
1433 }});
1434
1435 __PACKAGE__->register_method({
1436 name => 'vm_shutdown',
1437 path => '{vmid}/status/shutdown',
1438 method => 'POST',
1439 protected => 1,
1440 proxyto => 'node',
1441 description => "Shutdown virtual machine.",
1442 permissions => {
1443 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1444 },
1445 parameters => {
1446 additionalProperties => 0,
1447 properties => {
1448 node => get_standard_option('pve-node'),
1449 vmid => get_standard_option('pve-vmid'),
1450 skiplock => get_standard_option('skiplock'),
1451 timeout => {
1452 description => "Wait maximal timeout seconds.",
1453 type => 'integer',
1454 minimum => 0,
1455 optional => 1,
1456 },
1457 forceStop => {
1458 description => "Make sure the VM stops.",
1459 type => 'boolean',
1460 optional => 1,
1461 default => 0,
1462 },
1463 keepActive => {
1464 description => "Do not decativate storage volumes.",
1465 type => 'boolean',
1466 optional => 1,
1467 default => 0,
1468 }
1469 },
1470 },
1471 returns => {
1472 type => 'string',
1473 },
1474 code => sub {
1475 my ($param) = @_;
1476
1477 my $rpcenv = PVE::RPCEnvironment::get();
1478
1479 my $authuser = $rpcenv->get_user();
1480
1481 my $node = extract_param($param, 'node');
1482
1483 my $vmid = extract_param($param, 'vmid');
1484
1485 my $skiplock = extract_param($param, 'skiplock');
1486 raise_param_exc({ skiplock => "Only root may use this option." })
1487 if $skiplock && $authuser ne 'root@pam';
1488
1489 my $keepActive = extract_param($param, 'keepActive');
1490 raise_param_exc({ keepActive => "Only root may use this option." })
1491 if $keepActive && $authuser ne 'root@pam';
1492
1493 my $storecfg = PVE::Storage::config();
1494
1495 my $realcmd = sub {
1496 my $upid = shift;
1497
1498 syslog('info', "shutdown VM $vmid: $upid\n");
1499
1500 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
1501 1, $param->{forceStop}, $keepActive);
1502
1503 return;
1504 };
1505
1506 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
1507 }});
1508
1509 __PACKAGE__->register_method({
1510 name => 'vm_suspend',
1511 path => '{vmid}/status/suspend',
1512 method => 'POST',
1513 protected => 1,
1514 proxyto => 'node',
1515 description => "Suspend virtual machine.",
1516 permissions => {
1517 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1518 },
1519 parameters => {
1520 additionalProperties => 0,
1521 properties => {
1522 node => get_standard_option('pve-node'),
1523 vmid => get_standard_option('pve-vmid'),
1524 skiplock => get_standard_option('skiplock'),
1525 },
1526 },
1527 returns => {
1528 type => 'string',
1529 },
1530 code => sub {
1531 my ($param) = @_;
1532
1533 my $rpcenv = PVE::RPCEnvironment::get();
1534
1535 my $authuser = $rpcenv->get_user();
1536
1537 my $node = extract_param($param, 'node');
1538
1539 my $vmid = extract_param($param, 'vmid');
1540
1541 my $skiplock = extract_param($param, 'skiplock');
1542 raise_param_exc({ skiplock => "Only root may use this option." })
1543 if $skiplock && $authuser ne 'root@pam';
1544
1545 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1546
1547 my $realcmd = sub {
1548 my $upid = shift;
1549
1550 syslog('info', "suspend VM $vmid: $upid\n");
1551
1552 PVE::QemuServer::vm_suspend($vmid, $skiplock);
1553
1554 return;
1555 };
1556
1557 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
1558 }});
1559
1560 __PACKAGE__->register_method({
1561 name => 'vm_resume',
1562 path => '{vmid}/status/resume',
1563 method => 'POST',
1564 protected => 1,
1565 proxyto => 'node',
1566 description => "Resume virtual machine.",
1567 permissions => {
1568 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1569 },
1570 parameters => {
1571 additionalProperties => 0,
1572 properties => {
1573 node => get_standard_option('pve-node'),
1574 vmid => get_standard_option('pve-vmid'),
1575 skiplock => get_standard_option('skiplock'),
1576 },
1577 },
1578 returns => {
1579 type => 'string',
1580 },
1581 code => sub {
1582 my ($param) = @_;
1583
1584 my $rpcenv = PVE::RPCEnvironment::get();
1585
1586 my $authuser = $rpcenv->get_user();
1587
1588 my $node = extract_param($param, 'node');
1589
1590 my $vmid = extract_param($param, 'vmid');
1591
1592 my $skiplock = extract_param($param, 'skiplock');
1593 raise_param_exc({ skiplock => "Only root may use this option." })
1594 if $skiplock && $authuser ne 'root@pam';
1595
1596 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1597
1598 my $realcmd = sub {
1599 my $upid = shift;
1600
1601 syslog('info', "resume VM $vmid: $upid\n");
1602
1603 PVE::QemuServer::vm_resume($vmid, $skiplock);
1604
1605 return;
1606 };
1607
1608 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
1609 }});
1610
1611 __PACKAGE__->register_method({
1612 name => 'vm_sendkey',
1613 path => '{vmid}/sendkey',
1614 method => 'PUT',
1615 protected => 1,
1616 proxyto => 'node',
1617 description => "Send key event to virtual machine.",
1618 permissions => {
1619 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1620 },
1621 parameters => {
1622 additionalProperties => 0,
1623 properties => {
1624 node => get_standard_option('pve-node'),
1625 vmid => get_standard_option('pve-vmid'),
1626 skiplock => get_standard_option('skiplock'),
1627 key => {
1628 description => "The key (qemu monitor encoding).",
1629 type => 'string'
1630 }
1631 },
1632 },
1633 returns => { type => 'null'},
1634 code => sub {
1635 my ($param) = @_;
1636
1637 my $rpcenv = PVE::RPCEnvironment::get();
1638
1639 my $authuser = $rpcenv->get_user();
1640
1641 my $node = extract_param($param, 'node');
1642
1643 my $vmid = extract_param($param, 'vmid');
1644
1645 my $skiplock = extract_param($param, 'skiplock');
1646 raise_param_exc({ skiplock => "Only root may use this option." })
1647 if $skiplock && $authuser ne 'root@pam';
1648
1649 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1650
1651 return;
1652 }});
1653
1654 __PACKAGE__->register_method({
1655 name => 'migrate_vm',
1656 path => '{vmid}/migrate',
1657 method => 'POST',
1658 protected => 1,
1659 proxyto => 'node',
1660 description => "Migrate virtual machine. Creates a new migration task.",
1661 permissions => {
1662 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
1663 },
1664 parameters => {
1665 additionalProperties => 0,
1666 properties => {
1667 node => get_standard_option('pve-node'),
1668 vmid => get_standard_option('pve-vmid'),
1669 target => get_standard_option('pve-node', { description => "Target node." }),
1670 online => {
1671 type => 'boolean',
1672 description => "Use online/live migration.",
1673 optional => 1,
1674 },
1675 force => {
1676 type => 'boolean',
1677 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
1678 optional => 1,
1679 },
1680 },
1681 },
1682 returns => {
1683 type => 'string',
1684 description => "the task ID.",
1685 },
1686 code => sub {
1687 my ($param) = @_;
1688
1689 my $rpcenv = PVE::RPCEnvironment::get();
1690
1691 my $authuser = $rpcenv->get_user();
1692
1693 my $target = extract_param($param, 'target');
1694
1695 my $localnode = PVE::INotify::nodename();
1696 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
1697
1698 PVE::Cluster::check_cfs_quorum();
1699
1700 PVE::Cluster::check_node_exists($target);
1701
1702 my $targetip = PVE::Cluster::remote_node_ip($target);
1703
1704 my $vmid = extract_param($param, 'vmid');
1705
1706 raise_param_exc({ force => "Only root may use this option." })
1707 if $param->{force} && $authuser ne 'root@pam';
1708
1709 # test if VM exists
1710 my $conf = PVE::QemuServer::load_config($vmid);
1711
1712 # try to detect errors early
1713
1714 PVE::QemuServer::check_lock($conf);
1715
1716 if (PVE::QemuServer::check_running($vmid)) {
1717 die "cant migrate running VM without --online\n"
1718 if !$param->{online};
1719 }
1720
1721 my $storecfg = PVE::Storage::config();
1722 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
1723
1724 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
1725
1726 my $hacmd = sub {
1727 my $upid = shift;
1728
1729 my $service = "pvevm:$vmid";
1730
1731 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
1732
1733 print "Executing HA migrate for VM $vmid to node $target\n";
1734
1735 PVE::Tools::run_command($cmd);
1736
1737 return;
1738 };
1739
1740 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
1741
1742 } else {
1743
1744 my $realcmd = sub {
1745 my $upid = shift;
1746
1747 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
1748 };
1749
1750 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
1751 }
1752
1753 }});
1754
1755 __PACKAGE__->register_method({
1756 name => 'monitor',
1757 path => '{vmid}/monitor',
1758 method => 'POST',
1759 protected => 1,
1760 proxyto => 'node',
1761 description => "Execute Qemu monitor commands.",
1762 permissions => {
1763 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
1764 },
1765 parameters => {
1766 additionalProperties => 0,
1767 properties => {
1768 node => get_standard_option('pve-node'),
1769 vmid => get_standard_option('pve-vmid'),
1770 command => {
1771 type => 'string',
1772 description => "The monitor command.",
1773 }
1774 },
1775 },
1776 returns => { type => 'string'},
1777 code => sub {
1778 my ($param) = @_;
1779
1780 my $vmid = $param->{vmid};
1781
1782 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
1783
1784 my $res = '';
1785 eval {
1786 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
1787 };
1788 $res = "ERROR: $@" if $@;
1789
1790 return $res;
1791 }});
1792
1793 __PACKAGE__->register_method({
1794 name => 'resize_vm',
1795 path => '{vmid}/config',
1796 method => 'PUT',
1797 protected => 1,
1798 proxyto => 'node',
1799 description => "extend volume size.",
1800 permissions => {
1801 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
1802 },
1803 parameters => {
1804 additionalProperties => 0,
1805 properties => PVE::QemuServer::json_config_properties(
1806 {
1807 node => get_standard_option('pve-node'),
1808 vmid => get_standard_option('pve-vmid'),
1809 skiplock => get_standard_option('skiplock'),
1810 digest => {
1811 type => 'string',
1812 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1813 maxLength => 40,
1814 optional => 1,
1815 }
1816 }),
1817 },
1818 returns => { type => 'null'},
1819 code => sub {
1820 my ($param) = @_;
1821
1822 my $rpcenv = PVE::RPCEnvironment::get();
1823
1824 my $authuser = $rpcenv->get_user();
1825
1826 my $node = extract_param($param, 'node');
1827
1828 my $vmid = extract_param($param, 'vmid');
1829
1830 my $digest = extract_param($param, 'digest');
1831
1832 my @paramarr = (); # used for log message
1833 foreach my $key (keys %$param) {
1834 push @paramarr, "-$key", $param->{$key};
1835 }
1836
1837 my $skiplock = extract_param($param, 'skiplock');
1838 raise_param_exc({ skiplock => "Only root may use this option." })
1839 if $skiplock && $authuser ne 'root@pam';
1840
1841 my $force = extract_param($param, 'force');
1842
1843 die "no options specified\n" if !scalar(keys %$param);
1844
1845 my $storecfg = PVE::Storage::config();
1846
1847
1848 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
1849
1850 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1851
1852 my $updatefn = sub {
1853
1854 my $conf = PVE::QemuServer::load_config($vmid);
1855
1856 die "checksum missmatch (file change by other user?)\n"
1857 if $digest && $digest ne $conf->{digest};
1858 PVE::QemuServer::check_lock($conf) if !$skiplock;
1859
1860 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
1861
1862 foreach my $opt (keys %$param) { # add/change
1863 if (PVE::QemuServer::valid_drivename($opt)) {
1864 &$vmconfig_resize_disk($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $param->{$opt}, $force);
1865 }
1866 }
1867
1868 };
1869
1870 PVE::QemuServer::lock_config($vmid, $updatefn);
1871 return undef;
1872 }});
1873
1874 1;