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