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