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