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