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