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