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