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