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