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