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