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