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