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