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