]> git.proxmox.com Git - qemu-server.git/blob - PVE/API2/Qemu.pm
6d02ded146f6ab753d89e870ef997ad1ba4e1d4c
[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 use PVE::Network;
20
21 use Data::Dumper; # fixme: remove
22
23 use base qw(PVE::RESTHandler);
24
25 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.";
26
27 my $resolve_cdrom_alias = sub {
28 my $param = shift;
29
30 if (my $value = $param->{cdrom}) {
31 $value .= ",media=cdrom" if $value !~ m/media=/;
32 $param->{ide2} = $value;
33 delete $param->{cdrom};
34 }
35 };
36
37
38 my $check_storage_access = sub {
39 my ($rpcenv, $authuser, $storecfg, $vmid, $settings, $default_storage) = @_;
40
41 PVE::QemuServer::foreach_drive($settings, sub {
42 my ($ds, $drive) = @_;
43
44 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
45
46 my $volid = $drive->{file};
47
48 if (!$volid || $volid eq 'none') {
49 # nothing to check
50 } elsif ($isCDROM && ($volid eq 'cdrom')) {
51 $rpcenv->check($authuser, "/", ['Sys.Console']);
52 } elsif (!$isCDROM && ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/)) {
53 my ($storeid, $size) = ($2 || $default_storage, $3);
54 die "no storage ID specified (and no default storage)\n" if !$storeid;
55 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
56 } else {
57 $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $volid);
58 }
59 });
60 };
61
62 my $check_storage_access_copy = sub {
63 my ($rpcenv, $authuser, $storecfg, $conf, $storage) = @_;
64
65 my $sharedvm = 1;
66
67 PVE::QemuServer::foreach_drive($conf, sub {
68 my ($ds, $drive) = @_;
69
70 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
71
72 my $volid = $drive->{file};
73
74 return if !$volid || $volid eq 'none';
75
76 if ($isCDROM) {
77 if ($volid eq 'cdrom') {
78 $rpcenv->check($authuser, "/", ['Sys.Console']);
79 } else {
80 # we simply allow access
81 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
82 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
83 $sharedvm = 0 if !$scfg->{shared};
84
85 }
86 } else {
87 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
88 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
89 $sharedvm = 0 if !$scfg->{shared};
90
91 $sid = $storage if $storage;
92 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
93 }
94 });
95
96 return $sharedvm;
97 };
98
99 # Note: $pool is only needed when creating a VM, because pool permissions
100 # are automatically inherited if VM already exists inside a pool.
101 my $create_disks = sub {
102 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
103
104 my $vollist = [];
105
106 my $res = {};
107 PVE::QemuServer::foreach_drive($settings, sub {
108 my ($ds, $disk) = @_;
109
110 my $volid = $disk->{file};
111
112 if (!$volid || $volid eq 'none' || $volid eq 'cdrom') {
113 delete $disk->{size};
114 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
115 } elsif ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/) {
116 my ($storeid, $size) = ($2 || $default_storage, $3);
117 die "no storage ID specified (and no default storage)\n" if !$storeid;
118 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
119 my $fmt = $disk->{format} || $defformat;
120 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid,
121 $fmt, undef, $size*1024*1024);
122 $disk->{file} = $volid;
123 $disk->{size} = $size*1024*1024*1024;
124 push @$vollist, $volid;
125 delete $disk->{format}; # no longer needed
126 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
127 } else {
128
129 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $volid);
130
131 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
132
133 my $foundvolid = undef;
134
135 if ($storeid) {
136 PVE::Storage::activate_volumes($storecfg, [ $volid ]);
137 my $dl = PVE::Storage::vdisk_list($storecfg, $storeid, undef);
138
139 PVE::Storage::foreach_volid($dl, sub {
140 my ($volumeid) = @_;
141 if($volumeid eq $volid) {
142 $foundvolid = 1;
143 return;
144 }
145 });
146 }
147
148 die "image '$path' does not exists\n" if (!(-f $path || -b $path || $foundvolid));
149
150 my ($size) = PVE::Storage::volume_size_info($storecfg, $volid, 1);
151 $disk->{size} = $size;
152 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
153 }
154 });
155
156 # free allocated images on error
157 if (my $err = $@) {
158 syslog('err', "VM $vmid creating disks failed");
159 foreach my $volid (@$vollist) {
160 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
161 warn $@ if $@;
162 }
163 die $err;
164 }
165
166 # modify vm config if everything went well
167 foreach my $ds (keys %$res) {
168 $conf->{$ds} = $res->{$ds};
169 }
170
171 return $vollist;
172 };
173
174 my $check_vm_modify_config_perm = sub {
175 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
176
177 return 1 if $authuser eq 'root@pam';
178
179 foreach my $opt (@$key_list) {
180 # disk checks need to be done somewhere else
181 next if PVE::QemuServer::valid_drivename($opt);
182
183 if ($opt eq 'sockets' || $opt eq 'cores' ||
184 $opt eq 'cpu' || $opt eq 'smp' ||
185 $opt eq 'cpulimit' || $opt eq 'cpuunits') {
186 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
187 } elsif ($opt eq 'boot' || $opt eq 'bootdisk') {
188 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
189 } elsif ($opt eq 'memory' || $opt eq 'balloon' || $opt eq 'shares') {
190 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
191 } elsif ($opt eq 'args' || $opt eq 'lock') {
192 die "only root can set '$opt' config\n";
193 } elsif ($opt eq 'cpu' || $opt eq 'kvm' || $opt eq 'acpi' ||
194 $opt eq 'vga' || $opt eq 'watchdog' || $opt eq 'tablet') {
195 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
196 } elsif ($opt =~ m/^net\d+$/) {
197 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
198 } else {
199 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
200 }
201 }
202
203 return 1;
204 };
205
206 __PACKAGE__->register_method({
207 name => 'vmlist',
208 path => '',
209 method => 'GET',
210 description => "Virtual machine index (per node).",
211 permissions => {
212 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
213 user => 'all',
214 },
215 proxyto => 'node',
216 protected => 1, # qemu pid files are only readable by root
217 parameters => {
218 additionalProperties => 0,
219 properties => {
220 node => get_standard_option('pve-node'),
221 },
222 },
223 returns => {
224 type => 'array',
225 items => {
226 type => "object",
227 properties => {},
228 },
229 links => [ { rel => 'child', href => "{vmid}" } ],
230 },
231 code => sub {
232 my ($param) = @_;
233
234 my $rpcenv = PVE::RPCEnvironment::get();
235 my $authuser = $rpcenv->get_user();
236
237 my $vmstatus = PVE::QemuServer::vmstatus();
238
239 my $res = [];
240 foreach my $vmid (keys %$vmstatus) {
241 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
242
243 my $data = $vmstatus->{$vmid};
244 $data->{vmid} = $vmid;
245 push @$res, $data;
246 }
247
248 return $res;
249 }});
250
251 __PACKAGE__->register_method({
252 name => 'create_vm',
253 path => '',
254 method => 'POST',
255 description => "Create or restore a virtual machine.",
256 permissions => {
257 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.",
258 check => [ 'or',
259 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
260 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
261 ],
262 },
263 protected => 1,
264 proxyto => 'node',
265 parameters => {
266 additionalProperties => 0,
267 properties => PVE::QemuServer::json_config_properties(
268 {
269 node => get_standard_option('pve-node'),
270 vmid => get_standard_option('pve-vmid'),
271 archive => {
272 description => "The backup file.",
273 type => 'string',
274 optional => 1,
275 maxLength => 255,
276 },
277 storage => get_standard_option('pve-storage-id', {
278 description => "Default storage.",
279 optional => 1,
280 }),
281 force => {
282 optional => 1,
283 type => 'boolean',
284 description => "Allow to overwrite existing VM.",
285 requires => 'archive',
286 },
287 unique => {
288 optional => 1,
289 type => 'boolean',
290 description => "Assign a unique random ethernet address.",
291 requires => 'archive',
292 },
293 pool => {
294 optional => 1,
295 type => 'string', format => 'pve-poolid',
296 description => "Add the VM to the specified pool.",
297 },
298 }),
299 },
300 returns => {
301 type => 'string',
302 },
303 code => sub {
304 my ($param) = @_;
305
306 my $rpcenv = PVE::RPCEnvironment::get();
307
308 my $authuser = $rpcenv->get_user();
309
310 my $node = extract_param($param, 'node');
311
312 my $vmid = extract_param($param, 'vmid');
313
314 my $archive = extract_param($param, 'archive');
315
316 my $storage = extract_param($param, 'storage');
317
318 my $force = extract_param($param, 'force');
319
320 my $unique = extract_param($param, 'unique');
321
322 my $pool = extract_param($param, 'pool');
323
324 my $filename = PVE::QemuServer::config_file($vmid);
325
326 my $storecfg = PVE::Storage::config();
327
328 PVE::Cluster::check_cfs_quorum();
329
330 if (defined($pool)) {
331 $rpcenv->check_pool_exist($pool);
332 }
333
334 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace'])
335 if defined($storage);
336
337 if (!$archive) {
338 &$resolve_cdrom_alias($param);
339
340 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param, $storage);
341
342 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
343
344 foreach my $opt (keys %$param) {
345 if (PVE::QemuServer::valid_drivename($opt)) {
346 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
347 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
348
349 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
350 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
351 }
352 }
353
354 PVE::QemuServer::add_random_macs($param);
355 } else {
356 my $keystr = join(' ', keys %$param);
357 raise_param_exc({ archive => "option conflicts with other options ($keystr)"}) if $keystr;
358
359 if ($archive eq '-') {
360 die "pipe requires cli environment\n"
361 if $rpcenv->{type} ne 'cli';
362 } else {
363 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $archive);
364
365 PVE::Storage::activate_volumes($storecfg, [ $archive ])
366 if PVE::Storage::parse_volume_id ($archive, 1);
367
368 die "can't find archive file '$archive'\n" if !($path && -f $path);
369 $archive = $path;
370 }
371 }
372
373 my $addVMtoPoolFn = sub {
374 my $usercfg = cfs_read_file("user.cfg");
375 if (my $data = $usercfg->{pools}->{$pool}) {
376 $data->{vms}->{$vmid} = 1;
377 $usercfg->{vms}->{$vmid} = $pool;
378 cfs_write_file("user.cfg", $usercfg);
379 }
380 };
381
382 my $restorefn = sub {
383
384 # fixme: this test does not work if VM exists on other node!
385 if (-f $filename) {
386 die "unable to restore vm $vmid: config file already exists\n"
387 if !$force;
388
389 die "unable to restore vm $vmid: vm is running\n"
390 if PVE::QemuServer::check_running($vmid);
391 }
392
393 my $realcmd = sub {
394 PVE::QemuServer::restore_archive($archive, $vmid, $authuser, {
395 storage => $storage,
396 pool => $pool,
397 unique => $unique });
398
399 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
400 };
401
402 return $rpcenv->fork_worker('qmrestore', $vmid, $authuser, $realcmd);
403 };
404
405 my $createfn = sub {
406
407 # test after locking
408 die "unable to create vm $vmid: config file already exists\n"
409 if -f $filename;
410
411 my $realcmd = sub {
412
413 my $vollist = [];
414
415 my $conf = $param;
416
417 eval {
418
419 $vollist = &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $param, $storage);
420
421 # try to be smart about bootdisk
422 my @disks = PVE::QemuServer::disknames();
423 my $firstdisk;
424 foreach my $ds (reverse @disks) {
425 next if !$conf->{$ds};
426 my $disk = PVE::QemuServer::parse_drive($ds, $conf->{$ds});
427 next if PVE::QemuServer::drive_is_cdrom($disk);
428 $firstdisk = $ds;
429 }
430
431 if (!$conf->{bootdisk} && $firstdisk) {
432 $conf->{bootdisk} = $firstdisk;
433 }
434
435 PVE::QemuServer::update_config_nolock($vmid, $conf);
436
437 };
438 my $err = $@;
439
440 if ($err) {
441 foreach my $volid (@$vollist) {
442 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
443 warn $@ if $@;
444 }
445 die "create failed - $err";
446 }
447
448 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
449 };
450
451 return $rpcenv->fork_worker('qmcreate', $vmid, $authuser, $realcmd);
452 };
453
454 return PVE::QemuServer::lock_config_full($vmid, 1, $archive ? $restorefn : $createfn);
455 }});
456
457 __PACKAGE__->register_method({
458 name => 'vmdiridx',
459 path => '{vmid}',
460 method => 'GET',
461 proxyto => 'node',
462 description => "Directory index",
463 permissions => {
464 user => 'all',
465 },
466 parameters => {
467 additionalProperties => 0,
468 properties => {
469 node => get_standard_option('pve-node'),
470 vmid => get_standard_option('pve-vmid'),
471 },
472 },
473 returns => {
474 type => 'array',
475 items => {
476 type => "object",
477 properties => {
478 subdir => { type => 'string' },
479 },
480 },
481 links => [ { rel => 'child', href => "{subdir}" } ],
482 },
483 code => sub {
484 my ($param) = @_;
485
486 my $res = [
487 { subdir => 'config' },
488 { subdir => 'status' },
489 { subdir => 'unlink' },
490 { subdir => 'vncproxy' },
491 { subdir => 'migrate' },
492 { subdir => 'resize' },
493 { subdir => 'rrd' },
494 { subdir => 'rrddata' },
495 { subdir => 'monitor' },
496 { subdir => 'snapshot' },
497 ];
498
499 return $res;
500 }});
501
502 __PACKAGE__->register_method({
503 name => 'rrd',
504 path => '{vmid}/rrd',
505 method => 'GET',
506 protected => 1, # fixme: can we avoid that?
507 permissions => {
508 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
509 },
510 description => "Read VM RRD statistics (returns PNG)",
511 parameters => {
512 additionalProperties => 0,
513 properties => {
514 node => get_standard_option('pve-node'),
515 vmid => get_standard_option('pve-vmid'),
516 timeframe => {
517 description => "Specify the time frame you are interested in.",
518 type => 'string',
519 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
520 },
521 ds => {
522 description => "The list of datasources you want to display.",
523 type => 'string', format => 'pve-configid-list',
524 },
525 cf => {
526 description => "The RRD consolidation function",
527 type => 'string',
528 enum => [ 'AVERAGE', 'MAX' ],
529 optional => 1,
530 },
531 },
532 },
533 returns => {
534 type => "object",
535 properties => {
536 filename => { type => 'string' },
537 },
538 },
539 code => sub {
540 my ($param) = @_;
541
542 return PVE::Cluster::create_rrd_graph(
543 "pve2-vm/$param->{vmid}", $param->{timeframe},
544 $param->{ds}, $param->{cf});
545
546 }});
547
548 __PACKAGE__->register_method({
549 name => 'rrddata',
550 path => '{vmid}/rrddata',
551 method => 'GET',
552 protected => 1, # fixme: can we avoid that?
553 permissions => {
554 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
555 },
556 description => "Read VM RRD statistics",
557 parameters => {
558 additionalProperties => 0,
559 properties => {
560 node => get_standard_option('pve-node'),
561 vmid => get_standard_option('pve-vmid'),
562 timeframe => {
563 description => "Specify the time frame you are interested in.",
564 type => 'string',
565 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
566 },
567 cf => {
568 description => "The RRD consolidation function",
569 type => 'string',
570 enum => [ 'AVERAGE', 'MAX' ],
571 optional => 1,
572 },
573 },
574 },
575 returns => {
576 type => "array",
577 items => {
578 type => "object",
579 properties => {},
580 },
581 },
582 code => sub {
583 my ($param) = @_;
584
585 return PVE::Cluster::create_rrd_data(
586 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
587 }});
588
589
590 __PACKAGE__->register_method({
591 name => 'vm_config',
592 path => '{vmid}/config',
593 method => 'GET',
594 proxyto => 'node',
595 description => "Get virtual machine configuration.",
596 permissions => {
597 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
598 },
599 parameters => {
600 additionalProperties => 0,
601 properties => {
602 node => get_standard_option('pve-node'),
603 vmid => get_standard_option('pve-vmid'),
604 },
605 },
606 returns => {
607 type => "object",
608 properties => {
609 digest => {
610 type => 'string',
611 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
612 }
613 },
614 },
615 code => sub {
616 my ($param) = @_;
617
618 my $conf = PVE::QemuServer::load_config($param->{vmid});
619
620 delete $conf->{snapshots};
621
622 return $conf;
623 }});
624
625 my $vm_is_volid_owner = sub {
626 my ($storecfg, $vmid, $volid) =@_;
627
628 if ($volid !~ m|^/|) {
629 my ($path, $owner);
630 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
631 if ($owner && ($owner == $vmid)) {
632 return 1;
633 }
634 }
635
636 return undef;
637 };
638
639 my $test_deallocate_drive = sub {
640 my ($storecfg, $vmid, $key, $drive, $force) = @_;
641
642 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
643 my $volid = $drive->{file};
644 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
645 if ($force || $key =~ m/^unused/) {
646 my $sid = PVE::Storage::parse_volume_id($volid);
647 return $sid;
648 }
649 }
650 }
651
652 return undef;
653 };
654
655 my $delete_drive = sub {
656 my ($conf, $storecfg, $vmid, $key, $drive, $force) = @_;
657
658 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
659 my $volid = $drive->{file};
660 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
661 if ($force || $key =~ m/^unused/) {
662 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
663 die $@ if $@;
664 } else {
665 PVE::QemuServer::add_unused_volume($conf, $volid, $vmid);
666 }
667 }
668 }
669
670 delete $conf->{$key};
671 };
672
673 my $vmconfig_delete_option = sub {
674 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force) = @_;
675
676 return if !defined($conf->{$opt});
677
678 my $isDisk = PVE::QemuServer::valid_drivename($opt)|| ($opt =~ m/^unused/);
679
680 if ($isDisk) {
681 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
682
683 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
684 if (my $sid = &$test_deallocate_drive($storecfg, $vmid, $opt, $drive, $force)) {
685 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.Allocate']);
686 }
687 }
688
689 my $unplugwarning = "";
690 if($conf->{ostype} && $conf->{ostype} eq 'l26'){
691 $unplugwarning = "<br>verify that you have acpiphp && pci_hotplug modules loaded in your guest VM";
692 }elsif($conf->{ostype} && $conf->{ostype} eq 'l24'){
693 $unplugwarning = "<br>kernel 2.4 don't support hotplug, please disable hotplug in options";
694 }elsif(!$conf->{ostype} || ($conf->{ostype} && $conf->{ostype} eq 'other')){
695 $unplugwarning = "<br>verify that your guest support acpi hotplug";
696 }
697
698 if($opt eq 'tablet'){
699 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt);
700 }else{
701 die "error hot-unplug $opt $unplugwarning" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
702 }
703
704 if ($isDisk) {
705 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
706 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive, $force);
707 } else {
708 delete $conf->{$opt};
709 }
710
711 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
712 };
713
714 my $safe_num_ne = sub {
715 my ($a, $b) = @_;
716
717 return 0 if !defined($a) && !defined($b);
718 return 1 if !defined($a);
719 return 1 if !defined($b);
720
721 return $a != $b;
722 };
723
724 my $vmconfig_update_disk = sub {
725 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
726
727 my $drive = PVE::QemuServer::parse_drive($opt, $value);
728
729 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
730 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
731 } else {
732 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
733 }
734
735 if ($conf->{$opt}) {
736
737 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
738
739 my $media = $drive->{media} || 'disk';
740 my $oldmedia = $old_drive->{media} || 'disk';
741 die "unable to change media type\n" if $media ne $oldmedia;
742
743 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
744 ($drive->{file} ne $old_drive->{file})) { # delete old disks
745
746 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
747 $conf = PVE::QemuServer::load_config($vmid); # update/reload
748 }
749
750 if(&$safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
751 &$safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
752 &$safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
753 &$safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
754 &$safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
755 &$safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr})) {
756 PVE::QemuServer::qemu_block_set_io_throttle($vmid,"drive-$opt", $drive->{mbps}*1024*1024,
757 $drive->{mbps_rd}*1024*1024, $drive->{mbps_wr}*1024*1024,
758 $drive->{iops}, $drive->{iops_rd}, $drive->{iops_wr})
759 if !PVE::QemuServer::drive_is_cdrom($drive);
760 }
761 }
762 }
763
764 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
765 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
766
767 $conf = PVE::QemuServer::load_config($vmid); # update/reload
768 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
769
770 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
771
772 if (PVE::QemuServer::check_running($vmid)) {
773 if ($drive->{file} eq 'none') {
774 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
775 } else {
776 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
777 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt"); #force eject if locked
778 PVE::QemuServer::vm_mon_cmd($vmid, "change",device => "drive-$opt",target => "$path") if $path;
779 }
780 }
781
782 } else { # hotplug new disks
783
784 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
785 }
786 };
787
788 my $vmconfig_update_net = sub {
789 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
790
791 if ($conf->{$opt} && PVE::QemuServer::check_running($vmid)) {
792 my $oldnet = PVE::QemuServer::parse_net($conf->{$opt});
793 my $newnet = PVE::QemuServer::parse_net($value);
794
795 if($oldnet->{model} ne $newnet->{model}){
796 #if model change, we try to hot-unplug
797 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
798 }else{
799
800 if($newnet->{bridge} && $oldnet->{bridge}){
801 my $iface = "tap".$vmid."i".$1 if $opt =~ m/net(\d+)/;
802
803 if($newnet->{rate} ne $oldnet->{rate}){
804 PVE::Network::tap_rate_limit($iface, $newnet->{rate});
805 }
806
807 if(($newnet->{bridge} ne $oldnet->{bridge}) || ($newnet->{tag} ne $oldnet->{tag})){
808 eval{PVE::Network::tap_unplug($iface, $oldnet->{bridge}, $oldnet->{tag});};
809 PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag});
810 }
811
812 }else{
813 #if bridge/nat mode change, we try to hot-unplug
814 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
815 }
816 }
817
818 }
819 $conf->{$opt} = $value;
820 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
821 $conf = PVE::QemuServer::load_config($vmid); # update/reload
822
823 my $net = PVE::QemuServer::parse_net($conf->{$opt});
824
825 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
826 };
827
828 my $vm_config_perm_list = [
829 'VM.Config.Disk',
830 'VM.Config.CDROM',
831 'VM.Config.CPU',
832 'VM.Config.Memory',
833 'VM.Config.Network',
834 'VM.Config.HWType',
835 'VM.Config.Options',
836 ];
837
838 __PACKAGE__->register_method({
839 name => 'update_vm',
840 path => '{vmid}/config',
841 method => 'PUT',
842 protected => 1,
843 proxyto => 'node',
844 description => "Set virtual machine options.",
845 permissions => {
846 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
847 },
848 parameters => {
849 additionalProperties => 0,
850 properties => PVE::QemuServer::json_config_properties(
851 {
852 node => get_standard_option('pve-node'),
853 vmid => get_standard_option('pve-vmid'),
854 skiplock => get_standard_option('skiplock'),
855 delete => {
856 type => 'string', format => 'pve-configid-list',
857 description => "A list of settings you want to delete.",
858 optional => 1,
859 },
860 force => {
861 type => 'boolean',
862 description => $opt_force_description,
863 optional => 1,
864 requires => 'delete',
865 },
866 digest => {
867 type => 'string',
868 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
869 maxLength => 40,
870 optional => 1,
871 }
872 }),
873 },
874 returns => { type => 'null'},
875 code => sub {
876 my ($param) = @_;
877
878 my $rpcenv = PVE::RPCEnvironment::get();
879
880 my $authuser = $rpcenv->get_user();
881
882 my $node = extract_param($param, 'node');
883
884 my $vmid = extract_param($param, 'vmid');
885
886 my $digest = extract_param($param, 'digest');
887
888 my @paramarr = (); # used for log message
889 foreach my $key (keys %$param) {
890 push @paramarr, "-$key", $param->{$key};
891 }
892
893 my $skiplock = extract_param($param, 'skiplock');
894 raise_param_exc({ skiplock => "Only root may use this option." })
895 if $skiplock && $authuser ne 'root@pam';
896
897 my $delete_str = extract_param($param, 'delete');
898
899 my $force = extract_param($param, 'force');
900
901 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
902
903 my $storecfg = PVE::Storage::config();
904
905 my $defaults = PVE::QemuServer::load_defaults();
906
907 &$resolve_cdrom_alias($param);
908
909 # now try to verify all parameters
910
911 my @delete = ();
912 foreach my $opt (PVE::Tools::split_list($delete_str)) {
913 $opt = 'ide2' if $opt eq 'cdrom';
914 raise_param_exc({ delete => "you can't use '-$opt' and " .
915 "-delete $opt' at the same time" })
916 if defined($param->{$opt});
917
918 if (!PVE::QemuServer::option_exists($opt)) {
919 raise_param_exc({ delete => "unknown option '$opt'" });
920 }
921
922 push @delete, $opt;
923 }
924
925 foreach my $opt (keys %$param) {
926 if (PVE::QemuServer::valid_drivename($opt)) {
927 # cleanup drive path
928 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
929 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
930 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
931 } elsif ($opt =~ m/^net(\d+)$/) {
932 # add macaddr
933 my $net = PVE::QemuServer::parse_net($param->{$opt});
934 $param->{$opt} = PVE::QemuServer::print_net($net);
935 }
936 }
937
938 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
939
940 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
941
942 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
943
944 my $updatefn = sub {
945
946 my $conf = PVE::QemuServer::load_config($vmid);
947
948 die "checksum missmatch (file change by other user?)\n"
949 if $digest && $digest ne $conf->{digest};
950
951 PVE::QemuServer::check_lock($conf) if !$skiplock;
952
953 if ($param->{memory} || defined($param->{balloon})) {
954 my $maxmem = $param->{memory} || $conf->{memory} || $defaults->{memory};
955 my $balloon = defined($param->{balloon}) ? $param->{balloon} : $conf->{balloon};
956
957 die "balloon value too large (must be smaller than assigned memory)\n"
958 if $balloon > $maxmem;
959 }
960
961 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
962
963 foreach my $opt (@delete) { # delete
964 $conf = PVE::QemuServer::load_config($vmid); # update/reload
965 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
966 }
967
968 my $running = PVE::QemuServer::check_running($vmid);
969
970 foreach my $opt (keys %$param) { # add/change
971
972 $conf = PVE::QemuServer::load_config($vmid); # update/reload
973
974 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
975
976 if (PVE::QemuServer::valid_drivename($opt)) {
977
978 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
979 $opt, $param->{$opt}, $force);
980
981 } elsif ($opt =~ m/^net(\d+)$/) { #nics
982
983 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
984 $opt, $param->{$opt});
985
986 } else {
987
988 if($opt eq 'tablet' && $param->{$opt} == 1){
989 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt);
990 }elsif($opt eq 'tablet' && $param->{$opt} == 0){
991 PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
992 }
993
994 $conf->{$opt} = $param->{$opt};
995 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
996 }
997 }
998
999 # allow manual ballooning if shares is set to zero
1000 if ($running && defined($param->{balloon}) &&
1001 defined($conf->{shares}) && ($conf->{shares} == 0)) {
1002 my $balloon = $param->{'balloon'} || $conf->{memory} || $defaults->{memory};
1003 PVE::QemuServer::vm_mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
1004 }
1005
1006 };
1007
1008 PVE::QemuServer::lock_config($vmid, $updatefn);
1009
1010 return undef;
1011 }});
1012
1013
1014 __PACKAGE__->register_method({
1015 name => 'destroy_vm',
1016 path => '{vmid}',
1017 method => 'DELETE',
1018 protected => 1,
1019 proxyto => 'node',
1020 description => "Destroy the vm (also delete all used/owned volumes).",
1021 permissions => {
1022 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
1023 },
1024 parameters => {
1025 additionalProperties => 0,
1026 properties => {
1027 node => get_standard_option('pve-node'),
1028 vmid => get_standard_option('pve-vmid'),
1029 skiplock => get_standard_option('skiplock'),
1030 },
1031 },
1032 returns => {
1033 type => 'string',
1034 },
1035 code => sub {
1036 my ($param) = @_;
1037
1038 my $rpcenv = PVE::RPCEnvironment::get();
1039
1040 my $authuser = $rpcenv->get_user();
1041
1042 my $vmid = $param->{vmid};
1043
1044 my $skiplock = $param->{skiplock};
1045 raise_param_exc({ skiplock => "Only root may use this option." })
1046 if $skiplock && $authuser ne 'root@pam';
1047
1048 # test if VM exists
1049 my $conf = PVE::QemuServer::load_config($vmid);
1050
1051 my $storecfg = PVE::Storage::config();
1052
1053 my $delVMfromPoolFn = sub {
1054 my $usercfg = cfs_read_file("user.cfg");
1055 if (my $pool = $usercfg->{vms}->{$vmid}) {
1056 if (my $data = $usercfg->{pools}->{$pool}) {
1057 delete $data->{vms}->{$vmid};
1058 delete $usercfg->{vms}->{$vmid};
1059 cfs_write_file("user.cfg", $usercfg);
1060 }
1061 }
1062 };
1063
1064 my $realcmd = sub {
1065 my $upid = shift;
1066
1067 syslog('info', "destroy VM $vmid: $upid\n");
1068
1069 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
1070
1071 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
1072 };
1073
1074 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1075 }});
1076
1077 __PACKAGE__->register_method({
1078 name => 'unlink',
1079 path => '{vmid}/unlink',
1080 method => 'PUT',
1081 protected => 1,
1082 proxyto => 'node',
1083 description => "Unlink/delete disk images.",
1084 permissions => {
1085 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
1086 },
1087 parameters => {
1088 additionalProperties => 0,
1089 properties => {
1090 node => get_standard_option('pve-node'),
1091 vmid => get_standard_option('pve-vmid'),
1092 idlist => {
1093 type => 'string', format => 'pve-configid-list',
1094 description => "A list of disk IDs you want to delete.",
1095 },
1096 force => {
1097 type => 'boolean',
1098 description => $opt_force_description,
1099 optional => 1,
1100 },
1101 },
1102 },
1103 returns => { type => 'null'},
1104 code => sub {
1105 my ($param) = @_;
1106
1107 $param->{delete} = extract_param($param, 'idlist');
1108
1109 __PACKAGE__->update_vm($param);
1110
1111 return undef;
1112 }});
1113
1114 my $sslcert;
1115
1116 __PACKAGE__->register_method({
1117 name => 'vncproxy',
1118 path => '{vmid}/vncproxy',
1119 method => 'POST',
1120 protected => 1,
1121 permissions => {
1122 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1123 },
1124 description => "Creates a TCP VNC proxy connections.",
1125 parameters => {
1126 additionalProperties => 0,
1127 properties => {
1128 node => get_standard_option('pve-node'),
1129 vmid => get_standard_option('pve-vmid'),
1130 },
1131 },
1132 returns => {
1133 additionalProperties => 0,
1134 properties => {
1135 user => { type => 'string' },
1136 ticket => { type => 'string' },
1137 cert => { type => 'string' },
1138 port => { type => 'integer' },
1139 upid => { type => 'string' },
1140 },
1141 },
1142 code => sub {
1143 my ($param) = @_;
1144
1145 my $rpcenv = PVE::RPCEnvironment::get();
1146
1147 my $authuser = $rpcenv->get_user();
1148
1149 my $vmid = $param->{vmid};
1150 my $node = $param->{node};
1151
1152 my $authpath = "/vms/$vmid";
1153
1154 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
1155
1156 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1157 if !$sslcert;
1158
1159 my $port = PVE::Tools::next_vnc_port();
1160
1161 my $remip;
1162
1163 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1164 $remip = PVE::Cluster::remote_node_ip($node);
1165 }
1166
1167 # NOTE: kvm VNC traffic is already TLS encrypted
1168 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes', $remip] : [];
1169
1170 my $timeout = 10;
1171
1172 my $realcmd = sub {
1173 my $upid = shift;
1174
1175 syslog('info', "starting vnc proxy $upid\n");
1176
1177 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1178
1179 my $qmstr = join(' ', @$qmcmd);
1180
1181 # also redirect stderr (else we get RFB protocol errors)
1182 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1183
1184 PVE::Tools::run_command($cmd);
1185
1186 return;
1187 };
1188
1189 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1190
1191 PVE::Tools::wait_for_vnc_port($port);
1192
1193 return {
1194 user => $authuser,
1195 ticket => $ticket,
1196 port => $port,
1197 upid => $upid,
1198 cert => $sslcert,
1199 };
1200 }});
1201
1202 __PACKAGE__->register_method({
1203 name => 'vmcmdidx',
1204 path => '{vmid}/status',
1205 method => 'GET',
1206 proxyto => 'node',
1207 description => "Directory index",
1208 permissions => {
1209 user => 'all',
1210 },
1211 parameters => {
1212 additionalProperties => 0,
1213 properties => {
1214 node => get_standard_option('pve-node'),
1215 vmid => get_standard_option('pve-vmid'),
1216 },
1217 },
1218 returns => {
1219 type => 'array',
1220 items => {
1221 type => "object",
1222 properties => {
1223 subdir => { type => 'string' },
1224 },
1225 },
1226 links => [ { rel => 'child', href => "{subdir}" } ],
1227 },
1228 code => sub {
1229 my ($param) = @_;
1230
1231 # test if VM exists
1232 my $conf = PVE::QemuServer::load_config($param->{vmid});
1233
1234 my $res = [
1235 { subdir => 'current' },
1236 { subdir => 'start' },
1237 { subdir => 'stop' },
1238 ];
1239
1240 return $res;
1241 }});
1242
1243 my $vm_is_ha_managed = sub {
1244 my ($vmid) = @_;
1245
1246 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1247 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1248 return 1;
1249 }
1250 return 0;
1251 };
1252
1253 __PACKAGE__->register_method({
1254 name => 'vm_status',
1255 path => '{vmid}/status/current',
1256 method => 'GET',
1257 proxyto => 'node',
1258 protected => 1, # qemu pid files are only readable by root
1259 description => "Get virtual machine status.",
1260 permissions => {
1261 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1262 },
1263 parameters => {
1264 additionalProperties => 0,
1265 properties => {
1266 node => get_standard_option('pve-node'),
1267 vmid => get_standard_option('pve-vmid'),
1268 },
1269 },
1270 returns => { type => 'object' },
1271 code => sub {
1272 my ($param) = @_;
1273
1274 # test if VM exists
1275 my $conf = PVE::QemuServer::load_config($param->{vmid});
1276
1277 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
1278 my $status = $vmstatus->{$param->{vmid}};
1279
1280 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
1281
1282 return $status;
1283 }});
1284
1285 __PACKAGE__->register_method({
1286 name => 'vm_start',
1287 path => '{vmid}/status/start',
1288 method => 'POST',
1289 protected => 1,
1290 proxyto => 'node',
1291 description => "Start virtual machine.",
1292 permissions => {
1293 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1294 },
1295 parameters => {
1296 additionalProperties => 0,
1297 properties => {
1298 node => get_standard_option('pve-node'),
1299 vmid => get_standard_option('pve-vmid'),
1300 skiplock => get_standard_option('skiplock'),
1301 stateuri => get_standard_option('pve-qm-stateuri'),
1302 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
1303
1304 },
1305 },
1306 returns => {
1307 type => 'string',
1308 },
1309 code => sub {
1310 my ($param) = @_;
1311
1312 my $rpcenv = PVE::RPCEnvironment::get();
1313
1314 my $authuser = $rpcenv->get_user();
1315
1316 my $node = extract_param($param, 'node');
1317
1318 my $vmid = extract_param($param, 'vmid');
1319
1320 my $stateuri = extract_param($param, 'stateuri');
1321 raise_param_exc({ stateuri => "Only root may use this option." })
1322 if $stateuri && $authuser ne 'root@pam';
1323
1324 my $skiplock = extract_param($param, 'skiplock');
1325 raise_param_exc({ skiplock => "Only root may use this option." })
1326 if $skiplock && $authuser ne 'root@pam';
1327
1328 my $migratedfrom = extract_param($param, 'migratedfrom');
1329 raise_param_exc({ migratedfrom => "Only root may use this option." })
1330 if $migratedfrom && $authuser ne 'root@pam';
1331
1332 my $storecfg = PVE::Storage::config();
1333
1334 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1335 $rpcenv->{type} ne 'ha') {
1336
1337 my $hacmd = sub {
1338 my $upid = shift;
1339
1340 my $service = "pvevm:$vmid";
1341
1342 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1343
1344 print "Executing HA start for VM $vmid\n";
1345
1346 PVE::Tools::run_command($cmd);
1347
1348 return;
1349 };
1350
1351 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1352
1353 } else {
1354
1355 my $realcmd = sub {
1356 my $upid = shift;
1357
1358 syslog('info', "start VM $vmid: $upid\n");
1359
1360 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock, $migratedfrom);
1361
1362 return;
1363 };
1364
1365 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1366 }
1367 }});
1368
1369 __PACKAGE__->register_method({
1370 name => 'vm_stop',
1371 path => '{vmid}/status/stop',
1372 method => 'POST',
1373 protected => 1,
1374 proxyto => 'node',
1375 description => "Stop virtual machine.",
1376 permissions => {
1377 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1378 },
1379 parameters => {
1380 additionalProperties => 0,
1381 properties => {
1382 node => get_standard_option('pve-node'),
1383 vmid => get_standard_option('pve-vmid'),
1384 skiplock => get_standard_option('skiplock'),
1385 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
1386 timeout => {
1387 description => "Wait maximal timeout seconds.",
1388 type => 'integer',
1389 minimum => 0,
1390 optional => 1,
1391 },
1392 keepActive => {
1393 description => "Do not decativate storage volumes.",
1394 type => 'boolean',
1395 optional => 1,
1396 default => 0,
1397 }
1398 },
1399 },
1400 returns => {
1401 type => 'string',
1402 },
1403 code => sub {
1404 my ($param) = @_;
1405
1406 my $rpcenv = PVE::RPCEnvironment::get();
1407
1408 my $authuser = $rpcenv->get_user();
1409
1410 my $node = extract_param($param, 'node');
1411
1412 my $vmid = extract_param($param, 'vmid');
1413
1414 my $skiplock = extract_param($param, 'skiplock');
1415 raise_param_exc({ skiplock => "Only root may use this option." })
1416 if $skiplock && $authuser ne 'root@pam';
1417
1418 my $keepActive = extract_param($param, 'keepActive');
1419 raise_param_exc({ keepActive => "Only root may use this option." })
1420 if $keepActive && $authuser ne 'root@pam';
1421
1422 my $migratedfrom = extract_param($param, 'migratedfrom');
1423 raise_param_exc({ migratedfrom => "Only root may use this option." })
1424 if $migratedfrom && $authuser ne 'root@pam';
1425
1426
1427 my $storecfg = PVE::Storage::config();
1428
1429 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
1430
1431 my $hacmd = sub {
1432 my $upid = shift;
1433
1434 my $service = "pvevm:$vmid";
1435
1436 my $cmd = ['clusvcadm', '-d', $service];
1437
1438 print "Executing HA stop for VM $vmid\n";
1439
1440 PVE::Tools::run_command($cmd);
1441
1442 return;
1443 };
1444
1445 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1446
1447 } else {
1448 my $realcmd = sub {
1449 my $upid = shift;
1450
1451 syslog('info', "stop VM $vmid: $upid\n");
1452
1453 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
1454 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
1455
1456 return;
1457 };
1458
1459 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1460 }
1461 }});
1462
1463 __PACKAGE__->register_method({
1464 name => 'vm_reset',
1465 path => '{vmid}/status/reset',
1466 method => 'POST',
1467 protected => 1,
1468 proxyto => 'node',
1469 description => "Reset virtual machine.",
1470 permissions => {
1471 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1472 },
1473 parameters => {
1474 additionalProperties => 0,
1475 properties => {
1476 node => get_standard_option('pve-node'),
1477 vmid => get_standard_option('pve-vmid'),
1478 skiplock => get_standard_option('skiplock'),
1479 },
1480 },
1481 returns => {
1482 type => 'string',
1483 },
1484 code => sub {
1485 my ($param) = @_;
1486
1487 my $rpcenv = PVE::RPCEnvironment::get();
1488
1489 my $authuser = $rpcenv->get_user();
1490
1491 my $node = extract_param($param, 'node');
1492
1493 my $vmid = extract_param($param, 'vmid');
1494
1495 my $skiplock = extract_param($param, 'skiplock');
1496 raise_param_exc({ skiplock => "Only root may use this option." })
1497 if $skiplock && $authuser ne 'root@pam';
1498
1499 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1500
1501 my $realcmd = sub {
1502 my $upid = shift;
1503
1504 PVE::QemuServer::vm_reset($vmid, $skiplock);
1505
1506 return;
1507 };
1508
1509 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
1510 }});
1511
1512 __PACKAGE__->register_method({
1513 name => 'vm_shutdown',
1514 path => '{vmid}/status/shutdown',
1515 method => 'POST',
1516 protected => 1,
1517 proxyto => 'node',
1518 description => "Shutdown virtual machine.",
1519 permissions => {
1520 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1521 },
1522 parameters => {
1523 additionalProperties => 0,
1524 properties => {
1525 node => get_standard_option('pve-node'),
1526 vmid => get_standard_option('pve-vmid'),
1527 skiplock => get_standard_option('skiplock'),
1528 timeout => {
1529 description => "Wait maximal timeout seconds.",
1530 type => 'integer',
1531 minimum => 0,
1532 optional => 1,
1533 },
1534 forceStop => {
1535 description => "Make sure the VM stops.",
1536 type => 'boolean',
1537 optional => 1,
1538 default => 0,
1539 },
1540 keepActive => {
1541 description => "Do not decativate storage volumes.",
1542 type => 'boolean',
1543 optional => 1,
1544 default => 0,
1545 }
1546 },
1547 },
1548 returns => {
1549 type => 'string',
1550 },
1551 code => sub {
1552 my ($param) = @_;
1553
1554 my $rpcenv = PVE::RPCEnvironment::get();
1555
1556 my $authuser = $rpcenv->get_user();
1557
1558 my $node = extract_param($param, 'node');
1559
1560 my $vmid = extract_param($param, 'vmid');
1561
1562 my $skiplock = extract_param($param, 'skiplock');
1563 raise_param_exc({ skiplock => "Only root may use this option." })
1564 if $skiplock && $authuser ne 'root@pam';
1565
1566 my $keepActive = extract_param($param, 'keepActive');
1567 raise_param_exc({ keepActive => "Only root may use this option." })
1568 if $keepActive && $authuser ne 'root@pam';
1569
1570 my $storecfg = PVE::Storage::config();
1571
1572 my $realcmd = sub {
1573 my $upid = shift;
1574
1575 syslog('info', "shutdown VM $vmid: $upid\n");
1576
1577 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
1578 1, $param->{forceStop}, $keepActive);
1579
1580 return;
1581 };
1582
1583 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
1584 }});
1585
1586 __PACKAGE__->register_method({
1587 name => 'vm_suspend',
1588 path => '{vmid}/status/suspend',
1589 method => 'POST',
1590 protected => 1,
1591 proxyto => 'node',
1592 description => "Suspend virtual machine.",
1593 permissions => {
1594 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
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 },
1603 },
1604 returns => {
1605 type => 'string',
1606 },
1607 code => sub {
1608 my ($param) = @_;
1609
1610 my $rpcenv = PVE::RPCEnvironment::get();
1611
1612 my $authuser = $rpcenv->get_user();
1613
1614 my $node = extract_param($param, 'node');
1615
1616 my $vmid = extract_param($param, 'vmid');
1617
1618 my $skiplock = extract_param($param, 'skiplock');
1619 raise_param_exc({ skiplock => "Only root may use this option." })
1620 if $skiplock && $authuser ne 'root@pam';
1621
1622 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1623
1624 my $realcmd = sub {
1625 my $upid = shift;
1626
1627 syslog('info', "suspend VM $vmid: $upid\n");
1628
1629 PVE::QemuServer::vm_suspend($vmid, $skiplock);
1630
1631 return;
1632 };
1633
1634 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
1635 }});
1636
1637 __PACKAGE__->register_method({
1638 name => 'vm_resume',
1639 path => '{vmid}/status/resume',
1640 method => 'POST',
1641 protected => 1,
1642 proxyto => 'node',
1643 description => "Resume virtual machine.",
1644 permissions => {
1645 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1646 },
1647 parameters => {
1648 additionalProperties => 0,
1649 properties => {
1650 node => get_standard_option('pve-node'),
1651 vmid => get_standard_option('pve-vmid'),
1652 skiplock => get_standard_option('skiplock'),
1653 },
1654 },
1655 returns => {
1656 type => 'string',
1657 },
1658 code => sub {
1659 my ($param) = @_;
1660
1661 my $rpcenv = PVE::RPCEnvironment::get();
1662
1663 my $authuser = $rpcenv->get_user();
1664
1665 my $node = extract_param($param, 'node');
1666
1667 my $vmid = extract_param($param, 'vmid');
1668
1669 my $skiplock = extract_param($param, 'skiplock');
1670 raise_param_exc({ skiplock => "Only root may use this option." })
1671 if $skiplock && $authuser ne 'root@pam';
1672
1673 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1674
1675 my $realcmd = sub {
1676 my $upid = shift;
1677
1678 syslog('info', "resume VM $vmid: $upid\n");
1679
1680 PVE::QemuServer::vm_resume($vmid, $skiplock);
1681
1682 return;
1683 };
1684
1685 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
1686 }});
1687
1688 __PACKAGE__->register_method({
1689 name => 'vm_sendkey',
1690 path => '{vmid}/sendkey',
1691 method => 'PUT',
1692 protected => 1,
1693 proxyto => 'node',
1694 description => "Send key event to virtual machine.",
1695 permissions => {
1696 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1697 },
1698 parameters => {
1699 additionalProperties => 0,
1700 properties => {
1701 node => get_standard_option('pve-node'),
1702 vmid => get_standard_option('pve-vmid'),
1703 skiplock => get_standard_option('skiplock'),
1704 key => {
1705 description => "The key (qemu monitor encoding).",
1706 type => 'string'
1707 }
1708 },
1709 },
1710 returns => { type => 'null'},
1711 code => sub {
1712 my ($param) = @_;
1713
1714 my $rpcenv = PVE::RPCEnvironment::get();
1715
1716 my $authuser = $rpcenv->get_user();
1717
1718 my $node = extract_param($param, 'node');
1719
1720 my $vmid = extract_param($param, 'vmid');
1721
1722 my $skiplock = extract_param($param, 'skiplock');
1723 raise_param_exc({ skiplock => "Only root may use this option." })
1724 if $skiplock && $authuser ne 'root@pam';
1725
1726 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1727
1728 return;
1729 }});
1730
1731 __PACKAGE__->register_method({
1732 name => 'vm_feature',
1733 path => '{vmid}/feature',
1734 method => 'GET',
1735 proxyto => 'node',
1736 protected => 1,
1737 description => "Check if feature for virtual machine is available.",
1738 permissions => {
1739 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1740 },
1741 parameters => {
1742 additionalProperties => 0,
1743 properties => {
1744 node => get_standard_option('pve-node'),
1745 vmid => get_standard_option('pve-vmid'),
1746 feature => {
1747 description => "Feature to check.",
1748 type => 'string',
1749 enum => [ 'snapshot', 'clone' ],
1750 },
1751 snapname => get_standard_option('pve-snapshot-name', {
1752 optional => 1,
1753 }),
1754 },
1755 },
1756 returns => {
1757 type => 'boolean'
1758 },
1759 code => sub {
1760 my ($param) = @_;
1761
1762 my $node = extract_param($param, 'node');
1763
1764 my $vmid = extract_param($param, 'vmid');
1765
1766 my $snapname = extract_param($param, 'snapname');
1767
1768 my $feature = extract_param($param, 'feature');
1769
1770 my $running = PVE::QemuServer::check_running($vmid);
1771
1772 my $conf = PVE::QemuServer::load_config($vmid);
1773
1774 if($snapname){
1775 my $snap = $conf->{snapshots}->{$snapname};
1776 die "snapshot '$snapname' does not exist\n" if !defined($snap);
1777 $conf = $snap;
1778 }
1779 my $storecfg = PVE::Storage::config();
1780
1781 my $hasfeature = PVE::QemuServer::has_feature($feature, $conf, $storecfg, $snapname, $running);
1782 my $res = $hasfeature ? 1 : 0 ;
1783 return $res;
1784 }});
1785
1786 __PACKAGE__->register_method({
1787 name => 'copy_vm',
1788 path => '{vmid}/copy',
1789 method => 'POST',
1790 protected => 1,
1791 proxyto => 'node',
1792 description => "Create a copy of virtual machine/template.",
1793 permissions => {
1794 description => "You need 'VM.Copy' permissions on /vms/{vmid}, and 'VM.Allocate' permissions " .
1795 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
1796 "'Datastore.AllocateSpace' on any used storage.",
1797 check =>
1798 [ 'and',
1799 ['perm', '/vms/{vmid}', [ 'VM.Copy' ]],
1800 [ 'or',
1801 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
1802 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
1803 ],
1804 ]
1805 },
1806 parameters => {
1807 additionalProperties => 0,
1808 properties => {
1809 node => get_standard_option('pve-node'),
1810 vmid => get_standard_option('pve-vmid'),
1811 newid => get_standard_option('pve-vmid', { description => 'VMID for the copy.' }),
1812 name => {
1813 optional => 1,
1814 type => 'string', format => 'dns-name',
1815 description => "Set a name for the new VM.",
1816 },
1817 description => {
1818 optional => 1,
1819 type => 'string',
1820 description => "Description for the new VM.",
1821 },
1822 pool => {
1823 optional => 1,
1824 type => 'string', format => 'pve-poolid',
1825 description => "Add the new VM to the specified pool.",
1826 },
1827 snapname => get_standard_option('pve-snapshot-name', {
1828 requires => 'full',
1829 optional => 1,
1830 }),
1831 storage => get_standard_option('pve-storage-id', {
1832 description => "Target storage for full copy.",
1833 requires => 'full',
1834 optional => 1,
1835 }),
1836 'format' => {
1837 description => "Target format for file storage.",
1838 requires => 'full',
1839 type => 'string',
1840 optional => 1,
1841 enum => [ 'raw', 'qcow2', 'vmdk'],
1842 },
1843 full => {
1844 optional => 1,
1845 type => 'boolean',
1846 description => "Create a full copy of all disk. This is always done when " .
1847 "you copy a normal VM. For VM templates, we try to create a linked copy by default.",
1848 default => 0,
1849 },
1850 target => get_standard_option('pve-node', {
1851 description => "Target node. Only allowed if the original VM is on shared storage.",
1852 optional => 1,
1853 }),
1854 },
1855 },
1856 returns => {
1857 type => 'string',
1858 },
1859 code => sub {
1860 my ($param) = @_;
1861
1862 my $rpcenv = PVE::RPCEnvironment::get();
1863
1864 my $authuser = $rpcenv->get_user();
1865
1866 my $node = extract_param($param, 'node');
1867
1868 my $vmid = extract_param($param, 'vmid');
1869
1870 my $newid = extract_param($param, 'newid');
1871
1872 # fixme: update pool after create
1873 my $pool = extract_param($param, 'pool');
1874
1875 if (defined($pool)) {
1876 $rpcenv->check_pool_exist($pool);
1877 }
1878
1879 my $snapname = extract_param($param, 'snapname');
1880
1881 my $storage = extract_param($param, 'storage');
1882
1883 my $format = extract_param($param, 'format');
1884
1885 my $target = extract_param($param, 'target');
1886
1887 my $localnode = PVE::INotify::nodename();
1888
1889 undef $target if $target && ($target eq $localnode || $target eq 'localhost');
1890
1891 PVE::Cluster::check_node_exists($target) if $target;
1892
1893 my $storecfg = PVE::Storage::config();
1894
1895 PVE::Cluster::check_cfs_quorum();
1896
1897 my $running = PVE::QemuServer::check_running($vmid) || 0;
1898
1899 die "Copy running VM $vmid not implemented\n" if $running; # fixme: implement this
1900
1901 # exclusive lock if VM is running - else shared lock is enough;
1902 my $shared_lock = $running ? 0 : 1;
1903
1904 # fixme: do early checks - re-check after lock
1905
1906 # fixme: impl. target node parameter (mv VM config if all storages are shared)
1907
1908 my $copyfn = sub {
1909
1910 # all tests after lock
1911 my $conf = PVE::QemuServer::load_config($vmid);
1912
1913 PVE::QemuServer::check_lock($conf);
1914
1915 my $verify_running = PVE::QemuServer::check_running($vmid) || 0;
1916
1917 die "unexpected state change\n" if $verify_running != $running;
1918
1919 die "snapshot '$snapname' does not exist\n"
1920 if $snapname && !defined( $conf->{snapshots}->{$snapname});
1921
1922 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
1923
1924 my $sharedvm = &$check_storage_access_copy($rpcenv, $authuser, $storecfg, $oldconf, $storage);
1925
1926 die "can't copy VM to node '$target' (VM uses local storage)\n" if $target && !$sharedvm;
1927
1928 my $conffile = PVE::QemuServer::config_file($newid);
1929
1930 die "unable to create VM $newid: config file already exists\n"
1931 if -f $conffile;
1932
1933 # create empty/temp config - this fails if VM already exists on other node
1934 PVE::Tools::file_set_contents($conffile, "# qmcopy temporary file\nlock: copy\n");
1935
1936 my $realcmd = sub {
1937 my $upid = shift;
1938
1939 my $newvollist = [];
1940
1941 eval {
1942 my $newconf = { lock => 'copy' };
1943 my $drives = {};
1944 my $vollist = [];
1945
1946 foreach my $opt (keys %$oldconf) {
1947 my $value = $oldconf->{$opt};
1948
1949 # do not copy snapshot related info
1950 next if $opt eq 'snapshots' || $opt eq 'parent' || $opt eq 'snaptime' ||
1951 $opt eq 'vmstate' || $opt eq 'snapstate';
1952
1953 # always change MAC! address
1954 if ($opt =~ m/^net(\d+)$/) {
1955 my $net = PVE::QemuServer::parse_net($value);
1956 $net->{macaddr} = PVE::Tools::random_ether_addr();
1957 $newconf->{$opt} = PVE::QemuServer::print_net($net);
1958 } elsif (my $drive = PVE::QemuServer::parse_drive($opt, $value)) {
1959 if (PVE::QemuServer::drive_is_cdrom($drive)) {
1960 $newconf->{$opt} = $value; # simply copy configuration
1961 } else {
1962 $drives->{$opt} = $drive;
1963 push @$vollist, $drive->{file};
1964 }
1965 } else {
1966 # copy everything else
1967 $newconf->{$opt} = $value;
1968 }
1969 }
1970
1971 delete $newconf->{template};
1972
1973 if ($param->{name}) {
1974 $newconf->{name} = $param->{name};
1975 } else {
1976 $newconf->{name} = "Copy-of-$oldconf->{name}";
1977 }
1978
1979 if ($param->{description}) {
1980 $newconf->{description} = $param->{description};
1981 }
1982
1983 PVE::Storage::activate_volumes($storecfg, $vollist);
1984
1985 eval {
1986 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
1987
1988 foreach my $opt (keys %$drives) {
1989 my $drive = $drives->{$opt};
1990
1991 my $newvolid;
1992 if (!$param->{full} && PVE::Storage::volume_is_base($storecfg, $drive->{file})) {
1993 print "clone drive $opt ($drive->{file})\n";
1994 $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newid);
1995 push @$newvollist, $newvolid;
1996
1997 } else {
1998 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
1999 $storeid = $storage if $storage;
2000
2001 my $fmt = undef;
2002 if($format){
2003 $fmt = $format;
2004 }else{
2005 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
2006 $fmt = $drive->{format} || $defformat;
2007 }
2008
2009 my ($size) = PVE::Storage::volume_size_info($storecfg, $drive->{file}, 3);
2010
2011 print "copy drive $opt ($drive->{file})\n";
2012 $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $newid, $fmt, undef, ($size/1024));
2013 push @$newvollist, $newvolid;
2014
2015 PVE::QemuServer::qemu_img_convert($drive->{file}, $newvolid, $size, $snapname);
2016 }
2017
2018 my ($size) = PVE::Storage::volume_size_info($storecfg, $newvolid, 3);
2019 my $disk = { file => $newvolid, size => $size };
2020 $newconf->{$opt} = PVE::QemuServer::print_drive($vmid, $disk);
2021
2022 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
2023 }
2024 };
2025 die $@ if $@;
2026
2027 delete $newconf->{lock};
2028 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
2029
2030 if ($target) {
2031 my $newconffile = PVE::QemuServer::config_file($newid, $target);
2032 die "Failed to move config to node '$target' - rename failed: $!\n"
2033 if !rename($conffile, $newconffile);
2034 }
2035 };
2036 if (my $err = $@) {
2037 unlink $conffile;
2038
2039 sleep 1; # some storage like rbd need to wait before release volume - really?
2040
2041 foreach my $volid (@$newvollist) {
2042 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2043 warn $@ if $@;
2044 }
2045 die "copy failed: $err";
2046 }
2047
2048 return;
2049 };
2050
2051 return $rpcenv->fork_worker('qmcopy', $vmid, $authuser, $realcmd);
2052 };
2053
2054 return PVE::QemuServer::lock_config_mode($vmid, 1, $shared_lock, sub {
2055 # Aquire exclusive lock lock for $newid
2056 return PVE::QemuServer::lock_config_full($newid, 1, $copyfn);
2057 });
2058
2059 }});
2060
2061 __PACKAGE__->register_method({
2062 name => 'migrate_vm',
2063 path => '{vmid}/migrate',
2064 method => 'POST',
2065 protected => 1,
2066 proxyto => 'node',
2067 description => "Migrate virtual machine. Creates a new migration task.",
2068 permissions => {
2069 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
2070 },
2071 parameters => {
2072 additionalProperties => 0,
2073 properties => {
2074 node => get_standard_option('pve-node'),
2075 vmid => get_standard_option('pve-vmid'),
2076 target => get_standard_option('pve-node', { description => "Target node." }),
2077 online => {
2078 type => 'boolean',
2079 description => "Use online/live migration.",
2080 optional => 1,
2081 },
2082 force => {
2083 type => 'boolean',
2084 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
2085 optional => 1,
2086 },
2087 },
2088 },
2089 returns => {
2090 type => 'string',
2091 description => "the task ID.",
2092 },
2093 code => sub {
2094 my ($param) = @_;
2095
2096 my $rpcenv = PVE::RPCEnvironment::get();
2097
2098 my $authuser = $rpcenv->get_user();
2099
2100 my $target = extract_param($param, 'target');
2101
2102 my $localnode = PVE::INotify::nodename();
2103 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
2104
2105 PVE::Cluster::check_cfs_quorum();
2106
2107 PVE::Cluster::check_node_exists($target);
2108
2109 my $targetip = PVE::Cluster::remote_node_ip($target);
2110
2111 my $vmid = extract_param($param, 'vmid');
2112
2113 raise_param_exc({ force => "Only root may use this option." })
2114 if $param->{force} && $authuser ne 'root@pam';
2115
2116 # test if VM exists
2117 my $conf = PVE::QemuServer::load_config($vmid);
2118
2119 # try to detect errors early
2120
2121 PVE::QemuServer::check_lock($conf);
2122
2123 if (PVE::QemuServer::check_running($vmid)) {
2124 die "cant migrate running VM without --online\n"
2125 if !$param->{online};
2126 }
2127
2128 my $storecfg = PVE::Storage::config();
2129 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
2130
2131 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
2132
2133 my $hacmd = sub {
2134 my $upid = shift;
2135
2136 my $service = "pvevm:$vmid";
2137
2138 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
2139
2140 print "Executing HA migrate for VM $vmid to node $target\n";
2141
2142 PVE::Tools::run_command($cmd);
2143
2144 return;
2145 };
2146
2147 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
2148
2149 } else {
2150
2151 my $realcmd = sub {
2152 my $upid = shift;
2153
2154 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
2155 };
2156
2157 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
2158 }
2159
2160 }});
2161
2162 __PACKAGE__->register_method({
2163 name => 'monitor',
2164 path => '{vmid}/monitor',
2165 method => 'POST',
2166 protected => 1,
2167 proxyto => 'node',
2168 description => "Execute Qemu monitor commands.",
2169 permissions => {
2170 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
2171 },
2172 parameters => {
2173 additionalProperties => 0,
2174 properties => {
2175 node => get_standard_option('pve-node'),
2176 vmid => get_standard_option('pve-vmid'),
2177 command => {
2178 type => 'string',
2179 description => "The monitor command.",
2180 }
2181 },
2182 },
2183 returns => { type => 'string'},
2184 code => sub {
2185 my ($param) = @_;
2186
2187 my $vmid = $param->{vmid};
2188
2189 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
2190
2191 my $res = '';
2192 eval {
2193 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
2194 };
2195 $res = "ERROR: $@" if $@;
2196
2197 return $res;
2198 }});
2199
2200 __PACKAGE__->register_method({
2201 name => 'resize_vm',
2202 path => '{vmid}/resize',
2203 method => 'PUT',
2204 protected => 1,
2205 proxyto => 'node',
2206 description => "Extend volume size.",
2207 permissions => {
2208 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
2209 },
2210 parameters => {
2211 additionalProperties => 0,
2212 properties => {
2213 node => get_standard_option('pve-node'),
2214 vmid => get_standard_option('pve-vmid'),
2215 skiplock => get_standard_option('skiplock'),
2216 disk => {
2217 type => 'string',
2218 description => "The disk you want to resize.",
2219 enum => [PVE::QemuServer::disknames()],
2220 },
2221 size => {
2222 type => 'string',
2223 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2224 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.",
2225 },
2226 digest => {
2227 type => 'string',
2228 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2229 maxLength => 40,
2230 optional => 1,
2231 },
2232 },
2233 },
2234 returns => { type => 'null'},
2235 code => sub {
2236 my ($param) = @_;
2237
2238 my $rpcenv = PVE::RPCEnvironment::get();
2239
2240 my $authuser = $rpcenv->get_user();
2241
2242 my $node = extract_param($param, 'node');
2243
2244 my $vmid = extract_param($param, 'vmid');
2245
2246 my $digest = extract_param($param, 'digest');
2247
2248 my $disk = extract_param($param, 'disk');
2249
2250 my $sizestr = extract_param($param, 'size');
2251
2252 my $skiplock = extract_param($param, 'skiplock');
2253 raise_param_exc({ skiplock => "Only root may use this option." })
2254 if $skiplock && $authuser ne 'root@pam';
2255
2256 my $storecfg = PVE::Storage::config();
2257
2258 my $updatefn = sub {
2259
2260 my $conf = PVE::QemuServer::load_config($vmid);
2261
2262 die "checksum missmatch (file change by other user?)\n"
2263 if $digest && $digest ne $conf->{digest};
2264 PVE::QemuServer::check_lock($conf) if !$skiplock;
2265
2266 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2267
2268 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2269
2270 my $volid = $drive->{file};
2271
2272 die "disk '$disk' has no associated volume\n" if !$volid;
2273
2274 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2275
2276 die "you can't online resize a virtio windows bootdisk\n"
2277 if PVE::QemuServer::check_running($vmid) && $conf->{bootdisk} eq $disk && $conf->{ostype} =~ m/^w/ && $disk =~ m/^virtio/;
2278
2279 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
2280
2281 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
2282
2283 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
2284
2285 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
2286 my ($ext, $newsize, $unit) = ($1, $2, $4);
2287 if ($unit) {
2288 if ($unit eq 'K') {
2289 $newsize = $newsize * 1024;
2290 } elsif ($unit eq 'M') {
2291 $newsize = $newsize * 1024 * 1024;
2292 } elsif ($unit eq 'G') {
2293 $newsize = $newsize * 1024 * 1024 * 1024;
2294 } elsif ($unit eq 'T') {
2295 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
2296 }
2297 }
2298 $newsize += $size if $ext;
2299 $newsize = int($newsize);
2300
2301 die "unable to skrink disk size\n" if $newsize < $size;
2302
2303 return if $size == $newsize;
2304
2305 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
2306
2307 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
2308
2309 $drive->{size} = $newsize;
2310 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
2311
2312 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2313 };
2314
2315 PVE::QemuServer::lock_config($vmid, $updatefn);
2316 return undef;
2317 }});
2318
2319 __PACKAGE__->register_method({
2320 name => 'snapshot_list',
2321 path => '{vmid}/snapshot',
2322 method => 'GET',
2323 description => "List all snapshots.",
2324 permissions => {
2325 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2326 },
2327 proxyto => 'node',
2328 protected => 1, # qemu pid files are only readable by root
2329 parameters => {
2330 additionalProperties => 0,
2331 properties => {
2332 vmid => get_standard_option('pve-vmid'),
2333 node => get_standard_option('pve-node'),
2334 },
2335 },
2336 returns => {
2337 type => 'array',
2338 items => {
2339 type => "object",
2340 properties => {},
2341 },
2342 links => [ { rel => 'child', href => "{name}" } ],
2343 },
2344 code => sub {
2345 my ($param) = @_;
2346
2347 my $vmid = $param->{vmid};
2348
2349 my $conf = PVE::QemuServer::load_config($vmid);
2350 my $snaphash = $conf->{snapshots} || {};
2351
2352 my $res = [];
2353
2354 foreach my $name (keys %$snaphash) {
2355 my $d = $snaphash->{$name};
2356 my $item = {
2357 name => $name,
2358 snaptime => $d->{snaptime} || 0,
2359 vmstate => $d->{vmstate} ? 1 : 0,
2360 description => $d->{description} || '',
2361 };
2362 $item->{parent} = $d->{parent} if $d->{parent};
2363 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
2364 push @$res, $item;
2365 }
2366
2367 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
2368 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
2369 $current->{parent} = $conf->{parent} if $conf->{parent};
2370
2371 push @$res, $current;
2372
2373 return $res;
2374 }});
2375
2376 __PACKAGE__->register_method({
2377 name => 'snapshot',
2378 path => '{vmid}/snapshot',
2379 method => 'POST',
2380 protected => 1,
2381 proxyto => 'node',
2382 description => "Snapshot a VM.",
2383 permissions => {
2384 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2385 },
2386 parameters => {
2387 additionalProperties => 0,
2388 properties => {
2389 node => get_standard_option('pve-node'),
2390 vmid => get_standard_option('pve-vmid'),
2391 snapname => get_standard_option('pve-snapshot-name'),
2392 vmstate => {
2393 optional => 1,
2394 type => 'boolean',
2395 description => "Save the vmstate",
2396 },
2397 freezefs => {
2398 optional => 1,
2399 type => 'boolean',
2400 description => "Freeze the filesystem",
2401 },
2402 description => {
2403 optional => 1,
2404 type => 'string',
2405 description => "A textual description or comment.",
2406 },
2407 },
2408 },
2409 returns => {
2410 type => 'string',
2411 description => "the task ID.",
2412 },
2413 code => sub {
2414 my ($param) = @_;
2415
2416 my $rpcenv = PVE::RPCEnvironment::get();
2417
2418 my $authuser = $rpcenv->get_user();
2419
2420 my $node = extract_param($param, 'node');
2421
2422 my $vmid = extract_param($param, 'vmid');
2423
2424 my $snapname = extract_param($param, 'snapname');
2425
2426 die "unable to use snapshot name 'current' (reserved name)\n"
2427 if $snapname eq 'current';
2428
2429 my $realcmd = sub {
2430 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
2431 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
2432 $param->{freezefs}, $param->{description});
2433 };
2434
2435 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2436 }});
2437
2438 __PACKAGE__->register_method({
2439 name => 'snapshot_cmd_idx',
2440 path => '{vmid}/snapshot/{snapname}',
2441 description => '',
2442 method => 'GET',
2443 permissions => {
2444 user => 'all',
2445 },
2446 parameters => {
2447 additionalProperties => 0,
2448 properties => {
2449 vmid => get_standard_option('pve-vmid'),
2450 node => get_standard_option('pve-node'),
2451 snapname => get_standard_option('pve-snapshot-name'),
2452 },
2453 },
2454 returns => {
2455 type => 'array',
2456 items => {
2457 type => "object",
2458 properties => {},
2459 },
2460 links => [ { rel => 'child', href => "{cmd}" } ],
2461 },
2462 code => sub {
2463 my ($param) = @_;
2464
2465 my $res = [];
2466
2467 push @$res, { cmd => 'rollback' };
2468 push @$res, { cmd => 'config' };
2469
2470 return $res;
2471 }});
2472
2473 __PACKAGE__->register_method({
2474 name => 'update_snapshot_config',
2475 path => '{vmid}/snapshot/{snapname}/config',
2476 method => 'PUT',
2477 protected => 1,
2478 proxyto => 'node',
2479 description => "Update snapshot metadata.",
2480 permissions => {
2481 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2482 },
2483 parameters => {
2484 additionalProperties => 0,
2485 properties => {
2486 node => get_standard_option('pve-node'),
2487 vmid => get_standard_option('pve-vmid'),
2488 snapname => get_standard_option('pve-snapshot-name'),
2489 description => {
2490 optional => 1,
2491 type => 'string',
2492 description => "A textual description or comment.",
2493 },
2494 },
2495 },
2496 returns => { type => 'null' },
2497 code => sub {
2498 my ($param) = @_;
2499
2500 my $rpcenv = PVE::RPCEnvironment::get();
2501
2502 my $authuser = $rpcenv->get_user();
2503
2504 my $vmid = extract_param($param, 'vmid');
2505
2506 my $snapname = extract_param($param, 'snapname');
2507
2508 return undef if !defined($param->{description});
2509
2510 my $updatefn = sub {
2511
2512 my $conf = PVE::QemuServer::load_config($vmid);
2513
2514 PVE::QemuServer::check_lock($conf);
2515
2516 my $snap = $conf->{snapshots}->{$snapname};
2517
2518 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2519
2520 $snap->{description} = $param->{description} if defined($param->{description});
2521
2522 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2523 };
2524
2525 PVE::QemuServer::lock_config($vmid, $updatefn);
2526
2527 return undef;
2528 }});
2529
2530 __PACKAGE__->register_method({
2531 name => 'get_snapshot_config',
2532 path => '{vmid}/snapshot/{snapname}/config',
2533 method => 'GET',
2534 proxyto => 'node',
2535 description => "Get snapshot configuration",
2536 permissions => {
2537 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2538 },
2539 parameters => {
2540 additionalProperties => 0,
2541 properties => {
2542 node => get_standard_option('pve-node'),
2543 vmid => get_standard_option('pve-vmid'),
2544 snapname => get_standard_option('pve-snapshot-name'),
2545 },
2546 },
2547 returns => { type => "object" },
2548 code => sub {
2549 my ($param) = @_;
2550
2551 my $rpcenv = PVE::RPCEnvironment::get();
2552
2553 my $authuser = $rpcenv->get_user();
2554
2555 my $vmid = extract_param($param, 'vmid');
2556
2557 my $snapname = extract_param($param, 'snapname');
2558
2559 my $conf = PVE::QemuServer::load_config($vmid);
2560
2561 my $snap = $conf->{snapshots}->{$snapname};
2562
2563 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2564
2565 return $snap;
2566 }});
2567
2568 __PACKAGE__->register_method({
2569 name => 'rollback',
2570 path => '{vmid}/snapshot/{snapname}/rollback',
2571 method => 'POST',
2572 protected => 1,
2573 proxyto => 'node',
2574 description => "Rollback VM state to specified snapshot.",
2575 permissions => {
2576 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2577 },
2578 parameters => {
2579 additionalProperties => 0,
2580 properties => {
2581 node => get_standard_option('pve-node'),
2582 vmid => get_standard_option('pve-vmid'),
2583 snapname => get_standard_option('pve-snapshot-name'),
2584 },
2585 },
2586 returns => {
2587 type => 'string',
2588 description => "the task ID.",
2589 },
2590 code => sub {
2591 my ($param) = @_;
2592
2593 my $rpcenv = PVE::RPCEnvironment::get();
2594
2595 my $authuser = $rpcenv->get_user();
2596
2597 my $node = extract_param($param, 'node');
2598
2599 my $vmid = extract_param($param, 'vmid');
2600
2601 my $snapname = extract_param($param, 'snapname');
2602
2603 my $realcmd = sub {
2604 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
2605 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
2606 };
2607
2608 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
2609 }});
2610
2611 __PACKAGE__->register_method({
2612 name => 'delsnapshot',
2613 path => '{vmid}/snapshot/{snapname}',
2614 method => 'DELETE',
2615 protected => 1,
2616 proxyto => 'node',
2617 description => "Delete a VM snapshot.",
2618 permissions => {
2619 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2620 },
2621 parameters => {
2622 additionalProperties => 0,
2623 properties => {
2624 node => get_standard_option('pve-node'),
2625 vmid => get_standard_option('pve-vmid'),
2626 snapname => get_standard_option('pve-snapshot-name'),
2627 force => {
2628 optional => 1,
2629 type => 'boolean',
2630 description => "For removal from config file, even if removing disk snapshots fails.",
2631 },
2632 },
2633 },
2634 returns => {
2635 type => 'string',
2636 description => "the task ID.",
2637 },
2638 code => sub {
2639 my ($param) = @_;
2640
2641 my $rpcenv = PVE::RPCEnvironment::get();
2642
2643 my $authuser = $rpcenv->get_user();
2644
2645 my $node = extract_param($param, 'node');
2646
2647 my $vmid = extract_param($param, 'vmid');
2648
2649 my $snapname = extract_param($param, 'snapname');
2650
2651 my $realcmd = sub {
2652 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
2653 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
2654 };
2655
2656 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
2657 }});
2658
2659 __PACKAGE__->register_method({
2660 name => 'template',
2661 path => '{vmid}/template',
2662 method => 'POST',
2663 protected => 1,
2664 proxyto => 'node',
2665 description => "Create a Template.",
2666 permissions => {
2667 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}.",
2668 check => [ 'or',
2669 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
2670 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
2671 ],
2672 },
2673 parameters => {
2674 additionalProperties => 0,
2675 properties => {
2676 node => get_standard_option('pve-node'),
2677 vmid => get_standard_option('pve-vmid'),
2678 disk => {
2679 optional => 1,
2680 type => 'string',
2681 description => "If you want to convert only 1 disk to base image.",
2682 enum => [PVE::QemuServer::disknames()],
2683 },
2684
2685 },
2686 },
2687 returns => { type => 'null'},
2688 code => sub {
2689 my ($param) = @_;
2690
2691 my $rpcenv = PVE::RPCEnvironment::get();
2692
2693 my $authuser = $rpcenv->get_user();
2694
2695 my $node = extract_param($param, 'node');
2696
2697 my $vmid = extract_param($param, 'vmid');
2698
2699 my $disk = extract_param($param, 'disk');
2700
2701 my $updatefn = sub {
2702
2703 my $conf = PVE::QemuServer::load_config($vmid);
2704
2705 PVE::QemuServer::check_lock($conf);
2706
2707 die "unable to create template, because VM contains snapshots\n"
2708 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
2709
2710 die "you can't convert a template to a template\n"
2711 if PVE::QemuServer::is_template($conf) && !$disk;
2712
2713 die "you can't convert a VM to template if VM is running\n"
2714 if PVE::QemuServer::check_running($vmid);
2715
2716 my $realcmd = sub {
2717 PVE::QemuServer::template_create($vmid, $conf, $disk);
2718 };
2719
2720 $conf->{template} = 1;
2721 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2722
2723 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
2724 };
2725
2726 PVE::QemuServer::lock_config($vmid, $updatefn);
2727 return undef;
2728 }});
2729
2730
2731
2732 1;