]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
has_feature: add 'copy' to enum
[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 => {
1791 type => 'boolean'
1792 },
1793 code => sub {
1794 my ($param) = @_;
1795
1796 my $node = extract_param($param, 'node');
1797
1798 my $vmid = extract_param($param, 'vmid');
1799
1800 my $snapname = extract_param($param, 'snapname');
1801
1802 my $feature = extract_param($param, 'feature');
1803
1804 my $running = PVE::QemuServer::check_running($vmid);
1805
1806 my $conf = PVE::QemuServer::load_config($vmid);
1807
1808 if($snapname){
1809 my $snap = $conf->{snapshots}->{$snapname};
1810 die "snapshot '$snapname' does not exist\n" if !defined($snap);
1811 $conf = $snap;
1812 }
1813 my $storecfg = PVE::Storage::config();
1814
1815 my $hasfeature = PVE::QemuServer::has_feature($feature, $conf, $storecfg, $snapname, $running);
1816 my $res = $hasfeature ? 1 : 0 ;
1817 return $res;
1818 }});
1819
6116f729 1820__PACKAGE__->register_method({
9418baad
DM
1821 name => 'clone_vm',
1822 path => '{vmid}/clone',
6116f729
DM
1823 method => 'POST',
1824 protected => 1,
1825 proxyto => 'node',
37329185 1826 description => "Create a copy of virtual machine/template.",
6116f729 1827 permissions => {
9418baad 1828 description => "You need 'VM.Clone' permissions on /vms/{vmid}, and 'VM.Allocate' permissions " .
6116f729
DM
1829 "on /vms/{newid} (or on the VM pool /pool/{pool}). You also need " .
1830 "'Datastore.AllocateSpace' on any used storage.",
75466c4f
DM
1831 check =>
1832 [ 'and',
9418baad 1833 ['perm', '/vms/{vmid}', [ 'VM.Clone' ]],
75466c4f 1834 [ 'or',
6116f729
DM
1835 [ 'perm', '/vms/{newid}', ['VM.Allocate']],
1836 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
1837 ],
1838 ]
1839 },
1840 parameters => {
1841 additionalProperties => 0,
1842 properties => {
6116f729
DM
1843 node => get_standard_option('pve-node'),
1844 vmid => get_standard_option('pve-vmid'),
9418baad 1845 newid => get_standard_option('pve-vmid', { description => 'VMID for the clone.' }),
a60ab1a6
DM
1846 name => {
1847 optional => 1,
1848 type => 'string', format => 'dns-name',
1849 description => "Set a name for the new VM.",
1850 },
1851 description => {
1852 optional => 1,
1853 type => 'string',
1854 description => "Description for the new VM.",
1855 },
75466c4f 1856 pool => {
6116f729
DM
1857 optional => 1,
1858 type => 'string', format => 'pve-poolid',
1859 description => "Add the new VM to the specified pool.",
1860 },
9076d880
DM
1861 snapname => get_standard_option('pve-snapshot-name', {
1862 requires => 'full',
1863 optional => 1,
1864 }),
81f043eb 1865 storage => get_standard_option('pve-storage-id', {
9418baad 1866 description => "Target storage for full clone.",
4e4f83fe 1867 requires => 'full',
81f043eb
AD
1868 optional => 1,
1869 }),
55173c6b 1870 'format' => {
42a19c87
AD
1871 description => "Target format for file storage.",
1872 requires => 'full',
1873 type => 'string',
1874 optional => 1,
55173c6b 1875 enum => [ 'raw', 'qcow2', 'vmdk'],
42a19c87 1876 },
6116f729
DM
1877 full => {
1878 optional => 1,
55173c6b
DM
1879 type => 'boolean',
1880 description => "Create a full copy of all disk. This is always done when " .
9418baad 1881 "you clone a normal VM. For VM templates, we try to create a linked clone by default.",
6116f729
DM
1882 default => 0,
1883 },
75466c4f 1884 target => get_standard_option('pve-node', {
55173c6b
DM
1885 description => "Target node. Only allowed if the original VM is on shared storage.",
1886 optional => 1,
1887 }),
1888 },
6116f729
DM
1889 },
1890 returns => {
1891 type => 'string',
1892 },
1893 code => sub {
1894 my ($param) = @_;
1895
1896 my $rpcenv = PVE::RPCEnvironment::get();
1897
55173c6b 1898 my $authuser = $rpcenv->get_user();
6116f729
DM
1899
1900 my $node = extract_param($param, 'node');
1901
1902 my $vmid = extract_param($param, 'vmid');
1903
1904 my $newid = extract_param($param, 'newid');
1905
6116f729
DM
1906 my $pool = extract_param($param, 'pool');
1907
1908 if (defined($pool)) {
1909 $rpcenv->check_pool_exist($pool);
1910 }
1911
55173c6b 1912 my $snapname = extract_param($param, 'snapname');
9076d880 1913
81f043eb
AD
1914 my $storage = extract_param($param, 'storage');
1915
42a19c87
AD
1916 my $format = extract_param($param, 'format');
1917
55173c6b
DM
1918 my $target = extract_param($param, 'target');
1919
1920 my $localnode = PVE::INotify::nodename();
1921
751cc556 1922 undef $target if $target && ($target eq $localnode || $target eq 'localhost');
55173c6b
DM
1923
1924 PVE::Cluster::check_node_exists($target) if $target;
1925
6116f729
DM
1926 my $storecfg = PVE::Storage::config();
1927
55173c6b 1928 PVE::Cluster::check_cfs_quorum();
6116f729 1929
4e4f83fe
DM
1930 my $running = PVE::QemuServer::check_running($vmid) || 0;
1931
4e4f83fe
DM
1932 # exclusive lock if VM is running - else shared lock is enough;
1933 my $shared_lock = $running ? 0 : 1;
1934
9418baad 1935 my $clonefn = sub {
6116f729 1936
829967a9
DM
1937 # do all tests after lock
1938 # we also try to do all tests before we fork the worker
1939
6116f729
DM
1940 my $conf = PVE::QemuServer::load_config($vmid);
1941
1942 PVE::QemuServer::check_lock($conf);
1943
4e4f83fe 1944 my $verify_running = PVE::QemuServer::check_running($vmid) || 0;
6116f729 1945
4e4f83fe 1946 die "unexpected state change\n" if $verify_running != $running;
6116f729 1947
75466c4f
DM
1948 die "snapshot '$snapname' does not exist\n"
1949 if $snapname && !defined( $conf->{snapshots}->{$snapname});
6116f729 1950
75466c4f 1951 my $oldconf = $snapname ? $conf->{snapshots}->{$snapname} : $conf;
9076d880 1952
9418baad 1953 my $sharedvm = &$check_storage_access_clone($rpcenv, $authuser, $storecfg, $oldconf, $storage);
6116f729 1954
9418baad 1955 die "can't clone VM to node '$target' (VM uses local storage)\n" if $target && !$sharedvm;
75466c4f 1956
6116f729
DM
1957 my $conffile = PVE::QemuServer::config_file($newid);
1958
1959 die "unable to create VM $newid: config file already exists\n"
1960 if -f $conffile;
1961
9418baad 1962 my $newconf = { lock => 'clone' };
829967a9
DM
1963 my $drives = {};
1964 my $vollist = [];
1965
1966 foreach my $opt (keys %$oldconf) {
1967 my $value = $oldconf->{$opt};
1968
1969 # do not copy snapshot related info
1970 next if $opt eq 'snapshots' || $opt eq 'parent' || $opt eq 'snaptime' ||
1971 $opt eq 'vmstate' || $opt eq 'snapstate';
1972
1973 # always change MAC! address
1974 if ($opt =~ m/^net(\d+)$/) {
1975 my $net = PVE::QemuServer::parse_net($value);
1976 $net->{macaddr} = PVE::Tools::random_ether_addr();
1977 $newconf->{$opt} = PVE::QemuServer::print_net($net);
1978 } elsif (my $drive = PVE::QemuServer::parse_drive($opt, $value)) {
1979 if (PVE::QemuServer::drive_is_cdrom($drive)) {
1980 $newconf->{$opt} = $value; # simply copy configuration
1981 } else {
dba198b0 1982 if ($param->{full} || !PVE::Storage::volume_is_base($storecfg, $drive->{file})) {
2dd53043 1983 die "Full clone feature is not available"
dba198b0 1984 if !PVE::Storage::volume_has_feature($storecfg, 'copy', $drive->{file}, $snapname, $running);
2dd53043 1985 $drive->{full} = 1;
dba198b0 1986 }
829967a9
DM
1987 $drives->{$opt} = $drive;
1988 push @$vollist, $drive->{file};
1989 }
1990 } else {
1991 # copy everything else
1992 $newconf->{$opt} = $value;
1993 }
1994 }
1995
1996 delete $newconf->{template};
1997
1998 if ($param->{name}) {
1999 $newconf->{name} = $param->{name};
2000 } else {
2001 $newconf->{name} = "Copy-of-$oldconf->{name}";
2002 }
2dd53043 2003
829967a9
DM
2004 if ($param->{description}) {
2005 $newconf->{description} = $param->{description};
2006 }
2007
6116f729 2008 # create empty/temp config - this fails if VM already exists on other node
9418baad 2009 PVE::Tools::file_set_contents($conffile, "# qmclone temporary file\nlock: clone\n");
6116f729
DM
2010
2011 my $realcmd = sub {
2012 my $upid = shift;
2013
b83e0181 2014 my $newvollist = [];
6116f729 2015
b83e0181 2016 eval {
829967a9 2017 local $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = sub { die "interrupted by signal\n"; };
75466c4f 2018
6116f729
DM
2019 PVE::Storage::activate_volumes($storecfg, $vollist);
2020
829967a9
DM
2021 foreach my $opt (keys %$drives) {
2022 my $drive = $drives->{$opt};
2dd53043 2023
829967a9
DM
2024 my $newvolid;
2025 if (!$drive->{full}) {
9418baad 2026 print "create linked clone of drive $opt ($drive->{file})\n";
829967a9
DM
2027 $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newid);
2028 push @$newvollist, $newvolid;
c6d0c8a7 2029
829967a9
DM
2030 } else {
2031 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
2032 $storeid = $storage if $storage;
2033
2034 my $fmt = undef;
2035 if($format){
2036 $fmt = $format;
2037 }else{
2038 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
2039 $fmt = $drive->{format} || $defformat;
b83e0181
DM
2040 }
2041
829967a9
DM
2042 my ($size) = PVE::Storage::volume_size_info($storecfg, $drive->{file}, 3);
2043
2dd53043 2044 print "create full clone of drive $opt ($drive->{file})\n";
829967a9
DM
2045 $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $newid, $fmt, undef, ($size/1024));
2046 push @$newvollist, $newvolid;
6116f729 2047
00b095ca
AD
2048 if(!$running || $snapname){
2049 PVE::QemuServer::qemu_img_convert($drive->{file}, $newvolid, $size, $snapname);
2050 }else{
2051 PVE::QemuServer::qemu_drive_mirror($vmid, $opt, $newvolid, $newid);
2052 }
2053
b83e0181 2054 }
829967a9
DM
2055
2056 my ($size) = PVE::Storage::volume_size_info($storecfg, $newvolid, 3);
2057 my $disk = { file => $newvolid, size => $size };
2058 $newconf->{$opt} = PVE::QemuServer::print_drive($vmid, $disk);
2dd53043 2059
829967a9
DM
2060 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
2061 }
b83e0181
DM
2062
2063 delete $newconf->{lock};
2064 PVE::QemuServer::update_config_nolock($newid, $newconf, 1);
55173c6b
DM
2065
2066 if ($target) {
2067 my $newconffile = PVE::QemuServer::config_file($newid, $target);
2068 die "Failed to move config to node '$target' - rename failed: $!\n"
2069 if !rename($conffile, $newconffile);
2070 }
d703d4c0
DM
2071
2072 add_vm_to_pool($newid, $pool) if $pool;
6116f729 2073 };
75466c4f 2074 if (my $err = $@) {
6116f729
DM
2075 unlink $conffile;
2076
b83e0181
DM
2077 sleep 1; # some storage like rbd need to wait before release volume - really?
2078
2079 foreach my $volid (@$newvollist) {
2080 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2081 warn $@ if $@;
2082 }
9418baad 2083 die "clone failed: $err";
6116f729
DM
2084 }
2085
2086 return;
2087 };
2088
9418baad 2089 return $rpcenv->fork_worker('qmclone', $vmid, $authuser, $realcmd);
6116f729
DM
2090 };
2091
4e4f83fe 2092 return PVE::QemuServer::lock_config_mode($vmid, 1, $shared_lock, sub {
6116f729 2093 # Aquire exclusive lock lock for $newid
9418baad 2094 return PVE::QemuServer::lock_config_full($newid, 1, $clonefn);
6116f729
DM
2095 });
2096
2097 }});
2098
3ea94c60 2099__PACKAGE__->register_method({
afdb31d5 2100 name => 'migrate_vm',
3ea94c60
DM
2101 path => '{vmid}/migrate',
2102 method => 'POST',
2103 protected => 1,
2104 proxyto => 'node',
2105 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
2106 permissions => {
2107 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
2108 },
3ea94c60
DM
2109 parameters => {
2110 additionalProperties => 0,
2111 properties => {
2112 node => get_standard_option('pve-node'),
2113 vmid => get_standard_option('pve-vmid'),
2114 target => get_standard_option('pve-node', { description => "Target node." }),
2115 online => {
2116 type => 'boolean',
2117 description => "Use online/live migration.",
2118 optional => 1,
2119 },
2120 force => {
2121 type => 'boolean',
2122 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
2123 optional => 1,
2124 },
2125 },
2126 },
afdb31d5 2127 returns => {
3ea94c60
DM
2128 type => 'string',
2129 description => "the task ID.",
2130 },
2131 code => sub {
2132 my ($param) = @_;
2133
2134 my $rpcenv = PVE::RPCEnvironment::get();
2135
a0d1b1a2 2136 my $authuser = $rpcenv->get_user();
3ea94c60
DM
2137
2138 my $target = extract_param($param, 'target');
2139
2140 my $localnode = PVE::INotify::nodename();
2141 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
2142
2143 PVE::Cluster::check_cfs_quorum();
2144
2145 PVE::Cluster::check_node_exists($target);
2146
2147 my $targetip = PVE::Cluster::remote_node_ip($target);
2148
2149 my $vmid = extract_param($param, 'vmid');
2150
afdb31d5 2151 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 2152 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
2153
2154 # test if VM exists
a5ed42d3 2155 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
2156
2157 # try to detect errors early
a5ed42d3
DM
2158
2159 PVE::QemuServer::check_lock($conf);
2160
3ea94c60 2161 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 2162 die "cant migrate running VM without --online\n"
3ea94c60
DM
2163 if !$param->{online};
2164 }
2165
47152e2e 2166 my $storecfg = PVE::Storage::config();
22d646a7 2167 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
47152e2e 2168
3be30d63 2169 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3ea94c60 2170
88fc87b4
DM
2171 my $hacmd = sub {
2172 my $upid = shift;
3ea94c60 2173
88fc87b4
DM
2174 my $service = "pvevm:$vmid";
2175
2176 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
2177
2178 print "Executing HA migrate for VM $vmid to node $target\n";
2179
2180 PVE::Tools::run_command($cmd);
2181
2182 return;
2183 };
2184
2185 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
2186
2187 } else {
2188
2189 my $realcmd = sub {
2190 my $upid = shift;
2191
2192 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
2193 };
2194
2195 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
2196 }
3ea94c60 2197
3ea94c60 2198 }});
1e3baf05 2199
91c94f0a 2200__PACKAGE__->register_method({
afdb31d5
DM
2201 name => 'monitor',
2202 path => '{vmid}/monitor',
91c94f0a
DM
2203 method => 'POST',
2204 protected => 1,
2205 proxyto => 'node',
2206 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
2207 permissions => {
2208 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
2209 },
91c94f0a
DM
2210 parameters => {
2211 additionalProperties => 0,
2212 properties => {
2213 node => get_standard_option('pve-node'),
2214 vmid => get_standard_option('pve-vmid'),
2215 command => {
2216 type => 'string',
2217 description => "The monitor command.",
2218 }
2219 },
2220 },
2221 returns => { type => 'string'},
2222 code => sub {
2223 my ($param) = @_;
2224
2225 my $vmid = $param->{vmid};
2226
2227 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
2228
2229 my $res = '';
2230 eval {
7b7c6d1b 2231 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
91c94f0a
DM
2232 };
2233 $res = "ERROR: $@" if $@;
2234
2235 return $res;
2236 }});
2237
0d02881c
AD
2238__PACKAGE__->register_method({
2239 name => 'resize_vm',
614e3941 2240 path => '{vmid}/resize',
0d02881c
AD
2241 method => 'PUT',
2242 protected => 1,
2243 proxyto => 'node',
2f48a4f5 2244 description => "Extend volume size.",
0d02881c 2245 permissions => {
3b2773f6 2246 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
0d02881c
AD
2247 },
2248 parameters => {
2249 additionalProperties => 0,
2f48a4f5
DM
2250 properties => {
2251 node => get_standard_option('pve-node'),
2252 vmid => get_standard_option('pve-vmid'),
2253 skiplock => get_standard_option('skiplock'),
2254 disk => {
2255 type => 'string',
2256 description => "The disk you want to resize.",
2257 enum => [PVE::QemuServer::disknames()],
2258 },
2259 size => {
2260 type => 'string',
f91b2e45 2261 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2f48a4f5
DM
2262 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.",
2263 },
2264 digest => {
2265 type => 'string',
2266 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
2267 maxLength => 40,
2268 optional => 1,
2269 },
2270 },
0d02881c
AD
2271 },
2272 returns => { type => 'null'},
2273 code => sub {
2274 my ($param) = @_;
2275
2276 my $rpcenv = PVE::RPCEnvironment::get();
2277
2278 my $authuser = $rpcenv->get_user();
2279
2280 my $node = extract_param($param, 'node');
2281
2282 my $vmid = extract_param($param, 'vmid');
2283
2284 my $digest = extract_param($param, 'digest');
2285
2f48a4f5 2286 my $disk = extract_param($param, 'disk');
75466c4f 2287
2f48a4f5 2288 my $sizestr = extract_param($param, 'size');
0d02881c 2289
f91b2e45 2290 my $skiplock = extract_param($param, 'skiplock');
0d02881c
AD
2291 raise_param_exc({ skiplock => "Only root may use this option." })
2292 if $skiplock && $authuser ne 'root@pam';
2293
0d02881c
AD
2294 my $storecfg = PVE::Storage::config();
2295
0d02881c
AD
2296 my $updatefn = sub {
2297
2298 my $conf = PVE::QemuServer::load_config($vmid);
2299
2300 die "checksum missmatch (file change by other user?)\n"
2301 if $digest && $digest ne $conf->{digest};
2302 PVE::QemuServer::check_lock($conf) if !$skiplock;
2303
f91b2e45
DM
2304 die "disk '$disk' does not exist\n" if !$conf->{$disk};
2305
2306 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
2307
2308 my $volid = $drive->{file};
2309
2310 die "disk '$disk' has no associated volume\n" if !$volid;
2311
2312 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
2313
75466c4f 2314 die "you can't online resize a virtio windows bootdisk\n"
f2965e67
AD
2315 if PVE::QemuServer::check_running($vmid) && $conf->{bootdisk} eq $disk && $conf->{ostype} =~ m/^w/ && $disk =~ m/^virtio/;
2316
f91b2e45
DM
2317 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
2318
2319 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
2320
2321 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
2322
2323 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
2324 my ($ext, $newsize, $unit) = ($1, $2, $4);
2325 if ($unit) {
2326 if ($unit eq 'K') {
2327 $newsize = $newsize * 1024;
2328 } elsif ($unit eq 'M') {
2329 $newsize = $newsize * 1024 * 1024;
2330 } elsif ($unit eq 'G') {
2331 $newsize = $newsize * 1024 * 1024 * 1024;
2332 } elsif ($unit eq 'T') {
2333 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
2334 }
2335 }
2336 $newsize += $size if $ext;
2337 $newsize = int($newsize);
2338
2339 die "unable to skrink disk size\n" if $newsize < $size;
2340
2341 return if $size == $newsize;
2342
2f48a4f5 2343 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
0d02881c 2344
f91b2e45 2345 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
75466c4f 2346
f91b2e45
DM
2347 $drive->{size} = $newsize;
2348 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
2349
2350 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2351 };
0d02881c
AD
2352
2353 PVE::QemuServer::lock_config($vmid, $updatefn);
2354 return undef;
2355 }});
2356
9dbd1ee4 2357__PACKAGE__->register_method({
7e7d7b61 2358 name => 'snapshot_list',
9dbd1ee4 2359 path => '{vmid}/snapshot',
7e7d7b61
DM
2360 method => 'GET',
2361 description => "List all snapshots.",
2362 permissions => {
2363 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
2364 },
2365 proxyto => 'node',
2366 protected => 1, # qemu pid files are only readable by root
2367 parameters => {
2368 additionalProperties => 0,
2369 properties => {
2370 vmid => get_standard_option('pve-vmid'),
2371 node => get_standard_option('pve-node'),
2372 },
2373 },
2374 returns => {
2375 type => 'array',
2376 items => {
2377 type => "object",
2378 properties => {},
2379 },
2380 links => [ { rel => 'child', href => "{name}" } ],
2381 },
2382 code => sub {
2383 my ($param) = @_;
2384
6aa4651b
DM
2385 my $vmid = $param->{vmid};
2386
2387 my $conf = PVE::QemuServer::load_config($vmid);
7e7d7b61
DM
2388 my $snaphash = $conf->{snapshots} || {};
2389
2390 my $res = [];
2391
2392 foreach my $name (keys %$snaphash) {
0ea6bc69 2393 my $d = $snaphash->{$name};
75466c4f
DM
2394 my $item = {
2395 name => $name,
2396 snaptime => $d->{snaptime} || 0,
6aa4651b 2397 vmstate => $d->{vmstate} ? 1 : 0,
982c7f12
DM
2398 description => $d->{description} || '',
2399 };
0ea6bc69 2400 $item->{parent} = $d->{parent} if $d->{parent};
3ee28e38 2401 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
0ea6bc69
DM
2402 push @$res, $item;
2403 }
2404
6aa4651b
DM
2405 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
2406 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
d1914468
DM
2407 $current->{parent} = $conf->{parent} if $conf->{parent};
2408
2409 push @$res, $current;
7e7d7b61
DM
2410
2411 return $res;
2412 }});
2413
2414__PACKAGE__->register_method({
2415 name => 'snapshot',
2416 path => '{vmid}/snapshot',
2417 method => 'POST',
9dbd1ee4
AD
2418 protected => 1,
2419 proxyto => 'node',
2420 description => "Snapshot a VM.",
2421 permissions => {
f1baf1df 2422 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
9dbd1ee4
AD
2423 },
2424 parameters => {
2425 additionalProperties => 0,
2426 properties => {
2427 node => get_standard_option('pve-node'),
2428 vmid => get_standard_option('pve-vmid'),
8abd398b 2429 snapname => get_standard_option('pve-snapshot-name'),
9dbd1ee4
AD
2430 vmstate => {
2431 optional => 1,
2432 type => 'boolean',
2433 description => "Save the vmstate",
2434 },
2435 freezefs => {
2436 optional => 1,
2437 type => 'boolean',
2438 description => "Freeze the filesystem",
2439 },
782f4f75
DM
2440 description => {
2441 optional => 1,
2442 type => 'string',
2443 description => "A textual description or comment.",
2444 },
9dbd1ee4
AD
2445 },
2446 },
7e7d7b61
DM
2447 returns => {
2448 type => 'string',
2449 description => "the task ID.",
2450 },
9dbd1ee4
AD
2451 code => sub {
2452 my ($param) = @_;
2453
2454 my $rpcenv = PVE::RPCEnvironment::get();
2455
2456 my $authuser = $rpcenv->get_user();
2457
2458 my $node = extract_param($param, 'node');
2459
2460 my $vmid = extract_param($param, 'vmid');
2461
9dbd1ee4
AD
2462 my $snapname = extract_param($param, 'snapname');
2463
d1914468
DM
2464 die "unable to use snapshot name 'current' (reserved name)\n"
2465 if $snapname eq 'current';
2466
7e7d7b61 2467 my $realcmd = sub {
22c377f0 2468 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
75466c4f 2469 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
782f4f75 2470 $param->{freezefs}, $param->{description});
7e7d7b61
DM
2471 };
2472
2473 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2474 }});
2475
154ccdcd
DM
2476__PACKAGE__->register_method({
2477 name => 'snapshot_cmd_idx',
2478 path => '{vmid}/snapshot/{snapname}',
2479 description => '',
2480 method => 'GET',
2481 permissions => {
2482 user => 'all',
2483 },
2484 parameters => {
2485 additionalProperties => 0,
2486 properties => {
2487 vmid => get_standard_option('pve-vmid'),
2488 node => get_standard_option('pve-node'),
8abd398b 2489 snapname => get_standard_option('pve-snapshot-name'),
154ccdcd
DM
2490 },
2491 },
2492 returns => {
2493 type => 'array',
2494 items => {
2495 type => "object",
2496 properties => {},
2497 },
2498 links => [ { rel => 'child', href => "{cmd}" } ],
2499 },
2500 code => sub {
2501 my ($param) = @_;
2502
2503 my $res = [];
2504
2505 push @$res, { cmd => 'rollback' };
d788cea6 2506 push @$res, { cmd => 'config' };
154ccdcd
DM
2507
2508 return $res;
2509 }});
2510
d788cea6
DM
2511__PACKAGE__->register_method({
2512 name => 'update_snapshot_config',
2513 path => '{vmid}/snapshot/{snapname}/config',
2514 method => 'PUT',
2515 protected => 1,
2516 proxyto => 'node',
2517 description => "Update snapshot metadata.",
2518 permissions => {
2519 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2520 },
2521 parameters => {
2522 additionalProperties => 0,
2523 properties => {
2524 node => get_standard_option('pve-node'),
2525 vmid => get_standard_option('pve-vmid'),
2526 snapname => get_standard_option('pve-snapshot-name'),
2527 description => {
2528 optional => 1,
2529 type => 'string',
2530 description => "A textual description or comment.",
2531 },
2532 },
2533 },
2534 returns => { type => 'null' },
2535 code => sub {
2536 my ($param) = @_;
2537
2538 my $rpcenv = PVE::RPCEnvironment::get();
2539
2540 my $authuser = $rpcenv->get_user();
2541
2542 my $vmid = extract_param($param, 'vmid');
2543
2544 my $snapname = extract_param($param, 'snapname');
2545
2546 return undef if !defined($param->{description});
2547
2548 my $updatefn = sub {
2549
2550 my $conf = PVE::QemuServer::load_config($vmid);
2551
2552 PVE::QemuServer::check_lock($conf);
2553
2554 my $snap = $conf->{snapshots}->{$snapname};
2555
75466c4f
DM
2556 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2557
d788cea6
DM
2558 $snap->{description} = $param->{description} if defined($param->{description});
2559
2560 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2561 };
2562
2563 PVE::QemuServer::lock_config($vmid, $updatefn);
2564
2565 return undef;
2566 }});
2567
2568__PACKAGE__->register_method({
2569 name => 'get_snapshot_config',
2570 path => '{vmid}/snapshot/{snapname}/config',
2571 method => 'GET',
2572 proxyto => 'node',
2573 description => "Get snapshot configuration",
2574 permissions => {
2575 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2576 },
2577 parameters => {
2578 additionalProperties => 0,
2579 properties => {
2580 node => get_standard_option('pve-node'),
2581 vmid => get_standard_option('pve-vmid'),
2582 snapname => get_standard_option('pve-snapshot-name'),
2583 },
2584 },
2585 returns => { type => "object" },
2586 code => sub {
2587 my ($param) = @_;
2588
2589 my $rpcenv = PVE::RPCEnvironment::get();
2590
2591 my $authuser = $rpcenv->get_user();
2592
2593 my $vmid = extract_param($param, 'vmid');
2594
2595 my $snapname = extract_param($param, 'snapname');
2596
2597 my $conf = PVE::QemuServer::load_config($vmid);
2598
2599 my $snap = $conf->{snapshots}->{$snapname};
2600
75466c4f
DM
2601 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2602
d788cea6
DM
2603 return $snap;
2604 }});
2605
7e7d7b61
DM
2606__PACKAGE__->register_method({
2607 name => 'rollback',
154ccdcd 2608 path => '{vmid}/snapshot/{snapname}/rollback',
7e7d7b61
DM
2609 method => 'POST',
2610 protected => 1,
2611 proxyto => 'node',
2612 description => "Rollback VM state to specified snapshot.",
2613 permissions => {
f1baf1df 2614 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2615 },
2616 parameters => {
2617 additionalProperties => 0,
2618 properties => {
2619 node => get_standard_option('pve-node'),
2620 vmid => get_standard_option('pve-vmid'),
8abd398b 2621 snapname => get_standard_option('pve-snapshot-name'),
7e7d7b61
DM
2622 },
2623 },
2624 returns => {
2625 type => 'string',
2626 description => "the task ID.",
2627 },
2628 code => sub {
2629 my ($param) = @_;
2630
2631 my $rpcenv = PVE::RPCEnvironment::get();
2632
2633 my $authuser = $rpcenv->get_user();
2634
2635 my $node = extract_param($param, 'node');
2636
2637 my $vmid = extract_param($param, 'vmid');
2638
2639 my $snapname = extract_param($param, 'snapname');
2640
7e7d7b61 2641 my $realcmd = sub {
22c377f0
DM
2642 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
2643 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
7e7d7b61
DM
2644 };
2645
2646 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
2647 }});
2648
2649__PACKAGE__->register_method({
2650 name => 'delsnapshot',
2651 path => '{vmid}/snapshot/{snapname}',
2652 method => 'DELETE',
2653 protected => 1,
2654 proxyto => 'node',
2655 description => "Delete a VM snapshot.",
2656 permissions => {
f1baf1df 2657 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2658 },
2659 parameters => {
2660 additionalProperties => 0,
2661 properties => {
2662 node => get_standard_option('pve-node'),
2663 vmid => get_standard_option('pve-vmid'),
8abd398b 2664 snapname => get_standard_option('pve-snapshot-name'),
3ee28e38
DM
2665 force => {
2666 optional => 1,
2667 type => 'boolean',
2668 description => "For removal from config file, even if removing disk snapshots fails.",
2669 },
7e7d7b61
DM
2670 },
2671 },
2672 returns => {
2673 type => 'string',
2674 description => "the task ID.",
2675 },
2676 code => sub {
2677 my ($param) = @_;
2678
2679 my $rpcenv = PVE::RPCEnvironment::get();
2680
2681 my $authuser = $rpcenv->get_user();
2682
2683 my $node = extract_param($param, 'node');
2684
2685 my $vmid = extract_param($param, 'vmid');
2686
2687 my $snapname = extract_param($param, 'snapname');
2688
7e7d7b61 2689 my $realcmd = sub {
22c377f0 2690 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
3ee28e38 2691 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
7e7d7b61 2692 };
9dbd1ee4 2693
7b2257a8 2694 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
9dbd1ee4
AD
2695 }});
2696
04a69bb4
AD
2697__PACKAGE__->register_method({
2698 name => 'template',
2699 path => '{vmid}/template',
2700 method => 'POST',
2701 protected => 1,
2702 proxyto => 'node',
2703 description => "Create a Template.",
b02691d8 2704 permissions => {
7af0a6c8
DM
2705 description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
2706 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
b02691d8 2707 },
04a69bb4
AD
2708 parameters => {
2709 additionalProperties => 0,
2710 properties => {
2711 node => get_standard_option('pve-node'),
2712 vmid => get_standard_option('pve-vmid'),
2713 disk => {
2714 optional => 1,
2715 type => 'string',
2716 description => "If you want to convert only 1 disk to base image.",
2717 enum => [PVE::QemuServer::disknames()],
2718 },
2719
2720 },
2721 },
2722 returns => { type => 'null'},
2723 code => sub {
2724 my ($param) = @_;
2725
2726 my $rpcenv = PVE::RPCEnvironment::get();
2727
2728 my $authuser = $rpcenv->get_user();
2729
2730 my $node = extract_param($param, 'node');
2731
2732 my $vmid = extract_param($param, 'vmid');
2733
2734 my $disk = extract_param($param, 'disk');
2735
2736 my $updatefn = sub {
2737
2738 my $conf = PVE::QemuServer::load_config($vmid);
2739
2740 PVE::QemuServer::check_lock($conf);
2741
75466c4f 2742 die "unable to create template, because VM contains snapshots\n"
b91c2aae 2743 if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
0402a80b 2744
75466c4f 2745 die "you can't convert a template to a template\n"
03c2d0ad 2746 if PVE::QemuServer::is_template($conf) && !$disk;
0402a80b 2747
75466c4f 2748 die "you can't convert a VM to template if VM is running\n"
218cab9a 2749 if PVE::QemuServer::check_running($vmid);
35c5fdef 2750
04a69bb4
AD
2751 my $realcmd = sub {
2752 PVE::QemuServer::template_create($vmid, $conf, $disk);
2753 };
04a69bb4 2754
75e7e997 2755 $conf->{template} = 1;
04a69bb4 2756 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
75e7e997
DM
2757
2758 return $rpcenv->fork_worker('qmtemplate', $vmid, $authuser, $realcmd);
04a69bb4
AD
2759 };
2760
2761 PVE::QemuServer::lock_config($vmid, $updatefn);
2762 return undef;
2763 }});
2764
1e3baf05 27651;