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