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