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