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