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