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