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