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