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