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