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