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