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