]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
qemu_netdevadd : convert to qmp
[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
DM
648 }
649
650 die "error hot-unplug $opt" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
651
cd6ecb89
AD
652 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt) if $opt eq 'tablet';
653
ae57f6b3
DM
654 if ($isDisk) {
655 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
656 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive, $force);
5d7a6767 657 } else {
ae57f6b3
DM
658 delete $conf->{$opt};
659 }
660
661 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
662};
663
9bf371a6 664my $safe_num_ne = sub {
93ae06e1
DM
665 my ($a, $b) = @_;
666
667 return 0 if !defined($a) && !defined($b);
668 return 1 if !defined($a);
669 return 1 if !defined($b);
670
671 return $a != $b;
672};
673
ae57f6b3
DM
674my $vmconfig_update_disk = sub {
675 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
5d7a6767 676
ae57f6b3
DM
677 my $drive = PVE::QemuServer::parse_drive($opt, $value);
678
679 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
680 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
681 } else {
682 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
683 }
684
685 if ($conf->{$opt}) {
686
687 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
688
689 my $media = $drive->{media} || 'disk';
690 my $oldmedia = $old_drive->{media} || 'disk';
691 die "unable to change media type\n" if $media ne $oldmedia;
692
693 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
694 ($drive->{file} ne $old_drive->{file})) { # delete old disks
695
696 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
697 $conf = PVE::QemuServer::load_config($vmid); # update/reload
698 }
0f56d571 699
9bf371a6
DM
700 if(&$safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
701 &$safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
702 &$safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
703 &$safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
704 &$safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
705 &$safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr})) {
706 PVE::QemuServer::qemu_block_set_io_throttle($vmid,"drive-$opt", $drive->{mbps}*1024*1024,
707 $drive->{mbps_rd}*1024*1024, $drive->{mbps_wr}*1024*1024,
708 $drive->{iops}, $drive->{iops_rd}, $drive->{iops_wr})
709 if !PVE::QemuServer::drive_is_cdrom($drive);
0f56d571 710 }
ae57f6b3
DM
711 }
712 }
713
714 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
715 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
716
717 $conf = PVE::QemuServer::load_config($vmid); # update/reload
718 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
719
720 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
721
722 if (PVE::QemuServer::check_running($vmid)) {
723 if ($drive->{file} eq 'none') {
ce156282 724 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
ae57f6b3
DM
725 } else {
726 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
ce156282
AD
727 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt"); #force eject if locked
728 PVE::QemuServer::vm_mon_cmd($vmid, "change",device => "drive-$opt",target => "$path") if $path;
ae57f6b3
DM
729 }
730 }
731
732 } else { # hotplug new disks
733
734 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
5d7a6767 735 }
5d7a6767
DM
736};
737
ae57f6b3
DM
738my $vmconfig_update_net = sub {
739 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
740
741 if ($conf->{$opt}) {
742 #if online update, then unplug first
743 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
744 }
745
746 $conf->{$opt} = $value;
747 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
748 $conf = PVE::QemuServer::load_config($vmid); # update/reload
749
750 my $net = PVE::QemuServer::parse_net($conf->{$opt});
751
752 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
753};
754
a0d1b1a2
DM
755my $vm_config_perm_list = [
756 'VM.Config.Disk',
757 'VM.Config.CDROM',
758 'VM.Config.CPU',
759 'VM.Config.Memory',
760 'VM.Config.Network',
761 'VM.Config.HWType',
762 'VM.Config.Options',
763 ];
764
1e3baf05 765__PACKAGE__->register_method({
afdb31d5
DM
766 name => 'update_vm',
767 path => '{vmid}/config',
1e3baf05
DM
768 method => 'PUT',
769 protected => 1,
770 proxyto => 'node',
771 description => "Set virtual machine options.",
a0d1b1a2
DM
772 permissions => {
773 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
774 },
1e3baf05
DM
775 parameters => {
776 additionalProperties => 0,
777 properties => PVE::QemuServer::json_config_properties(
778 {
779 node => get_standard_option('pve-node'),
780 vmid => get_standard_option('pve-vmid'),
3ea94c60 781 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
782 delete => {
783 type => 'string', format => 'pve-configid-list',
784 description => "A list of settings you want to delete.",
785 optional => 1,
786 },
787 force => {
788 type => 'boolean',
789 description => $opt_force_description,
790 optional => 1,
791 requires => 'delete',
792 },
554ac7e7
DM
793 digest => {
794 type => 'string',
795 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
796 maxLength => 40,
afdb31d5 797 optional => 1,
554ac7e7 798 }
1e3baf05
DM
799 }),
800 },
801 returns => { type => 'null'},
802 code => sub {
803 my ($param) = @_;
804
805 my $rpcenv = PVE::RPCEnvironment::get();
806
a0d1b1a2 807 my $authuser = $rpcenv->get_user();
1e3baf05
DM
808
809 my $node = extract_param($param, 'node');
810
1e3baf05
DM
811 my $vmid = extract_param($param, 'vmid');
812
5fdbe4f0
DM
813 my $digest = extract_param($param, 'digest');
814
815 my @paramarr = (); # used for log message
816 foreach my $key (keys %$param) {
817 push @paramarr, "-$key", $param->{$key};
818 }
819
1e3baf05 820 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 821 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 822 if $skiplock && $authuser ne 'root@pam';
1e3baf05 823
0532bc63
DM
824 my $delete_str = extract_param($param, 'delete');
825
1e3baf05
DM
826 my $force = extract_param($param, 'force');
827
0532bc63
DM
828 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
829
1e68cb19
DM
830 my $storecfg = PVE::Storage::config();
831
7bfdeb5f
DM
832 my $defaults = PVE::QemuServer::load_defaults();
833
1e68cb19
DM
834 &$resolve_cdrom_alias($param);
835
836 # now try to verify all parameters
837
0532bc63
DM
838 my @delete = ();
839 foreach my $opt (PVE::Tools::split_list($delete_str)) {
840 $opt = 'ide2' if $opt eq 'cdrom';
841 raise_param_exc({ delete => "you can't use '-$opt' and " .
842 "-delete $opt' at the same time" })
843 if defined($param->{$opt});
844
845 if (!PVE::QemuServer::option_exists($opt)) {
846 raise_param_exc({ delete => "unknown option '$opt'" });
847 }
ae57f6b3 848
0532bc63
DM
849 push @delete, $opt;
850 }
1e3baf05 851
1e68cb19
DM
852 foreach my $opt (keys %$param) {
853 if (PVE::QemuServer::valid_drivename($opt)) {
854 # cleanup drive path
855 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
856 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
857 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
1e68cb19
DM
858 } elsif ($opt =~ m/^net(\d+)$/) {
859 # add macaddr
860 my $net = PVE::QemuServer::parse_net($param->{$opt});
861 $param->{$opt} = PVE::QemuServer::print_net($net);
1e68cb19
DM
862 }
863 }
1e3baf05 864
ae57f6b3
DM
865 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
866
867 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
868
fcbb753e 869 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1e3baf05 870
5d39a182 871 my $updatefn = sub {
1e3baf05 872
5d39a182 873 my $conf = PVE::QemuServer::load_config($vmid);
1e3baf05 874
5d39a182
DM
875 die "checksum missmatch (file change by other user?)\n"
876 if $digest && $digest ne $conf->{digest};
1e3baf05 877
5d39a182 878 PVE::QemuServer::check_lock($conf) if !$skiplock;
1e3baf05 879
7bfdeb5f
DM
880 if ($param->{memory} || defined($param->{balloon})) {
881 my $maxmem = $param->{memory} || $conf->{memory} || $defaults->{memory};
882 my $balloon = defined($param->{balloon}) ? $param->{balloon} : $conf->{balloon};
883
884 die "balloon value too large (must be smaller than assigned memory)\n"
885 if $balloon > $maxmem;
886 }
887
a0d1b1a2 888 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
c2a64aa7 889
5d7a6767 890 foreach my $opt (@delete) { # delete
1e68cb19 891 $conf = PVE::QemuServer::load_config($vmid); # update/reload
ae57f6b3 892 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
5d39a182 893 }
1e3baf05 894
7bfdeb5f
DM
895 my $running = PVE::QemuServer::check_running($vmid);
896
5d7a6767 897 foreach my $opt (keys %$param) { # add/change
1e3baf05 898
1e68cb19 899 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1e3baf05 900
5d7a6767
DM
901 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
902
ae57f6b3 903 if (PVE::QemuServer::valid_drivename($opt)) {
5d7a6767 904
ae57f6b3
DM
905 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
906 $opt, $param->{$opt}, $force);
1e68cb19 907
ae57f6b3 908 } elsif ($opt =~ m/^net(\d+)$/) { #nics
1858638f 909
ae57f6b3
DM
910 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
911 $opt, $param->{$opt});
1e68cb19
DM
912
913 } else {
914
cd6ecb89
AD
915 if($opt eq 'tablet' && $param->{$opt} == 1){
916 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt);
917 }elsif($opt eq 'tablet' && $param->{$opt} == 0){
918 PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
919 }
920
1858638f
DM
921 $conf->{$opt} = $param->{$opt};
922 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3a1e36bb 923 }
5d39a182 924 }
7bfdeb5f
DM
925
926 # allow manual ballooning if shares is set to zero
927 if ($running && defined($param->{balloon}) &&
928 defined($conf->{shares}) && ($conf->{shares} == 0)) {
929 my $balloon = $param->{'balloon'} || $conf->{memory} || $defaults->{memory};
930 PVE::QemuServer::vm_mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
931 }
932
5d39a182
DM
933 };
934
935 PVE::QemuServer::lock_config($vmid, $updatefn);
fcdb0117 936
1e3baf05
DM
937 return undef;
938 }});
939
940
941__PACKAGE__->register_method({
afdb31d5
DM
942 name => 'destroy_vm',
943 path => '{vmid}',
1e3baf05
DM
944 method => 'DELETE',
945 protected => 1,
946 proxyto => 'node',
947 description => "Destroy the vm (also delete all used/owned volumes).",
a0d1b1a2
DM
948 permissions => {
949 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
950 },
1e3baf05
DM
951 parameters => {
952 additionalProperties => 0,
953 properties => {
954 node => get_standard_option('pve-node'),
955 vmid => get_standard_option('pve-vmid'),
3ea94c60 956 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
957 },
958 },
afdb31d5 959 returns => {
5fdbe4f0
DM
960 type => 'string',
961 },
1e3baf05
DM
962 code => sub {
963 my ($param) = @_;
964
965 my $rpcenv = PVE::RPCEnvironment::get();
966
a0d1b1a2 967 my $authuser = $rpcenv->get_user();
1e3baf05
DM
968
969 my $vmid = $param->{vmid};
970
971 my $skiplock = $param->{skiplock};
afdb31d5 972 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 973 if $skiplock && $authuser ne 'root@pam';
1e3baf05 974
5fdbe4f0
DM
975 # test if VM exists
976 my $conf = PVE::QemuServer::load_config($vmid);
977
afdb31d5 978 my $storecfg = PVE::Storage::config();
1e3baf05 979
502d18a2
DM
980 my $delVMfromPoolFn = sub {
981 my $usercfg = cfs_read_file("user.cfg");
5d0094ea
DM
982 if (my $pool = $usercfg->{vms}->{$vmid}) {
983 if (my $data = $usercfg->{pools}->{$pool}) {
984 delete $data->{vms}->{$vmid};
985 delete $usercfg->{vms}->{$vmid};
986 cfs_write_file("user.cfg", $usercfg);
987 }
502d18a2
DM
988 }
989 };
990
5fdbe4f0 991 my $realcmd = sub {
ff1a2432
DM
992 my $upid = shift;
993
994 syslog('info', "destroy VM $vmid: $upid\n");
995
5fdbe4f0 996 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
502d18a2
DM
997
998 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
5fdbe4f0 999 };
1e3baf05 1000
a0d1b1a2 1001 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1e3baf05
DM
1002 }});
1003
1004__PACKAGE__->register_method({
afdb31d5
DM
1005 name => 'unlink',
1006 path => '{vmid}/unlink',
1e3baf05
DM
1007 method => 'PUT',
1008 protected => 1,
1009 proxyto => 'node',
1010 description => "Unlink/delete disk images.",
a0d1b1a2
DM
1011 permissions => {
1012 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
1013 },
1e3baf05
DM
1014 parameters => {
1015 additionalProperties => 0,
1016 properties => {
1017 node => get_standard_option('pve-node'),
1018 vmid => get_standard_option('pve-vmid'),
1019 idlist => {
1020 type => 'string', format => 'pve-configid-list',
1021 description => "A list of disk IDs you want to delete.",
1022 },
1023 force => {
1024 type => 'boolean',
1025 description => $opt_force_description,
1026 optional => 1,
1027 },
1028 },
1029 },
1030 returns => { type => 'null'},
1031 code => sub {
1032 my ($param) = @_;
1033
1034 $param->{delete} = extract_param($param, 'idlist');
1035
1036 __PACKAGE__->update_vm($param);
1037
1038 return undef;
1039 }});
1040
1041my $sslcert;
1042
1043__PACKAGE__->register_method({
afdb31d5
DM
1044 name => 'vncproxy',
1045 path => '{vmid}/vncproxy',
1e3baf05
DM
1046 method => 'POST',
1047 protected => 1,
1048 permissions => {
378b359e 1049 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1e3baf05
DM
1050 },
1051 description => "Creates a TCP VNC proxy connections.",
1052 parameters => {
1053 additionalProperties => 0,
1054 properties => {
1055 node => get_standard_option('pve-node'),
1056 vmid => get_standard_option('pve-vmid'),
1057 },
1058 },
afdb31d5 1059 returns => {
1e3baf05
DM
1060 additionalProperties => 0,
1061 properties => {
1062 user => { type => 'string' },
1063 ticket => { type => 'string' },
1064 cert => { type => 'string' },
1065 port => { type => 'integer' },
1066 upid => { type => 'string' },
1067 },
1068 },
1069 code => sub {
1070 my ($param) = @_;
1071
1072 my $rpcenv = PVE::RPCEnvironment::get();
1073
a0d1b1a2 1074 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1075
1076 my $vmid = $param->{vmid};
1077 my $node = $param->{node};
1078
b6f39da2
DM
1079 my $authpath = "/vms/$vmid";
1080
a0d1b1a2 1081 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
b6f39da2 1082
1e3baf05
DM
1083 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1084 if !$sslcert;
1085
1086 my $port = PVE::Tools::next_vnc_port();
1087
1088 my $remip;
afdb31d5 1089
4f1be36c 1090 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1e3baf05
DM
1091 $remip = PVE::Cluster::remote_node_ip($node);
1092 }
1093
6bb726c9
SP
1094 # NOTE: kvm VNC traffic is already TLS encrypted
1095 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes', $remip] : [];
1e3baf05 1096
afdb31d5 1097 my $timeout = 10;
1e3baf05
DM
1098
1099 my $realcmd = sub {
1100 my $upid = shift;
1101
1102 syslog('info', "starting vnc proxy $upid\n");
1103
1104 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1105
1106 my $qmstr = join(' ', @$qmcmd);
1107
1108 # also redirect stderr (else we get RFB protocol errors)
be62c45c 1109 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1e3baf05 1110
be62c45c 1111 PVE::Tools::run_command($cmd);
1e3baf05
DM
1112
1113 return;
1114 };
1115
a0d1b1a2 1116 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1e3baf05 1117
3da85107
DM
1118 PVE::Tools::wait_for_vnc_port($port);
1119
1e3baf05 1120 return {
a0d1b1a2 1121 user => $authuser,
1e3baf05 1122 ticket => $ticket,
afdb31d5
DM
1123 port => $port,
1124 upid => $upid,
1125 cert => $sslcert,
1e3baf05
DM
1126 };
1127 }});
1128
5fdbe4f0
DM
1129__PACKAGE__->register_method({
1130 name => 'vmcmdidx',
afdb31d5 1131 path => '{vmid}/status',
5fdbe4f0
DM
1132 method => 'GET',
1133 proxyto => 'node',
1134 description => "Directory index",
a0d1b1a2
DM
1135 permissions => {
1136 user => 'all',
1137 },
5fdbe4f0
DM
1138 parameters => {
1139 additionalProperties => 0,
1140 properties => {
1141 node => get_standard_option('pve-node'),
1142 vmid => get_standard_option('pve-vmid'),
1143 },
1144 },
1145 returns => {
1146 type => 'array',
1147 items => {
1148 type => "object",
1149 properties => {
1150 subdir => { type => 'string' },
1151 },
1152 },
1153 links => [ { rel => 'child', href => "{subdir}" } ],
1154 },
1155 code => sub {
1156 my ($param) = @_;
1157
1158 # test if VM exists
1159 my $conf = PVE::QemuServer::load_config($param->{vmid});
1160
1161 my $res = [
1162 { subdir => 'current' },
1163 { subdir => 'start' },
1164 { subdir => 'stop' },
1165 ];
afdb31d5 1166
5fdbe4f0
DM
1167 return $res;
1168 }});
1169
88fc87b4
DM
1170my $vm_is_ha_managed = sub {
1171 my ($vmid) = @_;
1172
1173 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1174 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1175 return 1;
1176 }
1177 return 0;
1178};
1179
1e3baf05 1180__PACKAGE__->register_method({
afdb31d5 1181 name => 'vm_status',
5fdbe4f0 1182 path => '{vmid}/status/current',
1e3baf05
DM
1183 method => 'GET',
1184 proxyto => 'node',
1185 protected => 1, # qemu pid files are only readable by root
1186 description => "Get virtual machine status.",
a0d1b1a2
DM
1187 permissions => {
1188 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1189 },
1e3baf05
DM
1190 parameters => {
1191 additionalProperties => 0,
1192 properties => {
1193 node => get_standard_option('pve-node'),
1194 vmid => get_standard_option('pve-vmid'),
1195 },
1196 },
1197 returns => { type => 'object' },
1198 code => sub {
1199 my ($param) = @_;
1200
1201 # test if VM exists
1202 my $conf = PVE::QemuServer::load_config($param->{vmid});
1203
03a33f30 1204 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
8610701a 1205 my $status = $vmstatus->{$param->{vmid}};
1e3baf05 1206
88fc87b4 1207 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
8610701a
DM
1208
1209 return $status;
1e3baf05
DM
1210 }});
1211
1212__PACKAGE__->register_method({
afdb31d5 1213 name => 'vm_start',
5fdbe4f0
DM
1214 path => '{vmid}/status/start',
1215 method => 'POST',
1e3baf05
DM
1216 protected => 1,
1217 proxyto => 'node',
5fdbe4f0 1218 description => "Start virtual machine.",
a0d1b1a2
DM
1219 permissions => {
1220 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1221 },
1e3baf05
DM
1222 parameters => {
1223 additionalProperties => 0,
1224 properties => {
1225 node => get_standard_option('pve-node'),
1226 vmid => get_standard_option('pve-vmid'),
3ea94c60
DM
1227 skiplock => get_standard_option('skiplock'),
1228 stateuri => get_standard_option('pve-qm-stateuri'),
7e8dcf2c
AD
1229 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
1230
1e3baf05
DM
1231 },
1232 },
afdb31d5 1233 returns => {
5fdbe4f0
DM
1234 type => 'string',
1235 },
1e3baf05
DM
1236 code => sub {
1237 my ($param) = @_;
1238
1239 my $rpcenv = PVE::RPCEnvironment::get();
1240
a0d1b1a2 1241 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1242
1243 my $node = extract_param($param, 'node');
1244
1e3baf05
DM
1245 my $vmid = extract_param($param, 'vmid');
1246
3ea94c60 1247 my $stateuri = extract_param($param, 'stateuri');
afdb31d5 1248 raise_param_exc({ stateuri => "Only root may use this option." })
a0d1b1a2 1249 if $stateuri && $authuser ne 'root@pam';
3ea94c60 1250
1e3baf05 1251 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1252 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1253 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1254
7e8dcf2c
AD
1255 my $migratedfrom = extract_param($param, 'migratedfrom');
1256 raise_param_exc({ migratedfrom => "Only root may use this option." })
1257 if $migratedfrom && $authuser ne 'root@pam';
1258
afdb31d5 1259 my $storecfg = PVE::Storage::config();
5fdbe4f0 1260
cce37749
DM
1261 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1262 $rpcenv->{type} ne 'ha') {
5fdbe4f0 1263
88fc87b4
DM
1264 my $hacmd = sub {
1265 my $upid = shift;
5fdbe4f0 1266
88fc87b4 1267 my $service = "pvevm:$vmid";
5fdbe4f0 1268
88fc87b4
DM
1269 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1270
1271 print "Executing HA start for VM $vmid\n";
1272
1273 PVE::Tools::run_command($cmd);
1274
1275 return;
1276 };
1277
1278 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1279
1280 } else {
1281
1282 my $realcmd = sub {
1283 my $upid = shift;
1284
1285 syslog('info', "start VM $vmid: $upid\n");
1286
7e8dcf2c 1287 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock, $migratedfrom);
88fc87b4
DM
1288
1289 return;
1290 };
5fdbe4f0 1291
88fc87b4
DM
1292 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1293 }
5fdbe4f0
DM
1294 }});
1295
1296__PACKAGE__->register_method({
afdb31d5 1297 name => 'vm_stop',
5fdbe4f0
DM
1298 path => '{vmid}/status/stop',
1299 method => 'POST',
1300 protected => 1,
1301 proxyto => 'node',
1302 description => "Stop virtual machine.",
a0d1b1a2
DM
1303 permissions => {
1304 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1305 },
5fdbe4f0
DM
1306 parameters => {
1307 additionalProperties => 0,
1308 properties => {
1309 node => get_standard_option('pve-node'),
1310 vmid => get_standard_option('pve-vmid'),
1311 skiplock => get_standard_option('skiplock'),
af30308f 1312 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
c6bb9502
DM
1313 timeout => {
1314 description => "Wait maximal timeout seconds.",
1315 type => 'integer',
1316 minimum => 0,
1317 optional => 1,
254575e9
DM
1318 },
1319 keepActive => {
1320 description => "Do not decativate storage volumes.",
1321 type => 'boolean',
1322 optional => 1,
1323 default => 0,
c6bb9502 1324 }
5fdbe4f0
DM
1325 },
1326 },
afdb31d5 1327 returns => {
5fdbe4f0
DM
1328 type => 'string',
1329 },
1330 code => sub {
1331 my ($param) = @_;
1332
1333 my $rpcenv = PVE::RPCEnvironment::get();
1334
a0d1b1a2 1335 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1336
1337 my $node = extract_param($param, 'node');
1338
1339 my $vmid = extract_param($param, 'vmid');
1340
1341 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1342 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1343 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1344
254575e9 1345 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1346 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1347 if $keepActive && $authuser ne 'root@pam';
254575e9 1348
af30308f
DM
1349 my $migratedfrom = extract_param($param, 'migratedfrom');
1350 raise_param_exc({ migratedfrom => "Only root may use this option." })
1351 if $migratedfrom && $authuser ne 'root@pam';
1352
1353
ff1a2432
DM
1354 my $storecfg = PVE::Storage::config();
1355
3be30d63 1356 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
5fdbe4f0 1357
88fc87b4
DM
1358 my $hacmd = sub {
1359 my $upid = shift;
5fdbe4f0 1360
88fc87b4 1361 my $service = "pvevm:$vmid";
c6bb9502 1362
88fc87b4
DM
1363 my $cmd = ['clusvcadm', '-d', $service];
1364
1365 print "Executing HA stop for VM $vmid\n";
1366
1367 PVE::Tools::run_command($cmd);
5fdbe4f0 1368
88fc87b4
DM
1369 return;
1370 };
1371
1372 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1373
1374 } else {
1375 my $realcmd = sub {
1376 my $upid = shift;
1377
1378 syslog('info', "stop VM $vmid: $upid\n");
1379
1380 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
af30308f 1381 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
88fc87b4
DM
1382
1383 return;
1384 };
1385
1386 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1387 }
5fdbe4f0
DM
1388 }});
1389
1390__PACKAGE__->register_method({
afdb31d5 1391 name => 'vm_reset',
5fdbe4f0
DM
1392 path => '{vmid}/status/reset',
1393 method => 'POST',
1394 protected => 1,
1395 proxyto => 'node',
1396 description => "Reset virtual machine.",
a0d1b1a2
DM
1397 permissions => {
1398 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1399 },
5fdbe4f0
DM
1400 parameters => {
1401 additionalProperties => 0,
1402 properties => {
1403 node => get_standard_option('pve-node'),
1404 vmid => get_standard_option('pve-vmid'),
1405 skiplock => get_standard_option('skiplock'),
1406 },
1407 },
afdb31d5 1408 returns => {
5fdbe4f0
DM
1409 type => 'string',
1410 },
1411 code => sub {
1412 my ($param) = @_;
1413
1414 my $rpcenv = PVE::RPCEnvironment::get();
1415
a0d1b1a2 1416 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1417
1418 my $node = extract_param($param, 'node');
1419
1420 my $vmid = extract_param($param, 'vmid');
1421
1422 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1423 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1424 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1425
ff1a2432
DM
1426 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1427
5fdbe4f0
DM
1428 my $realcmd = sub {
1429 my $upid = shift;
1430
1e3baf05 1431 PVE::QemuServer::vm_reset($vmid, $skiplock);
5fdbe4f0
DM
1432
1433 return;
1434 };
1435
a0d1b1a2 1436 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1437 }});
1438
1439__PACKAGE__->register_method({
afdb31d5 1440 name => 'vm_shutdown',
5fdbe4f0
DM
1441 path => '{vmid}/status/shutdown',
1442 method => 'POST',
1443 protected => 1,
1444 proxyto => 'node',
1445 description => "Shutdown virtual machine.",
a0d1b1a2
DM
1446 permissions => {
1447 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1448 },
5fdbe4f0
DM
1449 parameters => {
1450 additionalProperties => 0,
1451 properties => {
1452 node => get_standard_option('pve-node'),
1453 vmid => get_standard_option('pve-vmid'),
1454 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1455 timeout => {
1456 description => "Wait maximal timeout seconds.",
1457 type => 'integer',
1458 minimum => 0,
1459 optional => 1,
9269013a
DM
1460 },
1461 forceStop => {
1462 description => "Make sure the VM stops.",
1463 type => 'boolean',
1464 optional => 1,
1465 default => 0,
254575e9
DM
1466 },
1467 keepActive => {
1468 description => "Do not decativate storage volumes.",
1469 type => 'boolean',
1470 optional => 1,
1471 default => 0,
c6bb9502 1472 }
5fdbe4f0
DM
1473 },
1474 },
afdb31d5 1475 returns => {
5fdbe4f0
DM
1476 type => 'string',
1477 },
1478 code => sub {
1479 my ($param) = @_;
1480
1481 my $rpcenv = PVE::RPCEnvironment::get();
1482
a0d1b1a2 1483 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1484
1485 my $node = extract_param($param, 'node');
1486
1487 my $vmid = extract_param($param, 'vmid');
1488
1489 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1490 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1491 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1492
254575e9 1493 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1494 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1495 if $keepActive && $authuser ne 'root@pam';
254575e9 1496
02d07cf5
DM
1497 my $storecfg = PVE::Storage::config();
1498
5fdbe4f0
DM
1499 my $realcmd = sub {
1500 my $upid = shift;
1501
1502 syslog('info', "shutdown VM $vmid: $upid\n");
1503
afdb31d5 1504 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
254575e9 1505 1, $param->{forceStop}, $keepActive);
c6bb9502 1506
5fdbe4f0
DM
1507 return;
1508 };
1509
a0d1b1a2 1510 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1511 }});
1512
1513__PACKAGE__->register_method({
afdb31d5 1514 name => 'vm_suspend',
5fdbe4f0
DM
1515 path => '{vmid}/status/suspend',
1516 method => 'POST',
1517 protected => 1,
1518 proxyto => 'node',
1519 description => "Suspend virtual machine.",
a0d1b1a2
DM
1520 permissions => {
1521 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1522 },
5fdbe4f0
DM
1523 parameters => {
1524 additionalProperties => 0,
1525 properties => {
1526 node => get_standard_option('pve-node'),
1527 vmid => get_standard_option('pve-vmid'),
1528 skiplock => get_standard_option('skiplock'),
1529 },
1530 },
afdb31d5 1531 returns => {
5fdbe4f0
DM
1532 type => 'string',
1533 },
1534 code => sub {
1535 my ($param) = @_;
1536
1537 my $rpcenv = PVE::RPCEnvironment::get();
1538
a0d1b1a2 1539 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1540
1541 my $node = extract_param($param, 'node');
1542
1543 my $vmid = extract_param($param, 'vmid');
1544
1545 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1546 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1547 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1548
ff1a2432
DM
1549 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1550
5fdbe4f0
DM
1551 my $realcmd = sub {
1552 my $upid = shift;
1553
1554 syslog('info', "suspend VM $vmid: $upid\n");
1555
1e3baf05 1556 PVE::QemuServer::vm_suspend($vmid, $skiplock);
5fdbe4f0
DM
1557
1558 return;
1559 };
1560
a0d1b1a2 1561 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1562 }});
1563
1564__PACKAGE__->register_method({
afdb31d5 1565 name => 'vm_resume',
5fdbe4f0
DM
1566 path => '{vmid}/status/resume',
1567 method => 'POST',
1568 protected => 1,
1569 proxyto => 'node',
1570 description => "Resume virtual machine.",
a0d1b1a2
DM
1571 permissions => {
1572 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1573 },
5fdbe4f0
DM
1574 parameters => {
1575 additionalProperties => 0,
1576 properties => {
1577 node => get_standard_option('pve-node'),
1578 vmid => get_standard_option('pve-vmid'),
1579 skiplock => get_standard_option('skiplock'),
1580 },
1581 },
afdb31d5 1582 returns => {
5fdbe4f0
DM
1583 type => 'string',
1584 },
1585 code => sub {
1586 my ($param) = @_;
1587
1588 my $rpcenv = PVE::RPCEnvironment::get();
1589
a0d1b1a2 1590 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1591
1592 my $node = extract_param($param, 'node');
1593
1594 my $vmid = extract_param($param, 'vmid');
1595
1596 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1597 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1598 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1599
b7eeab21 1600 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
ff1a2432 1601
5fdbe4f0
DM
1602 my $realcmd = sub {
1603 my $upid = shift;
1604
1605 syslog('info', "resume VM $vmid: $upid\n");
1606
1e3baf05 1607 PVE::QemuServer::vm_resume($vmid, $skiplock);
1e3baf05 1608
5fdbe4f0
DM
1609 return;
1610 };
1611
a0d1b1a2 1612 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1613 }});
1614
1615__PACKAGE__->register_method({
afdb31d5 1616 name => 'vm_sendkey',
5fdbe4f0
DM
1617 path => '{vmid}/sendkey',
1618 method => 'PUT',
1619 protected => 1,
1620 proxyto => 'node',
1621 description => "Send key event to virtual machine.",
a0d1b1a2
DM
1622 permissions => {
1623 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1624 },
5fdbe4f0
DM
1625 parameters => {
1626 additionalProperties => 0,
1627 properties => {
1628 node => get_standard_option('pve-node'),
1629 vmid => get_standard_option('pve-vmid'),
1630 skiplock => get_standard_option('skiplock'),
1631 key => {
1632 description => "The key (qemu monitor encoding).",
1633 type => 'string'
1634 }
1635 },
1636 },
1637 returns => { type => 'null'},
1638 code => sub {
1639 my ($param) = @_;
1640
1641 my $rpcenv = PVE::RPCEnvironment::get();
1642
a0d1b1a2 1643 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1644
1645 my $node = extract_param($param, 'node');
1646
1647 my $vmid = extract_param($param, 'vmid');
1648
1649 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1650 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1651 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0
DM
1652
1653 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1654
1655 return;
1e3baf05
DM
1656 }});
1657
1ac0d2ee
AD
1658__PACKAGE__->register_method({
1659 name => 'vm_feature',
1660 path => '{vmid}/feature',
1661 method => 'GET',
1662 proxyto => 'node',
1663 protected => 1,
1664 description => "Check if feature for virtual machine is available.",
1665 permissions => {
1666 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1667 },
1668 parameters => {
1669 additionalProperties => 0,
1670 properties => {
1671 node => get_standard_option('pve-node'),
1672 vmid => get_standard_option('pve-vmid'),
1673 feature => {
1674 description => "Feature to check.",
1675 type => 'string',
1676 enum => [ 'snapshot', 'clone' ],
1677 },
1678 snapname => get_standard_option('pve-snapshot-name', {
1679 optional => 1,
1680 }),
1681 },
1682
1683 },
1684 returns => {
1685 type => 'boolean'
1686 },
1687 code => sub {
1688 my ($param) = @_;
1689
1690 my $node = extract_param($param, 'node');
1691
1692 my $vmid = extract_param($param, 'vmid');
1693
1694 my $snapname = extract_param($param, 'snapname');
1695
1696 my $feature = extract_param($param, 'feature');
1697
1698 my $running = PVE::QemuServer::check_running($vmid);
1699
1700 my $conf = PVE::QemuServer::load_config($vmid);
1701
1702 if($snapname){
1703 my $snap = $conf->{snapshots}->{$snapname};
1704 die "snapshot '$snapname' does not exist\n" if !defined($snap);
1705 $conf = $snap;
1706 }
1707 my $storecfg = PVE::Storage::config();
1708
1709 my $hasfeature = PVE::QemuServer::has_feature($feature, $conf, $storecfg, $snapname, $running);
1710 my $res = $hasfeature ? 1 : 0 ;
1711 return $res;
1712 }});
1713
3ea94c60 1714__PACKAGE__->register_method({
afdb31d5 1715 name => 'migrate_vm',
3ea94c60
DM
1716 path => '{vmid}/migrate',
1717 method => 'POST',
1718 protected => 1,
1719 proxyto => 'node',
1720 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
1721 permissions => {
1722 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
1723 },
3ea94c60
DM
1724 parameters => {
1725 additionalProperties => 0,
1726 properties => {
1727 node => get_standard_option('pve-node'),
1728 vmid => get_standard_option('pve-vmid'),
1729 target => get_standard_option('pve-node', { description => "Target node." }),
1730 online => {
1731 type => 'boolean',
1732 description => "Use online/live migration.",
1733 optional => 1,
1734 },
1735 force => {
1736 type => 'boolean',
1737 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
1738 optional => 1,
1739 },
1740 },
1741 },
afdb31d5 1742 returns => {
3ea94c60
DM
1743 type => 'string',
1744 description => "the task ID.",
1745 },
1746 code => sub {
1747 my ($param) = @_;
1748
1749 my $rpcenv = PVE::RPCEnvironment::get();
1750
a0d1b1a2 1751 my $authuser = $rpcenv->get_user();
3ea94c60
DM
1752
1753 my $target = extract_param($param, 'target');
1754
1755 my $localnode = PVE::INotify::nodename();
1756 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
1757
1758 PVE::Cluster::check_cfs_quorum();
1759
1760 PVE::Cluster::check_node_exists($target);
1761
1762 my $targetip = PVE::Cluster::remote_node_ip($target);
1763
1764 my $vmid = extract_param($param, 'vmid');
1765
afdb31d5 1766 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 1767 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
1768
1769 # test if VM exists
a5ed42d3 1770 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
1771
1772 # try to detect errors early
a5ed42d3
DM
1773
1774 PVE::QemuServer::check_lock($conf);
1775
3ea94c60 1776 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 1777 die "cant migrate running VM without --online\n"
3ea94c60
DM
1778 if !$param->{online};
1779 }
1780
47152e2e 1781 my $storecfg = PVE::Storage::config();
22d646a7 1782 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
47152e2e 1783
3be30d63 1784 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3ea94c60 1785
88fc87b4
DM
1786 my $hacmd = sub {
1787 my $upid = shift;
3ea94c60 1788
88fc87b4
DM
1789 my $service = "pvevm:$vmid";
1790
1791 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
1792
1793 print "Executing HA migrate for VM $vmid to node $target\n";
1794
1795 PVE::Tools::run_command($cmd);
1796
1797 return;
1798 };
1799
1800 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
1801
1802 } else {
1803
1804 my $realcmd = sub {
1805 my $upid = shift;
1806
1807 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
1808 };
1809
1810 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
1811 }
3ea94c60 1812
3ea94c60 1813 }});
1e3baf05 1814
91c94f0a 1815__PACKAGE__->register_method({
afdb31d5
DM
1816 name => 'monitor',
1817 path => '{vmid}/monitor',
91c94f0a
DM
1818 method => 'POST',
1819 protected => 1,
1820 proxyto => 'node',
1821 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
1822 permissions => {
1823 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
1824 },
91c94f0a
DM
1825 parameters => {
1826 additionalProperties => 0,
1827 properties => {
1828 node => get_standard_option('pve-node'),
1829 vmid => get_standard_option('pve-vmid'),
1830 command => {
1831 type => 'string',
1832 description => "The monitor command.",
1833 }
1834 },
1835 },
1836 returns => { type => 'string'},
1837 code => sub {
1838 my ($param) = @_;
1839
1840 my $vmid = $param->{vmid};
1841
1842 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
1843
1844 my $res = '';
1845 eval {
7b7c6d1b 1846 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
91c94f0a
DM
1847 };
1848 $res = "ERROR: $@" if $@;
1849
1850 return $res;
1851 }});
1852
0d02881c
AD
1853__PACKAGE__->register_method({
1854 name => 'resize_vm',
614e3941 1855 path => '{vmid}/resize',
0d02881c
AD
1856 method => 'PUT',
1857 protected => 1,
1858 proxyto => 'node',
2f48a4f5 1859 description => "Extend volume size.",
0d02881c 1860 permissions => {
3b2773f6 1861 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
0d02881c
AD
1862 },
1863 parameters => {
1864 additionalProperties => 0,
2f48a4f5
DM
1865 properties => {
1866 node => get_standard_option('pve-node'),
1867 vmid => get_standard_option('pve-vmid'),
1868 skiplock => get_standard_option('skiplock'),
1869 disk => {
1870 type => 'string',
1871 description => "The disk you want to resize.",
1872 enum => [PVE::QemuServer::disknames()],
1873 },
1874 size => {
1875 type => 'string',
f91b2e45 1876 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2f48a4f5
DM
1877 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.",
1878 },
1879 digest => {
1880 type => 'string',
1881 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1882 maxLength => 40,
1883 optional => 1,
1884 },
1885 },
0d02881c
AD
1886 },
1887 returns => { type => 'null'},
1888 code => sub {
1889 my ($param) = @_;
1890
1891 my $rpcenv = PVE::RPCEnvironment::get();
1892
1893 my $authuser = $rpcenv->get_user();
1894
1895 my $node = extract_param($param, 'node');
1896
1897 my $vmid = extract_param($param, 'vmid');
1898
1899 my $digest = extract_param($param, 'digest');
1900
2f48a4f5
DM
1901 my $disk = extract_param($param, 'disk');
1902
1903 my $sizestr = extract_param($param, 'size');
0d02881c 1904
f91b2e45 1905 my $skiplock = extract_param($param, 'skiplock');
0d02881c
AD
1906 raise_param_exc({ skiplock => "Only root may use this option." })
1907 if $skiplock && $authuser ne 'root@pam';
1908
0d02881c
AD
1909 my $storecfg = PVE::Storage::config();
1910
0d02881c
AD
1911 my $updatefn = sub {
1912
1913 my $conf = PVE::QemuServer::load_config($vmid);
1914
1915 die "checksum missmatch (file change by other user?)\n"
1916 if $digest && $digest ne $conf->{digest};
1917 PVE::QemuServer::check_lock($conf) if !$skiplock;
1918
f91b2e45
DM
1919 die "disk '$disk' does not exist\n" if !$conf->{$disk};
1920
1921 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
1922
1923 my $volid = $drive->{file};
1924
1925 die "disk '$disk' has no associated volume\n" if !$volid;
1926
1927 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
1928
1929 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
1930
1931 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
1932
1933 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
1934
1935 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
1936 my ($ext, $newsize, $unit) = ($1, $2, $4);
1937 if ($unit) {
1938 if ($unit eq 'K') {
1939 $newsize = $newsize * 1024;
1940 } elsif ($unit eq 'M') {
1941 $newsize = $newsize * 1024 * 1024;
1942 } elsif ($unit eq 'G') {
1943 $newsize = $newsize * 1024 * 1024 * 1024;
1944 } elsif ($unit eq 'T') {
1945 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
1946 }
1947 }
1948 $newsize += $size if $ext;
1949 $newsize = int($newsize);
1950
1951 die "unable to skrink disk size\n" if $newsize < $size;
1952
1953 return if $size == $newsize;
1954
2f48a4f5 1955 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
0d02881c 1956
f91b2e45
DM
1957 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
1958
1959 $drive->{size} = $newsize;
1960 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
1961
1962 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
1963 };
0d02881c
AD
1964
1965 PVE::QemuServer::lock_config($vmid, $updatefn);
1966 return undef;
1967 }});
1968
9dbd1ee4 1969__PACKAGE__->register_method({
7e7d7b61 1970 name => 'snapshot_list',
9dbd1ee4 1971 path => '{vmid}/snapshot',
7e7d7b61
DM
1972 method => 'GET',
1973 description => "List all snapshots.",
1974 permissions => {
1975 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1976 },
1977 proxyto => 'node',
1978 protected => 1, # qemu pid files are only readable by root
1979 parameters => {
1980 additionalProperties => 0,
1981 properties => {
1982 vmid => get_standard_option('pve-vmid'),
1983 node => get_standard_option('pve-node'),
1984 },
1985 },
1986 returns => {
1987 type => 'array',
1988 items => {
1989 type => "object",
1990 properties => {},
1991 },
1992 links => [ { rel => 'child', href => "{name}" } ],
1993 },
1994 code => sub {
1995 my ($param) = @_;
1996
6aa4651b
DM
1997 my $vmid = $param->{vmid};
1998
1999 my $conf = PVE::QemuServer::load_config($vmid);
7e7d7b61
DM
2000 my $snaphash = $conf->{snapshots} || {};
2001
2002 my $res = [];
2003
2004 foreach my $name (keys %$snaphash) {
0ea6bc69 2005 my $d = $snaphash->{$name};
982c7f12
DM
2006 my $item = {
2007 name => $name,
2008 snaptime => $d->{snaptime} || 0,
6aa4651b 2009 vmstate => $d->{vmstate} ? 1 : 0,
982c7f12
DM
2010 description => $d->{description} || '',
2011 };
0ea6bc69 2012 $item->{parent} = $d->{parent} if $d->{parent};
3ee28e38 2013 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
0ea6bc69
DM
2014 push @$res, $item;
2015 }
2016
6aa4651b
DM
2017 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
2018 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
d1914468
DM
2019 $current->{parent} = $conf->{parent} if $conf->{parent};
2020
2021 push @$res, $current;
7e7d7b61
DM
2022
2023 return $res;
2024 }});
2025
2026__PACKAGE__->register_method({
2027 name => 'snapshot',
2028 path => '{vmid}/snapshot',
2029 method => 'POST',
9dbd1ee4
AD
2030 protected => 1,
2031 proxyto => 'node',
2032 description => "Snapshot a VM.",
2033 permissions => {
f1baf1df 2034 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
9dbd1ee4
AD
2035 },
2036 parameters => {
2037 additionalProperties => 0,
2038 properties => {
2039 node => get_standard_option('pve-node'),
2040 vmid => get_standard_option('pve-vmid'),
8abd398b 2041 snapname => get_standard_option('pve-snapshot-name'),
9dbd1ee4
AD
2042 vmstate => {
2043 optional => 1,
2044 type => 'boolean',
2045 description => "Save the vmstate",
2046 },
2047 freezefs => {
2048 optional => 1,
2049 type => 'boolean',
2050 description => "Freeze the filesystem",
2051 },
782f4f75
DM
2052 description => {
2053 optional => 1,
2054 type => 'string',
2055 description => "A textual description or comment.",
2056 },
9dbd1ee4
AD
2057 },
2058 },
7e7d7b61
DM
2059 returns => {
2060 type => 'string',
2061 description => "the task ID.",
2062 },
9dbd1ee4
AD
2063 code => sub {
2064 my ($param) = @_;
2065
2066 my $rpcenv = PVE::RPCEnvironment::get();
2067
2068 my $authuser = $rpcenv->get_user();
2069
2070 my $node = extract_param($param, 'node');
2071
2072 my $vmid = extract_param($param, 'vmid');
2073
9dbd1ee4
AD
2074 my $snapname = extract_param($param, 'snapname');
2075
d1914468
DM
2076 die "unable to use snapshot name 'current' (reserved name)\n"
2077 if $snapname eq 'current';
2078
7e7d7b61 2079 my $realcmd = sub {
22c377f0 2080 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
782f4f75
DM
2081 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
2082 $param->{freezefs}, $param->{description});
7e7d7b61
DM
2083 };
2084
2085 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2086 }});
2087
154ccdcd
DM
2088__PACKAGE__->register_method({
2089 name => 'snapshot_cmd_idx',
2090 path => '{vmid}/snapshot/{snapname}',
2091 description => '',
2092 method => 'GET',
2093 permissions => {
2094 user => 'all',
2095 },
2096 parameters => {
2097 additionalProperties => 0,
2098 properties => {
2099 vmid => get_standard_option('pve-vmid'),
2100 node => get_standard_option('pve-node'),
8abd398b 2101 snapname => get_standard_option('pve-snapshot-name'),
154ccdcd
DM
2102 },
2103 },
2104 returns => {
2105 type => 'array',
2106 items => {
2107 type => "object",
2108 properties => {},
2109 },
2110 links => [ { rel => 'child', href => "{cmd}" } ],
2111 },
2112 code => sub {
2113 my ($param) = @_;
2114
2115 my $res = [];
2116
2117 push @$res, { cmd => 'rollback' };
d788cea6 2118 push @$res, { cmd => 'config' };
154ccdcd
DM
2119
2120 return $res;
2121 }});
2122
d788cea6
DM
2123__PACKAGE__->register_method({
2124 name => 'update_snapshot_config',
2125 path => '{vmid}/snapshot/{snapname}/config',
2126 method => 'PUT',
2127 protected => 1,
2128 proxyto => 'node',
2129 description => "Update snapshot metadata.",
2130 permissions => {
2131 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2132 },
2133 parameters => {
2134 additionalProperties => 0,
2135 properties => {
2136 node => get_standard_option('pve-node'),
2137 vmid => get_standard_option('pve-vmid'),
2138 snapname => get_standard_option('pve-snapshot-name'),
2139 description => {
2140 optional => 1,
2141 type => 'string',
2142 description => "A textual description or comment.",
2143 },
2144 },
2145 },
2146 returns => { type => 'null' },
2147 code => sub {
2148 my ($param) = @_;
2149
2150 my $rpcenv = PVE::RPCEnvironment::get();
2151
2152 my $authuser = $rpcenv->get_user();
2153
2154 my $vmid = extract_param($param, 'vmid');
2155
2156 my $snapname = extract_param($param, 'snapname');
2157
2158 return undef if !defined($param->{description});
2159
2160 my $updatefn = sub {
2161
2162 my $conf = PVE::QemuServer::load_config($vmid);
2163
2164 PVE::QemuServer::check_lock($conf);
2165
2166 my $snap = $conf->{snapshots}->{$snapname};
2167
2168 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2169
2170 $snap->{description} = $param->{description} if defined($param->{description});
2171
2172 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2173 };
2174
2175 PVE::QemuServer::lock_config($vmid, $updatefn);
2176
2177 return undef;
2178 }});
2179
2180__PACKAGE__->register_method({
2181 name => 'get_snapshot_config',
2182 path => '{vmid}/snapshot/{snapname}/config',
2183 method => 'GET',
2184 proxyto => 'node',
2185 description => "Get snapshot configuration",
2186 permissions => {
2187 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2188 },
2189 parameters => {
2190 additionalProperties => 0,
2191 properties => {
2192 node => get_standard_option('pve-node'),
2193 vmid => get_standard_option('pve-vmid'),
2194 snapname => get_standard_option('pve-snapshot-name'),
2195 },
2196 },
2197 returns => { type => "object" },
2198 code => sub {
2199 my ($param) = @_;
2200
2201 my $rpcenv = PVE::RPCEnvironment::get();
2202
2203 my $authuser = $rpcenv->get_user();
2204
2205 my $vmid = extract_param($param, 'vmid');
2206
2207 my $snapname = extract_param($param, 'snapname');
2208
2209 my $conf = PVE::QemuServer::load_config($vmid);
2210
2211 my $snap = $conf->{snapshots}->{$snapname};
2212
2213 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2214
2215 return $snap;
2216 }});
2217
7e7d7b61
DM
2218__PACKAGE__->register_method({
2219 name => 'rollback',
154ccdcd 2220 path => '{vmid}/snapshot/{snapname}/rollback',
7e7d7b61
DM
2221 method => 'POST',
2222 protected => 1,
2223 proxyto => 'node',
2224 description => "Rollback VM state to specified snapshot.",
2225 permissions => {
f1baf1df 2226 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2227 },
2228 parameters => {
2229 additionalProperties => 0,
2230 properties => {
2231 node => get_standard_option('pve-node'),
2232 vmid => get_standard_option('pve-vmid'),
8abd398b 2233 snapname => get_standard_option('pve-snapshot-name'),
7e7d7b61
DM
2234 },
2235 },
2236 returns => {
2237 type => 'string',
2238 description => "the task ID.",
2239 },
2240 code => sub {
2241 my ($param) = @_;
2242
2243 my $rpcenv = PVE::RPCEnvironment::get();
2244
2245 my $authuser = $rpcenv->get_user();
2246
2247 my $node = extract_param($param, 'node');
2248
2249 my $vmid = extract_param($param, 'vmid');
2250
2251 my $snapname = extract_param($param, 'snapname');
2252
7e7d7b61 2253 my $realcmd = sub {
22c377f0
DM
2254 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
2255 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
7e7d7b61
DM
2256 };
2257
2258 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
2259 }});
2260
2261__PACKAGE__->register_method({
2262 name => 'delsnapshot',
2263 path => '{vmid}/snapshot/{snapname}',
2264 method => 'DELETE',
2265 protected => 1,
2266 proxyto => 'node',
2267 description => "Delete a VM snapshot.",
2268 permissions => {
f1baf1df 2269 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2270 },
2271 parameters => {
2272 additionalProperties => 0,
2273 properties => {
2274 node => get_standard_option('pve-node'),
2275 vmid => get_standard_option('pve-vmid'),
8abd398b 2276 snapname => get_standard_option('pve-snapshot-name'),
3ee28e38
DM
2277 force => {
2278 optional => 1,
2279 type => 'boolean',
2280 description => "For removal from config file, even if removing disk snapshots fails.",
2281 },
7e7d7b61
DM
2282 },
2283 },
2284 returns => {
2285 type => 'string',
2286 description => "the task ID.",
2287 },
2288 code => sub {
2289 my ($param) = @_;
2290
2291 my $rpcenv = PVE::RPCEnvironment::get();
2292
2293 my $authuser = $rpcenv->get_user();
2294
2295 my $node = extract_param($param, 'node');
2296
2297 my $vmid = extract_param($param, 'vmid');
2298
2299 my $snapname = extract_param($param, 'snapname');
2300
7e7d7b61 2301 my $realcmd = sub {
22c377f0 2302 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
3ee28e38 2303 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
7e7d7b61 2304 };
9dbd1ee4 2305
7b2257a8 2306 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
9dbd1ee4
AD
2307 }});
2308
04a69bb4
AD
2309__PACKAGE__->register_method({
2310 name => 'template',
2311 path => '{vmid}/template',
2312 method => 'POST',
2313 protected => 1,
2314 proxyto => 'node',
2315 description => "Create a Template.",
04a69bb4
AD
2316 parameters => {
2317 additionalProperties => 0,
2318 properties => {
2319 node => get_standard_option('pve-node'),
2320 vmid => get_standard_option('pve-vmid'),
2321 disk => {
2322 optional => 1,
2323 type => 'string',
2324 description => "If you want to convert only 1 disk to base image.",
2325 enum => [PVE::QemuServer::disknames()],
2326 },
2327
2328 },
2329 },
2330 returns => { type => 'null'},
2331 code => sub {
2332 my ($param) = @_;
2333
2334 my $rpcenv = PVE::RPCEnvironment::get();
2335
2336 my $authuser = $rpcenv->get_user();
2337
2338 my $node = extract_param($param, 'node');
2339
2340 my $vmid = extract_param($param, 'vmid');
2341
2342 my $disk = extract_param($param, 'disk');
2343
2344 my $updatefn = sub {
2345
2346 my $conf = PVE::QemuServer::load_config($vmid);
2347
2348 PVE::QemuServer::check_lock($conf);
2349
03c2d0ad
DM
2350 die "you can't convert a template to a template"
2351 if PVE::QemuServer::is_template($conf) && !$disk;
04a69bb4
AD
2352 my $realcmd = sub {
2353 PVE::QemuServer::template_create($vmid, $conf, $disk);
2354 };
2355 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
2356
2357 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2358 };
2359
2360 PVE::QemuServer::lock_config($vmid, $updatefn);
2361 return undef;
2362 }});
2363
2364
2365
1e3baf05 23661;