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