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