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