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