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