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