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