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