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