]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
white-space cleanups
[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;
de8f60b2 19use PVE::Network;
1e3baf05
DM
20
21use Data::Dumper; # fixme: remove
22
23use base qw(PVE::RESTHandler);
24
25my $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.";
26
27my $resolve_cdrom_alias = sub {
28 my $param = shift;
29
30 if (my $value = $param->{cdrom}) {
31 $value .= ",media=cdrom" if $value !~ m/media=/;
32 $param->{ide2} = $value;
33 delete $param->{cdrom};
34 }
35};
36
a0d1b1a2 37
ae57f6b3 38my $check_storage_access = sub {
fcbb753e 39 my ($rpcenv, $authuser, $storecfg, $vmid, $settings, $default_storage) = @_;
a0d1b1a2 40
ae57f6b3
DM
41 PVE::QemuServer::foreach_drive($settings, sub {
42 my ($ds, $drive) = @_;
a0d1b1a2 43
ae57f6b3 44 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
a0d1b1a2 45
ae57f6b3 46 my $volid = $drive->{file};
a0d1b1a2 47
09d0ee64
DM
48 if (!$volid || $volid eq 'none') {
49 # nothing to check
f5782fd0
DM
50 } elsif ($isCDROM && ($volid eq 'cdrom')) {
51 $rpcenv->check($authuser, "/", ['Sys.Console']);
09d0ee64 52 } elsif (!$isCDROM && ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/)) {
a0d1b1a2
DM
53 my ($storeid, $size) = ($2 || $default_storage, $3);
54 die "no storage ID specified (and no default storage)\n" if !$storeid;
fcbb753e 55 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
a0d1b1a2 56 } else {
8b192abf 57 $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $volid);
a0d1b1a2
DM
58 }
59 });
ae57f6b3 60};
a0d1b1a2 61
6116f729 62my $check_storage_access_copy = sub {
81f043eb 63 my ($rpcenv, $authuser, $storecfg, $conf, $storage) = @_;
6116f729 64
55173c6b
DM
65 my $sharedvm = 1;
66
6116f729
DM
67 PVE::QemuServer::foreach_drive($conf, sub {
68 my ($ds, $drive) = @_;
69
70 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
71
72 my $volid = $drive->{file};
73
74 return if !$volid || $volid eq 'none';
75
76 if ($isCDROM) {
77 if ($volid eq 'cdrom') {
78 $rpcenv->check($authuser, "/", ['Sys.Console']);
79 } else {
75466c4f 80 # we simply allow access
55173c6b
DM
81 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
82 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
83 $sharedvm = 0 if !$scfg->{shared};
84
6116f729
DM
85 }
86 } else {
55173c6b
DM
87 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
88 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
89 $sharedvm = 0 if !$scfg->{shared};
90
81f043eb 91 $sid = $storage if $storage;
6116f729
DM
92 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
93 }
94 });
55173c6b
DM
95
96 return $sharedvm;
6116f729
DM
97};
98
ae57f6b3
DM
99# Note: $pool is only needed when creating a VM, because pool permissions
100# are automatically inherited if VM already exists inside a pool.
101my $create_disks = sub {
102 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
a0d1b1a2
DM
103
104 my $vollist = [];
a0d1b1a2 105
ae57f6b3
DM
106 my $res = {};
107 PVE::QemuServer::foreach_drive($settings, sub {
108 my ($ds, $disk) = @_;
109
110 my $volid = $disk->{file};
111
f5782fd0 112 if (!$volid || $volid eq 'none' || $volid eq 'cdrom') {
628e9a2b
AD
113 delete $disk->{size};
114 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
09d0ee64 115 } elsif ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/) {
ae57f6b3
DM
116 my ($storeid, $size) = ($2 || $default_storage, $3);
117 die "no storage ID specified (and no default storage)\n" if !$storeid;
118 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
119 my $fmt = $disk->{format} || $defformat;
a0d1b1a2
DM
120 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid,
121 $fmt, undef, $size*1024*1024);
a0d1b1a2 122 $disk->{file} = $volid;
24afaca0 123 $disk->{size} = $size*1024*1024*1024;
a0d1b1a2 124 push @$vollist, $volid;
ae57f6b3
DM
125 delete $disk->{format}; # no longer needed
126 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
127 } else {
eabe0da0 128
ba68cf09 129 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $volid);
75466c4f 130
eabe0da0 131 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
35cb731c 132
35cb731c
AD
133 my $foundvolid = undef;
134
eabe0da0
DM
135 if ($storeid) {
136 PVE::Storage::activate_volumes($storecfg, [ $volid ]);
137 my $dl = PVE::Storage::vdisk_list($storecfg, $storeid, undef);
138
139 PVE::Storage::foreach_volid($dl, sub {
140 my ($volumeid) = @_;
141 if($volumeid eq $volid) {
142 $foundvolid = 1;
143 return;
144 }
145 });
146 }
75466c4f 147
35cb731c 148 die "image '$path' does not exists\n" if (!(-f $path || -b $path || $foundvolid));
24afaca0
DM
149
150 my ($size) = PVE::Storage::volume_size_info($storecfg, $volid, 1);
151 $disk->{size} = $size;
152 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
a0d1b1a2 153 }
ae57f6b3 154 });
a0d1b1a2
DM
155
156 # free allocated images on error
157 if (my $err = $@) {
158 syslog('err', "VM $vmid creating disks failed");
159 foreach my $volid (@$vollist) {
160 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
161 warn $@ if $@;
162 }
163 die $err;
164 }
165
166 # modify vm config if everything went well
ae57f6b3
DM
167 foreach my $ds (keys %$res) {
168 $conf->{$ds} = $res->{$ds};
a0d1b1a2
DM
169 }
170
171 return $vollist;
172};
173
174my $check_vm_modify_config_perm = sub {
ae57f6b3 175 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
a0d1b1a2 176
6e5c4da7 177 return 1 if $authuser eq 'root@pam';
a0d1b1a2 178
ae57f6b3 179 foreach my $opt (@$key_list) {
a0d1b1a2
DM
180 # disk checks need to be done somewhere else
181 next if PVE::QemuServer::valid_drivename($opt);
182
183 if ($opt eq 'sockets' || $opt eq 'cores' ||
75466c4f 184 $opt eq 'cpu' || $opt eq 'smp' ||
ab6b35df 185 $opt eq 'cpulimit' || $opt eq 'cpuunits') {
a0d1b1a2
DM
186 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
187 } elsif ($opt eq 'boot' || $opt eq 'bootdisk') {
188 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
ccd5438f 189 } elsif ($opt eq 'memory' || $opt eq 'balloon' || $opt eq 'shares') {
a0d1b1a2
DM
190 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
191 } elsif ($opt eq 'args' || $opt eq 'lock') {
192 die "only root can set '$opt' config\n";
75466c4f 193 } elsif ($opt eq 'cpu' || $opt eq 'kvm' || $opt eq 'acpi' ||
a0d1b1a2
DM
194 $opt eq 'vga' || $opt eq 'watchdog' || $opt eq 'tablet') {
195 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
196 } elsif ($opt =~ m/^net\d+$/) {
197 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
198 } else {
199 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
200 }
201 }
202
203 return 1;
204};
205
1e3baf05 206__PACKAGE__->register_method({
afdb31d5
DM
207 name => 'vmlist',
208 path => '',
1e3baf05
DM
209 method => 'GET',
210 description => "Virtual machine index (per node).",
a0d1b1a2
DM
211 permissions => {
212 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
213 user => 'all',
214 },
1e3baf05
DM
215 proxyto => 'node',
216 protected => 1, # qemu pid files are only readable by root
217 parameters => {
218 additionalProperties => 0,
219 properties => {
220 node => get_standard_option('pve-node'),
221 },
222 },
223 returns => {
224 type => 'array',
225 items => {
226 type => "object",
227 properties => {},
228 },
229 links => [ { rel => 'child', href => "{vmid}" } ],
230 },
231 code => sub {
232 my ($param) = @_;
233
a0d1b1a2
DM
234 my $rpcenv = PVE::RPCEnvironment::get();
235 my $authuser = $rpcenv->get_user();
236
1e3baf05
DM
237 my $vmstatus = PVE::QemuServer::vmstatus();
238
a0d1b1a2
DM
239 my $res = [];
240 foreach my $vmid (keys %$vmstatus) {
241 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
242
243 my $data = $vmstatus->{$vmid};
244 $data->{vmid} = $vmid;
245 push @$res, $data;
246 }
1e3baf05 247
a0d1b1a2 248 return $res;
1e3baf05
DM
249 }});
250
251__PACKAGE__->register_method({
afdb31d5
DM
252 name => 'create_vm',
253 path => '',
1e3baf05 254 method => 'POST',
3e16d5fc 255 description => "Create or restore a virtual machine.",
a0d1b1a2
DM
256 permissions => {
257 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.",
75466c4f 258 check => [ 'or',
a0d1b1a2
DM
259 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
260 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
261 ],
262 },
1e3baf05
DM
263 protected => 1,
264 proxyto => 'node',
265 parameters => {
266 additionalProperties => 0,
267 properties => PVE::QemuServer::json_config_properties(
268 {
269 node => get_standard_option('pve-node'),
270 vmid => get_standard_option('pve-vmid'),
3e16d5fc
DM
271 archive => {
272 description => "The backup file.",
273 type => 'string',
274 optional => 1,
275 maxLength => 255,
276 },
277 storage => get_standard_option('pve-storage-id', {
278 description => "Default storage.",
279 optional => 1,
280 }),
281 force => {
afdb31d5 282 optional => 1,
3e16d5fc
DM
283 type => 'boolean',
284 description => "Allow to overwrite existing VM.",
51586c3a
DM
285 requires => 'archive',
286 },
287 unique => {
afdb31d5 288 optional => 1,
51586c3a
DM
289 type => 'boolean',
290 description => "Assign a unique random ethernet address.",
291 requires => 'archive',
3e16d5fc 292 },
75466c4f 293 pool => {
a0d1b1a2
DM
294 optional => 1,
295 type => 'string', format => 'pve-poolid',
296 description => "Add the VM to the specified pool.",
297 },
1e3baf05
DM
298 }),
299 },
afdb31d5 300 returns => {
5fdbe4f0
DM
301 type => 'string',
302 },
1e3baf05
DM
303 code => sub {
304 my ($param) = @_;
305
5fdbe4f0
DM
306 my $rpcenv = PVE::RPCEnvironment::get();
307
a0d1b1a2 308 my $authuser = $rpcenv->get_user();
5fdbe4f0 309
1e3baf05
DM
310 my $node = extract_param($param, 'node');
311
1e3baf05
DM
312 my $vmid = extract_param($param, 'vmid');
313
3e16d5fc
DM
314 my $archive = extract_param($param, 'archive');
315
316 my $storage = extract_param($param, 'storage');
317
51586c3a
DM
318 my $force = extract_param($param, 'force');
319
320 my $unique = extract_param($param, 'unique');
75466c4f 321
a0d1b1a2 322 my $pool = extract_param($param, 'pool');
51586c3a 323
1e3baf05 324 my $filename = PVE::QemuServer::config_file($vmid);
afdb31d5
DM
325
326 my $storecfg = PVE::Storage::config();
1e3baf05 327
3e16d5fc 328 PVE::Cluster::check_cfs_quorum();
1e3baf05 329
a0d1b1a2
DM
330 if (defined($pool)) {
331 $rpcenv->check_pool_exist($pool);
75466c4f 332 }
a0d1b1a2 333
fcbb753e 334 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace'])
a0d1b1a2
DM
335 if defined($storage);
336
afdb31d5 337 if (!$archive) {
3e16d5fc 338 &$resolve_cdrom_alias($param);
1e3baf05 339
fcbb753e 340 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param, $storage);
ae57f6b3
DM
341
342 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
343
3e16d5fc
DM
344 foreach my $opt (keys %$param) {
345 if (PVE::QemuServer::valid_drivename($opt)) {
346 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
347 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
afdb31d5 348
3e16d5fc
DM
349 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
350 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
351 }
1e3baf05 352 }
3e16d5fc
DM
353
354 PVE::QemuServer::add_random_macs($param);
51586c3a
DM
355 } else {
356 my $keystr = join(' ', keys %$param);
bc4dcb99
DM
357 raise_param_exc({ archive => "option conflicts with other options ($keystr)"}) if $keystr;
358
5b9d692a 359 if ($archive eq '-') {
afdb31d5 360 die "pipe requires cli environment\n"
d7810bc1 361 if $rpcenv->{type} ne 'cli';
5b9d692a 362 } else {
ba68cf09 363 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $archive);
d7810bc1
DM
364
365 PVE::Storage::activate_volumes($storecfg, [ $archive ])
366 if PVE::Storage::parse_volume_id ($archive, 1);
367
971f27c4
DM
368 die "can't find archive file '$archive'\n" if !($path && -f $path);
369 $archive = $path;
370 }
1e3baf05
DM
371 }
372
75466c4f 373 my $addVMtoPoolFn = sub {
502d18a2
DM
374 my $usercfg = cfs_read_file("user.cfg");
375 if (my $data = $usercfg->{pools}->{$pool}) {
376 $data->{vms}->{$vmid} = 1;
377 $usercfg->{vms}->{$vmid} = $pool;
378 cfs_write_file("user.cfg", $usercfg);
379 }
380 };
381
3e16d5fc
DM
382 my $restorefn = sub {
383
6116f729 384 # fixme: this test does not work if VM exists on other node!
3e16d5fc 385 if (-f $filename) {
afdb31d5 386 die "unable to restore vm $vmid: config file already exists\n"
51586c3a 387 if !$force;
3e16d5fc 388
afdb31d5 389 die "unable to restore vm $vmid: vm is running\n"
3e16d5fc
DM
390 if PVE::QemuServer::check_running($vmid);
391 }
392
393 my $realcmd = sub {
a0d1b1a2 394 PVE::QemuServer::restore_archive($archive, $vmid, $authuser, {
51586c3a 395 storage => $storage,
a0d1b1a2 396 pool => $pool,
51586c3a 397 unique => $unique });
502d18a2
DM
398
399 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
3e16d5fc
DM
400 };
401
a0d1b1a2 402 return $rpcenv->fork_worker('qmrestore', $vmid, $authuser, $realcmd);
3e16d5fc 403 };
1e3baf05 404
1e3baf05
DM
405 my $createfn = sub {
406
191435c6 407 # test after locking
afdb31d5 408 die "unable to create vm $vmid: config file already exists\n"
1e3baf05
DM
409 if -f $filename;
410
5fdbe4f0 411 my $realcmd = sub {
1e3baf05 412
5fdbe4f0 413 my $vollist = [];
1e3baf05 414
1858638f
DM
415 my $conf = $param;
416
5fdbe4f0 417 eval {
ae57f6b3 418
1858638f 419 $vollist = &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $param, $storage);
1e3baf05 420
5fdbe4f0
DM
421 # try to be smart about bootdisk
422 my @disks = PVE::QemuServer::disknames();
423 my $firstdisk;
424 foreach my $ds (reverse @disks) {
1858638f
DM
425 next if !$conf->{$ds};
426 my $disk = PVE::QemuServer::parse_drive($ds, $conf->{$ds});
5fdbe4f0
DM
427 next if PVE::QemuServer::drive_is_cdrom($disk);
428 $firstdisk = $ds;
429 }
1e3baf05 430
1858638f
DM
431 if (!$conf->{bootdisk} && $firstdisk) {
432 $conf->{bootdisk} = $firstdisk;
5fdbe4f0 433 }
1e3baf05 434
ae9ca91d
DM
435 PVE::QemuServer::update_config_nolock($vmid, $conf);
436
5fdbe4f0
DM
437 };
438 my $err = $@;
1e3baf05 439
5fdbe4f0
DM
440 if ($err) {
441 foreach my $volid (@$vollist) {
442 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
443 warn $@ if $@;
444 }
445 die "create failed - $err";
446 }
502d18a2
DM
447
448 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
5fdbe4f0
DM
449 };
450
a0d1b1a2 451 return $rpcenv->fork_worker('qmcreate', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
452 };
453
191435c6 454 return PVE::QemuServer::lock_config_full($vmid, 1, $archive ? $restorefn : $createfn);
1e3baf05
DM
455 }});
456
457__PACKAGE__->register_method({
458 name => 'vmdiridx',
afdb31d5 459 path => '{vmid}',
1e3baf05
DM
460 method => 'GET',
461 proxyto => 'node',
462 description => "Directory index",
a0d1b1a2
DM
463 permissions => {
464 user => 'all',
465 },
1e3baf05
DM
466 parameters => {
467 additionalProperties => 0,
468 properties => {
469 node => get_standard_option('pve-node'),
470 vmid => get_standard_option('pve-vmid'),
471 },
472 },
473 returns => {
474 type => 'array',
475 items => {
476 type => "object",
477 properties => {
478 subdir => { type => 'string' },
479 },
480 },
481 links => [ { rel => 'child', href => "{subdir}" } ],
482 },
483 code => sub {
484 my ($param) = @_;
485
486 my $res = [
487 { subdir => 'config' },
488 { subdir => 'status' },
489 { subdir => 'unlink' },
490 { subdir => 'vncproxy' },
3ea94c60 491 { subdir => 'migrate' },
2f48a4f5 492 { subdir => 'resize' },
1e3baf05
DM
493 { subdir => 'rrd' },
494 { subdir => 'rrddata' },
91c94f0a 495 { subdir => 'monitor' },
7e7d7b61 496 { subdir => 'snapshot' },
1e3baf05 497 ];
afdb31d5 498
1e3baf05
DM
499 return $res;
500 }});
501
502__PACKAGE__->register_method({
afdb31d5
DM
503 name => 'rrd',
504 path => '{vmid}/rrd',
1e3baf05
DM
505 method => 'GET',
506 protected => 1, # fixme: can we avoid that?
507 permissions => {
378b359e 508 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
509 },
510 description => "Read VM RRD statistics (returns PNG)",
511 parameters => {
512 additionalProperties => 0,
513 properties => {
514 node => get_standard_option('pve-node'),
515 vmid => get_standard_option('pve-vmid'),
516 timeframe => {
517 description => "Specify the time frame you are interested in.",
518 type => 'string',
519 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
520 },
521 ds => {
522 description => "The list of datasources you want to display.",
523 type => 'string', format => 'pve-configid-list',
524 },
525 cf => {
526 description => "The RRD consolidation function",
527 type => 'string',
528 enum => [ 'AVERAGE', 'MAX' ],
529 optional => 1,
530 },
531 },
532 },
533 returns => {
534 type => "object",
535 properties => {
536 filename => { type => 'string' },
537 },
538 },
539 code => sub {
540 my ($param) = @_;
541
542 return PVE::Cluster::create_rrd_graph(
afdb31d5 543 "pve2-vm/$param->{vmid}", $param->{timeframe},
1e3baf05 544 $param->{ds}, $param->{cf});
afdb31d5 545
1e3baf05
DM
546 }});
547
548__PACKAGE__->register_method({
afdb31d5
DM
549 name => 'rrddata',
550 path => '{vmid}/rrddata',
1e3baf05
DM
551 method => 'GET',
552 protected => 1, # fixme: can we avoid that?
553 permissions => {
378b359e 554 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
555 },
556 description => "Read VM RRD statistics",
557 parameters => {
558 additionalProperties => 0,
559 properties => {
560 node => get_standard_option('pve-node'),
561 vmid => get_standard_option('pve-vmid'),
562 timeframe => {
563 description => "Specify the time frame you are interested in.",
564 type => 'string',
565 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
566 },
567 cf => {
568 description => "The RRD consolidation function",
569 type => 'string',
570 enum => [ 'AVERAGE', 'MAX' ],
571 optional => 1,
572 },
573 },
574 },
575 returns => {
576 type => "array",
577 items => {
578 type => "object",
579 properties => {},
580 },
581 },
582 code => sub {
583 my ($param) = @_;
584
585 return PVE::Cluster::create_rrd_data(
586 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
587 }});
588
589
590__PACKAGE__->register_method({
afdb31d5
DM
591 name => 'vm_config',
592 path => '{vmid}/config',
1e3baf05
DM
593 method => 'GET',
594 proxyto => 'node',
595 description => "Get virtual machine configuration.",
a0d1b1a2
DM
596 permissions => {
597 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
598 },
1e3baf05
DM
599 parameters => {
600 additionalProperties => 0,
601 properties => {
602 node => get_standard_option('pve-node'),
603 vmid => get_standard_option('pve-vmid'),
604 },
605 },
afdb31d5 606 returns => {
1e3baf05 607 type => "object",
554ac7e7
DM
608 properties => {
609 digest => {
610 type => 'string',
611 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
612 }
613 },
1e3baf05
DM
614 },
615 code => sub {
616 my ($param) = @_;
617
618 my $conf = PVE::QemuServer::load_config($param->{vmid});
619
22c377f0
DM
620 delete $conf->{snapshots};
621
1e3baf05
DM
622 return $conf;
623 }});
624
ae57f6b3
DM
625my $vm_is_volid_owner = sub {
626 my ($storecfg, $vmid, $volid) =@_;
627
628 if ($volid !~ m|^/|) {
629 my ($path, $owner);
630 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
631 if ($owner && ($owner == $vmid)) {
632 return 1;
633 }
634 }
635
636 return undef;
637};
638
639my $test_deallocate_drive = sub {
640 my ($storecfg, $vmid, $key, $drive, $force) = @_;
641
642 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
643 my $volid = $drive->{file};
644 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
645 if ($force || $key =~ m/^unused/) {
646 my $sid = PVE::Storage::parse_volume_id($volid);
647 return $sid;
648 }
649 }
650 }
651
652 return undef;
653};
654
5d7a6767 655my $delete_drive = sub {
1858638f 656 my ($conf, $storecfg, $vmid, $key, $drive, $force) = @_;
5d7a6767
DM
657
658 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
659 my $volid = $drive->{file};
ae57f6b3
DM
660 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
661 if ($force || $key =~ m/^unused/) {
662 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
7e4e69a6 663 die $@ if $@;
ae57f6b3
DM
664 } else {
665 PVE::QemuServer::add_unused_volume($conf, $volid, $vmid);
5d7a6767 666 }
ae57f6b3
DM
667 }
668 }
49f9db93
DM
669
670 delete $conf->{$key};
ae57f6b3
DM
671};
672
673my $vmconfig_delete_option = sub {
674 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force) = @_;
675
676 return if !defined($conf->{$opt});
677
678 my $isDisk = PVE::QemuServer::valid_drivename($opt)|| ($opt =~ m/^unused/);
679
680 if ($isDisk) {
681 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
682
683 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
75466c4f 684 if (my $sid = &$test_deallocate_drive($storecfg, $vmid, $opt, $drive, $force)) {
fcbb753e 685 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.Allocate']);
5d7a6767 686 }
ae57f6b3 687 }
9a8d6b66
AD
688
689 my $unplugwarning = "";
690 if($conf->{ostype} && $conf->{ostype} eq 'l26'){
691 $unplugwarning = "<br>verify that you have acpiphp && pci_hotplug modules loaded in your guest VM";
692 }elsif($conf->{ostype} && $conf->{ostype} eq 'l24'){
693 $unplugwarning = "<br>kernel 2.4 don't support hotplug, please disable hotplug in options";
694 }elsif(!$conf->{ostype} || ($conf->{ostype} && $conf->{ostype} eq 'other')){
695 $unplugwarning = "<br>verify that your guest support acpi hotplug";
696 }
697
e8a7e9b4
AD
698 if($opt eq 'tablet'){
699 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt);
700 }else{
701 die "error hot-unplug $opt $unplugwarning" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
702 }
cd6ecb89 703
ae57f6b3
DM
704 if ($isDisk) {
705 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
706 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive, $force);
5d7a6767 707 } else {
ae57f6b3
DM
708 delete $conf->{$opt};
709 }
710
711 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
712};
713
9bf371a6 714my $safe_num_ne = sub {
93ae06e1
DM
715 my ($a, $b) = @_;
716
75466c4f
DM
717 return 0 if !defined($a) && !defined($b);
718 return 1 if !defined($a);
719 return 1 if !defined($b);
93ae06e1
DM
720
721 return $a != $b;
722};
723
ae57f6b3
DM
724my $vmconfig_update_disk = sub {
725 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
5d7a6767 726
ae57f6b3
DM
727 my $drive = PVE::QemuServer::parse_drive($opt, $value);
728
729 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
730 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
731 } else {
732 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
733 }
734
735 if ($conf->{$opt}) {
736
737 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
738
739 my $media = $drive->{media} || 'disk';
740 my $oldmedia = $old_drive->{media} || 'disk';
741 die "unable to change media type\n" if $media ne $oldmedia;
742
743 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
744 ($drive->{file} ne $old_drive->{file})) { # delete old disks
745
746 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
747 $conf = PVE::QemuServer::load_config($vmid); # update/reload
748 }
0f56d571 749
9bf371a6
DM
750 if(&$safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
751 &$safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
752 &$safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
753 &$safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
754 &$safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
755 &$safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr})) {
75466c4f
DM
756 PVE::QemuServer::qemu_block_set_io_throttle($vmid,"drive-$opt", $drive->{mbps}*1024*1024,
757 $drive->{mbps_rd}*1024*1024, $drive->{mbps_wr}*1024*1024,
758 $drive->{iops}, $drive->{iops_rd}, $drive->{iops_wr})
9bf371a6 759 if !PVE::QemuServer::drive_is_cdrom($drive);
0f56d571 760 }
ae57f6b3
DM
761 }
762 }
763
764 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
765 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
766
767 $conf = PVE::QemuServer::load_config($vmid); # update/reload
768 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
769
770 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
771
772 if (PVE::QemuServer::check_running($vmid)) {
773 if ($drive->{file} eq 'none') {
ce156282 774 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
ae57f6b3
DM
775 } else {
776 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
ce156282
AD
777 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt"); #force eject if locked
778 PVE::QemuServer::vm_mon_cmd($vmid, "change",device => "drive-$opt",target => "$path") if $path;
ae57f6b3
DM
779 }
780 }
781
782 } else { # hotplug new disks
783
784 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
5d7a6767 785 }
5d7a6767
DM
786};
787
ae57f6b3
DM
788my $vmconfig_update_net = sub {
789 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
790
de8f60b2
AD
791 if ($conf->{$opt} && PVE::QemuServer::check_running($vmid)) {
792 my $oldnet = PVE::QemuServer::parse_net($conf->{$opt});
793 my $newnet = PVE::QemuServer::parse_net($value);
794
795 if($oldnet->{model} ne $newnet->{model}){
796 #if model change, we try to hot-unplug
797 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
798 }else{
75466c4f 799
de8f60b2
AD
800 if($newnet->{bridge} && $oldnet->{bridge}){
801 my $iface = "tap".$vmid."i".$1 if $opt =~ m/net(\d+)/;
ae57f6b3 802
de8f60b2
AD
803 if($newnet->{rate} ne $oldnet->{rate}){
804 PVE::Network::tap_rate_limit($iface, $newnet->{rate});
805 }
806
807 if(($newnet->{bridge} ne $oldnet->{bridge}) || ($newnet->{tag} ne $oldnet->{tag})){
808 eval{PVE::Network::tap_unplug($iface, $oldnet->{bridge}, $oldnet->{tag});};
809 PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag});
810 }
811
812 }else{
813 #if bridge/nat mode change, we try to hot-unplug
814 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
815 }
816 }
75466c4f 817
de8f60b2 818 }
ae57f6b3
DM
819 $conf->{$opt} = $value;
820 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
821 $conf = PVE::QemuServer::load_config($vmid); # update/reload
822
823 my $net = PVE::QemuServer::parse_net($conf->{$opt});
824
825 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
826};
827
a0d1b1a2 828my $vm_config_perm_list = [
75466c4f
DM
829 'VM.Config.Disk',
830 'VM.Config.CDROM',
831 'VM.Config.CPU',
832 'VM.Config.Memory',
833 'VM.Config.Network',
a0d1b1a2
DM
834 'VM.Config.HWType',
835 'VM.Config.Options',
836 ];
837
1e3baf05 838__PACKAGE__->register_method({
afdb31d5
DM
839 name => 'update_vm',
840 path => '{vmid}/config',
1e3baf05
DM
841 method => 'PUT',
842 protected => 1,
843 proxyto => 'node',
844 description => "Set virtual machine options.",
a0d1b1a2
DM
845 permissions => {
846 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
847 },
1e3baf05
DM
848 parameters => {
849 additionalProperties => 0,
850 properties => PVE::QemuServer::json_config_properties(
851 {
852 node => get_standard_option('pve-node'),
853 vmid => get_standard_option('pve-vmid'),
3ea94c60 854 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
855 delete => {
856 type => 'string', format => 'pve-configid-list',
857 description => "A list of settings you want to delete.",
858 optional => 1,
859 },
860 force => {
861 type => 'boolean',
862 description => $opt_force_description,
863 optional => 1,
864 requires => 'delete',
865 },
554ac7e7
DM
866 digest => {
867 type => 'string',
868 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
869 maxLength => 40,
afdb31d5 870 optional => 1,
554ac7e7 871 }
1e3baf05
DM
872 }),
873 },
874 returns => { type => 'null'},
875 code => sub {
876 my ($param) = @_;
877
878 my $rpcenv = PVE::RPCEnvironment::get();
879
a0d1b1a2 880 my $authuser = $rpcenv->get_user();
1e3baf05
DM
881
882 my $node = extract_param($param, 'node');
883
1e3baf05
DM
884 my $vmid = extract_param($param, 'vmid');
885
5fdbe4f0
DM
886 my $digest = extract_param($param, 'digest');
887
888 my @paramarr = (); # used for log message
889 foreach my $key (keys %$param) {
890 push @paramarr, "-$key", $param->{$key};
891 }
892
1e3baf05 893 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 894 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 895 if $skiplock && $authuser ne 'root@pam';
1e3baf05 896
0532bc63
DM
897 my $delete_str = extract_param($param, 'delete');
898
1e3baf05
DM
899 my $force = extract_param($param, 'force');
900
0532bc63
DM
901 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
902
1e68cb19
DM
903 my $storecfg = PVE::Storage::config();
904
7bfdeb5f
DM
905 my $defaults = PVE::QemuServer::load_defaults();
906
1e68cb19
DM
907 &$resolve_cdrom_alias($param);
908
909 # now try to verify all parameters
910
0532bc63
DM
911 my @delete = ();
912 foreach my $opt (PVE::Tools::split_list($delete_str)) {
913 $opt = 'ide2' if $opt eq 'cdrom';
914 raise_param_exc({ delete => "you can't use '-$opt' and " .
915 "-delete $opt' at the same time" })
916 if defined($param->{$opt});
917
918 if (!PVE::QemuServer::option_exists($opt)) {
919 raise_param_exc({ delete => "unknown option '$opt'" });
920 }
ae57f6b3 921
0532bc63
DM
922 push @delete, $opt;
923 }
1e3baf05 924
1e68cb19
DM
925 foreach my $opt (keys %$param) {
926 if (PVE::QemuServer::valid_drivename($opt)) {
927 # cleanup drive path
928 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
929 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
930 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
75466c4f 931 } elsif ($opt =~ m/^net(\d+)$/) {
1e68cb19
DM
932 # add macaddr
933 my $net = PVE::QemuServer::parse_net($param->{$opt});
934 $param->{$opt} = PVE::QemuServer::print_net($net);
1e68cb19
DM
935 }
936 }
1e3baf05 937
ae57f6b3
DM
938 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
939
940 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
941
fcbb753e 942 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1e3baf05 943
5d39a182 944 my $updatefn = sub {
1e3baf05 945
5d39a182 946 my $conf = PVE::QemuServer::load_config($vmid);
1e3baf05 947
5d39a182
DM
948 die "checksum missmatch (file change by other user?)\n"
949 if $digest && $digest ne $conf->{digest};
1e3baf05 950
5d39a182 951 PVE::QemuServer::check_lock($conf) if !$skiplock;
1e3baf05 952
7bfdeb5f
DM
953 if ($param->{memory} || defined($param->{balloon})) {
954 my $maxmem = $param->{memory} || $conf->{memory} || $defaults->{memory};
955 my $balloon = defined($param->{balloon}) ? $param->{balloon} : $conf->{balloon};
956
957 die "balloon value too large (must be smaller than assigned memory)\n"
958 if $balloon > $maxmem;
959 }
960
a0d1b1a2 961 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
c2a64aa7 962
5d7a6767 963 foreach my $opt (@delete) { # delete
1e68cb19 964 $conf = PVE::QemuServer::load_config($vmid); # update/reload
ae57f6b3 965 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
5d39a182 966 }
1e3baf05 967
7bfdeb5f
DM
968 my $running = PVE::QemuServer::check_running($vmid);
969
5d7a6767 970 foreach my $opt (keys %$param) { # add/change
1e3baf05 971
1e68cb19 972 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1e3baf05 973
5d7a6767
DM
974 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
975
ae57f6b3 976 if (PVE::QemuServer::valid_drivename($opt)) {
5d7a6767 977
75466c4f 978 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
ae57f6b3 979 $opt, $param->{$opt}, $force);
75466c4f 980
ae57f6b3 981 } elsif ($opt =~ m/^net(\d+)$/) { #nics
1858638f 982
75466c4f 983 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
ae57f6b3 984 $opt, $param->{$opt});
1e68cb19
DM
985
986 } else {
987
cd6ecb89
AD
988 if($opt eq 'tablet' && $param->{$opt} == 1){
989 PVE::QemuServer::vm_deviceplug(undef, $conf, $vmid, $opt);
990 }elsif($opt eq 'tablet' && $param->{$opt} == 0){
991 PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
992 }
993
1858638f
DM
994 $conf->{$opt} = $param->{$opt};
995 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3a1e36bb 996 }
5d39a182 997 }
7bfdeb5f
DM
998
999 # allow manual ballooning if shares is set to zero
75466c4f 1000 if ($running && defined($param->{balloon}) &&
7bfdeb5f
DM
1001 defined($conf->{shares}) && ($conf->{shares} == 0)) {
1002 my $balloon = $param->{'balloon'} || $conf->{memory} || $defaults->{memory};
1003 PVE::QemuServer::vm_mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
1004 }
1005
5d39a182
DM
1006 };
1007
1008 PVE::QemuServer::lock_config($vmid, $updatefn);
fcdb0117 1009
1e3baf05
DM
1010 return undef;
1011 }});
1012
1013
1014__PACKAGE__->register_method({
afdb31d5
DM
1015 name => 'destroy_vm',
1016 path => '{vmid}',
1e3baf05
DM
1017 method => 'DELETE',
1018 protected => 1,
1019 proxyto => 'node',
1020 description => "Destroy the vm (also delete all used/owned volumes).",
a0d1b1a2
DM
1021 permissions => {
1022 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
1023 },
1e3baf05
DM
1024 parameters => {
1025 additionalProperties => 0,
1026 properties => {
1027 node => get_standard_option('pve-node'),
1028 vmid => get_standard_option('pve-vmid'),
3ea94c60 1029 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
1030 },
1031 },
afdb31d5 1032 returns => {
5fdbe4f0
DM
1033 type => 'string',
1034 },
1e3baf05
DM
1035 code => sub {
1036 my ($param) = @_;
1037
1038 my $rpcenv = PVE::RPCEnvironment::get();
1039
a0d1b1a2 1040 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1041
1042 my $vmid = $param->{vmid};
1043
1044 my $skiplock = $param->{skiplock};
afdb31d5 1045 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1046 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1047
5fdbe4f0
DM
1048 # test if VM exists
1049 my $conf = PVE::QemuServer::load_config($vmid);
1050
afdb31d5 1051 my $storecfg = PVE::Storage::config();
1e3baf05 1052
75466c4f 1053 my $delVMfromPoolFn = sub {
502d18a2 1054 my $usercfg = cfs_read_file("user.cfg");
5d0094ea
DM
1055 if (my $pool = $usercfg->{vms}->{$vmid}) {
1056 if (my $data = $usercfg->{pools}->{$pool}) {
1057 delete $data->{vms}->{$vmid};
1058 delete $usercfg->{vms}->{$vmid};
1059 cfs_write_file("user.cfg", $usercfg);
1060 }
502d18a2
DM
1061 }
1062 };
1063
5fdbe4f0 1064 my $realcmd = sub {
ff1a2432
DM
1065 my $upid = shift;
1066
1067 syslog('info', "destroy VM $vmid: $upid\n");
1068
5fdbe4f0 1069 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
502d18a2
DM
1070
1071 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
5fdbe4f0 1072 };
1e3baf05 1073
a0d1b1a2 1074 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1e3baf05
DM
1075 }});
1076
1077__PACKAGE__->register_method({
afdb31d5
DM
1078 name => 'unlink',
1079 path => '{vmid}/unlink',
1e3baf05
DM
1080 method => 'PUT',
1081 protected => 1,
1082 proxyto => 'node',
1083 description => "Unlink/delete disk images.",
a0d1b1a2
DM
1084 permissions => {
1085 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
1086 },
1e3baf05
DM
1087 parameters => {
1088 additionalProperties => 0,
1089 properties => {
1090 node => get_standard_option('pve-node'),
1091 vmid => get_standard_option('pve-vmid'),
1092 idlist => {
1093 type => 'string', format => 'pve-configid-list',
1094 description => "A list of disk IDs you want to delete.",
1095 },
1096 force => {
1097 type => 'boolean',
1098 description => $opt_force_description,
1099 optional => 1,
1100 },
1101 },
1102 },
1103 returns => { type => 'null'},
1104 code => sub {
1105 my ($param) = @_;
1106
1107 $param->{delete} = extract_param($param, 'idlist');
1108
1109 __PACKAGE__->update_vm($param);
1110
1111 return undef;
1112 }});
1113
1114my $sslcert;
1115
1116__PACKAGE__->register_method({
afdb31d5
DM
1117 name => 'vncproxy',
1118 path => '{vmid}/vncproxy',
1e3baf05
DM
1119 method => 'POST',
1120 protected => 1,
1121 permissions => {
378b359e 1122 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1e3baf05
DM
1123 },
1124 description => "Creates a TCP VNC proxy connections.",
1125 parameters => {
1126 additionalProperties => 0,
1127 properties => {
1128 node => get_standard_option('pve-node'),
1129 vmid => get_standard_option('pve-vmid'),
1130 },
1131 },
afdb31d5 1132 returns => {
1e3baf05
DM
1133 additionalProperties => 0,
1134 properties => {
1135 user => { type => 'string' },
1136 ticket => { type => 'string' },
1137 cert => { type => 'string' },
1138 port => { type => 'integer' },
1139 upid => { type => 'string' },
1140 },
1141 },
1142 code => sub {
1143 my ($param) = @_;
1144
1145 my $rpcenv = PVE::RPCEnvironment::get();
1146
a0d1b1a2 1147 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1148
1149 my $vmid = $param->{vmid};
1150 my $node = $param->{node};
1151
b6f39da2
DM
1152 my $authpath = "/vms/$vmid";
1153
a0d1b1a2 1154 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
b6f39da2 1155
1e3baf05
DM
1156 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1157 if !$sslcert;
1158
1159 my $port = PVE::Tools::next_vnc_port();
1160
1161 my $remip;
afdb31d5 1162
4f1be36c 1163 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1e3baf05
DM
1164 $remip = PVE::Cluster::remote_node_ip($node);
1165 }
1166
6bb726c9
SP
1167 # NOTE: kvm VNC traffic is already TLS encrypted
1168 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes', $remip] : [];
1e3baf05 1169
afdb31d5 1170 my $timeout = 10;
1e3baf05
DM
1171
1172 my $realcmd = sub {
1173 my $upid = shift;
1174
1175 syslog('info', "starting vnc proxy $upid\n");
1176
1177 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1178
1179 my $qmstr = join(' ', @$qmcmd);
1180
1181 # also redirect stderr (else we get RFB protocol errors)
be62c45c 1182 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1e3baf05 1183
be62c45c 1184 PVE::Tools::run_command($cmd);
1e3baf05
DM
1185
1186 return;
1187 };
1188
a0d1b1a2 1189 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1e3baf05 1190
3da85107
DM
1191 PVE::Tools::wait_for_vnc_port($port);
1192
1e3baf05 1193 return {
a0d1b1a2 1194 user => $authuser,
1e3baf05 1195 ticket => $ticket,
afdb31d5
DM
1196 port => $port,
1197 upid => $upid,
1198 cert => $sslcert,
1e3baf05
DM
1199 };
1200 }});
1201
5fdbe4f0
DM
1202__PACKAGE__->register_method({
1203 name => 'vmcmdidx',
afdb31d5 1204 path => '{vmid}/status',
5fdbe4f0
DM
1205 method => 'GET',
1206 proxyto => 'node',
1207 description => "Directory index",
a0d1b1a2
DM
1208 permissions => {
1209 user => 'all',
1210 },
5fdbe4f0
DM
1211 parameters => {
1212 additionalProperties => 0,
1213 properties => {
1214 node => get_standard_option('pve-node'),
1215 vmid => get_standard_option('pve-vmid'),
1216 },
1217 },
1218 returns => {
1219 type => 'array',
1220 items => {
1221 type => "object",
1222 properties => {
1223 subdir => { type => 'string' },
1224 },
1225 },
1226 links => [ { rel => 'child', href => "{subdir}" } ],
1227 },
1228 code => sub {
1229 my ($param) = @_;
1230
1231 # test if VM exists
1232 my $conf = PVE::QemuServer::load_config($param->{vmid});
1233
1234 my $res = [
1235 { subdir => 'current' },
1236 { subdir => 'start' },
1237 { subdir => 'stop' },
1238 ];
afdb31d5 1239
5fdbe4f0
DM
1240 return $res;
1241 }});
1242
88fc87b4
DM
1243my $vm_is_ha_managed = sub {
1244 my ($vmid) = @_;
1245
1246 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1247 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1248 return 1;
75466c4f 1249 }
88fc87b4
DM
1250 return 0;
1251};
1252
1e3baf05 1253__PACKAGE__->register_method({
afdb31d5 1254 name => 'vm_status',
5fdbe4f0 1255 path => '{vmid}/status/current',
1e3baf05
DM
1256 method => 'GET',
1257 proxyto => 'node',
1258 protected => 1, # qemu pid files are only readable by root
1259 description => "Get virtual machine status.",
a0d1b1a2
DM
1260 permissions => {
1261 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1262 },
1e3baf05
DM
1263 parameters => {
1264 additionalProperties => 0,
1265 properties => {
1266 node => get_standard_option('pve-node'),
1267 vmid => get_standard_option('pve-vmid'),
1268 },
1269 },
1270 returns => { type => 'object' },
1271 code => sub {
1272 my ($param) = @_;
1273
1274 # test if VM exists
1275 my $conf = PVE::QemuServer::load_config($param->{vmid});
1276
03a33f30 1277 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
8610701a 1278 my $status = $vmstatus->{$param->{vmid}};
1e3baf05 1279
88fc87b4 1280 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
8610701a
DM
1281
1282 return $status;
1e3baf05
DM
1283 }});
1284
1285__PACKAGE__->register_method({
afdb31d5 1286 name => 'vm_start',
5fdbe4f0
DM
1287 path => '{vmid}/status/start',
1288 method => 'POST',
1e3baf05
DM
1289 protected => 1,
1290 proxyto => 'node',
5fdbe4f0 1291 description => "Start virtual machine.",
a0d1b1a2
DM
1292 permissions => {
1293 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1294 },
1e3baf05
DM
1295 parameters => {
1296 additionalProperties => 0,
1297 properties => {
1298 node => get_standard_option('pve-node'),
1299 vmid => get_standard_option('pve-vmid'),
3ea94c60
DM
1300 skiplock => get_standard_option('skiplock'),
1301 stateuri => get_standard_option('pve-qm-stateuri'),
7e8dcf2c
AD
1302 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
1303
1e3baf05
DM
1304 },
1305 },
afdb31d5 1306 returns => {
5fdbe4f0
DM
1307 type => 'string',
1308 },
1e3baf05
DM
1309 code => sub {
1310 my ($param) = @_;
1311
1312 my $rpcenv = PVE::RPCEnvironment::get();
1313
a0d1b1a2 1314 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1315
1316 my $node = extract_param($param, 'node');
1317
1e3baf05
DM
1318 my $vmid = extract_param($param, 'vmid');
1319
3ea94c60 1320 my $stateuri = extract_param($param, 'stateuri');
afdb31d5 1321 raise_param_exc({ stateuri => "Only root may use this option." })
a0d1b1a2 1322 if $stateuri && $authuser ne 'root@pam';
3ea94c60 1323
1e3baf05 1324 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1325 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1326 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1327
7e8dcf2c
AD
1328 my $migratedfrom = extract_param($param, 'migratedfrom');
1329 raise_param_exc({ migratedfrom => "Only root may use this option." })
1330 if $migratedfrom && $authuser ne 'root@pam';
1331
afdb31d5 1332 my $storecfg = PVE::Storage::config();
5fdbe4f0 1333
cce37749
DM
1334 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1335 $rpcenv->{type} ne 'ha') {
5fdbe4f0 1336
88fc87b4
DM
1337 my $hacmd = sub {
1338 my $upid = shift;
5fdbe4f0 1339
88fc87b4 1340 my $service = "pvevm:$vmid";
5fdbe4f0 1341
88fc87b4
DM
1342 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1343
1344 print "Executing HA start for VM $vmid\n";
1345
1346 PVE::Tools::run_command($cmd);
1347
1348 return;
1349 };
1350
1351 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1352
1353 } else {
1354
1355 my $realcmd = sub {
1356 my $upid = shift;
1357
1358 syslog('info', "start VM $vmid: $upid\n");
1359
7e8dcf2c 1360 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock, $migratedfrom);
88fc87b4
DM
1361
1362 return;
1363 };
5fdbe4f0 1364
88fc87b4
DM
1365 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1366 }
5fdbe4f0
DM
1367 }});
1368
1369__PACKAGE__->register_method({
afdb31d5 1370 name => 'vm_stop',
5fdbe4f0
DM
1371 path => '{vmid}/status/stop',
1372 method => 'POST',
1373 protected => 1,
1374 proxyto => 'node',
1375 description => "Stop virtual machine.",
a0d1b1a2
DM
1376 permissions => {
1377 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1378 },
5fdbe4f0
DM
1379 parameters => {
1380 additionalProperties => 0,
1381 properties => {
1382 node => get_standard_option('pve-node'),
1383 vmid => get_standard_option('pve-vmid'),
1384 skiplock => get_standard_option('skiplock'),
af30308f 1385 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
c6bb9502
DM
1386 timeout => {
1387 description => "Wait maximal timeout seconds.",
1388 type => 'integer',
1389 minimum => 0,
1390 optional => 1,
254575e9
DM
1391 },
1392 keepActive => {
1393 description => "Do not decativate storage volumes.",
1394 type => 'boolean',
1395 optional => 1,
1396 default => 0,
c6bb9502 1397 }
5fdbe4f0
DM
1398 },
1399 },
afdb31d5 1400 returns => {
5fdbe4f0
DM
1401 type => 'string',
1402 },
1403 code => sub {
1404 my ($param) = @_;
1405
1406 my $rpcenv = PVE::RPCEnvironment::get();
1407
a0d1b1a2 1408 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1409
1410 my $node = extract_param($param, 'node');
1411
1412 my $vmid = extract_param($param, 'vmid');
1413
1414 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1415 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1416 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1417
254575e9 1418 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1419 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1420 if $keepActive && $authuser ne 'root@pam';
254575e9 1421
af30308f
DM
1422 my $migratedfrom = extract_param($param, 'migratedfrom');
1423 raise_param_exc({ migratedfrom => "Only root may use this option." })
1424 if $migratedfrom && $authuser ne 'root@pam';
1425
1426
ff1a2432
DM
1427 my $storecfg = PVE::Storage::config();
1428
3be30d63 1429 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
5fdbe4f0 1430
88fc87b4
DM
1431 my $hacmd = sub {
1432 my $upid = shift;
5fdbe4f0 1433
88fc87b4 1434 my $service = "pvevm:$vmid";
c6bb9502 1435
88fc87b4
DM
1436 my $cmd = ['clusvcadm', '-d', $service];
1437
1438 print "Executing HA stop for VM $vmid\n";
1439
1440 PVE::Tools::run_command($cmd);
5fdbe4f0 1441
88fc87b4
DM
1442 return;
1443 };
1444
1445 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1446
1447 } else {
1448 my $realcmd = sub {
1449 my $upid = shift;
1450
1451 syslog('info', "stop VM $vmid: $upid\n");
1452
1453 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
af30308f 1454 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
88fc87b4
DM
1455
1456 return;
1457 };
1458
1459 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1460 }
5fdbe4f0
DM
1461 }});
1462
1463__PACKAGE__->register_method({
afdb31d5 1464 name => 'vm_reset',
5fdbe4f0
DM
1465 path => '{vmid}/status/reset',
1466 method => 'POST',
1467 protected => 1,
1468 proxyto => 'node',
1469 description => "Reset virtual machine.",
a0d1b1a2
DM
1470 permissions => {
1471 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1472 },
5fdbe4f0
DM
1473 parameters => {
1474 additionalProperties => 0,
1475 properties => {
1476 node => get_standard_option('pve-node'),
1477 vmid => get_standard_option('pve-vmid'),
1478 skiplock => get_standard_option('skiplock'),
1479 },
1480 },
afdb31d5 1481 returns => {
5fdbe4f0
DM
1482 type => 'string',
1483 },
1484 code => sub {
1485 my ($param) = @_;
1486
1487 my $rpcenv = PVE::RPCEnvironment::get();
1488
a0d1b1a2 1489 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1490
1491 my $node = extract_param($param, 'node');
1492
1493 my $vmid = extract_param($param, 'vmid');
1494
1495 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1496 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1497 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1498
ff1a2432
DM
1499 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1500
5fdbe4f0
DM
1501 my $realcmd = sub {
1502 my $upid = shift;
1503
1e3baf05 1504 PVE::QemuServer::vm_reset($vmid, $skiplock);
5fdbe4f0
DM
1505
1506 return;
1507 };
1508
a0d1b1a2 1509 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1510 }});
1511
1512__PACKAGE__->register_method({
afdb31d5 1513 name => 'vm_shutdown',
5fdbe4f0
DM
1514 path => '{vmid}/status/shutdown',
1515 method => 'POST',
1516 protected => 1,
1517 proxyto => 'node',
1518 description => "Shutdown virtual machine.",
a0d1b1a2
DM
1519 permissions => {
1520 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1521 },
5fdbe4f0
DM
1522 parameters => {
1523 additionalProperties => 0,
1524 properties => {
1525 node => get_standard_option('pve-node'),
1526 vmid => get_standard_option('pve-vmid'),
1527 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1528 timeout => {
1529 description => "Wait maximal timeout seconds.",
1530 type => 'integer',
1531 minimum => 0,
1532 optional => 1,
9269013a
DM
1533 },
1534 forceStop => {
1535 description => "Make sure the VM stops.",
1536 type => 'boolean',
1537 optional => 1,
1538 default => 0,
254575e9
DM
1539 },
1540 keepActive => {
1541 description => "Do not decativate storage volumes.",
1542 type => 'boolean',
1543 optional => 1,
1544 default => 0,
c6bb9502 1545 }
5fdbe4f0
DM
1546 },
1547 },
afdb31d5 1548 returns => {
5fdbe4f0
DM
1549 type => 'string',
1550 },
1551 code => sub {
1552 my ($param) = @_;
1553
1554 my $rpcenv = PVE::RPCEnvironment::get();
1555
a0d1b1a2 1556 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1557
1558 my $node = extract_param($param, 'node');
1559
1560 my $vmid = extract_param($param, 'vmid');
1561
1562 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1563 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1564 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1565
254575e9 1566 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1567 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1568 if $keepActive && $authuser ne 'root@pam';
254575e9 1569
02d07cf5
DM
1570 my $storecfg = PVE::Storage::config();
1571
5fdbe4f0
DM
1572 my $realcmd = sub {
1573 my $upid = shift;
1574
1575 syslog('info', "shutdown VM $vmid: $upid\n");
1576
afdb31d5 1577 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
254575e9 1578 1, $param->{forceStop}, $keepActive);
c6bb9502 1579
5fdbe4f0
DM
1580 return;
1581 };
1582
a0d1b1a2 1583 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1584 }});
1585
1586__PACKAGE__->register_method({
afdb31d5 1587 name => 'vm_suspend',
5fdbe4f0
DM
1588 path => '{vmid}/status/suspend',
1589 method => 'POST',
1590 protected => 1,
1591 proxyto => 'node',
1592 description => "Suspend virtual machine.",
a0d1b1a2
DM
1593 permissions => {
1594 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1595 },
5fdbe4f0
DM
1596 parameters => {
1597 additionalProperties => 0,
1598 properties => {
1599 node => get_standard_option('pve-node'),
1600 vmid => get_standard_option('pve-vmid'),
1601 skiplock => get_standard_option('skiplock'),
1602 },
1603 },
afdb31d5 1604 returns => {
5fdbe4f0
DM
1605 type => 'string',
1606 },
1607 code => sub {
1608 my ($param) = @_;
1609
1610 my $rpcenv = PVE::RPCEnvironment::get();
1611
a0d1b1a2 1612 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1613
1614 my $node = extract_param($param, 'node');
1615
1616 my $vmid = extract_param($param, 'vmid');
1617
1618 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1619 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1620 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1621
ff1a2432
DM
1622 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1623
5fdbe4f0
DM
1624 my $realcmd = sub {
1625 my $upid = shift;
1626
1627 syslog('info', "suspend VM $vmid: $upid\n");
1628
1e3baf05 1629 PVE::QemuServer::vm_suspend($vmid, $skiplock);
5fdbe4f0
DM
1630
1631 return;
1632 };
1633
a0d1b1a2 1634 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1635 }});
1636
1637__PACKAGE__->register_method({
afdb31d5 1638 name => 'vm_resume',
5fdbe4f0
DM
1639 path => '{vmid}/status/resume',
1640 method => 'POST',
1641 protected => 1,
1642 proxyto => 'node',
1643 description => "Resume virtual machine.",
a0d1b1a2
DM
1644 permissions => {
1645 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1646 },
5fdbe4f0
DM
1647 parameters => {
1648 additionalProperties => 0,
1649 properties => {
1650 node => get_standard_option('pve-node'),
1651 vmid => get_standard_option('pve-vmid'),
1652 skiplock => get_standard_option('skiplock'),
1653 },
1654 },
afdb31d5 1655 returns => {
5fdbe4f0
DM
1656 type => 'string',
1657 },
1658 code => sub {
1659 my ($param) = @_;
1660
1661 my $rpcenv = PVE::RPCEnvironment::get();
1662
a0d1b1a2 1663 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1664
1665 my $node = extract_param($param, 'node');
1666
1667 my $vmid = extract_param($param, 'vmid');
1668
1669 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1670 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1671 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1672
b7eeab21 1673 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
ff1a2432 1674
5fdbe4f0
DM
1675 my $realcmd = sub {
1676 my $upid = shift;
1677
1678 syslog('info', "resume VM $vmid: $upid\n");
1679
1e3baf05 1680 PVE::QemuServer::vm_resume($vmid, $skiplock);
1e3baf05 1681
5fdbe4f0
DM
1682 return;
1683 };
1684
a0d1b1a2 1685 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1686 }});
1687
1688__PACKAGE__->register_method({
afdb31d5 1689 name => 'vm_sendkey',
5fdbe4f0
DM
1690 path => '{vmid}/sendkey',
1691 method => 'PUT',
1692 protected => 1,
1693 proxyto => 'node',
1694 description => "Send key event to virtual machine.",
a0d1b1a2
DM
1695 permissions => {
1696 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1697 },
5fdbe4f0
DM
1698 parameters => {
1699 additionalProperties => 0,
1700 properties => {
1701 node => get_standard_option('pve-node'),
1702 vmid => get_standard_option('pve-vmid'),
1703 skiplock => get_standard_option('skiplock'),
1704 key => {
1705 description => "The key (qemu monitor encoding).",
1706 type => 'string'
1707 }
1708 },
1709 },
1710 returns => { type => 'null'},
1711 code => sub {
1712 my ($param) = @_;
1713
1714 my $rpcenv = PVE::RPCEnvironment::get();
1715
a0d1b1a2 1716 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1717
1718 my $node = extract_param($param, 'node');
1719
1720 my $vmid = extract_param($param, 'vmid');
1721
1722 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1723 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1724 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0
DM
1725
1726 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1727
1728 return;
1e3baf05
DM
1729 }});
1730
1ac0d2ee
AD
1731__PACKAGE__->register_method({
1732 name => 'vm_feature',
1733 path => '{vmid}/feature',
1734 method => 'GET',
1735 proxyto => 'node',
75466c4f 1736 protected => 1,
1ac0d2ee
AD
1737 description => "Check if feature for virtual machine is available.",
1738 permissions => {
1739 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1740 },
1741 parameters => {
1742 additionalProperties => 0,
1743 properties => {
1744 node => get_standard_option('pve-node'),
1745 vmid => get_standard_option('pve-vmid'),
1746 feature => {
1747 description => "Feature to check.",
1748 type => 'string',
1749 enum => [ 'snapshot', 'clone' ],
1750 },
1751 snapname => get_standard_option('pve-snapshot-name', {
1752 optional => 1,
1753 }),
1754 },
1ac0d2ee
AD
1755 },
1756 returns => {
1757 type => 'boolean'
1758 },
1759 code => sub {
1760 my ($param) = @_;
1761
1762 my $node = extract_param($param, 'node');
1763
1764 my $vmid = extract_param($param, 'vmid');
1765
1766 my $snapname = extract_param($param, 'snapname');
1767
1768 my $feature = extract_param($param, 'feature');
1769
1770 my $running = PVE::QemuServer::check_running($vmid);
1771
1772 my $conf = PVE::QemuServer::load_config($vmid);
1773
1774 if($snapname){
1775 my $snap = $conf->{snapshots}->{$snapname};
1776 die "snapshot '$snapname' does not exist\n" if !defined($snap);
1777 $conf = $snap;
1778 }
1779 my $storecfg = PVE::Storage::config();
1780
1781 my $hasfeature = PVE::QemuServer::has_feature($feature, $conf, $storecfg, $snapname, $running);
1782 my $res = $hasfeature ? 1 : 0 ;
1783 return $res;
1784 }});
1785
6116f729
DM
1786__PACKAGE__->register_method({
1787 name => 'copy_vm',
1788 path => '{vmid}/copy',
1789 method => 'POST',
1790 protected => 1,
1791 proxyto => 'node',
37329185 1792 description => "Create a copy of virtual machine/template.",
6116f729
DM
1793 permissions => {
1794 description => "You need 'VM.Copy' permissions on /vms/{vmid}, and 'VM.Allocate' permissions " .
1795 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
1796 "'Datastore.AllocateSpace' on any used storage.",
75466c4f
DM
1797 check =>
1798 [ 'and',
6116f729 1799 ['perm', '/vms/{vmid}', [ 'VM.Copy' ]],
75466c4f 1800 [ 'or',
6116f729
DM
1801 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
1802 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
1803 ],
1804 ]
1805 },
1806 parameters => {
1807 additionalProperties => 0,
1808 properties => {
6116f729
DM
1809 node => get_standard_option('pve-node'),
1810 vmid => get_standard_option('pve-vmid'),
a60ab1a6
DM
1811 newid => get_standard_option('pve-vmid', { description => 'VMID for the copy.' }),
1812 name => {
1813 optional => 1,
1814 type => 'string', format => 'dns-name',
1815 description => "Set a name for the new VM.",
1816 },
1817 description => {
1818 optional => 1,
1819 type => 'string',
1820 description => "Description for the new VM.",
1821 },
75466c4f 1822 pool => {
6116f729
DM
1823 optional => 1,
1824 type => 'string', format => 'pve-poolid',
1825 description => "Add the new VM to the specified pool.",
1826 },
9076d880
DM
1827 snapname => get_standard_option('pve-snapshot-name', {
1828 requires => 'full',
1829 optional => 1,
1830 }),
81f043eb
AD
1831 storage => get_standard_option('pve-storage-id', {
1832 description => "Target storage for full copy.",
4e4f83fe 1833 requires => 'full',
81f043eb
AD
1834 optional => 1,
1835 }),
55173c6b 1836 'format' => {
42a19c87
AD
1837 description => "Target format for file storage.",
1838 requires => 'full',
1839 type => 'string',
1840 optional => 1,
55173c6b 1841 enum => [ 'raw', 'qcow2', 'vmdk'],
42a19c87 1842 },
6116f729
DM
1843 full => {
1844 optional => 1,
55173c6b
DM
1845 type => 'boolean',
1846 description => "Create a full copy of all disk. This is always done when " .
6116f729
DM
1847 "you copy a normal VM. For VM templates, we try to create a linked copy by default.",
1848 default => 0,
1849 },
75466c4f 1850 target => get_standard_option('pve-node', {
55173c6b
DM
1851 description => "Target node. Only allowed if the original VM is on shared storage.",
1852 optional => 1,
1853 }),
1854 },
6116f729
DM
1855 },
1856 returns => {
1857 type => 'string',
1858 },
1859 code => sub {
1860 my ($param) = @_;
1861
1862 my $rpcenv = PVE::RPCEnvironment::get();
1863
55173c6b 1864 my $authuser = $rpcenv->get_user();
6116f729
DM
1865
1866 my $node = extract_param($param, 'node');
1867
1868 my $vmid = extract_param($param, 'vmid');
1869
1870 my $newid = extract_param($param, 'newid');
1871
1872 # fixme: update pool after create
1873 my $pool = extract_param($param, 'pool');
1874
1875 if (defined($pool)) {
1876 $rpcenv->check_pool_exist($pool);
1877 }
1878
55173c6b 1879 my $snapname = extract_param($param, 'snapname');
9076d880 1880
81f043eb
AD
1881 my $storage = extract_param($param, 'storage');
1882
42a19c87
AD
1883 my $format = extract_param($param, 'format');
1884
55173c6b
DM
1885 my $target = extract_param($param, 'target');
1886
1887 my $localnode = PVE::INotify::nodename();
1888
1889 undef $target if $target eq $localnode || $target eq 'localhost';
1890
1891 PVE::Cluster::check_node_exists($target) if $target;
1892
6116f729
DM
1893 my $storecfg = PVE::Storage::config();
1894
55173c6b 1895 PVE::Cluster::check_cfs_quorum();
6116f729 1896
4e4f83fe
DM
1897 my $running = PVE::QemuServer::check_running($vmid) || 0;
1898
1899 die "Copy running VM $vmid not implemented\n" if $running; # fixme: implement this
1900
1901 # exclusive lock if VM is running - else shared lock is enough;
1902 my $shared_lock = $running ? 0 : 1;
1903
75466c4f 1904 # fixme: do early checks - re-check after lock
6116f729
DM
1905
1906 # fixme: impl. target node parameter (mv VM config if all storages are shared)
1907
1908 my $copyfn = sub {
1909
1910 # all tests after lock
1911 my $conf = PVE::QemuServer::load_config($vmid);
1912
1913 PVE::QemuServer::check_lock($conf);
1914
4e4f83fe 1915 my $verify_running = PVE::QemuServer::check_running($vmid) || 0;
6116f729 1916
4e4f83fe 1917 die "unexpected state change\n" if $verify_running != $running;
6116f729 1918
75466c4f
DM
1919 die "snapshot '$snapname' does not exist\n"
1920 if $snapname && !defined( $conf->{snapshots}->{$snapname});
6116f729 1921
75466c4f 1922 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
9076d880 1923
55173c6b 1924 my $sharedvm = &$check_storage_access_copy($rpcenv, $authuser, $storecfg, $oldconf, $storage);
6116f729 1925
55173c6b 1926 die "can't copy VM to node '$target' (VM uses local storage)\n" if $target && !$sharedvm;
75466c4f 1927
6116f729
DM
1928 my $conffile = PVE::QemuServer::config_file($newid);
1929
1930 die "unable to create VM $newid: config file already exists\n"
1931 if -f $conffile;
1932
1933 # create empty/temp config - this fails if VM already exists on other node
b83e0181 1934 PVE::Tools::file_set_contents($conffile, "# qmcopy temporary file\nlock: copy\n");
6116f729
DM
1935
1936 my $realcmd = sub {
1937 my $upid = shift;
1938
b83e0181 1939 my $newvollist = [];
6116f729 1940
b83e0181
DM
1941 eval {
1942 my $newconf = { lock => 'copy' };
6116f729
DM
1943 my $drives = {};
1944 my $vollist = [];
6116f729 1945
9076d880
DM
1946 foreach my $opt (keys %$oldconf) {
1947 my $value = $oldconf->{$opt};
1948
1949 # do not copy snapshot related info
1950 next if $opt eq 'snapshots' || $opt eq 'parent' || $opt eq 'snaptime' ||
1951 $opt eq 'vmstate' || $opt eq 'snapstate';
b83e0181 1952
6116f729
DM
1953 # always change MAC! address
1954 if ($opt =~ m/^net(\d+)$/) {
1955 my $net = PVE::QemuServer::parse_net($value);
1956 $net->{macaddr} = PVE::Tools::random_ether_addr();
1957 $newconf->{$opt} = PVE::QemuServer::print_net($net);
1958 } elsif (my $drive = PVE::QemuServer::parse_drive($opt, $value)) {
1959 if (PVE::QemuServer::drive_is_cdrom($drive)) {
1960 $newconf->{$opt} = $value; # simply copy configuration
1961 } else {
1962 $drives->{$opt} = $drive;
1963 push @$vollist, $drive->{file};
1964 }
1965 } else {
1966 # copy everything else
75466c4f 1967 $newconf->{$opt} = $value;
6116f729
DM
1968 }
1969 }
1970
1971 delete $newconf->{template};
a60ab1a6
DM
1972
1973 if ($param->{name}) {
1974 $newconf->{name} = $param->{name};
1975 } else {
1976 $newconf->{name} = "Copy-of-$oldconf->{name}";
1977 }
1978
1979 if ($param->{description}) {
1980 $newconf->{description} = $param->{description};
1981 }
75466c4f 1982
6116f729
DM
1983 PVE::Storage::activate_volumes($storecfg, $vollist);
1984
b83e0181
DM
1985 eval {
1986 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
6116f729 1987
b83e0181
DM
1988 foreach my $opt (keys %$drives) {
1989 my $drive = $drives->{$opt};
6116f729 1990
b83e0181
DM
1991 my $newvolid;
1992 if (!$param->{full} && PVE::Storage::volume_is_base($storecfg, $drive->{file})) {
1993 print "clone drive $opt ($drive->{file})\n";
1994 $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newid);
1995 } else {
1996 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
81f043eb 1997 $storeid = $storage if $storage;
42a19c87
AD
1998
1999 my $fmt = undef;
2000 if($format){
2001 $fmt = $format;
2002 }else{
2003 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
2004 $fmt = $drive->{format} || $defformat;
2005 }
b83e0181
DM
2006
2007 my ($size) = PVE::Storage::volume_size_info($storecfg, $drive->{file}, 3);
2008
2009 print "copy drive $opt ($drive->{file})\n";
2010 $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $newid, $fmt, undef, ($size/1024));
2011
9076d880 2012 PVE::QemuServer::qemu_img_convert($drive->{file}, $newvolid, $size, $snapname);
b83e0181
DM
2013 }
2014
2015 my ($size) = PVE::Storage::volume_size_info($storecfg, $newvolid, 3);
2016 my $disk = { file => $newvolid, size => $size };
75466c4f 2017 $newconf->{$opt} = PVE::QemuServer::print_drive($vmid, $disk);
b83e0181 2018 push @$newvollist, $newvolid;
6116f729 2019
b83e0181
DM
2020 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
2021 }
2022 };
2023 die $@ if $@;
2024
2025 delete $newconf->{lock};
2026 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
55173c6b
DM
2027
2028 if ($target) {
2029 my $newconffile = PVE::QemuServer::config_file($newid, $target);
2030 die "Failed to move config to node '$target' - rename failed: $!\n"
2031 if !rename($conffile, $newconffile);
2032 }
6116f729 2033 };
75466c4f 2034 if (my $err = $@) {
6116f729
DM
2035 unlink $conffile;
2036
b83e0181
DM
2037 sleep 1; # some storage like rbd need to wait before release volume - really?
2038
2039 foreach my $volid (@$newvollist) {
2040 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2041 warn $@ if $@;
2042 }
6116f729
DM
2043 die "copy failed: $err";
2044 }
2045
2046 return;
2047 };
2048
2049 return $rpcenv->fork_worker('qmcopy', $vmid, $authuser, $realcmd);
2050 };
2051
4e4f83fe 2052 return PVE::QemuServer::lock_config_mode($vmid, 1, $shared_lock, sub {
6116f729
DM
2053 # Aquire exclusive lock lock for $newid
2054 return PVE::QemuServer::lock_config_full($newid, 1, $copyfn);
2055 });
2056
2057 }});
2058
3ea94c60 2059__PACKAGE__->register_method({
afdb31d5 2060 name => 'migrate_vm',
3ea94c60
DM
2061 path => '{vmid}/migrate',
2062 method => 'POST',
2063 protected => 1,
2064 proxyto => 'node',
2065 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
2066 permissions => {
2067 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
2068 },
3ea94c60
DM
2069 parameters => {
2070 additionalProperties => 0,
2071 properties => {
2072 node => get_standard_option('pve-node'),
2073 vmid => get_standard_option('pve-vmid'),
2074 target => get_standard_option('pve-node', { description => "Target node." }),
2075 online => {
2076 type => 'boolean',
2077 description => "Use online/live migration.",
2078 optional => 1,
2079 },
2080 force => {
2081 type => 'boolean',
2082 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
2083 optional => 1,
2084 },
2085 },
2086 },
afdb31d5 2087 returns => {
3ea94c60
DM
2088 type => 'string',
2089 description => "the task ID.",
2090 },
2091 code => sub {
2092 my ($param) = @_;
2093
2094 my $rpcenv = PVE::RPCEnvironment::get();
2095
a0d1b1a2 2096 my $authuser = $rpcenv->get_user();
3ea94c60
DM
2097
2098 my $target = extract_param($param, 'target');
2099
2100 my $localnode = PVE::INotify::nodename();
2101 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
2102
2103 PVE::Cluster::check_cfs_quorum();
2104
2105 PVE::Cluster::check_node_exists($target);
2106
2107 my $targetip = PVE::Cluster::remote_node_ip($target);
2108
2109 my $vmid = extract_param($param, 'vmid');
2110
afdb31d5 2111 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 2112 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
2113
2114 # test if VM exists
a5ed42d3 2115 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
2116
2117 # try to detect errors early
a5ed42d3
DM
2118
2119 PVE::QemuServer::check_lock($conf);
2120
3ea94c60 2121 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 2122 die "cant migrate running VM without --online\n"
3ea94c60
DM
2123 if !$param->{online};
2124 }
2125
47152e2e 2126 my $storecfg = PVE::Storage::config();
22d646a7 2127 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
47152e2e 2128
3be30d63 2129 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3ea94c60 2130
88fc87b4
DM
2131 my $hacmd = sub {
2132 my $upid = shift;
3ea94c60 2133
88fc87b4
DM
2134 my $service = "pvevm:$vmid";
2135
2136 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
2137
2138 print "Executing HA migrate for VM $vmid to node $target\n";
2139
2140 PVE::Tools::run_command($cmd);
2141
2142 return;
2143 };
2144
2145 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
2146
2147 } else {
2148
2149 my $realcmd = sub {
2150 my $upid = shift;
2151
2152 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
2153 };
2154
2155 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
2156 }
3ea94c60 2157
3ea94c60 2158 }});
1e3baf05 2159
91c94f0a 2160__PACKAGE__->register_method({
afdb31d5
DM
2161 name => 'monitor',
2162 path => '{vmid}/monitor',
91c94f0a
DM
2163 method => 'POST',
2164 protected => 1,
2165 proxyto => 'node',
2166 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
2167 permissions => {
2168 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
2169 },
91c94f0a
DM
2170 parameters => {
2171 additionalProperties => 0,
2172 properties => {
2173 node => get_standard_option('pve-node'),
2174 vmid => get_standard_option('pve-vmid'),
2175 command => {
2176 type => 'string',
2177 description => "The monitor command.",
2178 }
2179 },
2180 },
2181 returns => { type => 'string'},
2182 code => sub {
2183 my ($param) = @_;
2184
2185 my $vmid = $param->{vmid};
2186
2187 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
2188
2189 my $res = '';
2190 eval {
7b7c6d1b 2191 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
91c94f0a
DM
2192 };
2193 $res = "ERROR: $@" if $@;
2194
2195 return $res;
2196 }});
2197
0d02881c
AD
2198__PACKAGE__->register_method({
2199 name => 'resize_vm',
614e3941 2200 path => '{vmid}/resize',
0d02881c
AD
2201 method => 'PUT',
2202 protected => 1,
2203 proxyto => 'node',
2f48a4f5 2204 description => "Extend volume size.",
0d02881c 2205 permissions => {
3b2773f6 2206 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
0d02881c
AD
2207 },
2208 parameters => {
2209 additionalProperties => 0,
2f48a4f5
DM
2210 properties => {
2211 node => get_standard_option('pve-node'),
2212 vmid => get_standard_option('pve-vmid'),
2213 skiplock => get_standard_option('skiplock'),
2214 disk => {
2215 type => 'string',
2216 description => "The disk you want to resize.",
2217 enum => [PVE::QemuServer::disknames()],
2218 },
2219 size => {
2220 type => 'string',
f91b2e45 2221 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2f48a4f5
DM
2222 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.",
2223 },
2224 digest => {
2225 type => 'string',
2226 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2227 maxLength => 40,
2228 optional => 1,
2229 },
2230 },
0d02881c
AD
2231 },
2232 returns => { type => 'null'},
2233 code => sub {
2234 my ($param) = @_;
2235
2236 my $rpcenv = PVE::RPCEnvironment::get();
2237
2238 my $authuser = $rpcenv->get_user();
2239
2240 my $node = extract_param($param, 'node');
2241
2242 my $vmid = extract_param($param, 'vmid');
2243
2244 my $digest = extract_param($param, 'digest');
2245
2f48a4f5 2246 my $disk = extract_param($param, 'disk');
75466c4f 2247
2f48a4f5 2248 my $sizestr = extract_param($param, 'size');
0d02881c 2249
f91b2e45 2250 my $skiplock = extract_param($param, 'skiplock');
0d02881c
AD
2251 raise_param_exc({ skiplock => "Only root may use this option." })
2252 if $skiplock && $authuser ne 'root@pam';
2253
0d02881c
AD
2254 my $storecfg = PVE::Storage::config();
2255
0d02881c
AD
2256 my $updatefn = sub {
2257
2258 my $conf = PVE::QemuServer::load_config($vmid);
2259
2260 die "checksum missmatch (file change by other user?)\n"
2261 if $digest && $digest ne $conf->{digest};
2262 PVE::QemuServer::check_lock($conf) if !$skiplock;
2263
f91b2e45
DM
2264 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2265
2266 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2267
2268 my $volid = $drive->{file};
2269
2270 die "disk '$disk' has no associated volume\n" if !$volid;
2271
2272 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2273
75466c4f 2274 die "you can't online resize a virtio windows bootdisk\n"
f2965e67
AD
2275 if PVE::QemuServer::check_running($vmid) && $conf->{bootdisk} eq $disk && $conf->{ostype} =~ m/^w/ && $disk =~ m/^virtio/;
2276
f91b2e45
DM
2277 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
2278
2279 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
2280
2281 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
2282
2283 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
2284 my ($ext, $newsize, $unit) = ($1, $2, $4);
2285 if ($unit) {
2286 if ($unit eq 'K') {
2287 $newsize = $newsize * 1024;
2288 } elsif ($unit eq 'M') {
2289 $newsize = $newsize * 1024 * 1024;
2290 } elsif ($unit eq 'G') {
2291 $newsize = $newsize * 1024 * 1024 * 1024;
2292 } elsif ($unit eq 'T') {
2293 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
2294 }
2295 }
2296 $newsize += $size if $ext;
2297 $newsize = int($newsize);
2298
2299 die "unable to skrink disk size\n" if $newsize < $size;
2300
2301 return if $size == $newsize;
2302
2f48a4f5 2303 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
0d02881c 2304
f91b2e45 2305 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
75466c4f 2306
f91b2e45
DM
2307 $drive->{size} = $newsize;
2308 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
2309
2310 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2311 };
0d02881c
AD
2312
2313 PVE::QemuServer::lock_config($vmid, $updatefn);
2314 return undef;
2315 }});
2316
9dbd1ee4 2317__PACKAGE__->register_method({
7e7d7b61 2318 name => 'snapshot_list',
9dbd1ee4 2319 path => '{vmid}/snapshot',
7e7d7b61
DM
2320 method => 'GET',
2321 description => "List all snapshots.",
2322 permissions => {
2323 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2324 },
2325 proxyto => 'node',
2326 protected => 1, # qemu pid files are only readable by root
2327 parameters => {
2328 additionalProperties => 0,
2329 properties => {
2330 vmid => get_standard_option('pve-vmid'),
2331 node => get_standard_option('pve-node'),
2332 },
2333 },
2334 returns => {
2335 type => 'array',
2336 items => {
2337 type => "object",
2338 properties => {},
2339 },
2340 links => [ { rel => 'child', href => "{name}" } ],
2341 },
2342 code => sub {
2343 my ($param) = @_;
2344
6aa4651b
DM
2345 my $vmid = $param->{vmid};
2346
2347 my $conf = PVE::QemuServer::load_config($vmid);
7e7d7b61
DM
2348 my $snaphash = $conf->{snapshots} || {};
2349
2350 my $res = [];
2351
2352 foreach my $name (keys %$snaphash) {
0ea6bc69 2353 my $d = $snaphash->{$name};
75466c4f
DM
2354 my $item = {
2355 name => $name,
2356 snaptime => $d->{snaptime} || 0,
6aa4651b 2357 vmstate => $d->{vmstate} ? 1 : 0,
982c7f12
DM
2358 description => $d->{description} || '',
2359 };
0ea6bc69 2360 $item->{parent} = $d->{parent} if $d->{parent};
3ee28e38 2361 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
0ea6bc69
DM
2362 push @$res, $item;
2363 }
2364
6aa4651b
DM
2365 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
2366 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
d1914468
DM
2367 $current->{parent} = $conf->{parent} if $conf->{parent};
2368
2369 push @$res, $current;
7e7d7b61
DM
2370
2371 return $res;
2372 }});
2373
2374__PACKAGE__->register_method({
2375 name => 'snapshot',
2376 path => '{vmid}/snapshot',
2377 method => 'POST',
9dbd1ee4
AD
2378 protected => 1,
2379 proxyto => 'node',
2380 description => "Snapshot a VM.",
2381 permissions => {
f1baf1df 2382 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
9dbd1ee4
AD
2383 },
2384 parameters => {
2385 additionalProperties => 0,
2386 properties => {
2387 node => get_standard_option('pve-node'),
2388 vmid => get_standard_option('pve-vmid'),
8abd398b 2389 snapname => get_standard_option('pve-snapshot-name'),
9dbd1ee4
AD
2390 vmstate => {
2391 optional => 1,
2392 type => 'boolean',
2393 description => "Save the vmstate",
2394 },
2395 freezefs => {
2396 optional => 1,
2397 type => 'boolean',
2398 description => "Freeze the filesystem",
2399 },
782f4f75
DM
2400 description => {
2401 optional => 1,
2402 type => 'string',
2403 description => "A textual description or comment.",
2404 },
9dbd1ee4
AD
2405 },
2406 },
7e7d7b61
DM
2407 returns => {
2408 type => 'string',
2409 description => "the task ID.",
2410 },
9dbd1ee4
AD
2411 code => sub {
2412 my ($param) = @_;
2413
2414 my $rpcenv = PVE::RPCEnvironment::get();
2415
2416 my $authuser = $rpcenv->get_user();
2417
2418 my $node = extract_param($param, 'node');
2419
2420 my $vmid = extract_param($param, 'vmid');
2421
9dbd1ee4
AD
2422 my $snapname = extract_param($param, 'snapname');
2423
d1914468
DM
2424 die "unable to use snapshot name 'current' (reserved name)\n"
2425 if $snapname eq 'current';
2426
7e7d7b61 2427 my $realcmd = sub {
22c377f0 2428 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
75466c4f 2429 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
782f4f75 2430 $param->{freezefs}, $param->{description});
7e7d7b61
DM
2431 };
2432
2433 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2434 }});
2435
154ccdcd
DM
2436__PACKAGE__->register_method({
2437 name => 'snapshot_cmd_idx',
2438 path => '{vmid}/snapshot/{snapname}',
2439 description => '',
2440 method => 'GET',
2441 permissions => {
2442 user => 'all',
2443 },
2444 parameters => {
2445 additionalProperties => 0,
2446 properties => {
2447 vmid => get_standard_option('pve-vmid'),
2448 node => get_standard_option('pve-node'),
8abd398b 2449 snapname => get_standard_option('pve-snapshot-name'),
154ccdcd
DM
2450 },
2451 },
2452 returns => {
2453 type => 'array',
2454 items => {
2455 type => "object",
2456 properties => {},
2457 },
2458 links => [ { rel => 'child', href => "{cmd}" } ],
2459 },
2460 code => sub {
2461 my ($param) = @_;
2462
2463 my $res = [];
2464
2465 push @$res, { cmd => 'rollback' };
d788cea6 2466 push @$res, { cmd => 'config' };
154ccdcd
DM
2467
2468 return $res;
2469 }});
2470
d788cea6
DM
2471__PACKAGE__->register_method({
2472 name => 'update_snapshot_config',
2473 path => '{vmid}/snapshot/{snapname}/config',
2474 method => 'PUT',
2475 protected => 1,
2476 proxyto => 'node',
2477 description => "Update snapshot metadata.",
2478 permissions => {
2479 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2480 },
2481 parameters => {
2482 additionalProperties => 0,
2483 properties => {
2484 node => get_standard_option('pve-node'),
2485 vmid => get_standard_option('pve-vmid'),
2486 snapname => get_standard_option('pve-snapshot-name'),
2487 description => {
2488 optional => 1,
2489 type => 'string',
2490 description => "A textual description or comment.",
2491 },
2492 },
2493 },
2494 returns => { type => 'null' },
2495 code => sub {
2496 my ($param) = @_;
2497
2498 my $rpcenv = PVE::RPCEnvironment::get();
2499
2500 my $authuser = $rpcenv->get_user();
2501
2502 my $vmid = extract_param($param, 'vmid');
2503
2504 my $snapname = extract_param($param, 'snapname');
2505
2506 return undef if !defined($param->{description});
2507
2508 my $updatefn = sub {
2509
2510 my $conf = PVE::QemuServer::load_config($vmid);
2511
2512 PVE::QemuServer::check_lock($conf);
2513
2514 my $snap = $conf->{snapshots}->{$snapname};
2515
75466c4f
DM
2516 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2517
d788cea6
DM
2518 $snap->{description} = $param->{description} if defined($param->{description});
2519
2520 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2521 };
2522
2523 PVE::QemuServer::lock_config($vmid, $updatefn);
2524
2525 return undef;
2526 }});
2527
2528__PACKAGE__->register_method({
2529 name => 'get_snapshot_config',
2530 path => '{vmid}/snapshot/{snapname}/config',
2531 method => 'GET',
2532 proxyto => 'node',
2533 description => "Get snapshot configuration",
2534 permissions => {
2535 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2536 },
2537 parameters => {
2538 additionalProperties => 0,
2539 properties => {
2540 node => get_standard_option('pve-node'),
2541 vmid => get_standard_option('pve-vmid'),
2542 snapname => get_standard_option('pve-snapshot-name'),
2543 },
2544 },
2545 returns => { type => "object" },
2546 code => sub {
2547 my ($param) = @_;
2548
2549 my $rpcenv = PVE::RPCEnvironment::get();
2550
2551 my $authuser = $rpcenv->get_user();
2552
2553 my $vmid = extract_param($param, 'vmid');
2554
2555 my $snapname = extract_param($param, 'snapname');
2556
2557 my $conf = PVE::QemuServer::load_config($vmid);
2558
2559 my $snap = $conf->{snapshots}->{$snapname};
2560
75466c4f
DM
2561 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2562
d788cea6
DM
2563 return $snap;
2564 }});
2565
7e7d7b61
DM
2566__PACKAGE__->register_method({
2567 name => 'rollback',
154ccdcd 2568 path => '{vmid}/snapshot/{snapname}/rollback',
7e7d7b61
DM
2569 method => 'POST',
2570 protected => 1,
2571 proxyto => 'node',
2572 description => "Rollback VM state to specified snapshot.",
2573 permissions => {
f1baf1df 2574 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2575 },
2576 parameters => {
2577 additionalProperties => 0,
2578 properties => {
2579 node => get_standard_option('pve-node'),
2580 vmid => get_standard_option('pve-vmid'),
8abd398b 2581 snapname => get_standard_option('pve-snapshot-name'),
7e7d7b61
DM
2582 },
2583 },
2584 returns => {
2585 type => 'string',
2586 description => "the task ID.",
2587 },
2588 code => sub {
2589 my ($param) = @_;
2590
2591 my $rpcenv = PVE::RPCEnvironment::get();
2592
2593 my $authuser = $rpcenv->get_user();
2594
2595 my $node = extract_param($param, 'node');
2596
2597 my $vmid = extract_param($param, 'vmid');
2598
2599 my $snapname = extract_param($param, 'snapname');
2600
7e7d7b61 2601 my $realcmd = sub {
22c377f0
DM
2602 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
2603 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
7e7d7b61
DM
2604 };
2605
2606 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
2607 }});
2608
2609__PACKAGE__->register_method({
2610 name => 'delsnapshot',
2611 path => '{vmid}/snapshot/{snapname}',
2612 method => 'DELETE',
2613 protected => 1,
2614 proxyto => 'node',
2615 description => "Delete a VM snapshot.",
2616 permissions => {
f1baf1df 2617 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2618 },
2619 parameters => {
2620 additionalProperties => 0,
2621 properties => {
2622 node => get_standard_option('pve-node'),
2623 vmid => get_standard_option('pve-vmid'),
8abd398b 2624 snapname => get_standard_option('pve-snapshot-name'),
3ee28e38
DM
2625 force => {
2626 optional => 1,
2627 type => 'boolean',
2628 description => "For removal from config file, even if removing disk snapshots fails.",
2629 },
7e7d7b61
DM
2630 },
2631 },
2632 returns => {
2633 type => 'string',
2634 description => "the task ID.",
2635 },
2636 code => sub {
2637 my ($param) = @_;
2638
2639 my $rpcenv = PVE::RPCEnvironment::get();
2640
2641 my $authuser = $rpcenv->get_user();
2642
2643 my $node = extract_param($param, 'node');
2644
2645 my $vmid = extract_param($param, 'vmid');
2646
2647 my $snapname = extract_param($param, 'snapname');
2648
7e7d7b61 2649 my $realcmd = sub {
22c377f0 2650 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
3ee28e38 2651 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
7e7d7b61 2652 };
9dbd1ee4 2653
7b2257a8 2654 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
9dbd1ee4
AD
2655 }});
2656
04a69bb4
AD
2657__PACKAGE__->register_method({
2658 name => 'template',
2659 path => '{vmid}/template',
2660 method => 'POST',
2661 protected => 1,
2662 proxyto => 'node',
2663 description => "Create a Template.",
b02691d8 2664 permissions => {
bef4463b 2665 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}.",
75466c4f 2666 check => [ 'or',
b02691d8
SP
2667 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
2668 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
2669 ],
2670 },
04a69bb4
AD
2671 parameters => {
2672 additionalProperties => 0,
2673 properties => {
2674 node => get_standard_option('pve-node'),
2675 vmid => get_standard_option('pve-vmid'),
2676 disk => {
2677 optional => 1,
2678 type => 'string',
2679 description => "If you want to convert only 1 disk to base image.",
2680 enum => [PVE::QemuServer::disknames()],
2681 },
2682
2683 },
2684 },
2685 returns => { type => 'null'},
2686 code => sub {
2687 my ($param) = @_;
2688
2689 my $rpcenv = PVE::RPCEnvironment::get();
2690
2691 my $authuser = $rpcenv->get_user();
2692
2693 my $node = extract_param($param, 'node');
2694
2695 my $vmid = extract_param($param, 'vmid');
2696
2697 my $disk = extract_param($param, 'disk');
2698
2699 my $updatefn = sub {
2700
2701 my $conf = PVE::QemuServer::load_config($vmid);
2702
2703 PVE::QemuServer::check_lock($conf);
2704
75466c4f 2705 die "unable to create template, because VM contains snapshots\n"
b91c2aae 2706 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
0402a80b 2707
75466c4f 2708 die "you can't convert a template to a template\n"
03c2d0ad 2709 if PVE::QemuServer::is_template($conf) && !$disk;
0402a80b 2710
75466c4f 2711 die "you can't convert a VM to template if VM is running\n"
218cab9a 2712 if PVE::QemuServer::check_running($vmid);
35c5fdef 2713
04a69bb4
AD
2714 my $realcmd = sub {
2715 PVE::QemuServer::template_create($vmid, $conf, $disk);
2716 };
04a69bb4 2717
75e7e997 2718 $conf->{template} = 1;
04a69bb4 2719 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
75e7e997
DM
2720
2721 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
04a69bb4
AD
2722 };
2723
2724 PVE::QemuServer::lock_config($vmid, $updatefn);
2725 return undef;
2726 }});
2727
2728
2729
1e3baf05 27301;