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