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