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