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