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