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