]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
use qmp for vm_devices_list
[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') {
09d0ee64
DM
75 $res->{$ds} = $settings->{$ds};
76 } elsif ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/) {
ae57f6b3
DM
77 my ($storeid, $size) = ($2 || $default_storage, $3);
78 die "no storage ID specified (and no default storage)\n" if !$storeid;
79 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
80 my $fmt = $disk->{format} || $defformat;
a0d1b1a2
DM
81 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid,
82 $fmt, undef, $size*1024*1024);
a0d1b1a2
DM
83 $disk->{file} = $volid;
84 push @$vollist, $volid;
ae57f6b3
DM
85 delete $disk->{format}; # no longer needed
86 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
87 } else {
ba68cf09 88 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $volid);
d7810bc1
DM
89 PVE::Storage::activate_volumes($storecfg, [ $volid ])
90 if PVE::Storage::parse_volume_id ($volid, 1);
35cb731c
AD
91
92 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
93 my $dl = PVE::Storage::vdisk_list($storecfg, $storeid, undef);
94 my $foundvolid = undef;
95
96 PVE::Storage::foreach_volid($dl, sub {
97 my ($volumeid) = @_;
98 if($volumeid eq $volid) {
99 $foundvolid = 1;
100 return;
101 }
102 });
103
104 die "image '$path' does not exists\n" if (!(-f $path || -b $path || $foundvolid));
09d0ee64 105 $res->{$ds} = $settings->{$ds};
a0d1b1a2 106 }
ae57f6b3 107 });
a0d1b1a2
DM
108
109 # free allocated images on error
110 if (my $err = $@) {
111 syslog('err', "VM $vmid creating disks failed");
112 foreach my $volid (@$vollist) {
113 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
114 warn $@ if $@;
115 }
116 die $err;
117 }
118
119 # modify vm config if everything went well
ae57f6b3
DM
120 foreach my $ds (keys %$res) {
121 $conf->{$ds} = $res->{$ds};
a0d1b1a2
DM
122 }
123
124 return $vollist;
125};
126
127my $check_vm_modify_config_perm = sub {
ae57f6b3 128 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
a0d1b1a2 129
6e5c4da7 130 return 1 if $authuser eq 'root@pam';
a0d1b1a2 131
ae57f6b3 132 foreach my $opt (@$key_list) {
a0d1b1a2
DM
133 # disk checks need to be done somewhere else
134 next if PVE::QemuServer::valid_drivename($opt);
135
136 if ($opt eq 'sockets' || $opt eq 'cores' ||
137 $opt eq 'cpu' || $opt eq 'smp' ||
ab6b35df 138 $opt eq 'cpulimit' || $opt eq 'cpuunits') {
a0d1b1a2
DM
139 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
140 } elsif ($opt eq 'boot' || $opt eq 'bootdisk') {
141 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
142 } elsif ($opt eq 'memory' || $opt eq 'balloon') {
143 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
144 } elsif ($opt eq 'args' || $opt eq 'lock') {
145 die "only root can set '$opt' config\n";
146 } elsif ($opt eq 'cpu' || $opt eq 'kvm' || $opt eq 'acpi' ||
147 $opt eq 'vga' || $opt eq 'watchdog' || $opt eq 'tablet') {
148 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
149 } elsif ($opt =~ m/^net\d+$/) {
150 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
151 } else {
152 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
153 }
154 }
155
156 return 1;
157};
158
1e3baf05 159__PACKAGE__->register_method({
afdb31d5
DM
160 name => 'vmlist',
161 path => '',
1e3baf05
DM
162 method => 'GET',
163 description => "Virtual machine index (per node).",
a0d1b1a2
DM
164 permissions => {
165 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
166 user => 'all',
167 },
1e3baf05
DM
168 proxyto => 'node',
169 protected => 1, # qemu pid files are only readable by root
170 parameters => {
171 additionalProperties => 0,
172 properties => {
173 node => get_standard_option('pve-node'),
174 },
175 },
176 returns => {
177 type => 'array',
178 items => {
179 type => "object",
180 properties => {},
181 },
182 links => [ { rel => 'child', href => "{vmid}" } ],
183 },
184 code => sub {
185 my ($param) = @_;
186
a0d1b1a2
DM
187 my $rpcenv = PVE::RPCEnvironment::get();
188 my $authuser = $rpcenv->get_user();
189
1e3baf05
DM
190 my $vmstatus = PVE::QemuServer::vmstatus();
191
a0d1b1a2
DM
192 my $res = [];
193 foreach my $vmid (keys %$vmstatus) {
194 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
195
196 my $data = $vmstatus->{$vmid};
197 $data->{vmid} = $vmid;
198 push @$res, $data;
199 }
1e3baf05 200
a0d1b1a2 201 return $res;
1e3baf05
DM
202 }});
203
204__PACKAGE__->register_method({
afdb31d5
DM
205 name => 'create_vm',
206 path => '',
1e3baf05 207 method => 'POST',
3e16d5fc 208 description => "Create or restore a virtual machine.",
a0d1b1a2
DM
209 permissions => {
210 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.",
211 check => [ 'or',
212 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
213 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
214 ],
215 },
1e3baf05
DM
216 protected => 1,
217 proxyto => 'node',
218 parameters => {
219 additionalProperties => 0,
220 properties => PVE::QemuServer::json_config_properties(
221 {
222 node => get_standard_option('pve-node'),
223 vmid => get_standard_option('pve-vmid'),
3e16d5fc
DM
224 archive => {
225 description => "The backup file.",
226 type => 'string',
227 optional => 1,
228 maxLength => 255,
229 },
230 storage => get_standard_option('pve-storage-id', {
231 description => "Default storage.",
232 optional => 1,
233 }),
234 force => {
afdb31d5 235 optional => 1,
3e16d5fc
DM
236 type => 'boolean',
237 description => "Allow to overwrite existing VM.",
51586c3a
DM
238 requires => 'archive',
239 },
240 unique => {
afdb31d5 241 optional => 1,
51586c3a
DM
242 type => 'boolean',
243 description => "Assign a unique random ethernet address.",
244 requires => 'archive',
3e16d5fc 245 },
a0d1b1a2
DM
246 pool => {
247 optional => 1,
248 type => 'string', format => 'pve-poolid',
249 description => "Add the VM to the specified pool.",
250 },
1e3baf05
DM
251 }),
252 },
afdb31d5 253 returns => {
5fdbe4f0
DM
254 type => 'string',
255 },
1e3baf05
DM
256 code => sub {
257 my ($param) = @_;
258
5fdbe4f0
DM
259 my $rpcenv = PVE::RPCEnvironment::get();
260
a0d1b1a2 261 my $authuser = $rpcenv->get_user();
5fdbe4f0 262
1e3baf05
DM
263 my $node = extract_param($param, 'node');
264
1e3baf05
DM
265 my $vmid = extract_param($param, 'vmid');
266
3e16d5fc
DM
267 my $archive = extract_param($param, 'archive');
268
269 my $storage = extract_param($param, 'storage');
270
51586c3a
DM
271 my $force = extract_param($param, 'force');
272
273 my $unique = extract_param($param, 'unique');
a0d1b1a2
DM
274
275 my $pool = extract_param($param, 'pool');
51586c3a 276
1e3baf05 277 my $filename = PVE::QemuServer::config_file($vmid);
afdb31d5
DM
278
279 my $storecfg = PVE::Storage::config();
1e3baf05 280
3e16d5fc 281 PVE::Cluster::check_cfs_quorum();
1e3baf05 282
a0d1b1a2
DM
283 if (defined($pool)) {
284 $rpcenv->check_pool_exist($pool);
a0d1b1a2
DM
285 }
286
fcbb753e 287 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace'])
a0d1b1a2
DM
288 if defined($storage);
289
afdb31d5 290 if (!$archive) {
3e16d5fc 291 &$resolve_cdrom_alias($param);
1e3baf05 292
fcbb753e 293 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param, $storage);
ae57f6b3
DM
294
295 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
296
3e16d5fc
DM
297 foreach my $opt (keys %$param) {
298 if (PVE::QemuServer::valid_drivename($opt)) {
299 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
300 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
afdb31d5 301
3e16d5fc
DM
302 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
303 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
304 }
1e3baf05 305 }
3e16d5fc
DM
306
307 PVE::QemuServer::add_random_macs($param);
51586c3a
DM
308 } else {
309 my $keystr = join(' ', keys %$param);
bc4dcb99
DM
310 raise_param_exc({ archive => "option conflicts with other options ($keystr)"}) if $keystr;
311
5b9d692a 312 if ($archive eq '-') {
afdb31d5 313 die "pipe requires cli environment\n"
d7810bc1 314 if $rpcenv->{type} ne 'cli';
5b9d692a 315 } else {
ba68cf09 316 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $archive);
d7810bc1
DM
317
318 PVE::Storage::activate_volumes($storecfg, [ $archive ])
319 if PVE::Storage::parse_volume_id ($archive, 1);
320
971f27c4
DM
321 die "can't find archive file '$archive'\n" if !($path && -f $path);
322 $archive = $path;
323 }
1e3baf05
DM
324 }
325
502d18a2
DM
326 my $addVMtoPoolFn = sub {
327 my $usercfg = cfs_read_file("user.cfg");
328 if (my $data = $usercfg->{pools}->{$pool}) {
329 $data->{vms}->{$vmid} = 1;
330 $usercfg->{vms}->{$vmid} = $pool;
331 cfs_write_file("user.cfg", $usercfg);
332 }
333 };
334
3e16d5fc
DM
335 my $restorefn = sub {
336
337 if (-f $filename) {
afdb31d5 338 die "unable to restore vm $vmid: config file already exists\n"
51586c3a 339 if !$force;
3e16d5fc 340
afdb31d5 341 die "unable to restore vm $vmid: vm is running\n"
3e16d5fc 342 if PVE::QemuServer::check_running($vmid);
a6af7b3e
DM
343
344 # destroy existing data - keep empty config
345 PVE::QemuServer::destroy_vm($storecfg, $vmid, 1);
3e16d5fc
DM
346 }
347
348 my $realcmd = sub {
a0d1b1a2 349 PVE::QemuServer::restore_archive($archive, $vmid, $authuser, {
51586c3a 350 storage => $storage,
a0d1b1a2 351 pool => $pool,
51586c3a 352 unique => $unique });
502d18a2
DM
353
354 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
3e16d5fc
DM
355 };
356
a0d1b1a2 357 return $rpcenv->fork_worker('qmrestore', $vmid, $authuser, $realcmd);
3e16d5fc 358 };
1e3baf05 359
1e3baf05
DM
360 my $createfn = sub {
361
191435c6 362 # test after locking
afdb31d5 363 die "unable to create vm $vmid: config file already exists\n"
1e3baf05
DM
364 if -f $filename;
365
5fdbe4f0 366 my $realcmd = sub {
1e3baf05 367
5fdbe4f0 368 my $vollist = [];
1e3baf05 369
1858638f
DM
370 my $conf = $param;
371
5fdbe4f0 372 eval {
ae57f6b3 373
1858638f 374 $vollist = &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $param, $storage);
1e3baf05 375
5fdbe4f0
DM
376 # try to be smart about bootdisk
377 my @disks = PVE::QemuServer::disknames();
378 my $firstdisk;
379 foreach my $ds (reverse @disks) {
1858638f
DM
380 next if !$conf->{$ds};
381 my $disk = PVE::QemuServer::parse_drive($ds, $conf->{$ds});
5fdbe4f0
DM
382 next if PVE::QemuServer::drive_is_cdrom($disk);
383 $firstdisk = $ds;
384 }
1e3baf05 385
1858638f
DM
386 if (!$conf->{bootdisk} && $firstdisk) {
387 $conf->{bootdisk} = $firstdisk;
5fdbe4f0 388 }
1e3baf05 389
ae9ca91d
DM
390 PVE::QemuServer::update_config_nolock($vmid, $conf);
391
5fdbe4f0
DM
392 };
393 my $err = $@;
1e3baf05 394
5fdbe4f0
DM
395 if ($err) {
396 foreach my $volid (@$vollist) {
397 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
398 warn $@ if $@;
399 }
400 die "create failed - $err";
401 }
502d18a2
DM
402
403 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
5fdbe4f0
DM
404 };
405
a0d1b1a2 406 return $rpcenv->fork_worker('qmcreate', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
407 };
408
191435c6 409 return PVE::QemuServer::lock_config_full($vmid, 1, $archive ? $restorefn : $createfn);
1e3baf05
DM
410 }});
411
412__PACKAGE__->register_method({
413 name => 'vmdiridx',
afdb31d5 414 path => '{vmid}',
1e3baf05
DM
415 method => 'GET',
416 proxyto => 'node',
417 description => "Directory index",
a0d1b1a2
DM
418 permissions => {
419 user => 'all',
420 },
1e3baf05
DM
421 parameters => {
422 additionalProperties => 0,
423 properties => {
424 node => get_standard_option('pve-node'),
425 vmid => get_standard_option('pve-vmid'),
426 },
427 },
428 returns => {
429 type => 'array',
430 items => {
431 type => "object",
432 properties => {
433 subdir => { type => 'string' },
434 },
435 },
436 links => [ { rel => 'child', href => "{subdir}" } ],
437 },
438 code => sub {
439 my ($param) = @_;
440
441 my $res = [
442 { subdir => 'config' },
443 { subdir => 'status' },
444 { subdir => 'unlink' },
445 { subdir => 'vncproxy' },
3ea94c60 446 { subdir => 'migrate' },
1e3baf05
DM
447 { subdir => 'rrd' },
448 { subdir => 'rrddata' },
91c94f0a 449 { subdir => 'monitor' },
1e3baf05 450 ];
afdb31d5 451
1e3baf05
DM
452 return $res;
453 }});
454
455__PACKAGE__->register_method({
afdb31d5
DM
456 name => 'rrd',
457 path => '{vmid}/rrd',
1e3baf05
DM
458 method => 'GET',
459 protected => 1, # fixme: can we avoid that?
460 permissions => {
378b359e 461 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
462 },
463 description => "Read VM RRD statistics (returns PNG)",
464 parameters => {
465 additionalProperties => 0,
466 properties => {
467 node => get_standard_option('pve-node'),
468 vmid => get_standard_option('pve-vmid'),
469 timeframe => {
470 description => "Specify the time frame you are interested in.",
471 type => 'string',
472 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
473 },
474 ds => {
475 description => "The list of datasources you want to display.",
476 type => 'string', format => 'pve-configid-list',
477 },
478 cf => {
479 description => "The RRD consolidation function",
480 type => 'string',
481 enum => [ 'AVERAGE', 'MAX' ],
482 optional => 1,
483 },
484 },
485 },
486 returns => {
487 type => "object",
488 properties => {
489 filename => { type => 'string' },
490 },
491 },
492 code => sub {
493 my ($param) = @_;
494
495 return PVE::Cluster::create_rrd_graph(
afdb31d5 496 "pve2-vm/$param->{vmid}", $param->{timeframe},
1e3baf05 497 $param->{ds}, $param->{cf});
afdb31d5 498
1e3baf05
DM
499 }});
500
501__PACKAGE__->register_method({
afdb31d5
DM
502 name => 'rrddata',
503 path => '{vmid}/rrddata',
1e3baf05
DM
504 method => 'GET',
505 protected => 1, # fixme: can we avoid that?
506 permissions => {
378b359e 507 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
508 },
509 description => "Read VM RRD statistics",
510 parameters => {
511 additionalProperties => 0,
512 properties => {
513 node => get_standard_option('pve-node'),
514 vmid => get_standard_option('pve-vmid'),
515 timeframe => {
516 description => "Specify the time frame you are interested in.",
517 type => 'string',
518 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
519 },
520 cf => {
521 description => "The RRD consolidation function",
522 type => 'string',
523 enum => [ 'AVERAGE', 'MAX' ],
524 optional => 1,
525 },
526 },
527 },
528 returns => {
529 type => "array",
530 items => {
531 type => "object",
532 properties => {},
533 },
534 },
535 code => sub {
536 my ($param) = @_;
537
538 return PVE::Cluster::create_rrd_data(
539 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
540 }});
541
542
543__PACKAGE__->register_method({
afdb31d5
DM
544 name => 'vm_config',
545 path => '{vmid}/config',
1e3baf05
DM
546 method => 'GET',
547 proxyto => 'node',
548 description => "Get virtual machine configuration.",
a0d1b1a2
DM
549 permissions => {
550 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
551 },
1e3baf05
DM
552 parameters => {
553 additionalProperties => 0,
554 properties => {
555 node => get_standard_option('pve-node'),
556 vmid => get_standard_option('pve-vmid'),
557 },
558 },
afdb31d5 559 returns => {
1e3baf05 560 type => "object",
554ac7e7
DM
561 properties => {
562 digest => {
563 type => 'string',
564 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
565 }
566 },
1e3baf05
DM
567 },
568 code => sub {
569 my ($param) = @_;
570
571 my $conf = PVE::QemuServer::load_config($param->{vmid});
572
573 return $conf;
574 }});
575
ae57f6b3
DM
576my $vm_is_volid_owner = sub {
577 my ($storecfg, $vmid, $volid) =@_;
578
579 if ($volid !~ m|^/|) {
580 my ($path, $owner);
581 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
582 if ($owner && ($owner == $vmid)) {
583 return 1;
584 }
585 }
586
587 return undef;
588};
589
590my $test_deallocate_drive = sub {
591 my ($storecfg, $vmid, $key, $drive, $force) = @_;
592
593 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
594 my $volid = $drive->{file};
595 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
596 if ($force || $key =~ m/^unused/) {
597 my $sid = PVE::Storage::parse_volume_id($volid);
598 return $sid;
599 }
600 }
601 }
602
603 return undef;
604};
605
5d7a6767 606my $delete_drive = sub {
1858638f 607 my ($conf, $storecfg, $vmid, $key, $drive, $force) = @_;
5d7a6767
DM
608
609 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
610 my $volid = $drive->{file};
ae57f6b3
DM
611 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
612 if ($force || $key =~ m/^unused/) {
613 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
7e4e69a6 614 die $@ if $@;
ae57f6b3
DM
615 } else {
616 PVE::QemuServer::add_unused_volume($conf, $volid, $vmid);
5d7a6767 617 }
ae57f6b3
DM
618 }
619 }
49f9db93
DM
620
621 delete $conf->{$key};
ae57f6b3
DM
622};
623
624my $vmconfig_delete_option = sub {
625 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force) = @_;
626
627 return if !defined($conf->{$opt});
628
629 my $isDisk = PVE::QemuServer::valid_drivename($opt)|| ($opt =~ m/^unused/);
630
631 if ($isDisk) {
632 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
633
634 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
635 if (my $sid = &$test_deallocate_drive($storecfg, $vmid, $opt, $drive, $force)) {
fcbb753e 636 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.Allocate']);
5d7a6767 637 }
ae57f6b3
DM
638 }
639
640 die "error hot-unplug $opt" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
641
642 if ($isDisk) {
643 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
644 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive, $force);
5d7a6767 645 } else {
ae57f6b3
DM
646 delete $conf->{$opt};
647 }
648
649 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
650};
651
652my $vmconfig_update_disk = sub {
653 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
5d7a6767 654
ae57f6b3
DM
655 my $drive = PVE::QemuServer::parse_drive($opt, $value);
656
657 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
658 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
659 } else {
660 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
661 }
662
663 if ($conf->{$opt}) {
664
665 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
666
667 my $media = $drive->{media} || 'disk';
668 my $oldmedia = $old_drive->{media} || 'disk';
669 die "unable to change media type\n" if $media ne $oldmedia;
670
671 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
672 ($drive->{file} ne $old_drive->{file})) { # delete old disks
673
674 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
675 $conf = PVE::QemuServer::load_config($vmid); # update/reload
676 }
677 }
678 }
679
680 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
681 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
682
683 $conf = PVE::QemuServer::load_config($vmid); # update/reload
684 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
685
686 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
687
688 if (PVE::QemuServer::check_running($vmid)) {
689 if ($drive->{file} eq 'none') {
ce156282 690 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
ae57f6b3
DM
691 } else {
692 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
ce156282
AD
693 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt"); #force eject if locked
694 PVE::QemuServer::vm_mon_cmd($vmid, "change",device => "drive-$opt",target => "$path") if $path;
ae57f6b3
DM
695 }
696 }
697
698 } else { # hotplug new disks
699
700 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
5d7a6767 701 }
5d7a6767
DM
702};
703
ae57f6b3
DM
704my $vmconfig_update_net = sub {
705 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
706
707 if ($conf->{$opt}) {
708 #if online update, then unplug first
709 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
710 }
711
712 $conf->{$opt} = $value;
713 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
714 $conf = PVE::QemuServer::load_config($vmid); # update/reload
715
716 my $net = PVE::QemuServer::parse_net($conf->{$opt});
717
718 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
719};
720
a0d1b1a2
DM
721my $vm_config_perm_list = [
722 'VM.Config.Disk',
723 'VM.Config.CDROM',
724 'VM.Config.CPU',
725 'VM.Config.Memory',
726 'VM.Config.Network',
727 'VM.Config.HWType',
728 'VM.Config.Options',
729 ];
730
1e3baf05 731__PACKAGE__->register_method({
afdb31d5
DM
732 name => 'update_vm',
733 path => '{vmid}/config',
1e3baf05
DM
734 method => 'PUT',
735 protected => 1,
736 proxyto => 'node',
737 description => "Set virtual machine options.",
a0d1b1a2
DM
738 permissions => {
739 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
740 },
1e3baf05
DM
741 parameters => {
742 additionalProperties => 0,
743 properties => PVE::QemuServer::json_config_properties(
744 {
745 node => get_standard_option('pve-node'),
746 vmid => get_standard_option('pve-vmid'),
3ea94c60 747 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
748 delete => {
749 type => 'string', format => 'pve-configid-list',
750 description => "A list of settings you want to delete.",
751 optional => 1,
752 },
753 force => {
754 type => 'boolean',
755 description => $opt_force_description,
756 optional => 1,
757 requires => 'delete',
758 },
554ac7e7
DM
759 digest => {
760 type => 'string',
761 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
762 maxLength => 40,
afdb31d5 763 optional => 1,
554ac7e7 764 }
1e3baf05
DM
765 }),
766 },
767 returns => { type => 'null'},
768 code => sub {
769 my ($param) = @_;
770
771 my $rpcenv = PVE::RPCEnvironment::get();
772
a0d1b1a2 773 my $authuser = $rpcenv->get_user();
1e3baf05
DM
774
775 my $node = extract_param($param, 'node');
776
1e3baf05
DM
777 my $vmid = extract_param($param, 'vmid');
778
5fdbe4f0
DM
779 my $digest = extract_param($param, 'digest');
780
781 my @paramarr = (); # used for log message
782 foreach my $key (keys %$param) {
783 push @paramarr, "-$key", $param->{$key};
784 }
785
1e3baf05 786 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 787 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 788 if $skiplock && $authuser ne 'root@pam';
1e3baf05 789
0532bc63
DM
790 my $delete_str = extract_param($param, 'delete');
791
1e3baf05
DM
792 my $force = extract_param($param, 'force');
793
0532bc63
DM
794 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
795
1e68cb19
DM
796 my $storecfg = PVE::Storage::config();
797
798 &$resolve_cdrom_alias($param);
799
800 # now try to verify all parameters
801
0532bc63
DM
802 my @delete = ();
803 foreach my $opt (PVE::Tools::split_list($delete_str)) {
804 $opt = 'ide2' if $opt eq 'cdrom';
805 raise_param_exc({ delete => "you can't use '-$opt' and " .
806 "-delete $opt' at the same time" })
807 if defined($param->{$opt});
808
809 if (!PVE::QemuServer::option_exists($opt)) {
810 raise_param_exc({ delete => "unknown option '$opt'" });
811 }
ae57f6b3 812
0532bc63
DM
813 push @delete, $opt;
814 }
1e3baf05 815
1e68cb19
DM
816 foreach my $opt (keys %$param) {
817 if (PVE::QemuServer::valid_drivename($opt)) {
818 # cleanup drive path
819 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
820 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
821 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
1e68cb19
DM
822 } elsif ($opt =~ m/^net(\d+)$/) {
823 # add macaddr
824 my $net = PVE::QemuServer::parse_net($param->{$opt});
825 $param->{$opt} = PVE::QemuServer::print_net($net);
1e68cb19
DM
826 }
827 }
1e3baf05 828
ae57f6b3
DM
829 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
830
831 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
832
fcbb753e 833 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1e3baf05 834
5d39a182 835 my $updatefn = sub {
1e3baf05 836
5d39a182 837 my $conf = PVE::QemuServer::load_config($vmid);
1e3baf05 838
5d39a182
DM
839 die "checksum missmatch (file change by other user?)\n"
840 if $digest && $digest ne $conf->{digest};
1e3baf05 841
5d39a182 842 PVE::QemuServer::check_lock($conf) if !$skiplock;
1e3baf05 843
a0d1b1a2 844 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
c2a64aa7 845
5d7a6767 846 foreach my $opt (@delete) { # delete
1e68cb19 847 $conf = PVE::QemuServer::load_config($vmid); # update/reload
ae57f6b3 848 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
5d39a182 849 }
1e3baf05 850
5d7a6767 851 foreach my $opt (keys %$param) { # add/change
1e3baf05 852
1e68cb19 853 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1e3baf05 854
5d7a6767
DM
855 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
856
ae57f6b3 857 if (PVE::QemuServer::valid_drivename($opt)) {
5d7a6767 858
ae57f6b3
DM
859 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
860 $opt, $param->{$opt}, $force);
1e68cb19 861
ae57f6b3 862 } elsif ($opt =~ m/^net(\d+)$/) { #nics
1858638f 863
ae57f6b3
DM
864 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
865 $opt, $param->{$opt});
1e68cb19
DM
866
867 } else {
868
1858638f
DM
869 $conf->{$opt} = $param->{$opt};
870 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3a1e36bb 871 }
5d39a182
DM
872 }
873 };
874
875 PVE::QemuServer::lock_config($vmid, $updatefn);
fcdb0117 876
1e3baf05
DM
877 return undef;
878 }});
879
880
881__PACKAGE__->register_method({
afdb31d5
DM
882 name => 'destroy_vm',
883 path => '{vmid}',
1e3baf05
DM
884 method => 'DELETE',
885 protected => 1,
886 proxyto => 'node',
887 description => "Destroy the vm (also delete all used/owned volumes).",
a0d1b1a2
DM
888 permissions => {
889 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
890 },
1e3baf05
DM
891 parameters => {
892 additionalProperties => 0,
893 properties => {
894 node => get_standard_option('pve-node'),
895 vmid => get_standard_option('pve-vmid'),
3ea94c60 896 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
897 },
898 },
afdb31d5 899 returns => {
5fdbe4f0
DM
900 type => 'string',
901 },
1e3baf05
DM
902 code => sub {
903 my ($param) = @_;
904
905 my $rpcenv = PVE::RPCEnvironment::get();
906
a0d1b1a2 907 my $authuser = $rpcenv->get_user();
1e3baf05
DM
908
909 my $vmid = $param->{vmid};
910
911 my $skiplock = $param->{skiplock};
afdb31d5 912 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 913 if $skiplock && $authuser ne 'root@pam';
1e3baf05 914
5fdbe4f0
DM
915 # test if VM exists
916 my $conf = PVE::QemuServer::load_config($vmid);
917
afdb31d5 918 my $storecfg = PVE::Storage::config();
1e3baf05 919
502d18a2
DM
920 my $delVMfromPoolFn = sub {
921 my $usercfg = cfs_read_file("user.cfg");
5d0094ea
DM
922 if (my $pool = $usercfg->{vms}->{$vmid}) {
923 if (my $data = $usercfg->{pools}->{$pool}) {
924 delete $data->{vms}->{$vmid};
925 delete $usercfg->{vms}->{$vmid};
926 cfs_write_file("user.cfg", $usercfg);
927 }
502d18a2
DM
928 }
929 };
930
5fdbe4f0 931 my $realcmd = sub {
ff1a2432
DM
932 my $upid = shift;
933
934 syslog('info', "destroy VM $vmid: $upid\n");
935
5fdbe4f0 936 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
502d18a2
DM
937
938 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
5fdbe4f0 939 };
1e3baf05 940
a0d1b1a2 941 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1e3baf05
DM
942 }});
943
944__PACKAGE__->register_method({
afdb31d5
DM
945 name => 'unlink',
946 path => '{vmid}/unlink',
1e3baf05
DM
947 method => 'PUT',
948 protected => 1,
949 proxyto => 'node',
950 description => "Unlink/delete disk images.",
a0d1b1a2
DM
951 permissions => {
952 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
953 },
1e3baf05
DM
954 parameters => {
955 additionalProperties => 0,
956 properties => {
957 node => get_standard_option('pve-node'),
958 vmid => get_standard_option('pve-vmid'),
959 idlist => {
960 type => 'string', format => 'pve-configid-list',
961 description => "A list of disk IDs you want to delete.",
962 },
963 force => {
964 type => 'boolean',
965 description => $opt_force_description,
966 optional => 1,
967 },
968 },
969 },
970 returns => { type => 'null'},
971 code => sub {
972 my ($param) = @_;
973
974 $param->{delete} = extract_param($param, 'idlist');
975
976 __PACKAGE__->update_vm($param);
977
978 return undef;
979 }});
980
981my $sslcert;
982
983__PACKAGE__->register_method({
afdb31d5
DM
984 name => 'vncproxy',
985 path => '{vmid}/vncproxy',
1e3baf05
DM
986 method => 'POST',
987 protected => 1,
988 permissions => {
378b359e 989 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1e3baf05
DM
990 },
991 description => "Creates a TCP VNC proxy connections.",
992 parameters => {
993 additionalProperties => 0,
994 properties => {
995 node => get_standard_option('pve-node'),
996 vmid => get_standard_option('pve-vmid'),
997 },
998 },
afdb31d5 999 returns => {
1e3baf05
DM
1000 additionalProperties => 0,
1001 properties => {
1002 user => { type => 'string' },
1003 ticket => { type => 'string' },
1004 cert => { type => 'string' },
1005 port => { type => 'integer' },
1006 upid => { type => 'string' },
1007 },
1008 },
1009 code => sub {
1010 my ($param) = @_;
1011
1012 my $rpcenv = PVE::RPCEnvironment::get();
1013
a0d1b1a2 1014 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1015
1016 my $vmid = $param->{vmid};
1017 my $node = $param->{node};
1018
b6f39da2
DM
1019 my $authpath = "/vms/$vmid";
1020
a0d1b1a2 1021 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
b6f39da2 1022
1e3baf05
DM
1023 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1024 if !$sslcert;
1025
1026 my $port = PVE::Tools::next_vnc_port();
1027
1028 my $remip;
afdb31d5 1029
4f1be36c 1030 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1e3baf05
DM
1031 $remip = PVE::Cluster::remote_node_ip($node);
1032 }
1033
1034 # NOTE: kvm VNC traffic is already TLS encrypted,
1035 # so we select the fastest chipher here (or 'none'?)
1036 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes',
1037 '-c', 'blowfish-cbc', $remip] : [];
1038
afdb31d5 1039 my $timeout = 10;
1e3baf05
DM
1040
1041 my $realcmd = sub {
1042 my $upid = shift;
1043
1044 syslog('info', "starting vnc proxy $upid\n");
1045
1046 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1047
1048 my $qmstr = join(' ', @$qmcmd);
1049
1050 # also redirect stderr (else we get RFB protocol errors)
be62c45c 1051 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1e3baf05 1052
be62c45c 1053 PVE::Tools::run_command($cmd);
1e3baf05
DM
1054
1055 return;
1056 };
1057
a0d1b1a2 1058 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1e3baf05
DM
1059
1060 return {
a0d1b1a2 1061 user => $authuser,
1e3baf05 1062 ticket => $ticket,
afdb31d5
DM
1063 port => $port,
1064 upid => $upid,
1065 cert => $sslcert,
1e3baf05
DM
1066 };
1067 }});
1068
5fdbe4f0
DM
1069__PACKAGE__->register_method({
1070 name => 'vmcmdidx',
afdb31d5 1071 path => '{vmid}/status',
5fdbe4f0
DM
1072 method => 'GET',
1073 proxyto => 'node',
1074 description => "Directory index",
a0d1b1a2
DM
1075 permissions => {
1076 user => 'all',
1077 },
5fdbe4f0
DM
1078 parameters => {
1079 additionalProperties => 0,
1080 properties => {
1081 node => get_standard_option('pve-node'),
1082 vmid => get_standard_option('pve-vmid'),
1083 },
1084 },
1085 returns => {
1086 type => 'array',
1087 items => {
1088 type => "object",
1089 properties => {
1090 subdir => { type => 'string' },
1091 },
1092 },
1093 links => [ { rel => 'child', href => "{subdir}" } ],
1094 },
1095 code => sub {
1096 my ($param) = @_;
1097
1098 # test if VM exists
1099 my $conf = PVE::QemuServer::load_config($param->{vmid});
1100
1101 my $res = [
1102 { subdir => 'current' },
1103 { subdir => 'start' },
1104 { subdir => 'stop' },
1105 ];
afdb31d5 1106
5fdbe4f0
DM
1107 return $res;
1108 }});
1109
88fc87b4
DM
1110my $vm_is_ha_managed = sub {
1111 my ($vmid) = @_;
1112
1113 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1114 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1115 return 1;
1116 }
1117 return 0;
1118};
1119
1e3baf05 1120__PACKAGE__->register_method({
afdb31d5 1121 name => 'vm_status',
5fdbe4f0 1122 path => '{vmid}/status/current',
1e3baf05
DM
1123 method => 'GET',
1124 proxyto => 'node',
1125 protected => 1, # qemu pid files are only readable by root
1126 description => "Get virtual machine status.",
a0d1b1a2
DM
1127 permissions => {
1128 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1129 },
1e3baf05
DM
1130 parameters => {
1131 additionalProperties => 0,
1132 properties => {
1133 node => get_standard_option('pve-node'),
1134 vmid => get_standard_option('pve-vmid'),
1135 },
1136 },
1137 returns => { type => 'object' },
1138 code => sub {
1139 my ($param) = @_;
1140
1141 # test if VM exists
1142 my $conf = PVE::QemuServer::load_config($param->{vmid});
1143
ff1a2432 1144 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid});
8610701a 1145 my $status = $vmstatus->{$param->{vmid}};
1e3baf05 1146
88fc87b4 1147 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
8610701a
DM
1148
1149 return $status;
1e3baf05
DM
1150 }});
1151
1152__PACKAGE__->register_method({
afdb31d5 1153 name => 'vm_start',
5fdbe4f0
DM
1154 path => '{vmid}/status/start',
1155 method => 'POST',
1e3baf05
DM
1156 protected => 1,
1157 proxyto => 'node',
5fdbe4f0 1158 description => "Start virtual machine.",
a0d1b1a2
DM
1159 permissions => {
1160 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1161 },
1e3baf05
DM
1162 parameters => {
1163 additionalProperties => 0,
1164 properties => {
1165 node => get_standard_option('pve-node'),
1166 vmid => get_standard_option('pve-vmid'),
3ea94c60
DM
1167 skiplock => get_standard_option('skiplock'),
1168 stateuri => get_standard_option('pve-qm-stateuri'),
1e3baf05
DM
1169 },
1170 },
afdb31d5 1171 returns => {
5fdbe4f0
DM
1172 type => 'string',
1173 },
1e3baf05
DM
1174 code => sub {
1175 my ($param) = @_;
1176
1177 my $rpcenv = PVE::RPCEnvironment::get();
1178
a0d1b1a2 1179 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1180
1181 my $node = extract_param($param, 'node');
1182
1e3baf05
DM
1183 my $vmid = extract_param($param, 'vmid');
1184
3ea94c60 1185 my $stateuri = extract_param($param, 'stateuri');
afdb31d5 1186 raise_param_exc({ stateuri => "Only root may use this option." })
a0d1b1a2 1187 if $stateuri && $authuser ne 'root@pam';
3ea94c60 1188
1e3baf05 1189 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1190 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1191 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1192
afdb31d5 1193 my $storecfg = PVE::Storage::config();
5fdbe4f0 1194
cce37749
DM
1195 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1196 $rpcenv->{type} ne 'ha') {
5fdbe4f0 1197
88fc87b4
DM
1198 my $hacmd = sub {
1199 my $upid = shift;
5fdbe4f0 1200
88fc87b4 1201 my $service = "pvevm:$vmid";
5fdbe4f0 1202
88fc87b4
DM
1203 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1204
1205 print "Executing HA start for VM $vmid\n";
1206
1207 PVE::Tools::run_command($cmd);
1208
1209 return;
1210 };
1211
1212 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1213
1214 } else {
1215
1216 my $realcmd = sub {
1217 my $upid = shift;
1218
1219 syslog('info', "start VM $vmid: $upid\n");
1220
1221 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock);
1222
1223 return;
1224 };
5fdbe4f0 1225
88fc87b4
DM
1226 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1227 }
5fdbe4f0
DM
1228 }});
1229
1230__PACKAGE__->register_method({
afdb31d5 1231 name => 'vm_stop',
5fdbe4f0
DM
1232 path => '{vmid}/status/stop',
1233 method => 'POST',
1234 protected => 1,
1235 proxyto => 'node',
1236 description => "Stop virtual machine.",
a0d1b1a2
DM
1237 permissions => {
1238 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1239 },
5fdbe4f0
DM
1240 parameters => {
1241 additionalProperties => 0,
1242 properties => {
1243 node => get_standard_option('pve-node'),
1244 vmid => get_standard_option('pve-vmid'),
1245 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1246 timeout => {
1247 description => "Wait maximal timeout seconds.",
1248 type => 'integer',
1249 minimum => 0,
1250 optional => 1,
254575e9
DM
1251 },
1252 keepActive => {
1253 description => "Do not decativate storage volumes.",
1254 type => 'boolean',
1255 optional => 1,
1256 default => 0,
c6bb9502 1257 }
5fdbe4f0
DM
1258 },
1259 },
afdb31d5 1260 returns => {
5fdbe4f0
DM
1261 type => 'string',
1262 },
1263 code => sub {
1264 my ($param) = @_;
1265
1266 my $rpcenv = PVE::RPCEnvironment::get();
1267
a0d1b1a2 1268 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1269
1270 my $node = extract_param($param, 'node');
1271
1272 my $vmid = extract_param($param, 'vmid');
1273
1274 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1275 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1276 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1277
254575e9 1278 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1279 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1280 if $keepActive && $authuser ne 'root@pam';
254575e9 1281
ff1a2432
DM
1282 my $storecfg = PVE::Storage::config();
1283
3be30d63 1284 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
5fdbe4f0 1285
88fc87b4
DM
1286 my $hacmd = sub {
1287 my $upid = shift;
5fdbe4f0 1288
88fc87b4 1289 my $service = "pvevm:$vmid";
c6bb9502 1290
88fc87b4
DM
1291 my $cmd = ['clusvcadm', '-d', $service];
1292
1293 print "Executing HA stop for VM $vmid\n";
1294
1295 PVE::Tools::run_command($cmd);
5fdbe4f0 1296
88fc87b4
DM
1297 return;
1298 };
1299
1300 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1301
1302 } else {
1303 my $realcmd = sub {
1304 my $upid = shift;
1305
1306 syslog('info', "stop VM $vmid: $upid\n");
1307
1308 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
1309 $param->{timeout}, 0, 1, $keepActive);
1310
1311 return;
1312 };
1313
1314 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1315 }
5fdbe4f0
DM
1316 }});
1317
1318__PACKAGE__->register_method({
afdb31d5 1319 name => 'vm_reset',
5fdbe4f0
DM
1320 path => '{vmid}/status/reset',
1321 method => 'POST',
1322 protected => 1,
1323 proxyto => 'node',
1324 description => "Reset virtual machine.",
a0d1b1a2
DM
1325 permissions => {
1326 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1327 },
5fdbe4f0
DM
1328 parameters => {
1329 additionalProperties => 0,
1330 properties => {
1331 node => get_standard_option('pve-node'),
1332 vmid => get_standard_option('pve-vmid'),
1333 skiplock => get_standard_option('skiplock'),
1334 },
1335 },
afdb31d5 1336 returns => {
5fdbe4f0
DM
1337 type => 'string',
1338 },
1339 code => sub {
1340 my ($param) = @_;
1341
1342 my $rpcenv = PVE::RPCEnvironment::get();
1343
a0d1b1a2 1344 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1345
1346 my $node = extract_param($param, 'node');
1347
1348 my $vmid = extract_param($param, 'vmid');
1349
1350 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1351 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1352 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1353
ff1a2432
DM
1354 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1355
5fdbe4f0
DM
1356 my $realcmd = sub {
1357 my $upid = shift;
1358
1e3baf05 1359 PVE::QemuServer::vm_reset($vmid, $skiplock);
5fdbe4f0
DM
1360
1361 return;
1362 };
1363
a0d1b1a2 1364 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1365 }});
1366
1367__PACKAGE__->register_method({
afdb31d5 1368 name => 'vm_shutdown',
5fdbe4f0
DM
1369 path => '{vmid}/status/shutdown',
1370 method => 'POST',
1371 protected => 1,
1372 proxyto => 'node',
1373 description => "Shutdown virtual machine.",
a0d1b1a2
DM
1374 permissions => {
1375 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1376 },
5fdbe4f0
DM
1377 parameters => {
1378 additionalProperties => 0,
1379 properties => {
1380 node => get_standard_option('pve-node'),
1381 vmid => get_standard_option('pve-vmid'),
1382 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1383 timeout => {
1384 description => "Wait maximal timeout seconds.",
1385 type => 'integer',
1386 minimum => 0,
1387 optional => 1,
9269013a
DM
1388 },
1389 forceStop => {
1390 description => "Make sure the VM stops.",
1391 type => 'boolean',
1392 optional => 1,
1393 default => 0,
254575e9
DM
1394 },
1395 keepActive => {
1396 description => "Do not decativate storage volumes.",
1397 type => 'boolean',
1398 optional => 1,
1399 default => 0,
c6bb9502 1400 }
5fdbe4f0
DM
1401 },
1402 },
afdb31d5 1403 returns => {
5fdbe4f0
DM
1404 type => 'string',
1405 },
1406 code => sub {
1407 my ($param) = @_;
1408
1409 my $rpcenv = PVE::RPCEnvironment::get();
1410
a0d1b1a2 1411 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1412
1413 my $node = extract_param($param, 'node');
1414
1415 my $vmid = extract_param($param, 'vmid');
1416
1417 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1418 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1419 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1420
254575e9 1421 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1422 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1423 if $keepActive && $authuser ne 'root@pam';
254575e9 1424
02d07cf5
DM
1425 my $storecfg = PVE::Storage::config();
1426
5fdbe4f0
DM
1427 my $realcmd = sub {
1428 my $upid = shift;
1429
1430 syslog('info', "shutdown VM $vmid: $upid\n");
1431
afdb31d5 1432 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
254575e9 1433 1, $param->{forceStop}, $keepActive);
c6bb9502 1434
5fdbe4f0
DM
1435 return;
1436 };
1437
a0d1b1a2 1438 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1439 }});
1440
1441__PACKAGE__->register_method({
afdb31d5 1442 name => 'vm_suspend',
5fdbe4f0
DM
1443 path => '{vmid}/status/suspend',
1444 method => 'POST',
1445 protected => 1,
1446 proxyto => 'node',
1447 description => "Suspend virtual machine.",
a0d1b1a2
DM
1448 permissions => {
1449 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1450 },
5fdbe4f0
DM
1451 parameters => {
1452 additionalProperties => 0,
1453 properties => {
1454 node => get_standard_option('pve-node'),
1455 vmid => get_standard_option('pve-vmid'),
1456 skiplock => get_standard_option('skiplock'),
1457 },
1458 },
afdb31d5 1459 returns => {
5fdbe4f0
DM
1460 type => 'string',
1461 },
1462 code => sub {
1463 my ($param) = @_;
1464
1465 my $rpcenv = PVE::RPCEnvironment::get();
1466
a0d1b1a2 1467 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1468
1469 my $node = extract_param($param, 'node');
1470
1471 my $vmid = extract_param($param, 'vmid');
1472
1473 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1474 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1475 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1476
ff1a2432
DM
1477 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1478
5fdbe4f0
DM
1479 my $realcmd = sub {
1480 my $upid = shift;
1481
1482 syslog('info', "suspend VM $vmid: $upid\n");
1483
1e3baf05 1484 PVE::QemuServer::vm_suspend($vmid, $skiplock);
5fdbe4f0
DM
1485
1486 return;
1487 };
1488
a0d1b1a2 1489 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1490 }});
1491
1492__PACKAGE__->register_method({
afdb31d5 1493 name => 'vm_resume',
5fdbe4f0
DM
1494 path => '{vmid}/status/resume',
1495 method => 'POST',
1496 protected => 1,
1497 proxyto => 'node',
1498 description => "Resume virtual machine.",
a0d1b1a2
DM
1499 permissions => {
1500 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1501 },
5fdbe4f0
DM
1502 parameters => {
1503 additionalProperties => 0,
1504 properties => {
1505 node => get_standard_option('pve-node'),
1506 vmid => get_standard_option('pve-vmid'),
1507 skiplock => get_standard_option('skiplock'),
1508 },
1509 },
afdb31d5 1510 returns => {
5fdbe4f0
DM
1511 type => 'string',
1512 },
1513 code => sub {
1514 my ($param) = @_;
1515
1516 my $rpcenv = PVE::RPCEnvironment::get();
1517
a0d1b1a2 1518 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1519
1520 my $node = extract_param($param, 'node');
1521
1522 my $vmid = extract_param($param, 'vmid');
1523
1524 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1525 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1526 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1527
b7eeab21 1528 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
ff1a2432 1529
5fdbe4f0
DM
1530 my $realcmd = sub {
1531 my $upid = shift;
1532
1533 syslog('info', "resume VM $vmid: $upid\n");
1534
1e3baf05 1535 PVE::QemuServer::vm_resume($vmid, $skiplock);
1e3baf05 1536
5fdbe4f0
DM
1537 return;
1538 };
1539
a0d1b1a2 1540 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1541 }});
1542
1543__PACKAGE__->register_method({
afdb31d5 1544 name => 'vm_sendkey',
5fdbe4f0
DM
1545 path => '{vmid}/sendkey',
1546 method => 'PUT',
1547 protected => 1,
1548 proxyto => 'node',
1549 description => "Send key event to virtual machine.",
a0d1b1a2
DM
1550 permissions => {
1551 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1552 },
5fdbe4f0
DM
1553 parameters => {
1554 additionalProperties => 0,
1555 properties => {
1556 node => get_standard_option('pve-node'),
1557 vmid => get_standard_option('pve-vmid'),
1558 skiplock => get_standard_option('skiplock'),
1559 key => {
1560 description => "The key (qemu monitor encoding).",
1561 type => 'string'
1562 }
1563 },
1564 },
1565 returns => { type => 'null'},
1566 code => sub {
1567 my ($param) = @_;
1568
1569 my $rpcenv = PVE::RPCEnvironment::get();
1570
a0d1b1a2 1571 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1572
1573 my $node = extract_param($param, 'node');
1574
1575 my $vmid = extract_param($param, 'vmid');
1576
1577 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1578 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1579 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0
DM
1580
1581 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1582
1583 return;
1e3baf05
DM
1584 }});
1585
3ea94c60 1586__PACKAGE__->register_method({
afdb31d5 1587 name => 'migrate_vm',
3ea94c60
DM
1588 path => '{vmid}/migrate',
1589 method => 'POST',
1590 protected => 1,
1591 proxyto => 'node',
1592 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
1593 permissions => {
1594 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
1595 },
3ea94c60
DM
1596 parameters => {
1597 additionalProperties => 0,
1598 properties => {
1599 node => get_standard_option('pve-node'),
1600 vmid => get_standard_option('pve-vmid'),
1601 target => get_standard_option('pve-node', { description => "Target node." }),
1602 online => {
1603 type => 'boolean',
1604 description => "Use online/live migration.",
1605 optional => 1,
1606 },
1607 force => {
1608 type => 'boolean',
1609 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
1610 optional => 1,
1611 },
1612 },
1613 },
afdb31d5 1614 returns => {
3ea94c60
DM
1615 type => 'string',
1616 description => "the task ID.",
1617 },
1618 code => sub {
1619 my ($param) = @_;
1620
1621 my $rpcenv = PVE::RPCEnvironment::get();
1622
a0d1b1a2 1623 my $authuser = $rpcenv->get_user();
3ea94c60
DM
1624
1625 my $target = extract_param($param, 'target');
1626
1627 my $localnode = PVE::INotify::nodename();
1628 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
1629
1630 PVE::Cluster::check_cfs_quorum();
1631
1632 PVE::Cluster::check_node_exists($target);
1633
1634 my $targetip = PVE::Cluster::remote_node_ip($target);
1635
1636 my $vmid = extract_param($param, 'vmid');
1637
afdb31d5 1638 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 1639 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
1640
1641 # test if VM exists
a5ed42d3 1642 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
1643
1644 # try to detect errors early
a5ed42d3
DM
1645
1646 PVE::QemuServer::check_lock($conf);
1647
3ea94c60 1648 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 1649 die "cant migrate running VM without --online\n"
3ea94c60
DM
1650 if !$param->{online};
1651 }
1652
47152e2e 1653 my $storecfg = PVE::Storage::config();
22d646a7 1654 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
47152e2e 1655
3be30d63 1656 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3ea94c60 1657
88fc87b4
DM
1658 my $hacmd = sub {
1659 my $upid = shift;
3ea94c60 1660
88fc87b4
DM
1661 my $service = "pvevm:$vmid";
1662
1663 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
1664
1665 print "Executing HA migrate for VM $vmid to node $target\n";
1666
1667 PVE::Tools::run_command($cmd);
1668
1669 return;
1670 };
1671
1672 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
1673
1674 } else {
1675
1676 my $realcmd = sub {
1677 my $upid = shift;
1678
1679 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
1680 };
1681
1682 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
1683 }
3ea94c60 1684
3ea94c60 1685 }});
1e3baf05 1686
91c94f0a 1687__PACKAGE__->register_method({
afdb31d5
DM
1688 name => 'monitor',
1689 path => '{vmid}/monitor',
91c94f0a
DM
1690 method => 'POST',
1691 protected => 1,
1692 proxyto => 'node',
1693 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
1694 permissions => {
1695 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
1696 },
91c94f0a
DM
1697 parameters => {
1698 additionalProperties => 0,
1699 properties => {
1700 node => get_standard_option('pve-node'),
1701 vmid => get_standard_option('pve-vmid'),
1702 command => {
1703 type => 'string',
1704 description => "The monitor command.",
1705 }
1706 },
1707 },
1708 returns => { type => 'string'},
1709 code => sub {
1710 my ($param) = @_;
1711
1712 my $vmid = $param->{vmid};
1713
1714 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
1715
1716 my $res = '';
1717 eval {
1718 $res = PVE::QemuServer::vm_monitor_command($vmid, $param->{command});
1719 };
1720 $res = "ERROR: $@" if $@;
1721
1722 return $res;
1723 }});
1724
1e3baf05 17251;