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