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