]> git.proxmox.com Git - qemu-server.git/blob - PVE/API2/Qemu.pm
vm_start: apply pending changes
[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 # fixme: wrong place? howto handle pending changes? @delete ?
949 if ($param->{memory} || defined($param->{balloon})) {
950 my $maxmem = $param->{memory} || $conf->{memory} || $defaults->{memory};
951 my $balloon = defined($param->{balloon}) ? $param->{balloon} : $conf->{balloon};
952
953 die "balloon value too large (must be smaller than assigned memory)\n"
954 if $balloon && $balloon > $maxmem;
955 }
956
957 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
958
959 my $worker = sub {
960
961 print "update VM $vmid: " . join (' ', @paramarr) . "\n";
962
963 # write updates to pending section
964
965 foreach my $opt (@delete) {
966 $conf = PVE::QemuServer::load_config($vmid); # update/reload
967 if ($opt =~ m/^unused/) {
968 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
969 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
970 if (my $sid = &$test_deallocate_drive($storecfg, $vmid, $opt, $drive, $force)) {
971 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
972 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive);
973 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
974 }
975 } elsif (PVE::QemuServer::valid_drivename($opt)) {
976 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
977 PVE::QemuServer::vmconfig_register_unused_drive($storecfg, $vmid, $conf, PVE::QemuServer::parse_drive($opt, $conf->{pending}->{$opt}))
978 if defined($conf->{pending}->{$opt});
979 PVE::QemuServer::vmconfig_delete_pending_option($conf, $opt);
980 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
981 } else {
982 PVE::QemuServer::vmconfig_delete_pending_option($conf, $opt);
983 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
984 }
985 }
986
987 foreach my $opt (keys %$param) { # add/change
988 $conf = PVE::QemuServer::load_config($vmid); # update/reload
989 next if defined($conf->{pending}->{$opt}) && ($param->{$opt} eq $conf->{pending}->{$opt}); # skip if nothing changed
990
991 if (PVE::QemuServer::valid_drivename($opt)) {
992 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
993 if (PVE::QemuServer::drive_is_cdrom($drive)) { # CDROM
994 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
995 } else {
996 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
997 }
998 PVE::QemuServer::vmconfig_register_unused_drive($storecfg, $vmid, $conf, PVE::QemuServer::parse_drive($opt, $conf->{pending}->{$opt}))
999 if defined($conf->{pending}->{$opt});
1000
1001 &$create_disks($rpcenv, $authuser, $conf->{pending}, $storecfg, $vmid, undef, {$opt => $param->{$opt}});
1002 } else {
1003 $conf->{pending}->{$opt} = $param->{$opt};
1004 }
1005 PVE::QemuServer::vmconfig_undelete_pending_option($conf, $opt);
1006 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
1007 }
1008
1009 # remove pending changes when nothing changed
1010 my $changes;
1011 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1012 foreach my $opt (keys %{$conf->{pending}}) { # add/change
1013 if (defined($conf->{$opt}) && ($conf->{pending}->{$opt} eq $conf->{$opt})) {
1014 $changes = 1;
1015 delete $conf->{pending}->{$opt};
1016 }
1017 }
1018 PVE::QemuServer::update_config_nolock($vmid, $conf, 1) if $changes;
1019
1020 return if !scalar(keys %{$conf->{pending}});
1021
1022 my $running = PVE::QemuServer::check_running($vmid);
1023
1024 # apply pending changes
1025
1026 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1027 PVE::QemuServer::vmconfig_apply_pending($vmid, $conf, $storecfg, $running);
1028
1029 return; # TODO: remove old code below
1030
1031 foreach my $opt (keys %$param) { # add/change
1032
1033 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1034
1035 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
1036
1037 if (PVE::QemuServer::valid_drivename($opt)) {
1038
1039 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
1040 $opt, $param->{$opt}, $force);
1041
1042 } elsif ($opt =~ m/^net(\d+)$/) { #nics
1043
1044 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
1045 $opt, $param->{$opt});
1046
1047 } else {
1048
1049 if($opt eq 'tablet' && $param->{$opt} == 1){
1050 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt);
1051 } elsif($opt eq 'tablet' && $param->{$opt} == 0){
1052 PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
1053 }
1054
1055 if($opt eq 'cores' && $conf->{maxcpus}){
1056 PVE::QemuServer::qemu_cpu_hotplug($vmid, $conf, $param->{$opt});
1057 }
1058
1059 $conf->{$opt} = $param->{$opt};
1060 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
1061 }
1062 }
1063
1064 # allow manual ballooning if shares is set to zero
1065 if ($running && defined($param->{balloon}) &&
1066 defined($conf->{shares}) && ($conf->{shares} == 0)) {
1067 my $balloon = $param->{'balloon'} || $conf->{memory} || $defaults->{memory};
1068 PVE::QemuServer::vm_mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
1069 }
1070 };
1071
1072 if ($sync) {
1073 &$worker();
1074 return undef;
1075 } else {
1076 my $upid = $rpcenv->fork_worker('qmconfig', $vmid, $authuser, $worker);
1077
1078 if ($background_delay) {
1079
1080 # Note: It would be better to do that in the Event based HTTPServer
1081 # to avoid blocking call to sleep.
1082
1083 my $end_time = time() + $background_delay;
1084
1085 my $task = PVE::Tools::upid_decode($upid);
1086
1087 my $running = 1;
1088 while (time() < $end_time) {
1089 $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
1090 last if !$running;
1091 sleep(1); # this gets interrupted when child process ends
1092 }
1093
1094 if (!$running) {
1095 my $status = PVE::Tools::upid_read_status($upid);
1096 return undef if $status eq 'OK';
1097 die $status;
1098 }
1099 }
1100
1101 return $upid;
1102 }
1103 };
1104
1105 return PVE::QemuServer::lock_config($vmid, $updatefn);
1106 };
1107
1108 my $vm_config_perm_list = [
1109 'VM.Config.Disk',
1110 'VM.Config.CDROM',
1111 'VM.Config.CPU',
1112 'VM.Config.Memory',
1113 'VM.Config.Network',
1114 'VM.Config.HWType',
1115 'VM.Config.Options',
1116 ];
1117
1118 __PACKAGE__->register_method({
1119 name => 'update_vm_async',
1120 path => '{vmid}/config',
1121 method => 'POST',
1122 protected => 1,
1123 proxyto => 'node',
1124 description => "Set virtual machine options (asynchrounous API).",
1125 permissions => {
1126 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
1127 },
1128 parameters => {
1129 additionalProperties => 0,
1130 properties => PVE::QemuServer::json_config_properties(
1131 {
1132 node => get_standard_option('pve-node'),
1133 vmid => get_standard_option('pve-vmid'),
1134 skiplock => get_standard_option('skiplock'),
1135 delete => {
1136 type => 'string', format => 'pve-configid-list',
1137 description => "A list of settings you want to delete.",
1138 optional => 1,
1139 },
1140 force => {
1141 type => 'boolean',
1142 description => $opt_force_description,
1143 optional => 1,
1144 requires => 'delete',
1145 },
1146 digest => {
1147 type => 'string',
1148 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1149 maxLength => 40,
1150 optional => 1,
1151 },
1152 background_delay => {
1153 type => 'integer',
1154 description => "Time to wait for the task to finish. We return 'null' if the task finish within that time.",
1155 minimum => 1,
1156 maximum => 30,
1157 optional => 1,
1158 },
1159 }),
1160 },
1161 returns => {
1162 type => 'string',
1163 optional => 1,
1164 },
1165 code => $update_vm_api,
1166 });
1167
1168 __PACKAGE__->register_method({
1169 name => 'update_vm',
1170 path => '{vmid}/config',
1171 method => 'PUT',
1172 protected => 1,
1173 proxyto => 'node',
1174 description => "Set virtual machine options (synchrounous API) - You should consider using the POST method instead for any actions involving hotplug or storage allocation.",
1175 permissions => {
1176 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
1177 },
1178 parameters => {
1179 additionalProperties => 0,
1180 properties => PVE::QemuServer::json_config_properties(
1181 {
1182 node => get_standard_option('pve-node'),
1183 vmid => get_standard_option('pve-vmid'),
1184 skiplock => get_standard_option('skiplock'),
1185 delete => {
1186 type => 'string', format => 'pve-configid-list',
1187 description => "A list of settings you want to delete.",
1188 optional => 1,
1189 },
1190 force => {
1191 type => 'boolean',
1192 description => $opt_force_description,
1193 optional => 1,
1194 requires => 'delete',
1195 },
1196 digest => {
1197 type => 'string',
1198 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1199 maxLength => 40,
1200 optional => 1,
1201 },
1202 }),
1203 },
1204 returns => { type => 'null' },
1205 code => sub {
1206 my ($param) = @_;
1207 &$update_vm_api($param, 1);
1208 return undef;
1209 }
1210 });
1211
1212
1213 __PACKAGE__->register_method({
1214 name => 'destroy_vm',
1215 path => '{vmid}',
1216 method => 'DELETE',
1217 protected => 1,
1218 proxyto => 'node',
1219 description => "Destroy the vm (also delete all used/owned volumes).",
1220 permissions => {
1221 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
1222 },
1223 parameters => {
1224 additionalProperties => 0,
1225 properties => {
1226 node => get_standard_option('pve-node'),
1227 vmid => get_standard_option('pve-vmid'),
1228 skiplock => get_standard_option('skiplock'),
1229 },
1230 },
1231 returns => {
1232 type => 'string',
1233 },
1234 code => sub {
1235 my ($param) = @_;
1236
1237 my $rpcenv = PVE::RPCEnvironment::get();
1238
1239 my $authuser = $rpcenv->get_user();
1240
1241 my $vmid = $param->{vmid};
1242
1243 my $skiplock = $param->{skiplock};
1244 raise_param_exc({ skiplock => "Only root may use this option." })
1245 if $skiplock && $authuser ne 'root@pam';
1246
1247 # test if VM exists
1248 my $conf = PVE::QemuServer::load_config($vmid);
1249
1250 my $storecfg = PVE::Storage::config();
1251
1252 my $delVMfromPoolFn = sub {
1253 my $usercfg = cfs_read_file("user.cfg");
1254 if (my $pool = $usercfg->{vms}->{$vmid}) {
1255 if (my $data = $usercfg->{pools}->{$pool}) {
1256 delete $data->{vms}->{$vmid};
1257 delete $usercfg->{vms}->{$vmid};
1258 cfs_write_file("user.cfg", $usercfg);
1259 }
1260 }
1261 };
1262
1263 my $realcmd = sub {
1264 my $upid = shift;
1265
1266 syslog('info', "destroy VM $vmid: $upid\n");
1267
1268 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
1269
1270 PVE::AccessControl::remove_vm_from_pool($vmid);
1271 };
1272
1273 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1274 }});
1275
1276 __PACKAGE__->register_method({
1277 name => 'unlink',
1278 path => '{vmid}/unlink',
1279 method => 'PUT',
1280 protected => 1,
1281 proxyto => 'node',
1282 description => "Unlink/delete disk images.",
1283 permissions => {
1284 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
1285 },
1286 parameters => {
1287 additionalProperties => 0,
1288 properties => {
1289 node => get_standard_option('pve-node'),
1290 vmid => get_standard_option('pve-vmid'),
1291 idlist => {
1292 type => 'string', format => 'pve-configid-list',
1293 description => "A list of disk IDs you want to delete.",
1294 },
1295 force => {
1296 type => 'boolean',
1297 description => $opt_force_description,
1298 optional => 1,
1299 },
1300 },
1301 },
1302 returns => { type => 'null'},
1303 code => sub {
1304 my ($param) = @_;
1305
1306 $param->{delete} = extract_param($param, 'idlist');
1307
1308 __PACKAGE__->update_vm($param);
1309
1310 return undef;
1311 }});
1312
1313 my $sslcert;
1314
1315 __PACKAGE__->register_method({
1316 name => 'vncproxy',
1317 path => '{vmid}/vncproxy',
1318 method => 'POST',
1319 protected => 1,
1320 permissions => {
1321 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1322 },
1323 description => "Creates a TCP VNC proxy connections.",
1324 parameters => {
1325 additionalProperties => 0,
1326 properties => {
1327 node => get_standard_option('pve-node'),
1328 vmid => get_standard_option('pve-vmid'),
1329 websocket => {
1330 optional => 1,
1331 type => 'boolean',
1332 description => "starts websockify instead of vncproxy",
1333 },
1334 },
1335 },
1336 returns => {
1337 additionalProperties => 0,
1338 properties => {
1339 user => { type => 'string' },
1340 ticket => { type => 'string' },
1341 cert => { type => 'string' },
1342 port => { type => 'integer' },
1343 upid => { type => 'string' },
1344 },
1345 },
1346 code => sub {
1347 my ($param) = @_;
1348
1349 my $rpcenv = PVE::RPCEnvironment::get();
1350
1351 my $authuser = $rpcenv->get_user();
1352
1353 my $vmid = $param->{vmid};
1354 my $node = $param->{node};
1355 my $websocket = $param->{websocket};
1356
1357 my $conf = PVE::QemuServer::load_config($vmid, $node); # check if VM exists
1358
1359 my $authpath = "/vms/$vmid";
1360
1361 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
1362
1363 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1364 if !$sslcert;
1365
1366 my $port = PVE::Tools::next_vnc_port();
1367
1368 my $remip;
1369 my $remcmd = [];
1370
1371 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1372 $remip = PVE::Cluster::remote_node_ip($node);
1373 # NOTE: kvm VNC traffic is already TLS encrypted or is known unsecure
1374 $remcmd = ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes', $remip];
1375 }
1376
1377 my $timeout = 10;
1378
1379 my $realcmd = sub {
1380 my $upid = shift;
1381
1382 syslog('info', "starting vnc proxy $upid\n");
1383
1384 my $cmd;
1385
1386 if ($conf->{vga} && ($conf->{vga} =~ m/^serial\d+$/)) {
1387
1388 die "Websocket mode is not supported in vga serial mode!" if $websocket;
1389
1390 my $termcmd = [ '/usr/sbin/qm', 'terminal', $vmid, '-iface', $conf->{vga} ];
1391 #my $termcmd = "/usr/bin/qm terminal -iface $conf->{vga}";
1392 $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
1393 '-timeout', $timeout, '-authpath', $authpath,
1394 '-perm', 'Sys.Console', '-c', @$remcmd, @$termcmd];
1395 } else {
1396
1397 $ENV{LC_PVE_TICKET} = $ticket if $websocket; # set ticket with "qm vncproxy"
1398
1399 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1400
1401 my $qmstr = join(' ', @$qmcmd);
1402
1403 # also redirect stderr (else we get RFB protocol errors)
1404 $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1405 }
1406
1407 PVE::Tools::run_command($cmd);
1408
1409 return;
1410 };
1411
1412 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1413
1414 PVE::Tools::wait_for_vnc_port($port);
1415
1416 return {
1417 user => $authuser,
1418 ticket => $ticket,
1419 port => $port,
1420 upid => $upid,
1421 cert => $sslcert,
1422 };
1423 }});
1424
1425 __PACKAGE__->register_method({
1426 name => 'vncwebsocket',
1427 path => '{vmid}/vncwebsocket',
1428 method => 'GET',
1429 permissions => {
1430 description => "You also need to pass a valid ticket (vncticket).",
1431 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1432 },
1433 description => "Opens a weksocket for VNC traffic.",
1434 parameters => {
1435 additionalProperties => 0,
1436 properties => {
1437 node => get_standard_option('pve-node'),
1438 vmid => get_standard_option('pve-vmid'),
1439 vncticket => {
1440 description => "Ticket from previous call to vncproxy.",
1441 type => 'string',
1442 maxLength => 512,
1443 },
1444 port => {
1445 description => "Port number returned by previous vncproxy call.",
1446 type => 'integer',
1447 minimum => 5900,
1448 maximum => 5999,
1449 },
1450 },
1451 },
1452 returns => {
1453 type => "object",
1454 properties => {
1455 port => { type => 'string' },
1456 },
1457 },
1458 code => sub {
1459 my ($param) = @_;
1460
1461 my $rpcenv = PVE::RPCEnvironment::get();
1462
1463 my $authuser = $rpcenv->get_user();
1464
1465 my $vmid = $param->{vmid};
1466 my $node = $param->{node};
1467
1468 my $authpath = "/vms/$vmid";
1469
1470 PVE::AccessControl::verify_vnc_ticket($param->{vncticket}, $authuser, $authpath);
1471
1472 my $conf = PVE::QemuServer::load_config($vmid, $node); # VM exists ?
1473
1474 # Note: VNC ports are acessible from outside, so we do not gain any
1475 # security if we verify that $param->{port} belongs to VM $vmid. This
1476 # check is done by verifying the VNC ticket (inside VNC protocol).
1477
1478 my $port = $param->{port};
1479
1480 return { port => $port };
1481 }});
1482
1483 __PACKAGE__->register_method({
1484 name => 'spiceproxy',
1485 path => '{vmid}/spiceproxy',
1486 method => 'POST',
1487 protected => 1,
1488 proxyto => 'node',
1489 permissions => {
1490 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1491 },
1492 description => "Returns a SPICE configuration to connect to the VM.",
1493 parameters => {
1494 additionalProperties => 0,
1495 properties => {
1496 node => get_standard_option('pve-node'),
1497 vmid => get_standard_option('pve-vmid'),
1498 proxy => get_standard_option('spice-proxy', { optional => 1 }),
1499 },
1500 },
1501 returns => get_standard_option('remote-viewer-config'),
1502 code => sub {
1503 my ($param) = @_;
1504
1505 my $rpcenv = PVE::RPCEnvironment::get();
1506
1507 my $authuser = $rpcenv->get_user();
1508
1509 my $vmid = $param->{vmid};
1510 my $node = $param->{node};
1511 my $proxy = $param->{proxy};
1512
1513 my $conf = PVE::QemuServer::load_config($vmid, $node);
1514 my $title = "VM $vmid - $conf->{'name'}",
1515
1516 my $port = PVE::QemuServer::spice_port($vmid);
1517
1518 my ($ticket, undef, $remote_viewer_config) =
1519 PVE::AccessControl::remote_viewer_config($authuser, $vmid, $node, $proxy, $title, $port);
1520
1521 PVE::QemuServer::vm_mon_cmd($vmid, "set_password", protocol => 'spice', password => $ticket);
1522 PVE::QemuServer::vm_mon_cmd($vmid, "expire_password", protocol => 'spice', time => "+30");
1523
1524 return $remote_viewer_config;
1525 }});
1526
1527 __PACKAGE__->register_method({
1528 name => 'vmcmdidx',
1529 path => '{vmid}/status',
1530 method => 'GET',
1531 proxyto => 'node',
1532 description => "Directory index",
1533 permissions => {
1534 user => 'all',
1535 },
1536 parameters => {
1537 additionalProperties => 0,
1538 properties => {
1539 node => get_standard_option('pve-node'),
1540 vmid => get_standard_option('pve-vmid'),
1541 },
1542 },
1543 returns => {
1544 type => 'array',
1545 items => {
1546 type => "object",
1547 properties => {
1548 subdir => { type => 'string' },
1549 },
1550 },
1551 links => [ { rel => 'child', href => "{subdir}" } ],
1552 },
1553 code => sub {
1554 my ($param) = @_;
1555
1556 # test if VM exists
1557 my $conf = PVE::QemuServer::load_config($param->{vmid});
1558
1559 my $res = [
1560 { subdir => 'current' },
1561 { subdir => 'start' },
1562 { subdir => 'stop' },
1563 ];
1564
1565 return $res;
1566 }});
1567
1568 my $vm_is_ha_managed = sub {
1569 my ($vmid) = @_;
1570
1571 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1572 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1573 return 1;
1574 }
1575 return 0;
1576 };
1577
1578 __PACKAGE__->register_method({
1579 name => 'vm_status',
1580 path => '{vmid}/status/current',
1581 method => 'GET',
1582 proxyto => 'node',
1583 protected => 1, # qemu pid files are only readable by root
1584 description => "Get virtual machine status.",
1585 permissions => {
1586 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1587 },
1588 parameters => {
1589 additionalProperties => 0,
1590 properties => {
1591 node => get_standard_option('pve-node'),
1592 vmid => get_standard_option('pve-vmid'),
1593 },
1594 },
1595 returns => { type => 'object' },
1596 code => sub {
1597 my ($param) = @_;
1598
1599 # test if VM exists
1600 my $conf = PVE::QemuServer::load_config($param->{vmid});
1601
1602 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
1603 my $status = $vmstatus->{$param->{vmid}};
1604
1605 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
1606
1607 $status->{spice} = 1 if PVE::QemuServer::vga_conf_has_spice($conf->{vga});
1608
1609 return $status;
1610 }});
1611
1612 __PACKAGE__->register_method({
1613 name => 'vm_start',
1614 path => '{vmid}/status/start',
1615 method => 'POST',
1616 protected => 1,
1617 proxyto => 'node',
1618 description => "Start virtual machine.",
1619 permissions => {
1620 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1621 },
1622 parameters => {
1623 additionalProperties => 0,
1624 properties => {
1625 node => get_standard_option('pve-node'),
1626 vmid => get_standard_option('pve-vmid'),
1627 skiplock => get_standard_option('skiplock'),
1628 stateuri => get_standard_option('pve-qm-stateuri'),
1629 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
1630 machine => get_standard_option('pve-qm-machine'),
1631 },
1632 },
1633 returns => {
1634 type => 'string',
1635 },
1636 code => sub {
1637 my ($param) = @_;
1638
1639 my $rpcenv = PVE::RPCEnvironment::get();
1640
1641 my $authuser = $rpcenv->get_user();
1642
1643 my $node = extract_param($param, 'node');
1644
1645 my $vmid = extract_param($param, 'vmid');
1646
1647 my $machine = extract_param($param, 'machine');
1648
1649 my $stateuri = extract_param($param, 'stateuri');
1650 raise_param_exc({ stateuri => "Only root may use this option." })
1651 if $stateuri && $authuser ne 'root@pam';
1652
1653 my $skiplock = extract_param($param, 'skiplock');
1654 raise_param_exc({ skiplock => "Only root may use this option." })
1655 if $skiplock && $authuser ne 'root@pam';
1656
1657 my $migratedfrom = extract_param($param, 'migratedfrom');
1658 raise_param_exc({ migratedfrom => "Only root may use this option." })
1659 if $migratedfrom && $authuser ne 'root@pam';
1660
1661 # read spice ticket from STDIN
1662 my $spice_ticket;
1663 if ($stateuri && ($stateuri eq 'tcp') && $migratedfrom && ($rpcenv->{type} eq 'cli')) {
1664 if (defined(my $line = <>)) {
1665 chomp $line;
1666 $spice_ticket = $line;
1667 }
1668 }
1669
1670 my $storecfg = PVE::Storage::config();
1671
1672 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1673 $rpcenv->{type} ne 'ha') {
1674
1675 my $hacmd = sub {
1676 my $upid = shift;
1677
1678 my $service = "pvevm:$vmid";
1679
1680 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1681
1682 print "Executing HA start for VM $vmid\n";
1683
1684 PVE::Tools::run_command($cmd);
1685
1686 return;
1687 };
1688
1689 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1690
1691 } else {
1692
1693 my $realcmd = sub {
1694 my $upid = shift;
1695
1696 syslog('info', "start VM $vmid: $upid\n");
1697
1698 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock, $migratedfrom, undef,
1699 $machine, $spice_ticket);
1700
1701 return;
1702 };
1703
1704 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1705 }
1706 }});
1707
1708 __PACKAGE__->register_method({
1709 name => 'vm_stop',
1710 path => '{vmid}/status/stop',
1711 method => 'POST',
1712 protected => 1,
1713 proxyto => 'node',
1714 description => "Stop virtual machine.",
1715 permissions => {
1716 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1717 },
1718 parameters => {
1719 additionalProperties => 0,
1720 properties => {
1721 node => get_standard_option('pve-node'),
1722 vmid => get_standard_option('pve-vmid'),
1723 skiplock => get_standard_option('skiplock'),
1724 migratedfrom => get_standard_option('pve-node', { optional => 1 }),
1725 timeout => {
1726 description => "Wait maximal timeout seconds.",
1727 type => 'integer',
1728 minimum => 0,
1729 optional => 1,
1730 },
1731 keepActive => {
1732 description => "Do not decativate storage volumes.",
1733 type => 'boolean',
1734 optional => 1,
1735 default => 0,
1736 }
1737 },
1738 },
1739 returns => {
1740 type => 'string',
1741 },
1742 code => sub {
1743 my ($param) = @_;
1744
1745 my $rpcenv = PVE::RPCEnvironment::get();
1746
1747 my $authuser = $rpcenv->get_user();
1748
1749 my $node = extract_param($param, 'node');
1750
1751 my $vmid = extract_param($param, 'vmid');
1752
1753 my $skiplock = extract_param($param, 'skiplock');
1754 raise_param_exc({ skiplock => "Only root may use this option." })
1755 if $skiplock && $authuser ne 'root@pam';
1756
1757 my $keepActive = extract_param($param, 'keepActive');
1758 raise_param_exc({ keepActive => "Only root may use this option." })
1759 if $keepActive && $authuser ne 'root@pam';
1760
1761 my $migratedfrom = extract_param($param, 'migratedfrom');
1762 raise_param_exc({ migratedfrom => "Only root may use this option." })
1763 if $migratedfrom && $authuser ne 'root@pam';
1764
1765
1766 my $storecfg = PVE::Storage::config();
1767
1768 if (&$vm_is_ha_managed($vmid) && ($rpcenv->{type} ne 'ha') && !defined($migratedfrom)) {
1769
1770 my $hacmd = sub {
1771 my $upid = shift;
1772
1773 my $service = "pvevm:$vmid";
1774
1775 my $cmd = ['clusvcadm', '-d', $service];
1776
1777 print "Executing HA stop for VM $vmid\n";
1778
1779 PVE::Tools::run_command($cmd);
1780
1781 return;
1782 };
1783
1784 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1785
1786 } else {
1787 my $realcmd = sub {
1788 my $upid = shift;
1789
1790 syslog('info', "stop VM $vmid: $upid\n");
1791
1792 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
1793 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
1794
1795 return;
1796 };
1797
1798 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1799 }
1800 }});
1801
1802 __PACKAGE__->register_method({
1803 name => 'vm_reset',
1804 path => '{vmid}/status/reset',
1805 method => 'POST',
1806 protected => 1,
1807 proxyto => 'node',
1808 description => "Reset virtual machine.",
1809 permissions => {
1810 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1811 },
1812 parameters => {
1813 additionalProperties => 0,
1814 properties => {
1815 node => get_standard_option('pve-node'),
1816 vmid => get_standard_option('pve-vmid'),
1817 skiplock => get_standard_option('skiplock'),
1818 },
1819 },
1820 returns => {
1821 type => 'string',
1822 },
1823 code => sub {
1824 my ($param) = @_;
1825
1826 my $rpcenv = PVE::RPCEnvironment::get();
1827
1828 my $authuser = $rpcenv->get_user();
1829
1830 my $node = extract_param($param, 'node');
1831
1832 my $vmid = extract_param($param, 'vmid');
1833
1834 my $skiplock = extract_param($param, 'skiplock');
1835 raise_param_exc({ skiplock => "Only root may use this option." })
1836 if $skiplock && $authuser ne 'root@pam';
1837
1838 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1839
1840 my $realcmd = sub {
1841 my $upid = shift;
1842
1843 PVE::QemuServer::vm_reset($vmid, $skiplock);
1844
1845 return;
1846 };
1847
1848 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
1849 }});
1850
1851 __PACKAGE__->register_method({
1852 name => 'vm_shutdown',
1853 path => '{vmid}/status/shutdown',
1854 method => 'POST',
1855 protected => 1,
1856 proxyto => 'node',
1857 description => "Shutdown virtual machine.",
1858 permissions => {
1859 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1860 },
1861 parameters => {
1862 additionalProperties => 0,
1863 properties => {
1864 node => get_standard_option('pve-node'),
1865 vmid => get_standard_option('pve-vmid'),
1866 skiplock => get_standard_option('skiplock'),
1867 timeout => {
1868 description => "Wait maximal timeout seconds.",
1869 type => 'integer',
1870 minimum => 0,
1871 optional => 1,
1872 },
1873 forceStop => {
1874 description => "Make sure the VM stops.",
1875 type => 'boolean',
1876 optional => 1,
1877 default => 0,
1878 },
1879 keepActive => {
1880 description => "Do not decativate storage volumes.",
1881 type => 'boolean',
1882 optional => 1,
1883 default => 0,
1884 }
1885 },
1886 },
1887 returns => {
1888 type => 'string',
1889 },
1890 code => sub {
1891 my ($param) = @_;
1892
1893 my $rpcenv = PVE::RPCEnvironment::get();
1894
1895 my $authuser = $rpcenv->get_user();
1896
1897 my $node = extract_param($param, 'node');
1898
1899 my $vmid = extract_param($param, 'vmid');
1900
1901 my $skiplock = extract_param($param, 'skiplock');
1902 raise_param_exc({ skiplock => "Only root may use this option." })
1903 if $skiplock && $authuser ne 'root@pam';
1904
1905 my $keepActive = extract_param($param, 'keepActive');
1906 raise_param_exc({ keepActive => "Only root may use this option." })
1907 if $keepActive && $authuser ne 'root@pam';
1908
1909 my $storecfg = PVE::Storage::config();
1910
1911 my $realcmd = sub {
1912 my $upid = shift;
1913
1914 syslog('info', "shutdown VM $vmid: $upid\n");
1915
1916 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
1917 1, $param->{forceStop}, $keepActive);
1918
1919 return;
1920 };
1921
1922 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
1923 }});
1924
1925 __PACKAGE__->register_method({
1926 name => 'vm_suspend',
1927 path => '{vmid}/status/suspend',
1928 method => 'POST',
1929 protected => 1,
1930 proxyto => 'node',
1931 description => "Suspend virtual machine.",
1932 permissions => {
1933 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1934 },
1935 parameters => {
1936 additionalProperties => 0,
1937 properties => {
1938 node => get_standard_option('pve-node'),
1939 vmid => get_standard_option('pve-vmid'),
1940 skiplock => get_standard_option('skiplock'),
1941 },
1942 },
1943 returns => {
1944 type => 'string',
1945 },
1946 code => sub {
1947 my ($param) = @_;
1948
1949 my $rpcenv = PVE::RPCEnvironment::get();
1950
1951 my $authuser = $rpcenv->get_user();
1952
1953 my $node = extract_param($param, 'node');
1954
1955 my $vmid = extract_param($param, 'vmid');
1956
1957 my $skiplock = extract_param($param, 'skiplock');
1958 raise_param_exc({ skiplock => "Only root may use this option." })
1959 if $skiplock && $authuser ne 'root@pam';
1960
1961 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1962
1963 my $realcmd = sub {
1964 my $upid = shift;
1965
1966 syslog('info', "suspend VM $vmid: $upid\n");
1967
1968 PVE::QemuServer::vm_suspend($vmid, $skiplock);
1969
1970 return;
1971 };
1972
1973 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
1974 }});
1975
1976 __PACKAGE__->register_method({
1977 name => 'vm_resume',
1978 path => '{vmid}/status/resume',
1979 method => 'POST',
1980 protected => 1,
1981 proxyto => 'node',
1982 description => "Resume virtual machine.",
1983 permissions => {
1984 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1985 },
1986 parameters => {
1987 additionalProperties => 0,
1988 properties => {
1989 node => get_standard_option('pve-node'),
1990 vmid => get_standard_option('pve-vmid'),
1991 skiplock => get_standard_option('skiplock'),
1992 },
1993 },
1994 returns => {
1995 type => 'string',
1996 },
1997 code => sub {
1998 my ($param) = @_;
1999
2000 my $rpcenv = PVE::RPCEnvironment::get();
2001
2002 my $authuser = $rpcenv->get_user();
2003
2004 my $node = extract_param($param, 'node');
2005
2006 my $vmid = extract_param($param, 'vmid');
2007
2008 my $skiplock = extract_param($param, 'skiplock');
2009 raise_param_exc({ skiplock => "Only root may use this option." })
2010 if $skiplock && $authuser ne 'root@pam';
2011
2012 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
2013
2014 my $realcmd = sub {
2015 my $upid = shift;
2016
2017 syslog('info', "resume VM $vmid: $upid\n");
2018
2019 PVE::QemuServer::vm_resume($vmid, $skiplock);
2020
2021 return;
2022 };
2023
2024 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
2025 }});
2026
2027 __PACKAGE__->register_method({
2028 name => 'vm_sendkey',
2029 path => '{vmid}/sendkey',
2030 method => 'PUT',
2031 protected => 1,
2032 proxyto => 'node',
2033 description => "Send key event to virtual machine.",
2034 permissions => {
2035 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
2036 },
2037 parameters => {
2038 additionalProperties => 0,
2039 properties => {
2040 node => get_standard_option('pve-node'),
2041 vmid => get_standard_option('pve-vmid'),
2042 skiplock => get_standard_option('skiplock'),
2043 key => {
2044 description => "The key (qemu monitor encoding).",
2045 type => 'string'
2046 }
2047 },
2048 },
2049 returns => { type => 'null'},
2050 code => sub {
2051 my ($param) = @_;
2052
2053 my $rpcenv = PVE::RPCEnvironment::get();
2054
2055 my $authuser = $rpcenv->get_user();
2056
2057 my $node = extract_param($param, 'node');
2058
2059 my $vmid = extract_param($param, 'vmid');
2060
2061 my $skiplock = extract_param($param, 'skiplock');
2062 raise_param_exc({ skiplock => "Only root may use this option." })
2063 if $skiplock && $authuser ne 'root@pam';
2064
2065 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
2066
2067 return;
2068 }});
2069
2070 __PACKAGE__->register_method({
2071 name => 'vm_feature',
2072 path => '{vmid}/feature',
2073 method => 'GET',
2074 proxyto => 'node',
2075 protected => 1,
2076 description => "Check if feature for virtual machine is available.",
2077 permissions => {
2078 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2079 },
2080 parameters => {
2081 additionalProperties => 0,
2082 properties => {
2083 node => get_standard_option('pve-node'),
2084 vmid => get_standard_option('pve-vmid'),
2085 feature => {
2086 description => "Feature to check.",
2087 type => 'string',
2088 enum => [ 'snapshot', 'clone', 'copy' ],
2089 },
2090 snapname => get_standard_option('pve-snapshot-name', {
2091 optional => 1,
2092 }),
2093 },
2094 },
2095 returns => {
2096 type => "object",
2097 properties => {
2098 hasFeature => { type => 'boolean' },
2099 nodes => {
2100 type => 'array',
2101 items => { type => 'string' },
2102 }
2103 },
2104 },
2105 code => sub {
2106 my ($param) = @_;
2107
2108 my $node = extract_param($param, 'node');
2109
2110 my $vmid = extract_param($param, 'vmid');
2111
2112 my $snapname = extract_param($param, 'snapname');
2113
2114 my $feature = extract_param($param, 'feature');
2115
2116 my $running = PVE::QemuServer::check_running($vmid);
2117
2118 my $conf = PVE::QemuServer::load_config($vmid);
2119
2120 if($snapname){
2121 my $snap = $conf->{snapshots}->{$snapname};
2122 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2123 $conf = $snap;
2124 }
2125 my $storecfg = PVE::Storage::config();
2126
2127 my $nodelist = PVE::QemuServer::shared_nodes($conf, $storecfg);
2128 my $hasFeature = PVE::QemuServer::has_feature($feature, $conf, $storecfg, $snapname, $running);
2129
2130 return {
2131 hasFeature => $hasFeature,
2132 nodes => [ keys %$nodelist ],
2133 };
2134 }});
2135
2136 __PACKAGE__->register_method({
2137 name => 'clone_vm',
2138 path => '{vmid}/clone',
2139 method => 'POST',
2140 protected => 1,
2141 proxyto => 'node',
2142 description => "Create a copy of virtual machine/template.",
2143 permissions => {
2144 description => "You need 'VM.Clone' permissions on /vms/{vmid}, and 'VM.Allocate' permissions " .
2145 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
2146 "'Datastore.AllocateSpace' on any used storage.",
2147 check =>
2148 [ 'and',
2149 ['perm', '/vms/{vmid}', [ 'VM.Clone' ]],
2150 [ 'or',
2151 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
2152 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
2153 ],
2154 ]
2155 },
2156 parameters => {
2157 additionalProperties => 0,
2158 properties => {
2159 node => get_standard_option('pve-node'),
2160 vmid => get_standard_option('pve-vmid'),
2161 newid => get_standard_option('pve-vmid', { description => 'VMID for the clone.' }),
2162 name => {
2163 optional => 1,
2164 type => 'string', format => 'dns-name',
2165 description => "Set a name for the new VM.",
2166 },
2167 description => {
2168 optional => 1,
2169 type => 'string',
2170 description => "Description for the new VM.",
2171 },
2172 pool => {
2173 optional => 1,
2174 type => 'string', format => 'pve-poolid',
2175 description => "Add the new VM to the specified pool.",
2176 },
2177 snapname => get_standard_option('pve-snapshot-name', {
2178 optional => 1,
2179 }),
2180 storage => get_standard_option('pve-storage-id', {
2181 description => "Target storage for full clone.",
2182 requires => 'full',
2183 optional => 1,
2184 }),
2185 'format' => {
2186 description => "Target format for file storage.",
2187 requires => 'full',
2188 type => 'string',
2189 optional => 1,
2190 enum => [ 'raw', 'qcow2', 'vmdk'],
2191 },
2192 full => {
2193 optional => 1,
2194 type => 'boolean',
2195 description => "Create a full copy of all disk. This is always done when " .
2196 "you clone a normal VM. For VM templates, we try to create a linked clone by default.",
2197 default => 0,
2198 },
2199 target => get_standard_option('pve-node', {
2200 description => "Target node. Only allowed if the original VM is on shared storage.",
2201 optional => 1,
2202 }),
2203 },
2204 },
2205 returns => {
2206 type => 'string',
2207 },
2208 code => sub {
2209 my ($param) = @_;
2210
2211 my $rpcenv = PVE::RPCEnvironment::get();
2212
2213 my $authuser = $rpcenv->get_user();
2214
2215 my $node = extract_param($param, 'node');
2216
2217 my $vmid = extract_param($param, 'vmid');
2218
2219 my $newid = extract_param($param, 'newid');
2220
2221 my $pool = extract_param($param, 'pool');
2222
2223 if (defined($pool)) {
2224 $rpcenv->check_pool_exist($pool);
2225 }
2226
2227 my $snapname = extract_param($param, 'snapname');
2228
2229 my $storage = extract_param($param, 'storage');
2230
2231 my $format = extract_param($param, 'format');
2232
2233 my $target = extract_param($param, 'target');
2234
2235 my $localnode = PVE::INotify::nodename();
2236
2237 undef $target if $target && ($target eq $localnode || $target eq 'localhost');
2238
2239 PVE::Cluster::check_node_exists($target) if $target;
2240
2241 my $storecfg = PVE::Storage::config();
2242
2243 if ($storage) {
2244 # check if storage is enabled on local node
2245 PVE::Storage::storage_check_enabled($storecfg, $storage);
2246 if ($target) {
2247 # check if storage is available on target node
2248 PVE::Storage::storage_check_node($storecfg, $storage, $target);
2249 # clone only works if target storage is shared
2250 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
2251 die "can't clone to non-shared storage '$storage'\n" if !$scfg->{shared};
2252 }
2253 }
2254
2255 PVE::Cluster::check_cfs_quorum();
2256
2257 my $running = PVE::QemuServer::check_running($vmid) || 0;
2258
2259 # exclusive lock if VM is running - else shared lock is enough;
2260 my $shared_lock = $running ? 0 : 1;
2261
2262 my $clonefn = sub {
2263
2264 # do all tests after lock
2265 # we also try to do all tests before we fork the worker
2266
2267 my $conf = PVE::QemuServer::load_config($vmid);
2268
2269 PVE::QemuServer::check_lock($conf);
2270
2271 my $verify_running = PVE::QemuServer::check_running($vmid) || 0;
2272
2273 die "unexpected state change\n" if $verify_running != $running;
2274
2275 die "snapshot '$snapname' does not exist\n"
2276 if $snapname && !defined( $conf->{snapshots}->{$snapname});
2277
2278 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
2279
2280 my $sharedvm = &$check_storage_access_clone($rpcenv, $authuser, $storecfg, $oldconf, $storage);
2281
2282 die "can't clone VM to node '$target' (VM uses local storage)\n" if $target && !$sharedvm;
2283
2284 my $conffile = PVE::QemuServer::config_file($newid);
2285
2286 die "unable to create VM $newid: config file already exists\n"
2287 if -f $conffile;
2288
2289 my $newconf = { lock => 'clone' };
2290 my $drives = {};
2291 my $vollist = [];
2292
2293 foreach my $opt (keys %$oldconf) {
2294 my $value = $oldconf->{$opt};
2295
2296 # do not copy snapshot related info
2297 next if $opt eq 'snapshots' || $opt eq 'parent' || $opt eq 'snaptime' ||
2298 $opt eq 'vmstate' || $opt eq 'snapstate';
2299
2300 # always change MAC! address
2301 if ($opt =~ m/^net(\d+)$/) {
2302 my $net = PVE::QemuServer::parse_net($value);
2303 $net->{macaddr} = PVE::Tools::random_ether_addr();
2304 $newconf->{$opt} = PVE::QemuServer::print_net($net);
2305 } elsif (PVE::QemuServer::valid_drivename($opt)) {
2306 my $drive = PVE::QemuServer::parse_drive($opt, $value);
2307 die "unable to parse drive options for '$opt'\n" if !$drive;
2308 if (PVE::QemuServer::drive_is_cdrom($drive)) {
2309 $newconf->{$opt} = $value; # simply copy configuration
2310 } else {
2311 if ($param->{full}) {
2312 die "Full clone feature is not available"
2313 if !PVE::Storage::volume_has_feature($storecfg, 'copy', $drive->{file}, $snapname, $running);
2314 $drive->{full} = 1;
2315 } else {
2316 # not full means clone instead of copy
2317 die "Linked clone feature is not available"
2318 if !PVE::Storage::volume_has_feature($storecfg, 'clone', $drive->{file}, $snapname, $running);
2319 }
2320 $drives->{$opt} = $drive;
2321 push @$vollist, $drive->{file};
2322 }
2323 } else {
2324 # copy everything else
2325 $newconf->{$opt} = $value;
2326 }
2327 }
2328
2329 # auto generate a new uuid
2330 my ($uuid, $uuid_str);
2331 UUID::generate($uuid);
2332 UUID::unparse($uuid, $uuid_str);
2333 my $smbios1 = PVE::QemuServer::parse_smbios1($newconf->{smbios1} || '');
2334 $smbios1->{uuid} = $uuid_str;
2335 $newconf->{smbios1} = PVE::QemuServer::print_smbios1($smbios1);
2336
2337 delete $newconf->{template};
2338
2339 if ($param->{name}) {
2340 $newconf->{name} = $param->{name};
2341 } else {
2342 if ($oldconf->{name}) {
2343 $newconf->{name} = "Copy-of-$oldconf->{name}";
2344 } else {
2345 $newconf->{name} = "Copy-of-VM-$vmid";
2346 }
2347 }
2348
2349 if ($param->{description}) {
2350 $newconf->{description} = $param->{description};
2351 }
2352
2353 # create empty/temp config - this fails if VM already exists on other node
2354 PVE::Tools::file_set_contents($conffile, "# qmclone temporary file\nlock: clone\n");
2355
2356 my $realcmd = sub {
2357 my $upid = shift;
2358
2359 my $newvollist = [];
2360
2361 eval {
2362 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
2363
2364 PVE::Storage::activate_volumes($storecfg, $vollist);
2365
2366 foreach my $opt (keys %$drives) {
2367 my $drive = $drives->{$opt};
2368
2369 my $newdrive = PVE::QemuServer::clone_disk($storecfg, $vmid, $running, $opt, $drive, $snapname,
2370 $newid, $storage, $format, $drive->{full}, $newvollist);
2371
2372 $newconf->{$opt} = PVE::QemuServer::print_drive($vmid, $newdrive);
2373
2374 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
2375 }
2376
2377 delete $newconf->{lock};
2378 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
2379
2380 if ($target) {
2381 # always deactivate volumes - avoid lvm LVs to be active on several nodes
2382 PVE::Storage::deactivate_volumes($storecfg, $vollist);
2383
2384 my $newconffile = PVE::QemuServer::config_file($newid, $target);
2385 die "Failed to move config to node '$target' - rename failed: $!\n"
2386 if !rename($conffile, $newconffile);
2387 }
2388
2389 PVE::AccessControl::add_vm_to_pool($newid, $pool) if $pool;
2390 };
2391 if (my $err = $@) {
2392 unlink $conffile;
2393
2394 sleep 1; # some storage like rbd need to wait before release volume - really?
2395
2396 foreach my $volid (@$newvollist) {
2397 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2398 warn $@ if $@;
2399 }
2400 die "clone failed: $err";
2401 }
2402
2403 return;
2404 };
2405
2406 return $rpcenv->fork_worker('qmclone', $vmid, $authuser, $realcmd);
2407 };
2408
2409 return PVE::QemuServer::lock_config_mode($vmid, 1, $shared_lock, sub {
2410 # Aquire exclusive lock lock for $newid
2411 return PVE::QemuServer::lock_config_full($newid, 1, $clonefn);
2412 });
2413
2414 }});
2415
2416 __PACKAGE__->register_method({
2417 name => 'move_vm_disk',
2418 path => '{vmid}/move_disk',
2419 method => 'POST',
2420 protected => 1,
2421 proxyto => 'node',
2422 description => "Move volume to different storage.",
2423 permissions => {
2424 description => "You need 'VM.Config.Disk' permissions on /vms/{vmid}, " .
2425 "and 'Datastore.AllocateSpace' permissions on the storage.",
2426 check =>
2427 [ 'and',
2428 ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
2429 ['perm', '/storage/{storage}', [ 'Datastore.AllocateSpace' ]],
2430 ],
2431 },
2432 parameters => {
2433 additionalProperties => 0,
2434 properties => {
2435 node => get_standard_option('pve-node'),
2436 vmid => get_standard_option('pve-vmid'),
2437 disk => {
2438 type => 'string',
2439 description => "The disk you want to move.",
2440 enum => [ PVE::QemuServer::disknames() ],
2441 },
2442 storage => get_standard_option('pve-storage-id', { description => "Target Storage." }),
2443 'format' => {
2444 type => 'string',
2445 description => "Target Format.",
2446 enum => [ 'raw', 'qcow2', 'vmdk' ],
2447 optional => 1,
2448 },
2449 delete => {
2450 type => 'boolean',
2451 description => "Delete the original disk after successful copy. By default the original disk is kept as unused disk.",
2452 optional => 1,
2453 default => 0,
2454 },
2455 digest => {
2456 type => 'string',
2457 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2458 maxLength => 40,
2459 optional => 1,
2460 },
2461 },
2462 },
2463 returns => {
2464 type => 'string',
2465 description => "the task ID.",
2466 },
2467 code => sub {
2468 my ($param) = @_;
2469
2470 my $rpcenv = PVE::RPCEnvironment::get();
2471
2472 my $authuser = $rpcenv->get_user();
2473
2474 my $node = extract_param($param, 'node');
2475
2476 my $vmid = extract_param($param, 'vmid');
2477
2478 my $digest = extract_param($param, 'digest');
2479
2480 my $disk = extract_param($param, 'disk');
2481
2482 my $storeid = extract_param($param, 'storage');
2483
2484 my $format = extract_param($param, 'format');
2485
2486 my $storecfg = PVE::Storage::config();
2487
2488 my $updatefn = sub {
2489
2490 my $conf = PVE::QemuServer::load_config($vmid);
2491
2492 die "checksum missmatch (file change by other user?)\n"
2493 if $digest && $digest ne $conf->{digest};
2494
2495 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2496
2497 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2498
2499 my $old_volid = $drive->{file} || die "disk '$disk' has no associated volume\n";
2500
2501 die "you can't move a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2502
2503 my $oldfmt;
2504 my ($oldstoreid, $oldvolname) = PVE::Storage::parse_volume_id($old_volid);
2505 if ($oldvolname =~ m/\.(raw|qcow2|vmdk)$/){
2506 $oldfmt = $1;
2507 }
2508
2509 die "you can't move on the same storage with same format\n" if $oldstoreid eq $storeid &&
2510 (!$format || !$oldfmt || $oldfmt eq $format);
2511
2512 PVE::Cluster::log_msg('info', $authuser, "move disk VM $vmid: move --disk $disk --storage $storeid");
2513
2514 my $running = PVE::QemuServer::check_running($vmid);
2515
2516 PVE::Storage::activate_volumes($storecfg, [ $drive->{file} ]);
2517
2518 my $realcmd = sub {
2519
2520 my $newvollist = [];
2521
2522 eval {
2523 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
2524
2525 my $newdrive = PVE::QemuServer::clone_disk($storecfg, $vmid, $running, $disk, $drive, undef,
2526 $vmid, $storeid, $format, 1, $newvollist);
2527
2528 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $newdrive);
2529
2530 PVE::QemuServer::add_unused_volume($conf, $old_volid) if !$param->{delete};
2531
2532 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2533
2534 eval {
2535 # try to deactivate volumes - avoid lvm LVs to be active on several nodes
2536 PVE::Storage::deactivate_volumes($storecfg, [ $newdrive->{file} ])
2537 if !$running;
2538 };
2539 warn $@ if $@;
2540 };
2541 if (my $err = $@) {
2542
2543 foreach my $volid (@$newvollist) {
2544 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2545 warn $@ if $@;
2546 }
2547 die "storage migration failed: $err";
2548 }
2549
2550 if ($param->{delete}) {
2551 my $used_paths = PVE::QemuServer::get_used_paths($vmid, $storecfg, $conf, 1, 1);
2552 my $path = PVE::Storage::path($storecfg, $old_volid);
2553 if ($used_paths->{$path}){
2554 warn "volume $old_volid have snapshots. Can't delete it\n";
2555 PVE::QemuServer::add_unused_volume($conf, $old_volid);
2556 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2557 } else {
2558 eval { PVE::Storage::vdisk_free($storecfg, $old_volid); };
2559 warn $@ if $@;
2560 }
2561 }
2562 };
2563
2564 return $rpcenv->fork_worker('qmmove', $vmid, $authuser, $realcmd);
2565 };
2566
2567 return PVE::QemuServer::lock_config($vmid, $updatefn);
2568 }});
2569
2570 __PACKAGE__->register_method({
2571 name => 'migrate_vm',
2572 path => '{vmid}/migrate',
2573 method => 'POST',
2574 protected => 1,
2575 proxyto => 'node',
2576 description => "Migrate virtual machine. Creates a new migration task.",
2577 permissions => {
2578 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
2579 },
2580 parameters => {
2581 additionalProperties => 0,
2582 properties => {
2583 node => get_standard_option('pve-node'),
2584 vmid => get_standard_option('pve-vmid'),
2585 target => get_standard_option('pve-node', { description => "Target node." }),
2586 online => {
2587 type => 'boolean',
2588 description => "Use online/live migration.",
2589 optional => 1,
2590 },
2591 force => {
2592 type => 'boolean',
2593 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
2594 optional => 1,
2595 },
2596 },
2597 },
2598 returns => {
2599 type => 'string',
2600 description => "the task ID.",
2601 },
2602 code => sub {
2603 my ($param) = @_;
2604
2605 my $rpcenv = PVE::RPCEnvironment::get();
2606
2607 my $authuser = $rpcenv->get_user();
2608
2609 my $target = extract_param($param, 'target');
2610
2611 my $localnode = PVE::INotify::nodename();
2612 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
2613
2614 PVE::Cluster::check_cfs_quorum();
2615
2616 PVE::Cluster::check_node_exists($target);
2617
2618 my $targetip = PVE::Cluster::remote_node_ip($target);
2619
2620 my $vmid = extract_param($param, 'vmid');
2621
2622 raise_param_exc({ force => "Only root may use this option." })
2623 if $param->{force} && $authuser ne 'root@pam';
2624
2625 # test if VM exists
2626 my $conf = PVE::QemuServer::load_config($vmid);
2627
2628 # try to detect errors early
2629
2630 PVE::QemuServer::check_lock($conf);
2631
2632 if (PVE::QemuServer::check_running($vmid)) {
2633 die "cant migrate running VM without --online\n"
2634 if !$param->{online};
2635 }
2636
2637 my $storecfg = PVE::Storage::config();
2638 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
2639
2640 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
2641
2642 my $hacmd = sub {
2643 my $upid = shift;
2644
2645 my $service = "pvevm:$vmid";
2646
2647 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
2648
2649 print "Executing HA migrate for VM $vmid to node $target\n";
2650
2651 PVE::Tools::run_command($cmd);
2652
2653 return;
2654 };
2655
2656 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
2657
2658 } else {
2659
2660 my $realcmd = sub {
2661 my $upid = shift;
2662
2663 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
2664 };
2665
2666 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
2667 }
2668
2669 }});
2670
2671 __PACKAGE__->register_method({
2672 name => 'monitor',
2673 path => '{vmid}/monitor',
2674 method => 'POST',
2675 protected => 1,
2676 proxyto => 'node',
2677 description => "Execute Qemu monitor commands.",
2678 permissions => {
2679 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
2680 },
2681 parameters => {
2682 additionalProperties => 0,
2683 properties => {
2684 node => get_standard_option('pve-node'),
2685 vmid => get_standard_option('pve-vmid'),
2686 command => {
2687 type => 'string',
2688 description => "The monitor command.",
2689 }
2690 },
2691 },
2692 returns => { type => 'string'},
2693 code => sub {
2694 my ($param) = @_;
2695
2696 my $vmid = $param->{vmid};
2697
2698 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
2699
2700 my $res = '';
2701 eval {
2702 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
2703 };
2704 $res = "ERROR: $@" if $@;
2705
2706 return $res;
2707 }});
2708
2709 __PACKAGE__->register_method({
2710 name => 'resize_vm',
2711 path => '{vmid}/resize',
2712 method => 'PUT',
2713 protected => 1,
2714 proxyto => 'node',
2715 description => "Extend volume size.",
2716 permissions => {
2717 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
2718 },
2719 parameters => {
2720 additionalProperties => 0,
2721 properties => {
2722 node => get_standard_option('pve-node'),
2723 vmid => get_standard_option('pve-vmid'),
2724 skiplock => get_standard_option('skiplock'),
2725 disk => {
2726 type => 'string',
2727 description => "The disk you want to resize.",
2728 enum => [PVE::QemuServer::disknames()],
2729 },
2730 size => {
2731 type => 'string',
2732 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2733 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.",
2734 },
2735 digest => {
2736 type => 'string',
2737 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2738 maxLength => 40,
2739 optional => 1,
2740 },
2741 },
2742 },
2743 returns => { type => 'null'},
2744 code => sub {
2745 my ($param) = @_;
2746
2747 my $rpcenv = PVE::RPCEnvironment::get();
2748
2749 my $authuser = $rpcenv->get_user();
2750
2751 my $node = extract_param($param, 'node');
2752
2753 my $vmid = extract_param($param, 'vmid');
2754
2755 my $digest = extract_param($param, 'digest');
2756
2757 my $disk = extract_param($param, 'disk');
2758
2759 my $sizestr = extract_param($param, 'size');
2760
2761 my $skiplock = extract_param($param, 'skiplock');
2762 raise_param_exc({ skiplock => "Only root may use this option." })
2763 if $skiplock && $authuser ne 'root@pam';
2764
2765 my $storecfg = PVE::Storage::config();
2766
2767 my $updatefn = sub {
2768
2769 my $conf = PVE::QemuServer::load_config($vmid);
2770
2771 die "checksum missmatch (file change by other user?)\n"
2772 if $digest && $digest ne $conf->{digest};
2773 PVE::QemuServer::check_lock($conf) if !$skiplock;
2774
2775 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2776
2777 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2778
2779 my $volid = $drive->{file};
2780
2781 die "disk '$disk' has no associated volume\n" if !$volid;
2782
2783 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2784
2785 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
2786
2787 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
2788
2789 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
2790
2791 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
2792 my ($ext, $newsize, $unit) = ($1, $2, $4);
2793 if ($unit) {
2794 if ($unit eq 'K') {
2795 $newsize = $newsize * 1024;
2796 } elsif ($unit eq 'M') {
2797 $newsize = $newsize * 1024 * 1024;
2798 } elsif ($unit eq 'G') {
2799 $newsize = $newsize * 1024 * 1024 * 1024;
2800 } elsif ($unit eq 'T') {
2801 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
2802 }
2803 }
2804 $newsize += $size if $ext;
2805 $newsize = int($newsize);
2806
2807 die "unable to skrink disk size\n" if $newsize < $size;
2808
2809 return if $size == $newsize;
2810
2811 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
2812
2813 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
2814
2815 $drive->{size} = $newsize;
2816 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
2817
2818 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2819 };
2820
2821 PVE::QemuServer::lock_config($vmid, $updatefn);
2822 return undef;
2823 }});
2824
2825 __PACKAGE__->register_method({
2826 name => 'snapshot_list',
2827 path => '{vmid}/snapshot',
2828 method => 'GET',
2829 description => "List all snapshots.",
2830 permissions => {
2831 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2832 },
2833 proxyto => 'node',
2834 protected => 1, # qemu pid files are only readable by root
2835 parameters => {
2836 additionalProperties => 0,
2837 properties => {
2838 vmid => get_standard_option('pve-vmid'),
2839 node => get_standard_option('pve-node'),
2840 },
2841 },
2842 returns => {
2843 type => 'array',
2844 items => {
2845 type => "object",
2846 properties => {},
2847 },
2848 links => [ { rel => 'child', href => "{name}" } ],
2849 },
2850 code => sub {
2851 my ($param) = @_;
2852
2853 my $vmid = $param->{vmid};
2854
2855 my $conf = PVE::QemuServer::load_config($vmid);
2856 my $snaphash = $conf->{snapshots} || {};
2857
2858 my $res = [];
2859
2860 foreach my $name (keys %$snaphash) {
2861 my $d = $snaphash->{$name};
2862 my $item = {
2863 name => $name,
2864 snaptime => $d->{snaptime} || 0,
2865 vmstate => $d->{vmstate} ? 1 : 0,
2866 description => $d->{description} || '',
2867 };
2868 $item->{parent} = $d->{parent} if $d->{parent};
2869 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
2870 push @$res, $item;
2871 }
2872
2873 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
2874 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
2875 $current->{parent} = $conf->{parent} if $conf->{parent};
2876
2877 push @$res, $current;
2878
2879 return $res;
2880 }});
2881
2882 __PACKAGE__->register_method({
2883 name => 'snapshot',
2884 path => '{vmid}/snapshot',
2885 method => 'POST',
2886 protected => 1,
2887 proxyto => 'node',
2888 description => "Snapshot a VM.",
2889 permissions => {
2890 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2891 },
2892 parameters => {
2893 additionalProperties => 0,
2894 properties => {
2895 node => get_standard_option('pve-node'),
2896 vmid => get_standard_option('pve-vmid'),
2897 snapname => get_standard_option('pve-snapshot-name'),
2898 vmstate => {
2899 optional => 1,
2900 type => 'boolean',
2901 description => "Save the vmstate",
2902 },
2903 description => {
2904 optional => 1,
2905 type => 'string',
2906 description => "A textual description or comment.",
2907 },
2908 },
2909 },
2910 returns => {
2911 type => 'string',
2912 description => "the task ID.",
2913 },
2914 code => sub {
2915 my ($param) = @_;
2916
2917 my $rpcenv = PVE::RPCEnvironment::get();
2918
2919 my $authuser = $rpcenv->get_user();
2920
2921 my $node = extract_param($param, 'node');
2922
2923 my $vmid = extract_param($param, 'vmid');
2924
2925 my $snapname = extract_param($param, 'snapname');
2926
2927 die "unable to use snapshot name 'current' (reserved name)\n"
2928 if $snapname eq 'current';
2929
2930 my $realcmd = sub {
2931 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
2932 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
2933 $param->{description});
2934 };
2935
2936 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2937 }});
2938
2939 __PACKAGE__->register_method({
2940 name => 'snapshot_cmd_idx',
2941 path => '{vmid}/snapshot/{snapname}',
2942 description => '',
2943 method => 'GET',
2944 permissions => {
2945 user => 'all',
2946 },
2947 parameters => {
2948 additionalProperties => 0,
2949 properties => {
2950 vmid => get_standard_option('pve-vmid'),
2951 node => get_standard_option('pve-node'),
2952 snapname => get_standard_option('pve-snapshot-name'),
2953 },
2954 },
2955 returns => {
2956 type => 'array',
2957 items => {
2958 type => "object",
2959 properties => {},
2960 },
2961 links => [ { rel => 'child', href => "{cmd}" } ],
2962 },
2963 code => sub {
2964 my ($param) = @_;
2965
2966 my $res = [];
2967
2968 push @$res, { cmd => 'rollback' };
2969 push @$res, { cmd => 'config' };
2970
2971 return $res;
2972 }});
2973
2974 __PACKAGE__->register_method({
2975 name => 'update_snapshot_config',
2976 path => '{vmid}/snapshot/{snapname}/config',
2977 method => 'PUT',
2978 protected => 1,
2979 proxyto => 'node',
2980 description => "Update snapshot metadata.",
2981 permissions => {
2982 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2983 },
2984 parameters => {
2985 additionalProperties => 0,
2986 properties => {
2987 node => get_standard_option('pve-node'),
2988 vmid => get_standard_option('pve-vmid'),
2989 snapname => get_standard_option('pve-snapshot-name'),
2990 description => {
2991 optional => 1,
2992 type => 'string',
2993 description => "A textual description or comment.",
2994 },
2995 },
2996 },
2997 returns => { type => 'null' },
2998 code => sub {
2999 my ($param) = @_;
3000
3001 my $rpcenv = PVE::RPCEnvironment::get();
3002
3003 my $authuser = $rpcenv->get_user();
3004
3005 my $vmid = extract_param($param, 'vmid');
3006
3007 my $snapname = extract_param($param, 'snapname');
3008
3009 return undef if !defined($param->{description});
3010
3011 my $updatefn = sub {
3012
3013 my $conf = PVE::QemuServer::load_config($vmid);
3014
3015 PVE::QemuServer::check_lock($conf);
3016
3017 my $snap = $conf->{snapshots}->{$snapname};
3018
3019 die "snapshot '$snapname' does not exist\n" if !defined($snap);
3020
3021 $snap->{description} = $param->{description} if defined($param->{description});
3022
3023 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3024 };
3025
3026 PVE::QemuServer::lock_config($vmid, $updatefn);
3027
3028 return undef;
3029 }});
3030
3031 __PACKAGE__->register_method({
3032 name => 'get_snapshot_config',
3033 path => '{vmid}/snapshot/{snapname}/config',
3034 method => 'GET',
3035 proxyto => 'node',
3036 description => "Get snapshot configuration",
3037 permissions => {
3038 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
3039 },
3040 parameters => {
3041 additionalProperties => 0,
3042 properties => {
3043 node => get_standard_option('pve-node'),
3044 vmid => get_standard_option('pve-vmid'),
3045 snapname => get_standard_option('pve-snapshot-name'),
3046 },
3047 },
3048 returns => { type => "object" },
3049 code => sub {
3050 my ($param) = @_;
3051
3052 my $rpcenv = PVE::RPCEnvironment::get();
3053
3054 my $authuser = $rpcenv->get_user();
3055
3056 my $vmid = extract_param($param, 'vmid');
3057
3058 my $snapname = extract_param($param, 'snapname');
3059
3060 my $conf = PVE::QemuServer::load_config($vmid);
3061
3062 my $snap = $conf->{snapshots}->{$snapname};
3063
3064 die "snapshot '$snapname' does not exist\n" if !defined($snap);
3065
3066 return $snap;
3067 }});
3068
3069 __PACKAGE__->register_method({
3070 name => 'rollback',
3071 path => '{vmid}/snapshot/{snapname}/rollback',
3072 method => 'POST',
3073 protected => 1,
3074 proxyto => 'node',
3075 description => "Rollback VM state to specified snapshot.",
3076 permissions => {
3077 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
3078 },
3079 parameters => {
3080 additionalProperties => 0,
3081 properties => {
3082 node => get_standard_option('pve-node'),
3083 vmid => get_standard_option('pve-vmid'),
3084 snapname => get_standard_option('pve-snapshot-name'),
3085 },
3086 },
3087 returns => {
3088 type => 'string',
3089 description => "the task ID.",
3090 },
3091 code => sub {
3092 my ($param) = @_;
3093
3094 my $rpcenv = PVE::RPCEnvironment::get();
3095
3096 my $authuser = $rpcenv->get_user();
3097
3098 my $node = extract_param($param, 'node');
3099
3100 my $vmid = extract_param($param, 'vmid');
3101
3102 my $snapname = extract_param($param, 'snapname');
3103
3104 my $realcmd = sub {
3105 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
3106 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
3107 };
3108
3109 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
3110 }});
3111
3112 __PACKAGE__->register_method({
3113 name => 'delsnapshot',
3114 path => '{vmid}/snapshot/{snapname}',
3115 method => 'DELETE',
3116 protected => 1,
3117 proxyto => 'node',
3118 description => "Delete a VM snapshot.",
3119 permissions => {
3120 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
3121 },
3122 parameters => {
3123 additionalProperties => 0,
3124 properties => {
3125 node => get_standard_option('pve-node'),
3126 vmid => get_standard_option('pve-vmid'),
3127 snapname => get_standard_option('pve-snapshot-name'),
3128 force => {
3129 optional => 1,
3130 type => 'boolean',
3131 description => "For removal from config file, even if removing disk snapshots fails.",
3132 },
3133 },
3134 },
3135 returns => {
3136 type => 'string',
3137 description => "the task ID.",
3138 },
3139 code => sub {
3140 my ($param) = @_;
3141
3142 my $rpcenv = PVE::RPCEnvironment::get();
3143
3144 my $authuser = $rpcenv->get_user();
3145
3146 my $node = extract_param($param, 'node');
3147
3148 my $vmid = extract_param($param, 'vmid');
3149
3150 my $snapname = extract_param($param, 'snapname');
3151
3152 my $realcmd = sub {
3153 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
3154 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
3155 };
3156
3157 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
3158 }});
3159
3160 __PACKAGE__->register_method({
3161 name => 'template',
3162 path => '{vmid}/template',
3163 method => 'POST',
3164 protected => 1,
3165 proxyto => 'node',
3166 description => "Create a Template.",
3167 permissions => {
3168 description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
3169 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
3170 },
3171 parameters => {
3172 additionalProperties => 0,
3173 properties => {
3174 node => get_standard_option('pve-node'),
3175 vmid => get_standard_option('pve-vmid'),
3176 disk => {
3177 optional => 1,
3178 type => 'string',
3179 description => "If you want to convert only 1 disk to base image.",
3180 enum => [PVE::QemuServer::disknames()],
3181 },
3182
3183 },
3184 },
3185 returns => { type => 'null'},
3186 code => sub {
3187 my ($param) = @_;
3188
3189 my $rpcenv = PVE::RPCEnvironment::get();
3190
3191 my $authuser = $rpcenv->get_user();
3192
3193 my $node = extract_param($param, 'node');
3194
3195 my $vmid = extract_param($param, 'vmid');
3196
3197 my $disk = extract_param($param, 'disk');
3198
3199 my $updatefn = sub {
3200
3201 my $conf = PVE::QemuServer::load_config($vmid);
3202
3203 PVE::QemuServer::check_lock($conf);
3204
3205 die "unable to create template, because VM contains snapshots\n"
3206 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
3207
3208 die "you can't convert a template to a template\n"
3209 if PVE::QemuServer::is_template($conf) && !$disk;
3210
3211 die "you can't convert a VM to template if VM is running\n"
3212 if PVE::QemuServer::check_running($vmid);
3213
3214 my $realcmd = sub {
3215 PVE::QemuServer::template_create($vmid, $conf, $disk);
3216 };
3217
3218 $conf->{template} = 1;
3219 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3220
3221 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
3222 };
3223
3224 PVE::QemuServer::lock_config($vmid, $updatefn);
3225 return undef;
3226 }});
3227
3228 1;