]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
bump version to 2.0-47
[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
656my $vmconfig_update_disk = sub {
657 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
5d7a6767 658
ae57f6b3
DM
659 my $drive = PVE::QemuServer::parse_drive($opt, $value);
660
661 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
662 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
663 } else {
664 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
665 }
666
667 if ($conf->{$opt}) {
668
669 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
670
671 my $media = $drive->{media} || 'disk';
672 my $oldmedia = $old_drive->{media} || 'disk';
673 die "unable to change media type\n" if $media ne $oldmedia;
674
675 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
676 ($drive->{file} ne $old_drive->{file})) { # delete old disks
677
678 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
679 $conf = PVE::QemuServer::load_config($vmid); # update/reload
680 }
0f56d571
AD
681
682 if($drive->{bps} != $old_drive->{bps} ||
683 $drive->{bps_rd} != $old_drive->{bps_rd} ||
684 $drive->{bps_wr} != $old_drive->{bps_wr} ||
685 $drive->{iops} != $old_drive->{iops} ||
686 $drive->{iops_rd} != $old_drive->{iops_rd} ||
687 $drive->{iops_wr} != $old_drive->{iops_wr} ) {
688 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);
689 }
ae57f6b3
DM
690 }
691 }
692
693 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
694 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
695
696 $conf = PVE::QemuServer::load_config($vmid); # update/reload
697 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
698
699 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
700
701 if (PVE::QemuServer::check_running($vmid)) {
702 if ($drive->{file} eq 'none') {
ce156282 703 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
ae57f6b3
DM
704 } else {
705 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
ce156282
AD
706 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt"); #force eject if locked
707 PVE::QemuServer::vm_mon_cmd($vmid, "change",device => "drive-$opt",target => "$path") if $path;
ae57f6b3
DM
708 }
709 }
710
711 } else { # hotplug new disks
712
713 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
5d7a6767 714 }
5d7a6767
DM
715};
716
ae57f6b3
DM
717my $vmconfig_update_net = sub {
718 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
719
720 if ($conf->{$opt}) {
721 #if online update, then unplug first
722 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
723 }
724
725 $conf->{$opt} = $value;
726 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
727 $conf = PVE::QemuServer::load_config($vmid); # update/reload
728
729 my $net = PVE::QemuServer::parse_net($conf->{$opt});
730
731 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
732};
733
a0d1b1a2
DM
734my $vm_config_perm_list = [
735 'VM.Config.Disk',
736 'VM.Config.CDROM',
737 'VM.Config.CPU',
738 'VM.Config.Memory',
739 'VM.Config.Network',
740 'VM.Config.HWType',
741 'VM.Config.Options',
742 ];
743
1e3baf05 744__PACKAGE__->register_method({
afdb31d5
DM
745 name => 'update_vm',
746 path => '{vmid}/config',
1e3baf05
DM
747 method => 'PUT',
748 protected => 1,
749 proxyto => 'node',
750 description => "Set virtual machine options.",
a0d1b1a2
DM
751 permissions => {
752 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
753 },
1e3baf05
DM
754 parameters => {
755 additionalProperties => 0,
756 properties => PVE::QemuServer::json_config_properties(
757 {
758 node => get_standard_option('pve-node'),
759 vmid => get_standard_option('pve-vmid'),
3ea94c60 760 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
761 delete => {
762 type => 'string', format => 'pve-configid-list',
763 description => "A list of settings you want to delete.",
764 optional => 1,
765 },
766 force => {
767 type => 'boolean',
768 description => $opt_force_description,
769 optional => 1,
770 requires => 'delete',
771 },
554ac7e7
DM
772 digest => {
773 type => 'string',
774 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
775 maxLength => 40,
afdb31d5 776 optional => 1,
554ac7e7 777 }
1e3baf05
DM
778 }),
779 },
780 returns => { type => 'null'},
781 code => sub {
782 my ($param) = @_;
783
784 my $rpcenv = PVE::RPCEnvironment::get();
785
a0d1b1a2 786 my $authuser = $rpcenv->get_user();
1e3baf05
DM
787
788 my $node = extract_param($param, 'node');
789
1e3baf05
DM
790 my $vmid = extract_param($param, 'vmid');
791
5fdbe4f0
DM
792 my $digest = extract_param($param, 'digest');
793
794 my @paramarr = (); # used for log message
795 foreach my $key (keys %$param) {
796 push @paramarr, "-$key", $param->{$key};
797 }
798
1e3baf05 799 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 800 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 801 if $skiplock && $authuser ne 'root@pam';
1e3baf05 802
0532bc63
DM
803 my $delete_str = extract_param($param, 'delete');
804
1e3baf05
DM
805 my $force = extract_param($param, 'force');
806
0532bc63
DM
807 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
808
1e68cb19
DM
809 my $storecfg = PVE::Storage::config();
810
811 &$resolve_cdrom_alias($param);
812
813 # now try to verify all parameters
814
0532bc63
DM
815 my @delete = ();
816 foreach my $opt (PVE::Tools::split_list($delete_str)) {
817 $opt = 'ide2' if $opt eq 'cdrom';
818 raise_param_exc({ delete => "you can't use '-$opt' and " .
819 "-delete $opt' at the same time" })
820 if defined($param->{$opt});
821
822 if (!PVE::QemuServer::option_exists($opt)) {
823 raise_param_exc({ delete => "unknown option '$opt'" });
824 }
ae57f6b3 825
0532bc63
DM
826 push @delete, $opt;
827 }
1e3baf05 828
1e68cb19
DM
829 foreach my $opt (keys %$param) {
830 if (PVE::QemuServer::valid_drivename($opt)) {
831 # cleanup drive path
832 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
833 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
834 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
1e68cb19
DM
835 } elsif ($opt =~ m/^net(\d+)$/) {
836 # add macaddr
837 my $net = PVE::QemuServer::parse_net($param->{$opt});
838 $param->{$opt} = PVE::QemuServer::print_net($net);
1e68cb19
DM
839 }
840 }
1e3baf05 841
ae57f6b3
DM
842 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
843
844 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
845
fcbb753e 846 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1e3baf05 847
5d39a182 848 my $updatefn = sub {
1e3baf05 849
5d39a182 850 my $conf = PVE::QemuServer::load_config($vmid);
1e3baf05 851
5d39a182
DM
852 die "checksum missmatch (file change by other user?)\n"
853 if $digest && $digest ne $conf->{digest};
1e3baf05 854
5d39a182 855 PVE::QemuServer::check_lock($conf) if !$skiplock;
1e3baf05 856
a0d1b1a2 857 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
c2a64aa7 858
5d7a6767 859 foreach my $opt (@delete) { # delete
1e68cb19 860 $conf = PVE::QemuServer::load_config($vmid); # update/reload
ae57f6b3 861 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
5d39a182 862 }
1e3baf05 863
5d7a6767 864 foreach my $opt (keys %$param) { # add/change
1e3baf05 865
1e68cb19 866 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1e3baf05 867
5d7a6767
DM
868 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
869
ae57f6b3 870 if (PVE::QemuServer::valid_drivename($opt)) {
5d7a6767 871
ae57f6b3
DM
872 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
873 $opt, $param->{$opt}, $force);
1e68cb19 874
ae57f6b3 875 } elsif ($opt =~ m/^net(\d+)$/) { #nics
1858638f 876
ae57f6b3
DM
877 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
878 $opt, $param->{$opt});
1e68cb19
DM
879
880 } else {
881
1858638f
DM
882 $conf->{$opt} = $param->{$opt};
883 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3a1e36bb 884 }
5d39a182
DM
885 }
886 };
887
888 PVE::QemuServer::lock_config($vmid, $updatefn);
fcdb0117 889
1e3baf05
DM
890 return undef;
891 }});
892
893
894__PACKAGE__->register_method({
afdb31d5
DM
895 name => 'destroy_vm',
896 path => '{vmid}',
1e3baf05
DM
897 method => 'DELETE',
898 protected => 1,
899 proxyto => 'node',
900 description => "Destroy the vm (also delete all used/owned volumes).",
a0d1b1a2
DM
901 permissions => {
902 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
903 },
1e3baf05
DM
904 parameters => {
905 additionalProperties => 0,
906 properties => {
907 node => get_standard_option('pve-node'),
908 vmid => get_standard_option('pve-vmid'),
3ea94c60 909 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
910 },
911 },
afdb31d5 912 returns => {
5fdbe4f0
DM
913 type => 'string',
914 },
1e3baf05
DM
915 code => sub {
916 my ($param) = @_;
917
918 my $rpcenv = PVE::RPCEnvironment::get();
919
a0d1b1a2 920 my $authuser = $rpcenv->get_user();
1e3baf05
DM
921
922 my $vmid = $param->{vmid};
923
924 my $skiplock = $param->{skiplock};
afdb31d5 925 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 926 if $skiplock && $authuser ne 'root@pam';
1e3baf05 927
5fdbe4f0
DM
928 # test if VM exists
929 my $conf = PVE::QemuServer::load_config($vmid);
930
afdb31d5 931 my $storecfg = PVE::Storage::config();
1e3baf05 932
502d18a2
DM
933 my $delVMfromPoolFn = sub {
934 my $usercfg = cfs_read_file("user.cfg");
5d0094ea
DM
935 if (my $pool = $usercfg->{vms}->{$vmid}) {
936 if (my $data = $usercfg->{pools}->{$pool}) {
937 delete $data->{vms}->{$vmid};
938 delete $usercfg->{vms}->{$vmid};
939 cfs_write_file("user.cfg", $usercfg);
940 }
502d18a2
DM
941 }
942 };
943
5fdbe4f0 944 my $realcmd = sub {
ff1a2432
DM
945 my $upid = shift;
946
947 syslog('info', "destroy VM $vmid: $upid\n");
948
5fdbe4f0 949 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
502d18a2
DM
950
951 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
5fdbe4f0 952 };
1e3baf05 953
a0d1b1a2 954 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1e3baf05
DM
955 }});
956
957__PACKAGE__->register_method({
afdb31d5
DM
958 name => 'unlink',
959 path => '{vmid}/unlink',
1e3baf05
DM
960 method => 'PUT',
961 protected => 1,
962 proxyto => 'node',
963 description => "Unlink/delete disk images.",
a0d1b1a2
DM
964 permissions => {
965 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
966 },
1e3baf05
DM
967 parameters => {
968 additionalProperties => 0,
969 properties => {
970 node => get_standard_option('pve-node'),
971 vmid => get_standard_option('pve-vmid'),
972 idlist => {
973 type => 'string', format => 'pve-configid-list',
974 description => "A list of disk IDs you want to delete.",
975 },
976 force => {
977 type => 'boolean',
978 description => $opt_force_description,
979 optional => 1,
980 },
981 },
982 },
983 returns => { type => 'null'},
984 code => sub {
985 my ($param) = @_;
986
987 $param->{delete} = extract_param($param, 'idlist');
988
989 __PACKAGE__->update_vm($param);
990
991 return undef;
992 }});
993
994my $sslcert;
995
996__PACKAGE__->register_method({
afdb31d5
DM
997 name => 'vncproxy',
998 path => '{vmid}/vncproxy',
1e3baf05
DM
999 method => 'POST',
1000 protected => 1,
1001 permissions => {
378b359e 1002 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1e3baf05
DM
1003 },
1004 description => "Creates a TCP VNC proxy connections.",
1005 parameters => {
1006 additionalProperties => 0,
1007 properties => {
1008 node => get_standard_option('pve-node'),
1009 vmid => get_standard_option('pve-vmid'),
1010 },
1011 },
afdb31d5 1012 returns => {
1e3baf05
DM
1013 additionalProperties => 0,
1014 properties => {
1015 user => { type => 'string' },
1016 ticket => { type => 'string' },
1017 cert => { type => 'string' },
1018 port => { type => 'integer' },
1019 upid => { type => 'string' },
1020 },
1021 },
1022 code => sub {
1023 my ($param) = @_;
1024
1025 my $rpcenv = PVE::RPCEnvironment::get();
1026
a0d1b1a2 1027 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1028
1029 my $vmid = $param->{vmid};
1030 my $node = $param->{node};
1031
b6f39da2
DM
1032 my $authpath = "/vms/$vmid";
1033
a0d1b1a2 1034 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
b6f39da2 1035
1e3baf05
DM
1036 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1037 if !$sslcert;
1038
1039 my $port = PVE::Tools::next_vnc_port();
1040
1041 my $remip;
afdb31d5 1042
4f1be36c 1043 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1e3baf05
DM
1044 $remip = PVE::Cluster::remote_node_ip($node);
1045 }
1046
1047 # NOTE: kvm VNC traffic is already TLS encrypted,
1048 # so we select the fastest chipher here (or 'none'?)
1049 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes',
1050 '-c', 'blowfish-cbc', $remip] : [];
1051
afdb31d5 1052 my $timeout = 10;
1e3baf05
DM
1053
1054 my $realcmd = sub {
1055 my $upid = shift;
1056
1057 syslog('info', "starting vnc proxy $upid\n");
1058
1059 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1060
1061 my $qmstr = join(' ', @$qmcmd);
1062
1063 # also redirect stderr (else we get RFB protocol errors)
be62c45c 1064 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1e3baf05 1065
be62c45c 1066 PVE::Tools::run_command($cmd);
1e3baf05
DM
1067
1068 return;
1069 };
1070
a0d1b1a2 1071 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1e3baf05
DM
1072
1073 return {
a0d1b1a2 1074 user => $authuser,
1e3baf05 1075 ticket => $ticket,
afdb31d5
DM
1076 port => $port,
1077 upid => $upid,
1078 cert => $sslcert,
1e3baf05
DM
1079 };
1080 }});
1081
5fdbe4f0
DM
1082__PACKAGE__->register_method({
1083 name => 'vmcmdidx',
afdb31d5 1084 path => '{vmid}/status',
5fdbe4f0
DM
1085 method => 'GET',
1086 proxyto => 'node',
1087 description => "Directory index",
a0d1b1a2
DM
1088 permissions => {
1089 user => 'all',
1090 },
5fdbe4f0
DM
1091 parameters => {
1092 additionalProperties => 0,
1093 properties => {
1094 node => get_standard_option('pve-node'),
1095 vmid => get_standard_option('pve-vmid'),
1096 },
1097 },
1098 returns => {
1099 type => 'array',
1100 items => {
1101 type => "object",
1102 properties => {
1103 subdir => { type => 'string' },
1104 },
1105 },
1106 links => [ { rel => 'child', href => "{subdir}" } ],
1107 },
1108 code => sub {
1109 my ($param) = @_;
1110
1111 # test if VM exists
1112 my $conf = PVE::QemuServer::load_config($param->{vmid});
1113
1114 my $res = [
1115 { subdir => 'current' },
1116 { subdir => 'start' },
1117 { subdir => 'stop' },
1118 ];
afdb31d5 1119
5fdbe4f0
DM
1120 return $res;
1121 }});
1122
88fc87b4
DM
1123my $vm_is_ha_managed = sub {
1124 my ($vmid) = @_;
1125
1126 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1127 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1128 return 1;
1129 }
1130 return 0;
1131};
1132
1e3baf05 1133__PACKAGE__->register_method({
afdb31d5 1134 name => 'vm_status',
5fdbe4f0 1135 path => '{vmid}/status/current',
1e3baf05
DM
1136 method => 'GET',
1137 proxyto => 'node',
1138 protected => 1, # qemu pid files are only readable by root
1139 description => "Get virtual machine status.",
a0d1b1a2
DM
1140 permissions => {
1141 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1142 },
1e3baf05
DM
1143 parameters => {
1144 additionalProperties => 0,
1145 properties => {
1146 node => get_standard_option('pve-node'),
1147 vmid => get_standard_option('pve-vmid'),
1148 },
1149 },
1150 returns => { type => 'object' },
1151 code => sub {
1152 my ($param) = @_;
1153
1154 # test if VM exists
1155 my $conf = PVE::QemuServer::load_config($param->{vmid});
1156
03a33f30 1157 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
8610701a 1158 my $status = $vmstatus->{$param->{vmid}};
1e3baf05 1159
88fc87b4 1160 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
8610701a
DM
1161
1162 return $status;
1e3baf05
DM
1163 }});
1164
1165__PACKAGE__->register_method({
afdb31d5 1166 name => 'vm_start',
5fdbe4f0
DM
1167 path => '{vmid}/status/start',
1168 method => 'POST',
1e3baf05
DM
1169 protected => 1,
1170 proxyto => 'node',
5fdbe4f0 1171 description => "Start virtual machine.",
a0d1b1a2
DM
1172 permissions => {
1173 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1174 },
1e3baf05
DM
1175 parameters => {
1176 additionalProperties => 0,
1177 properties => {
1178 node => get_standard_option('pve-node'),
1179 vmid => get_standard_option('pve-vmid'),
3ea94c60
DM
1180 skiplock => get_standard_option('skiplock'),
1181 stateuri => get_standard_option('pve-qm-stateuri'),
1e3baf05
DM
1182 },
1183 },
afdb31d5 1184 returns => {
5fdbe4f0
DM
1185 type => 'string',
1186 },
1e3baf05
DM
1187 code => sub {
1188 my ($param) = @_;
1189
1190 my $rpcenv = PVE::RPCEnvironment::get();
1191
a0d1b1a2 1192 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1193
1194 my $node = extract_param($param, 'node');
1195
1e3baf05
DM
1196 my $vmid = extract_param($param, 'vmid');
1197
3ea94c60 1198 my $stateuri = extract_param($param, 'stateuri');
afdb31d5 1199 raise_param_exc({ stateuri => "Only root may use this option." })
a0d1b1a2 1200 if $stateuri && $authuser ne 'root@pam';
3ea94c60 1201
1e3baf05 1202 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1203 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1204 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1205
afdb31d5 1206 my $storecfg = PVE::Storage::config();
5fdbe4f0 1207
cce37749
DM
1208 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1209 $rpcenv->{type} ne 'ha') {
5fdbe4f0 1210
88fc87b4
DM
1211 my $hacmd = sub {
1212 my $upid = shift;
5fdbe4f0 1213
88fc87b4 1214 my $service = "pvevm:$vmid";
5fdbe4f0 1215
88fc87b4
DM
1216 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1217
1218 print "Executing HA start for VM $vmid\n";
1219
1220 PVE::Tools::run_command($cmd);
1221
1222 return;
1223 };
1224
1225 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1226
1227 } else {
1228
1229 my $realcmd = sub {
1230 my $upid = shift;
1231
1232 syslog('info', "start VM $vmid: $upid\n");
1233
1234 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock);
1235
1236 return;
1237 };
5fdbe4f0 1238
88fc87b4
DM
1239 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1240 }
5fdbe4f0
DM
1241 }});
1242
1243__PACKAGE__->register_method({
afdb31d5 1244 name => 'vm_stop',
5fdbe4f0
DM
1245 path => '{vmid}/status/stop',
1246 method => 'POST',
1247 protected => 1,
1248 proxyto => 'node',
1249 description => "Stop virtual machine.",
a0d1b1a2
DM
1250 permissions => {
1251 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1252 },
5fdbe4f0
DM
1253 parameters => {
1254 additionalProperties => 0,
1255 properties => {
1256 node => get_standard_option('pve-node'),
1257 vmid => get_standard_option('pve-vmid'),
1258 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1259 timeout => {
1260 description => "Wait maximal timeout seconds.",
1261 type => 'integer',
1262 minimum => 0,
1263 optional => 1,
254575e9
DM
1264 },
1265 keepActive => {
1266 description => "Do not decativate storage volumes.",
1267 type => 'boolean',
1268 optional => 1,
1269 default => 0,
c6bb9502 1270 }
5fdbe4f0
DM
1271 },
1272 },
afdb31d5 1273 returns => {
5fdbe4f0
DM
1274 type => 'string',
1275 },
1276 code => sub {
1277 my ($param) = @_;
1278
1279 my $rpcenv = PVE::RPCEnvironment::get();
1280
a0d1b1a2 1281 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1282
1283 my $node = extract_param($param, 'node');
1284
1285 my $vmid = extract_param($param, 'vmid');
1286
1287 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1288 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1289 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1290
254575e9 1291 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1292 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1293 if $keepActive && $authuser ne 'root@pam';
254575e9 1294
ff1a2432
DM
1295 my $storecfg = PVE::Storage::config();
1296
3be30d63 1297 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
5fdbe4f0 1298
88fc87b4
DM
1299 my $hacmd = sub {
1300 my $upid = shift;
5fdbe4f0 1301
88fc87b4 1302 my $service = "pvevm:$vmid";
c6bb9502 1303
88fc87b4
DM
1304 my $cmd = ['clusvcadm', '-d', $service];
1305
1306 print "Executing HA stop for VM $vmid\n";
1307
1308 PVE::Tools::run_command($cmd);
5fdbe4f0 1309
88fc87b4
DM
1310 return;
1311 };
1312
1313 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1314
1315 } else {
1316 my $realcmd = sub {
1317 my $upid = shift;
1318
1319 syslog('info', "stop VM $vmid: $upid\n");
1320
1321 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
1322 $param->{timeout}, 0, 1, $keepActive);
1323
1324 return;
1325 };
1326
1327 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1328 }
5fdbe4f0
DM
1329 }});
1330
1331__PACKAGE__->register_method({
afdb31d5 1332 name => 'vm_reset',
5fdbe4f0
DM
1333 path => '{vmid}/status/reset',
1334 method => 'POST',
1335 protected => 1,
1336 proxyto => 'node',
1337 description => "Reset virtual machine.",
a0d1b1a2
DM
1338 permissions => {
1339 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1340 },
5fdbe4f0
DM
1341 parameters => {
1342 additionalProperties => 0,
1343 properties => {
1344 node => get_standard_option('pve-node'),
1345 vmid => get_standard_option('pve-vmid'),
1346 skiplock => get_standard_option('skiplock'),
1347 },
1348 },
afdb31d5 1349 returns => {
5fdbe4f0
DM
1350 type => 'string',
1351 },
1352 code => sub {
1353 my ($param) = @_;
1354
1355 my $rpcenv = PVE::RPCEnvironment::get();
1356
a0d1b1a2 1357 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1358
1359 my $node = extract_param($param, 'node');
1360
1361 my $vmid = extract_param($param, 'vmid');
1362
1363 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1364 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1365 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1366
ff1a2432
DM
1367 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1368
5fdbe4f0
DM
1369 my $realcmd = sub {
1370 my $upid = shift;
1371
1e3baf05 1372 PVE::QemuServer::vm_reset($vmid, $skiplock);
5fdbe4f0
DM
1373
1374 return;
1375 };
1376
a0d1b1a2 1377 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1378 }});
1379
1380__PACKAGE__->register_method({
afdb31d5 1381 name => 'vm_shutdown',
5fdbe4f0
DM
1382 path => '{vmid}/status/shutdown',
1383 method => 'POST',
1384 protected => 1,
1385 proxyto => 'node',
1386 description => "Shutdown virtual machine.",
a0d1b1a2
DM
1387 permissions => {
1388 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1389 },
5fdbe4f0
DM
1390 parameters => {
1391 additionalProperties => 0,
1392 properties => {
1393 node => get_standard_option('pve-node'),
1394 vmid => get_standard_option('pve-vmid'),
1395 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1396 timeout => {
1397 description => "Wait maximal timeout seconds.",
1398 type => 'integer',
1399 minimum => 0,
1400 optional => 1,
9269013a
DM
1401 },
1402 forceStop => {
1403 description => "Make sure the VM stops.",
1404 type => 'boolean',
1405 optional => 1,
1406 default => 0,
254575e9
DM
1407 },
1408 keepActive => {
1409 description => "Do not decativate storage volumes.",
1410 type => 'boolean',
1411 optional => 1,
1412 default => 0,
c6bb9502 1413 }
5fdbe4f0
DM
1414 },
1415 },
afdb31d5 1416 returns => {
5fdbe4f0
DM
1417 type => 'string',
1418 },
1419 code => sub {
1420 my ($param) = @_;
1421
1422 my $rpcenv = PVE::RPCEnvironment::get();
1423
a0d1b1a2 1424 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1425
1426 my $node = extract_param($param, 'node');
1427
1428 my $vmid = extract_param($param, 'vmid');
1429
1430 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1431 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1432 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1433
254575e9 1434 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1435 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1436 if $keepActive && $authuser ne 'root@pam';
254575e9 1437
02d07cf5
DM
1438 my $storecfg = PVE::Storage::config();
1439
5fdbe4f0
DM
1440 my $realcmd = sub {
1441 my $upid = shift;
1442
1443 syslog('info', "shutdown VM $vmid: $upid\n");
1444
afdb31d5 1445 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
254575e9 1446 1, $param->{forceStop}, $keepActive);
c6bb9502 1447
5fdbe4f0
DM
1448 return;
1449 };
1450
a0d1b1a2 1451 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1452 }});
1453
1454__PACKAGE__->register_method({
afdb31d5 1455 name => 'vm_suspend',
5fdbe4f0
DM
1456 path => '{vmid}/status/suspend',
1457 method => 'POST',
1458 protected => 1,
1459 proxyto => 'node',
1460 description => "Suspend virtual machine.",
a0d1b1a2
DM
1461 permissions => {
1462 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1463 },
5fdbe4f0
DM
1464 parameters => {
1465 additionalProperties => 0,
1466 properties => {
1467 node => get_standard_option('pve-node'),
1468 vmid => get_standard_option('pve-vmid'),
1469 skiplock => get_standard_option('skiplock'),
1470 },
1471 },
afdb31d5 1472 returns => {
5fdbe4f0
DM
1473 type => 'string',
1474 },
1475 code => sub {
1476 my ($param) = @_;
1477
1478 my $rpcenv = PVE::RPCEnvironment::get();
1479
a0d1b1a2 1480 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1481
1482 my $node = extract_param($param, 'node');
1483
1484 my $vmid = extract_param($param, 'vmid');
1485
1486 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1487 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1488 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1489
ff1a2432
DM
1490 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1491
5fdbe4f0
DM
1492 my $realcmd = sub {
1493 my $upid = shift;
1494
1495 syslog('info', "suspend VM $vmid: $upid\n");
1496
1e3baf05 1497 PVE::QemuServer::vm_suspend($vmid, $skiplock);
5fdbe4f0
DM
1498
1499 return;
1500 };
1501
a0d1b1a2 1502 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1503 }});
1504
1505__PACKAGE__->register_method({
afdb31d5 1506 name => 'vm_resume',
5fdbe4f0
DM
1507 path => '{vmid}/status/resume',
1508 method => 'POST',
1509 protected => 1,
1510 proxyto => 'node',
1511 description => "Resume virtual machine.",
a0d1b1a2
DM
1512 permissions => {
1513 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1514 },
5fdbe4f0
DM
1515 parameters => {
1516 additionalProperties => 0,
1517 properties => {
1518 node => get_standard_option('pve-node'),
1519 vmid => get_standard_option('pve-vmid'),
1520 skiplock => get_standard_option('skiplock'),
1521 },
1522 },
afdb31d5 1523 returns => {
5fdbe4f0
DM
1524 type => 'string',
1525 },
1526 code => sub {
1527 my ($param) = @_;
1528
1529 my $rpcenv = PVE::RPCEnvironment::get();
1530
a0d1b1a2 1531 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1532
1533 my $node = extract_param($param, 'node');
1534
1535 my $vmid = extract_param($param, 'vmid');
1536
1537 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1538 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1539 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1540
b7eeab21 1541 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
ff1a2432 1542
5fdbe4f0
DM
1543 my $realcmd = sub {
1544 my $upid = shift;
1545
1546 syslog('info', "resume VM $vmid: $upid\n");
1547
1e3baf05 1548 PVE::QemuServer::vm_resume($vmid, $skiplock);
1e3baf05 1549
5fdbe4f0
DM
1550 return;
1551 };
1552
a0d1b1a2 1553 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1554 }});
1555
1556__PACKAGE__->register_method({
afdb31d5 1557 name => 'vm_sendkey',
5fdbe4f0
DM
1558 path => '{vmid}/sendkey',
1559 method => 'PUT',
1560 protected => 1,
1561 proxyto => 'node',
1562 description => "Send key event to virtual machine.",
a0d1b1a2
DM
1563 permissions => {
1564 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1565 },
5fdbe4f0
DM
1566 parameters => {
1567 additionalProperties => 0,
1568 properties => {
1569 node => get_standard_option('pve-node'),
1570 vmid => get_standard_option('pve-vmid'),
1571 skiplock => get_standard_option('skiplock'),
1572 key => {
1573 description => "The key (qemu monitor encoding).",
1574 type => 'string'
1575 }
1576 },
1577 },
1578 returns => { type => 'null'},
1579 code => sub {
1580 my ($param) = @_;
1581
1582 my $rpcenv = PVE::RPCEnvironment::get();
1583
a0d1b1a2 1584 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1585
1586 my $node = extract_param($param, 'node');
1587
1588 my $vmid = extract_param($param, 'vmid');
1589
1590 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1591 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1592 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0
DM
1593
1594 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1595
1596 return;
1e3baf05
DM
1597 }});
1598
3ea94c60 1599__PACKAGE__->register_method({
afdb31d5 1600 name => 'migrate_vm',
3ea94c60
DM
1601 path => '{vmid}/migrate',
1602 method => 'POST',
1603 protected => 1,
1604 proxyto => 'node',
1605 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
1606 permissions => {
1607 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
1608 },
3ea94c60
DM
1609 parameters => {
1610 additionalProperties => 0,
1611 properties => {
1612 node => get_standard_option('pve-node'),
1613 vmid => get_standard_option('pve-vmid'),
1614 target => get_standard_option('pve-node', { description => "Target node." }),
1615 online => {
1616 type => 'boolean',
1617 description => "Use online/live migration.",
1618 optional => 1,
1619 },
1620 force => {
1621 type => 'boolean',
1622 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
1623 optional => 1,
1624 },
1625 },
1626 },
afdb31d5 1627 returns => {
3ea94c60
DM
1628 type => 'string',
1629 description => "the task ID.",
1630 },
1631 code => sub {
1632 my ($param) = @_;
1633
1634 my $rpcenv = PVE::RPCEnvironment::get();
1635
a0d1b1a2 1636 my $authuser = $rpcenv->get_user();
3ea94c60
DM
1637
1638 my $target = extract_param($param, 'target');
1639
1640 my $localnode = PVE::INotify::nodename();
1641 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
1642
1643 PVE::Cluster::check_cfs_quorum();
1644
1645 PVE::Cluster::check_node_exists($target);
1646
1647 my $targetip = PVE::Cluster::remote_node_ip($target);
1648
1649 my $vmid = extract_param($param, 'vmid');
1650
afdb31d5 1651 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 1652 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
1653
1654 # test if VM exists
a5ed42d3 1655 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
1656
1657 # try to detect errors early
a5ed42d3
DM
1658
1659 PVE::QemuServer::check_lock($conf);
1660
3ea94c60 1661 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 1662 die "cant migrate running VM without --online\n"
3ea94c60
DM
1663 if !$param->{online};
1664 }
1665
47152e2e 1666 my $storecfg = PVE::Storage::config();
22d646a7 1667 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
47152e2e 1668
3be30d63 1669 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3ea94c60 1670
88fc87b4
DM
1671 my $hacmd = sub {
1672 my $upid = shift;
3ea94c60 1673
88fc87b4
DM
1674 my $service = "pvevm:$vmid";
1675
1676 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
1677
1678 print "Executing HA migrate for VM $vmid to node $target\n";
1679
1680 PVE::Tools::run_command($cmd);
1681
1682 return;
1683 };
1684
1685 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
1686
1687 } else {
1688
1689 my $realcmd = sub {
1690 my $upid = shift;
1691
1692 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
1693 };
1694
1695 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
1696 }
3ea94c60 1697
3ea94c60 1698 }});
1e3baf05 1699
91c94f0a 1700__PACKAGE__->register_method({
afdb31d5
DM
1701 name => 'monitor',
1702 path => '{vmid}/monitor',
91c94f0a
DM
1703 method => 'POST',
1704 protected => 1,
1705 proxyto => 'node',
1706 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
1707 permissions => {
1708 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
1709 },
91c94f0a
DM
1710 parameters => {
1711 additionalProperties => 0,
1712 properties => {
1713 node => get_standard_option('pve-node'),
1714 vmid => get_standard_option('pve-vmid'),
1715 command => {
1716 type => 'string',
1717 description => "The monitor command.",
1718 }
1719 },
1720 },
1721 returns => { type => 'string'},
1722 code => sub {
1723 my ($param) = @_;
1724
1725 my $vmid = $param->{vmid};
1726
1727 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
1728
1729 my $res = '';
1730 eval {
7b7c6d1b 1731 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
91c94f0a
DM
1732 };
1733 $res = "ERROR: $@" if $@;
1734
1735 return $res;
1736 }});
1737
1e3baf05 17381;