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