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