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