]> git.proxmox.com Git - qemu-server.git/blame - PVE/API2/Qemu.pm
fix memory leak in QMP Client (many thanks to Stefan!)
[qemu-server.git] / PVE / API2 / Qemu.pm
CommitLineData
1e3baf05
DM
1package PVE::API2::Qemu;
2
3use strict;
4use warnings;
5b9d692a 5use Cwd 'abs_path';
1e3baf05 6
502d18a2 7use PVE::Cluster qw (cfs_read_file cfs_write_file);;
1e3baf05
DM
8use PVE::SafeSyslog;
9use PVE::Tools qw(extract_param);
10use PVE::Exception qw(raise raise_param_exc);
11use PVE::Storage;
12use PVE::JSONSchema qw(get_standard_option);
13use PVE::RESTHandler;
14use PVE::QemuServer;
3ea94c60 15use PVE::QemuMigrate;
1e3baf05
DM
16use PVE::RPCEnvironment;
17use PVE::AccessControl;
18use PVE::INotify;
19
20use Data::Dumper; # fixme: remove
21
22use base qw(PVE::RESTHandler);
23
24my $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.";
25
26my $resolve_cdrom_alias = sub {
27 my $param = shift;
28
29 if (my $value = $param->{cdrom}) {
30 $value .= ",media=cdrom" if $value !~ m/media=/;
31 $param->{ide2} = $value;
32 delete $param->{cdrom};
33 }
34};
35
a0d1b1a2 36
ae57f6b3 37my $check_storage_access = sub {
fcbb753e 38 my ($rpcenv, $authuser, $storecfg, $vmid, $settings, $default_storage) = @_;
a0d1b1a2 39
ae57f6b3
DM
40 PVE::QemuServer::foreach_drive($settings, sub {
41 my ($ds, $drive) = @_;
a0d1b1a2 42
ae57f6b3 43 my $isCDROM = PVE::QemuServer::drive_is_cdrom($drive);
a0d1b1a2 44
ae57f6b3 45 my $volid = $drive->{file};
a0d1b1a2 46
09d0ee64
DM
47 if (!$volid || $volid eq 'none') {
48 # nothing to check
f5782fd0
DM
49 } elsif ($isCDROM && ($volid eq 'cdrom')) {
50 $rpcenv->check($authuser, "/", ['Sys.Console']);
09d0ee64 51 } elsif (!$isCDROM && ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/)) {
a0d1b1a2
DM
52 my ($storeid, $size) = ($2 || $default_storage, $3);
53 die "no storage ID specified (and no default storage)\n" if !$storeid;
fcbb753e 54 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
a0d1b1a2 55 } else {
8b192abf 56 $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $volid);
a0d1b1a2
DM
57 }
58 });
ae57f6b3 59};
a0d1b1a2 60
ae57f6b3
DM
61# Note: $pool is only needed when creating a VM, because pool permissions
62# are automatically inherited if VM already exists inside a pool.
63my $create_disks = sub {
64 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $settings, $default_storage) = @_;
a0d1b1a2
DM
65
66 my $vollist = [];
a0d1b1a2 67
ae57f6b3
DM
68 my $res = {};
69 PVE::QemuServer::foreach_drive($settings, sub {
70 my ($ds, $disk) = @_;
71
72 my $volid = $disk->{file};
73
f5782fd0 74 if (!$volid || $volid eq 'none' || $volid eq 'cdrom') {
09d0ee64
DM
75 $res->{$ds} = $settings->{$ds};
76 } elsif ($volid =~ m/^(([^:\s]+):)?(\d+(\.\d+)?)$/) {
ae57f6b3
DM
77 my ($storeid, $size) = ($2 || $default_storage, $3);
78 die "no storage ID specified (and no default storage)\n" if !$storeid;
79 my $defformat = PVE::Storage::storage_default_format($storecfg, $storeid);
80 my $fmt = $disk->{format} || $defformat;
a0d1b1a2
DM
81 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid,
82 $fmt, undef, $size*1024*1024);
a0d1b1a2 83 $disk->{file} = $volid;
24afaca0 84 $disk->{size} = $size*1024*1024*1024;
a0d1b1a2 85 push @$vollist, $volid;
ae57f6b3
DM
86 delete $disk->{format}; # no longer needed
87 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
88 } else {
eabe0da0 89
ba68cf09 90 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $volid);
eabe0da0
DM
91
92 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
35cb731c 93
35cb731c
AD
94 my $foundvolid = undef;
95
eabe0da0
DM
96 if ($storeid) {
97 PVE::Storage::activate_volumes($storecfg, [ $volid ]);
98 my $dl = PVE::Storage::vdisk_list($storecfg, $storeid, undef);
99
100 PVE::Storage::foreach_volid($dl, sub {
101 my ($volumeid) = @_;
102 if($volumeid eq $volid) {
103 $foundvolid = 1;
104 return;
105 }
106 });
107 }
35cb731c
AD
108
109 die "image '$path' does not exists\n" if (!(-f $path || -b $path || $foundvolid));
24afaca0
DM
110
111 my ($size) = PVE::Storage::volume_size_info($storecfg, $volid, 1);
112 $disk->{size} = $size;
113 $res->{$ds} = PVE::QemuServer::print_drive($vmid, $disk);
a0d1b1a2 114 }
ae57f6b3 115 });
a0d1b1a2
DM
116
117 # free allocated images on error
118 if (my $err = $@) {
119 syslog('err', "VM $vmid creating disks failed");
120 foreach my $volid (@$vollist) {
121 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
122 warn $@ if $@;
123 }
124 die $err;
125 }
126
127 # modify vm config if everything went well
ae57f6b3
DM
128 foreach my $ds (keys %$res) {
129 $conf->{$ds} = $res->{$ds};
a0d1b1a2
DM
130 }
131
132 return $vollist;
133};
134
135my $check_vm_modify_config_perm = sub {
ae57f6b3 136 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
a0d1b1a2 137
6e5c4da7 138 return 1 if $authuser eq 'root@pam';
a0d1b1a2 139
ae57f6b3 140 foreach my $opt (@$key_list) {
a0d1b1a2
DM
141 # disk checks need to be done somewhere else
142 next if PVE::QemuServer::valid_drivename($opt);
143
144 if ($opt eq 'sockets' || $opt eq 'cores' ||
145 $opt eq 'cpu' || $opt eq 'smp' ||
ab6b35df 146 $opt eq 'cpulimit' || $opt eq 'cpuunits') {
a0d1b1a2
DM
147 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
148 } elsif ($opt eq 'boot' || $opt eq 'bootdisk') {
149 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
150 } elsif ($opt eq 'memory' || $opt eq 'balloon') {
151 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
152 } elsif ($opt eq 'args' || $opt eq 'lock') {
153 die "only root can set '$opt' config\n";
154 } elsif ($opt eq 'cpu' || $opt eq 'kvm' || $opt eq 'acpi' ||
155 $opt eq 'vga' || $opt eq 'watchdog' || $opt eq 'tablet') {
156 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.HWType']);
157 } elsif ($opt =~ m/^net\d+$/) {
158 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
159 } else {
160 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
161 }
162 }
163
164 return 1;
165};
166
1e3baf05 167__PACKAGE__->register_method({
afdb31d5
DM
168 name => 'vmlist',
169 path => '',
1e3baf05
DM
170 method => 'GET',
171 description => "Virtual machine index (per node).",
a0d1b1a2
DM
172 permissions => {
173 description => "Only list VMs where you have VM.Audit permissons on /vms/<vmid>.",
174 user => 'all',
175 },
1e3baf05
DM
176 proxyto => 'node',
177 protected => 1, # qemu pid files are only readable by root
178 parameters => {
179 additionalProperties => 0,
180 properties => {
181 node => get_standard_option('pve-node'),
182 },
183 },
184 returns => {
185 type => 'array',
186 items => {
187 type => "object",
188 properties => {},
189 },
190 links => [ { rel => 'child', href => "{vmid}" } ],
191 },
192 code => sub {
193 my ($param) = @_;
194
a0d1b1a2
DM
195 my $rpcenv = PVE::RPCEnvironment::get();
196 my $authuser = $rpcenv->get_user();
197
1e3baf05
DM
198 my $vmstatus = PVE::QemuServer::vmstatus();
199
a0d1b1a2
DM
200 my $res = [];
201 foreach my $vmid (keys %$vmstatus) {
202 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
203
204 my $data = $vmstatus->{$vmid};
205 $data->{vmid} = $vmid;
206 push @$res, $data;
207 }
1e3baf05 208
a0d1b1a2 209 return $res;
1e3baf05
DM
210 }});
211
212__PACKAGE__->register_method({
afdb31d5
DM
213 name => 'create_vm',
214 path => '',
1e3baf05 215 method => 'POST',
3e16d5fc 216 description => "Create or restore a virtual machine.",
a0d1b1a2
DM
217 permissions => {
218 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. If you create disks you need 'Datastore.AllocateSpace' on any used storage.",
219 check => [ 'or',
220 [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
221 [ 'perm', '/pool/{pool}', ['VM.Allocate'], require_param => 'pool'],
222 ],
223 },
1e3baf05
DM
224 protected => 1,
225 proxyto => 'node',
226 parameters => {
227 additionalProperties => 0,
228 properties => PVE::QemuServer::json_config_properties(
229 {
230 node => get_standard_option('pve-node'),
231 vmid => get_standard_option('pve-vmid'),
3e16d5fc
DM
232 archive => {
233 description => "The backup file.",
234 type => 'string',
235 optional => 1,
236 maxLength => 255,
237 },
238 storage => get_standard_option('pve-storage-id', {
239 description => "Default storage.",
240 optional => 1,
241 }),
242 force => {
afdb31d5 243 optional => 1,
3e16d5fc
DM
244 type => 'boolean',
245 description => "Allow to overwrite existing VM.",
51586c3a
DM
246 requires => 'archive',
247 },
248 unique => {
afdb31d5 249 optional => 1,
51586c3a
DM
250 type => 'boolean',
251 description => "Assign a unique random ethernet address.",
252 requires => 'archive',
3e16d5fc 253 },
a0d1b1a2
DM
254 pool => {
255 optional => 1,
256 type => 'string', format => 'pve-poolid',
257 description => "Add the VM to the specified pool.",
258 },
1e3baf05
DM
259 }),
260 },
afdb31d5 261 returns => {
5fdbe4f0
DM
262 type => 'string',
263 },
1e3baf05
DM
264 code => sub {
265 my ($param) = @_;
266
5fdbe4f0
DM
267 my $rpcenv = PVE::RPCEnvironment::get();
268
a0d1b1a2 269 my $authuser = $rpcenv->get_user();
5fdbe4f0 270
1e3baf05
DM
271 my $node = extract_param($param, 'node');
272
1e3baf05
DM
273 my $vmid = extract_param($param, 'vmid');
274
3e16d5fc
DM
275 my $archive = extract_param($param, 'archive');
276
277 my $storage = extract_param($param, 'storage');
278
51586c3a
DM
279 my $force = extract_param($param, 'force');
280
281 my $unique = extract_param($param, 'unique');
a0d1b1a2
DM
282
283 my $pool = extract_param($param, 'pool');
51586c3a 284
1e3baf05 285 my $filename = PVE::QemuServer::config_file($vmid);
afdb31d5
DM
286
287 my $storecfg = PVE::Storage::config();
1e3baf05 288
3e16d5fc 289 PVE::Cluster::check_cfs_quorum();
1e3baf05 290
a0d1b1a2
DM
291 if (defined($pool)) {
292 $rpcenv->check_pool_exist($pool);
a0d1b1a2
DM
293 }
294
fcbb753e 295 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace'])
a0d1b1a2
DM
296 if defined($storage);
297
afdb31d5 298 if (!$archive) {
3e16d5fc 299 &$resolve_cdrom_alias($param);
1e3baf05 300
fcbb753e 301 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param, $storage);
ae57f6b3
DM
302
303 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
304
3e16d5fc
DM
305 foreach my $opt (keys %$param) {
306 if (PVE::QemuServer::valid_drivename($opt)) {
307 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
308 raise_param_exc({ $opt => "unable to parse drive options" }) if !$drive;
afdb31d5 309
3e16d5fc
DM
310 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
311 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
312 }
1e3baf05 313 }
3e16d5fc
DM
314
315 PVE::QemuServer::add_random_macs($param);
51586c3a
DM
316 } else {
317 my $keystr = join(' ', keys %$param);
bc4dcb99
DM
318 raise_param_exc({ archive => "option conflicts with other options ($keystr)"}) if $keystr;
319
5b9d692a 320 if ($archive eq '-') {
afdb31d5 321 die "pipe requires cli environment\n"
d7810bc1 322 if $rpcenv->{type} ne 'cli';
5b9d692a 323 } else {
ba68cf09 324 my $path = $rpcenv->check_volume_access($authuser, $storecfg, $vmid, $archive);
d7810bc1
DM
325
326 PVE::Storage::activate_volumes($storecfg, [ $archive ])
327 if PVE::Storage::parse_volume_id ($archive, 1);
328
971f27c4
DM
329 die "can't find archive file '$archive'\n" if !($path && -f $path);
330 $archive = $path;
331 }
1e3baf05
DM
332 }
333
502d18a2
DM
334 my $addVMtoPoolFn = sub {
335 my $usercfg = cfs_read_file("user.cfg");
336 if (my $data = $usercfg->{pools}->{$pool}) {
337 $data->{vms}->{$vmid} = 1;
338 $usercfg->{vms}->{$vmid} = $pool;
339 cfs_write_file("user.cfg", $usercfg);
340 }
341 };
342
3e16d5fc
DM
343 my $restorefn = sub {
344
345 if (-f $filename) {
afdb31d5 346 die "unable to restore vm $vmid: config file already exists\n"
51586c3a 347 if !$force;
3e16d5fc 348
afdb31d5 349 die "unable to restore vm $vmid: vm is running\n"
3e16d5fc 350 if PVE::QemuServer::check_running($vmid);
a6af7b3e
DM
351
352 # destroy existing data - keep empty config
353 PVE::QemuServer::destroy_vm($storecfg, $vmid, 1);
3e16d5fc
DM
354 }
355
356 my $realcmd = sub {
a0d1b1a2 357 PVE::QemuServer::restore_archive($archive, $vmid, $authuser, {
51586c3a 358 storage => $storage,
a0d1b1a2 359 pool => $pool,
51586c3a 360 unique => $unique });
502d18a2
DM
361
362 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
3e16d5fc
DM
363 };
364
a0d1b1a2 365 return $rpcenv->fork_worker('qmrestore', $vmid, $authuser, $realcmd);
3e16d5fc 366 };
1e3baf05 367
1e3baf05
DM
368 my $createfn = sub {
369
191435c6 370 # test after locking
afdb31d5 371 die "unable to create vm $vmid: config file already exists\n"
1e3baf05
DM
372 if -f $filename;
373
5fdbe4f0 374 my $realcmd = sub {
1e3baf05 375
5fdbe4f0 376 my $vollist = [];
1e3baf05 377
1858638f
DM
378 my $conf = $param;
379
5fdbe4f0 380 eval {
ae57f6b3 381
1858638f 382 $vollist = &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, $pool, $param, $storage);
1e3baf05 383
5fdbe4f0
DM
384 # try to be smart about bootdisk
385 my @disks = PVE::QemuServer::disknames();
386 my $firstdisk;
387 foreach my $ds (reverse @disks) {
1858638f
DM
388 next if !$conf->{$ds};
389 my $disk = PVE::QemuServer::parse_drive($ds, $conf->{$ds});
5fdbe4f0
DM
390 next if PVE::QemuServer::drive_is_cdrom($disk);
391 $firstdisk = $ds;
392 }
1e3baf05 393
1858638f
DM
394 if (!$conf->{bootdisk} && $firstdisk) {
395 $conf->{bootdisk} = $firstdisk;
5fdbe4f0 396 }
1e3baf05 397
ae9ca91d
DM
398 PVE::QemuServer::update_config_nolock($vmid, $conf);
399
5fdbe4f0
DM
400 };
401 my $err = $@;
1e3baf05 402
5fdbe4f0
DM
403 if ($err) {
404 foreach my $volid (@$vollist) {
405 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
406 warn $@ if $@;
407 }
408 die "create failed - $err";
409 }
502d18a2
DM
410
411 PVE::AccessControl::lock_user_config($addVMtoPoolFn, "can't add VM to pool") if $pool;
5fdbe4f0
DM
412 };
413
a0d1b1a2 414 return $rpcenv->fork_worker('qmcreate', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
415 };
416
191435c6 417 return PVE::QemuServer::lock_config_full($vmid, 1, $archive ? $restorefn : $createfn);
1e3baf05
DM
418 }});
419
420__PACKAGE__->register_method({
421 name => 'vmdiridx',
afdb31d5 422 path => '{vmid}',
1e3baf05
DM
423 method => 'GET',
424 proxyto => 'node',
425 description => "Directory index",
a0d1b1a2
DM
426 permissions => {
427 user => 'all',
428 },
1e3baf05
DM
429 parameters => {
430 additionalProperties => 0,
431 properties => {
432 node => get_standard_option('pve-node'),
433 vmid => get_standard_option('pve-vmid'),
434 },
435 },
436 returns => {
437 type => 'array',
438 items => {
439 type => "object",
440 properties => {
441 subdir => { type => 'string' },
442 },
443 },
444 links => [ { rel => 'child', href => "{subdir}" } ],
445 },
446 code => sub {
447 my ($param) = @_;
448
449 my $res = [
450 { subdir => 'config' },
451 { subdir => 'status' },
452 { subdir => 'unlink' },
453 { subdir => 'vncproxy' },
3ea94c60 454 { subdir => 'migrate' },
2f48a4f5 455 { subdir => 'resize' },
1e3baf05
DM
456 { subdir => 'rrd' },
457 { subdir => 'rrddata' },
91c94f0a 458 { subdir => 'monitor' },
7e7d7b61 459 { subdir => 'snapshot' },
1e3baf05 460 ];
afdb31d5 461
1e3baf05
DM
462 return $res;
463 }});
464
465__PACKAGE__->register_method({
afdb31d5
DM
466 name => 'rrd',
467 path => '{vmid}/rrd',
1e3baf05
DM
468 method => 'GET',
469 protected => 1, # fixme: can we avoid that?
470 permissions => {
378b359e 471 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
472 },
473 description => "Read VM RRD statistics (returns PNG)",
474 parameters => {
475 additionalProperties => 0,
476 properties => {
477 node => get_standard_option('pve-node'),
478 vmid => get_standard_option('pve-vmid'),
479 timeframe => {
480 description => "Specify the time frame you are interested in.",
481 type => 'string',
482 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
483 },
484 ds => {
485 description => "The list of datasources you want to display.",
486 type => 'string', format => 'pve-configid-list',
487 },
488 cf => {
489 description => "The RRD consolidation function",
490 type => 'string',
491 enum => [ 'AVERAGE', 'MAX' ],
492 optional => 1,
493 },
494 },
495 },
496 returns => {
497 type => "object",
498 properties => {
499 filename => { type => 'string' },
500 },
501 },
502 code => sub {
503 my ($param) = @_;
504
505 return PVE::Cluster::create_rrd_graph(
afdb31d5 506 "pve2-vm/$param->{vmid}", $param->{timeframe},
1e3baf05 507 $param->{ds}, $param->{cf});
afdb31d5 508
1e3baf05
DM
509 }});
510
511__PACKAGE__->register_method({
afdb31d5
DM
512 name => 'rrddata',
513 path => '{vmid}/rrddata',
1e3baf05
DM
514 method => 'GET',
515 protected => 1, # fixme: can we avoid that?
516 permissions => {
378b359e 517 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1e3baf05
DM
518 },
519 description => "Read VM RRD statistics",
520 parameters => {
521 additionalProperties => 0,
522 properties => {
523 node => get_standard_option('pve-node'),
524 vmid => get_standard_option('pve-vmid'),
525 timeframe => {
526 description => "Specify the time frame you are interested in.",
527 type => 'string',
528 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
529 },
530 cf => {
531 description => "The RRD consolidation function",
532 type => 'string',
533 enum => [ 'AVERAGE', 'MAX' ],
534 optional => 1,
535 },
536 },
537 },
538 returns => {
539 type => "array",
540 items => {
541 type => "object",
542 properties => {},
543 },
544 },
545 code => sub {
546 my ($param) = @_;
547
548 return PVE::Cluster::create_rrd_data(
549 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
550 }});
551
552
553__PACKAGE__->register_method({
afdb31d5
DM
554 name => 'vm_config',
555 path => '{vmid}/config',
1e3baf05
DM
556 method => 'GET',
557 proxyto => 'node',
558 description => "Get virtual machine configuration.",
a0d1b1a2
DM
559 permissions => {
560 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
561 },
1e3baf05
DM
562 parameters => {
563 additionalProperties => 0,
564 properties => {
565 node => get_standard_option('pve-node'),
566 vmid => get_standard_option('pve-vmid'),
567 },
568 },
afdb31d5 569 returns => {
1e3baf05 570 type => "object",
554ac7e7
DM
571 properties => {
572 digest => {
573 type => 'string',
574 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
575 }
576 },
1e3baf05
DM
577 },
578 code => sub {
579 my ($param) = @_;
580
581 my $conf = PVE::QemuServer::load_config($param->{vmid});
582
22c377f0
DM
583 delete $conf->{snapshots};
584
1e3baf05
DM
585 return $conf;
586 }});
587
ae57f6b3
DM
588my $vm_is_volid_owner = sub {
589 my ($storecfg, $vmid, $volid) =@_;
590
591 if ($volid !~ m|^/|) {
592 my ($path, $owner);
593 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
594 if ($owner && ($owner == $vmid)) {
595 return 1;
596 }
597 }
598
599 return undef;
600};
601
602my $test_deallocate_drive = sub {
603 my ($storecfg, $vmid, $key, $drive, $force) = @_;
604
605 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
606 my $volid = $drive->{file};
607 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
608 if ($force || $key =~ m/^unused/) {
609 my $sid = PVE::Storage::parse_volume_id($volid);
610 return $sid;
611 }
612 }
613 }
614
615 return undef;
616};
617
5d7a6767 618my $delete_drive = sub {
1858638f 619 my ($conf, $storecfg, $vmid, $key, $drive, $force) = @_;
5d7a6767
DM
620
621 if (!PVE::QemuServer::drive_is_cdrom($drive)) {
622 my $volid = $drive->{file};
ae57f6b3
DM
623 if (&$vm_is_volid_owner($storecfg, $vmid, $volid)) {
624 if ($force || $key =~ m/^unused/) {
625 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
7e4e69a6 626 die $@ if $@;
ae57f6b3
DM
627 } else {
628 PVE::QemuServer::add_unused_volume($conf, $volid, $vmid);
5d7a6767 629 }
ae57f6b3
DM
630 }
631 }
49f9db93
DM
632
633 delete $conf->{$key};
ae57f6b3
DM
634};
635
636my $vmconfig_delete_option = sub {
637 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force) = @_;
638
639 return if !defined($conf->{$opt});
640
641 my $isDisk = PVE::QemuServer::valid_drivename($opt)|| ($opt =~ m/^unused/);
642
643 if ($isDisk) {
644 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
645
646 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
647 if (my $sid = &$test_deallocate_drive($storecfg, $vmid, $opt, $drive, $force)) {
fcbb753e 648 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.Allocate']);
5d7a6767 649 }
ae57f6b3
DM
650 }
651
652 die "error hot-unplug $opt" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
653
654 if ($isDisk) {
655 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
656 &$delete_drive($conf, $storecfg, $vmid, $opt, $drive, $force);
5d7a6767 657 } else {
ae57f6b3
DM
658 delete $conf->{$opt};
659 }
660
661 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
662};
663
9bf371a6 664my $safe_num_ne = sub {
93ae06e1
DM
665 my ($a, $b) = @_;
666
667 return 0 if !defined($a) && !defined($b);
668 return 1 if !defined($a);
669 return 1 if !defined($b);
670
671 return $a != $b;
672};
673
ae57f6b3
DM
674my $vmconfig_update_disk = sub {
675 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value, $force) = @_;
5d7a6767 676
ae57f6b3
DM
677 my $drive = PVE::QemuServer::parse_drive($opt, $value);
678
679 if (PVE::QemuServer::drive_is_cdrom($drive)) { #cdrom
680 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.CDROM']);
681 } else {
682 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
683 }
684
685 if ($conf->{$opt}) {
686
687 if (my $old_drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt})) {
688
689 my $media = $drive->{media} || 'disk';
690 my $oldmedia = $old_drive->{media} || 'disk';
691 die "unable to change media type\n" if $media ne $oldmedia;
692
693 if (!PVE::QemuServer::drive_is_cdrom($old_drive) &&
694 ($drive->{file} ne $old_drive->{file})) { # delete old disks
695
696 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
697 $conf = PVE::QemuServer::load_config($vmid); # update/reload
698 }
0f56d571 699
9bf371a6
DM
700 if(&$safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
701 &$safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
702 &$safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
703 &$safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
704 &$safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
705 &$safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr})) {
706 PVE::QemuServer::qemu_block_set_io_throttle($vmid,"drive-$opt", $drive->{mbps}*1024*1024,
707 $drive->{mbps_rd}*1024*1024, $drive->{mbps_wr}*1024*1024,
708 $drive->{iops}, $drive->{iops_rd}, $drive->{iops_wr})
709 if !PVE::QemuServer::drive_is_cdrom($drive);
0f56d571 710 }
ae57f6b3
DM
711 }
712 }
713
714 &$create_disks($rpcenv, $authuser, $conf, $storecfg, $vmid, undef, {$opt => $value});
715 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
716
717 $conf = PVE::QemuServer::load_config($vmid); # update/reload
718 $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
719
720 if (PVE::QemuServer::drive_is_cdrom($drive)) { # cdrom
721
722 if (PVE::QemuServer::check_running($vmid)) {
723 if ($drive->{file} eq 'none') {
ce156282 724 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
ae57f6b3
DM
725 } else {
726 my $path = PVE::QemuServer::get_iso_path($storecfg, $vmid, $drive->{file});
ce156282
AD
727 PVE::QemuServer::vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt"); #force eject if locked
728 PVE::QemuServer::vm_mon_cmd($vmid, "change",device => "drive-$opt",target => "$path") if $path;
ae57f6b3
DM
729 }
730 }
731
732 } else { # hotplug new disks
733
734 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
5d7a6767 735 }
5d7a6767
DM
736};
737
ae57f6b3
DM
738my $vmconfig_update_net = sub {
739 my ($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $value) = @_;
740
741 if ($conf->{$opt}) {
742 #if online update, then unplug first
743 die "error hot-unplug $opt for update" if !PVE::QemuServer::vm_deviceunplug($vmid, $conf, $opt);
744 }
745
746 $conf->{$opt} = $value;
747 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
748 $conf = PVE::QemuServer::load_config($vmid); # update/reload
749
750 my $net = PVE::QemuServer::parse_net($conf->{$opt});
751
752 die "error hotplug $opt" if !PVE::QemuServer::vm_deviceplug($storecfg, $conf, $vmid, $opt, $net);
753};
754
a0d1b1a2
DM
755my $vm_config_perm_list = [
756 'VM.Config.Disk',
757 'VM.Config.CDROM',
758 'VM.Config.CPU',
759 'VM.Config.Memory',
760 'VM.Config.Network',
761 'VM.Config.HWType',
762 'VM.Config.Options',
763 ];
764
1e3baf05 765__PACKAGE__->register_method({
afdb31d5
DM
766 name => 'update_vm',
767 path => '{vmid}/config',
1e3baf05
DM
768 method => 'PUT',
769 protected => 1,
770 proxyto => 'node',
771 description => "Set virtual machine options.",
a0d1b1a2
DM
772 permissions => {
773 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
774 },
1e3baf05
DM
775 parameters => {
776 additionalProperties => 0,
777 properties => PVE::QemuServer::json_config_properties(
778 {
779 node => get_standard_option('pve-node'),
780 vmid => get_standard_option('pve-vmid'),
3ea94c60 781 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
782 delete => {
783 type => 'string', format => 'pve-configid-list',
784 description => "A list of settings you want to delete.",
785 optional => 1,
786 },
787 force => {
788 type => 'boolean',
789 description => $opt_force_description,
790 optional => 1,
791 requires => 'delete',
792 },
554ac7e7
DM
793 digest => {
794 type => 'string',
795 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
796 maxLength => 40,
afdb31d5 797 optional => 1,
554ac7e7 798 }
1e3baf05
DM
799 }),
800 },
801 returns => { type => 'null'},
802 code => sub {
803 my ($param) = @_;
804
805 my $rpcenv = PVE::RPCEnvironment::get();
806
a0d1b1a2 807 my $authuser = $rpcenv->get_user();
1e3baf05
DM
808
809 my $node = extract_param($param, 'node');
810
1e3baf05
DM
811 my $vmid = extract_param($param, 'vmid');
812
5fdbe4f0
DM
813 my $digest = extract_param($param, 'digest');
814
815 my @paramarr = (); # used for log message
816 foreach my $key (keys %$param) {
817 push @paramarr, "-$key", $param->{$key};
818 }
819
1e3baf05 820 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 821 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 822 if $skiplock && $authuser ne 'root@pam';
1e3baf05 823
0532bc63
DM
824 my $delete_str = extract_param($param, 'delete');
825
1e3baf05
DM
826 my $force = extract_param($param, 'force');
827
0532bc63
DM
828 die "no options specified\n" if !$delete_str && !scalar(keys %$param);
829
1e68cb19
DM
830 my $storecfg = PVE::Storage::config();
831
832 &$resolve_cdrom_alias($param);
833
834 # now try to verify all parameters
835
0532bc63
DM
836 my @delete = ();
837 foreach my $opt (PVE::Tools::split_list($delete_str)) {
838 $opt = 'ide2' if $opt eq 'cdrom';
839 raise_param_exc({ delete => "you can't use '-$opt' and " .
840 "-delete $opt' at the same time" })
841 if defined($param->{$opt});
842
843 if (!PVE::QemuServer::option_exists($opt)) {
844 raise_param_exc({ delete => "unknown option '$opt'" });
845 }
ae57f6b3 846
0532bc63
DM
847 push @delete, $opt;
848 }
1e3baf05 849
1e68cb19
DM
850 foreach my $opt (keys %$param) {
851 if (PVE::QemuServer::valid_drivename($opt)) {
852 # cleanup drive path
853 my $drive = PVE::QemuServer::parse_drive($opt, $param->{$opt});
854 PVE::QemuServer::cleanup_drive_path($opt, $storecfg, $drive);
855 $param->{$opt} = PVE::QemuServer::print_drive($vmid, $drive);
1e68cb19
DM
856 } elsif ($opt =~ m/^net(\d+)$/) {
857 # add macaddr
858 my $net = PVE::QemuServer::parse_net($param->{$opt});
859 $param->{$opt} = PVE::QemuServer::print_net($net);
1e68cb19
DM
860 }
861 }
1e3baf05 862
ae57f6b3
DM
863 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
864
865 &$check_vm_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
866
fcbb753e 867 &$check_storage_access($rpcenv, $authuser, $storecfg, $vmid, $param);
1e3baf05 868
5d39a182 869 my $updatefn = sub {
1e3baf05 870
5d39a182 871 my $conf = PVE::QemuServer::load_config($vmid);
1e3baf05 872
5d39a182
DM
873 die "checksum missmatch (file change by other user?)\n"
874 if $digest && $digest ne $conf->{digest};
1e3baf05 875
5d39a182 876 PVE::QemuServer::check_lock($conf) if !$skiplock;
1e3baf05 877
a0d1b1a2 878 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: " . join (' ', @paramarr));
c2a64aa7 879
5d7a6767 880 foreach my $opt (@delete) { # delete
1e68cb19 881 $conf = PVE::QemuServer::load_config($vmid); # update/reload
ae57f6b3 882 &$vmconfig_delete_option($rpcenv, $authuser, $conf, $storecfg, $vmid, $opt, $force);
5d39a182 883 }
1e3baf05 884
5d7a6767 885 foreach my $opt (keys %$param) { # add/change
1e3baf05 886
1e68cb19 887 $conf = PVE::QemuServer::load_config($vmid); # update/reload
1e3baf05 888
5d7a6767
DM
889 next if $conf->{$opt} && ($param->{$opt} eq $conf->{$opt}); # skip if nothing changed
890
ae57f6b3 891 if (PVE::QemuServer::valid_drivename($opt)) {
5d7a6767 892
ae57f6b3
DM
893 &$vmconfig_update_disk($rpcenv, $authuser, $conf, $storecfg, $vmid,
894 $opt, $param->{$opt}, $force);
1e68cb19 895
ae57f6b3 896 } elsif ($opt =~ m/^net(\d+)$/) { #nics
1858638f 897
ae57f6b3
DM
898 &$vmconfig_update_net($rpcenv, $authuser, $conf, $storecfg, $vmid,
899 $opt, $param->{$opt});
1e68cb19
DM
900
901 } else {
902
1858638f
DM
903 $conf->{$opt} = $param->{$opt};
904 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
3a1e36bb 905 }
5d39a182
DM
906 }
907 };
908
909 PVE::QemuServer::lock_config($vmid, $updatefn);
fcdb0117 910
1e3baf05
DM
911 return undef;
912 }});
913
914
915__PACKAGE__->register_method({
afdb31d5
DM
916 name => 'destroy_vm',
917 path => '{vmid}',
1e3baf05
DM
918 method => 'DELETE',
919 protected => 1,
920 proxyto => 'node',
921 description => "Destroy the vm (also delete all used/owned volumes).",
a0d1b1a2
DM
922 permissions => {
923 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
924 },
1e3baf05
DM
925 parameters => {
926 additionalProperties => 0,
927 properties => {
928 node => get_standard_option('pve-node'),
929 vmid => get_standard_option('pve-vmid'),
3ea94c60 930 skiplock => get_standard_option('skiplock'),
1e3baf05
DM
931 },
932 },
afdb31d5 933 returns => {
5fdbe4f0
DM
934 type => 'string',
935 },
1e3baf05
DM
936 code => sub {
937 my ($param) = @_;
938
939 my $rpcenv = PVE::RPCEnvironment::get();
940
a0d1b1a2 941 my $authuser = $rpcenv->get_user();
1e3baf05
DM
942
943 my $vmid = $param->{vmid};
944
945 my $skiplock = $param->{skiplock};
afdb31d5 946 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 947 if $skiplock && $authuser ne 'root@pam';
1e3baf05 948
5fdbe4f0
DM
949 # test if VM exists
950 my $conf = PVE::QemuServer::load_config($vmid);
951
afdb31d5 952 my $storecfg = PVE::Storage::config();
1e3baf05 953
502d18a2
DM
954 my $delVMfromPoolFn = sub {
955 my $usercfg = cfs_read_file("user.cfg");
5d0094ea
DM
956 if (my $pool = $usercfg->{vms}->{$vmid}) {
957 if (my $data = $usercfg->{pools}->{$pool}) {
958 delete $data->{vms}->{$vmid};
959 delete $usercfg->{vms}->{$vmid};
960 cfs_write_file("user.cfg", $usercfg);
961 }
502d18a2
DM
962 }
963 };
964
5fdbe4f0 965 my $realcmd = sub {
ff1a2432
DM
966 my $upid = shift;
967
968 syslog('info', "destroy VM $vmid: $upid\n");
969
5fdbe4f0 970 PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock);
502d18a2
DM
971
972 PVE::AccessControl::lock_user_config($delVMfromPoolFn, "pool cleanup failed");
5fdbe4f0 973 };
1e3baf05 974
a0d1b1a2 975 return $rpcenv->fork_worker('qmdestroy', $vmid, $authuser, $realcmd);
1e3baf05
DM
976 }});
977
978__PACKAGE__->register_method({
afdb31d5
DM
979 name => 'unlink',
980 path => '{vmid}/unlink',
1e3baf05
DM
981 method => 'PUT',
982 protected => 1,
983 proxyto => 'node',
984 description => "Unlink/delete disk images.",
a0d1b1a2
DM
985 permissions => {
986 check => [ 'perm', '/vms/{vmid}', ['VM.Config.Disk']],
987 },
1e3baf05
DM
988 parameters => {
989 additionalProperties => 0,
990 properties => {
991 node => get_standard_option('pve-node'),
992 vmid => get_standard_option('pve-vmid'),
993 idlist => {
994 type => 'string', format => 'pve-configid-list',
995 description => "A list of disk IDs you want to delete.",
996 },
997 force => {
998 type => 'boolean',
999 description => $opt_force_description,
1000 optional => 1,
1001 },
1002 },
1003 },
1004 returns => { type => 'null'},
1005 code => sub {
1006 my ($param) = @_;
1007
1008 $param->{delete} = extract_param($param, 'idlist');
1009
1010 __PACKAGE__->update_vm($param);
1011
1012 return undef;
1013 }});
1014
1015my $sslcert;
1016
1017__PACKAGE__->register_method({
afdb31d5
DM
1018 name => 'vncproxy',
1019 path => '{vmid}/vncproxy',
1e3baf05
DM
1020 method => 'POST',
1021 protected => 1,
1022 permissions => {
378b359e 1023 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1e3baf05
DM
1024 },
1025 description => "Creates a TCP VNC proxy connections.",
1026 parameters => {
1027 additionalProperties => 0,
1028 properties => {
1029 node => get_standard_option('pve-node'),
1030 vmid => get_standard_option('pve-vmid'),
1031 },
1032 },
afdb31d5 1033 returns => {
1e3baf05
DM
1034 additionalProperties => 0,
1035 properties => {
1036 user => { type => 'string' },
1037 ticket => { type => 'string' },
1038 cert => { type => 'string' },
1039 port => { type => 'integer' },
1040 upid => { type => 'string' },
1041 },
1042 },
1043 code => sub {
1044 my ($param) = @_;
1045
1046 my $rpcenv = PVE::RPCEnvironment::get();
1047
a0d1b1a2 1048 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1049
1050 my $vmid = $param->{vmid};
1051 my $node = $param->{node};
1052
b6f39da2
DM
1053 my $authpath = "/vms/$vmid";
1054
a0d1b1a2 1055 my $ticket = PVE::AccessControl::assemble_vnc_ticket($authuser, $authpath);
b6f39da2 1056
1e3baf05
DM
1057 $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
1058 if !$sslcert;
1059
1060 my $port = PVE::Tools::next_vnc_port();
1061
1062 my $remip;
afdb31d5 1063
4f1be36c 1064 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
1e3baf05
DM
1065 $remip = PVE::Cluster::remote_node_ip($node);
1066 }
1067
1068 # NOTE: kvm VNC traffic is already TLS encrypted,
1069 # so we select the fastest chipher here (or 'none'?)
1070 my $remcmd = $remip ? ['/usr/bin/ssh', '-T', '-o', 'BatchMode=yes',
1071 '-c', 'blowfish-cbc', $remip] : [];
1072
afdb31d5 1073 my $timeout = 10;
1e3baf05
DM
1074
1075 my $realcmd = sub {
1076 my $upid = shift;
1077
1078 syslog('info', "starting vnc proxy $upid\n");
1079
1080 my $qmcmd = [@$remcmd, "/usr/sbin/qm", 'vncproxy', $vmid];
1081
1082 my $qmstr = join(' ', @$qmcmd);
1083
1084 # also redirect stderr (else we get RFB protocol errors)
be62c45c 1085 my $cmd = ['/bin/nc', '-l', '-p', $port, '-w', $timeout, '-c', "$qmstr 2>/dev/null"];
1e3baf05 1086
be62c45c 1087 PVE::Tools::run_command($cmd);
1e3baf05
DM
1088
1089 return;
1090 };
1091
a0d1b1a2 1092 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
1e3baf05 1093
3da85107
DM
1094 PVE::Tools::wait_for_vnc_port($port);
1095
1e3baf05 1096 return {
a0d1b1a2 1097 user => $authuser,
1e3baf05 1098 ticket => $ticket,
afdb31d5
DM
1099 port => $port,
1100 upid => $upid,
1101 cert => $sslcert,
1e3baf05
DM
1102 };
1103 }});
1104
5fdbe4f0
DM
1105__PACKAGE__->register_method({
1106 name => 'vmcmdidx',
afdb31d5 1107 path => '{vmid}/status',
5fdbe4f0
DM
1108 method => 'GET',
1109 proxyto => 'node',
1110 description => "Directory index",
a0d1b1a2
DM
1111 permissions => {
1112 user => 'all',
1113 },
5fdbe4f0
DM
1114 parameters => {
1115 additionalProperties => 0,
1116 properties => {
1117 node => get_standard_option('pve-node'),
1118 vmid => get_standard_option('pve-vmid'),
1119 },
1120 },
1121 returns => {
1122 type => 'array',
1123 items => {
1124 type => "object",
1125 properties => {
1126 subdir => { type => 'string' },
1127 },
1128 },
1129 links => [ { rel => 'child', href => "{subdir}" } ],
1130 },
1131 code => sub {
1132 my ($param) = @_;
1133
1134 # test if VM exists
1135 my $conf = PVE::QemuServer::load_config($param->{vmid});
1136
1137 my $res = [
1138 { subdir => 'current' },
1139 { subdir => 'start' },
1140 { subdir => 'stop' },
1141 ];
afdb31d5 1142
5fdbe4f0
DM
1143 return $res;
1144 }});
1145
88fc87b4
DM
1146my $vm_is_ha_managed = sub {
1147 my ($vmid) = @_;
1148
1149 my $cc = PVE::Cluster::cfs_read_file('cluster.conf');
1150 if (PVE::Cluster::cluster_conf_lookup_pvevm($cc, 0, $vmid, 1)) {
1151 return 1;
1152 }
1153 return 0;
1154};
1155
1e3baf05 1156__PACKAGE__->register_method({
afdb31d5 1157 name => 'vm_status',
5fdbe4f0 1158 path => '{vmid}/status/current',
1e3baf05
DM
1159 method => 'GET',
1160 proxyto => 'node',
1161 protected => 1, # qemu pid files are only readable by root
1162 description => "Get virtual machine status.",
a0d1b1a2
DM
1163 permissions => {
1164 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1165 },
1e3baf05
DM
1166 parameters => {
1167 additionalProperties => 0,
1168 properties => {
1169 node => get_standard_option('pve-node'),
1170 vmid => get_standard_option('pve-vmid'),
1171 },
1172 },
1173 returns => { type => 'object' },
1174 code => sub {
1175 my ($param) = @_;
1176
1177 # test if VM exists
1178 my $conf = PVE::QemuServer::load_config($param->{vmid});
1179
03a33f30 1180 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
8610701a 1181 my $status = $vmstatus->{$param->{vmid}};
1e3baf05 1182
88fc87b4 1183 $status->{ha} = &$vm_is_ha_managed($param->{vmid});
8610701a
DM
1184
1185 return $status;
1e3baf05
DM
1186 }});
1187
1188__PACKAGE__->register_method({
afdb31d5 1189 name => 'vm_start',
5fdbe4f0
DM
1190 path => '{vmid}/status/start',
1191 method => 'POST',
1e3baf05
DM
1192 protected => 1,
1193 proxyto => 'node',
5fdbe4f0 1194 description => "Start virtual machine.",
a0d1b1a2
DM
1195 permissions => {
1196 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1197 },
1e3baf05
DM
1198 parameters => {
1199 additionalProperties => 0,
1200 properties => {
1201 node => get_standard_option('pve-node'),
1202 vmid => get_standard_option('pve-vmid'),
3ea94c60
DM
1203 skiplock => get_standard_option('skiplock'),
1204 stateuri => get_standard_option('pve-qm-stateuri'),
7e8dcf2c
AD
1205 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
1206
1e3baf05
DM
1207 },
1208 },
afdb31d5 1209 returns => {
5fdbe4f0
DM
1210 type => 'string',
1211 },
1e3baf05
DM
1212 code => sub {
1213 my ($param) = @_;
1214
1215 my $rpcenv = PVE::RPCEnvironment::get();
1216
a0d1b1a2 1217 my $authuser = $rpcenv->get_user();
1e3baf05
DM
1218
1219 my $node = extract_param($param, 'node');
1220
1e3baf05
DM
1221 my $vmid = extract_param($param, 'vmid');
1222
3ea94c60 1223 my $stateuri = extract_param($param, 'stateuri');
afdb31d5 1224 raise_param_exc({ stateuri => "Only root may use this option." })
a0d1b1a2 1225 if $stateuri && $authuser ne 'root@pam';
3ea94c60 1226
1e3baf05 1227 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1228 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1229 if $skiplock && $authuser ne 'root@pam';
1e3baf05 1230
7e8dcf2c
AD
1231 my $migratedfrom = extract_param($param, 'migratedfrom');
1232 raise_param_exc({ migratedfrom => "Only root may use this option." })
1233 if $migratedfrom && $authuser ne 'root@pam';
1234
afdb31d5 1235 my $storecfg = PVE::Storage::config();
5fdbe4f0 1236
cce37749
DM
1237 if (&$vm_is_ha_managed($vmid) && !$stateuri &&
1238 $rpcenv->{type} ne 'ha') {
5fdbe4f0 1239
88fc87b4
DM
1240 my $hacmd = sub {
1241 my $upid = shift;
5fdbe4f0 1242
88fc87b4 1243 my $service = "pvevm:$vmid";
5fdbe4f0 1244
88fc87b4
DM
1245 my $cmd = ['clusvcadm', '-e', $service, '-m', $node];
1246
1247 print "Executing HA start for VM $vmid\n";
1248
1249 PVE::Tools::run_command($cmd);
1250
1251 return;
1252 };
1253
1254 return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
1255
1256 } else {
1257
1258 my $realcmd = sub {
1259 my $upid = shift;
1260
1261 syslog('info', "start VM $vmid: $upid\n");
1262
7e8dcf2c 1263 PVE::QemuServer::vm_start($storecfg, $vmid, $stateuri, $skiplock, $migratedfrom);
88fc87b4
DM
1264
1265 return;
1266 };
5fdbe4f0 1267
88fc87b4
DM
1268 return $rpcenv->fork_worker('qmstart', $vmid, $authuser, $realcmd);
1269 }
5fdbe4f0
DM
1270 }});
1271
1272__PACKAGE__->register_method({
afdb31d5 1273 name => 'vm_stop',
5fdbe4f0
DM
1274 path => '{vmid}/status/stop',
1275 method => 'POST',
1276 protected => 1,
1277 proxyto => 'node',
1278 description => "Stop virtual machine.",
a0d1b1a2
DM
1279 permissions => {
1280 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1281 },
5fdbe4f0
DM
1282 parameters => {
1283 additionalProperties => 0,
1284 properties => {
1285 node => get_standard_option('pve-node'),
1286 vmid => get_standard_option('pve-vmid'),
1287 skiplock => get_standard_option('skiplock'),
af30308f 1288 migratedfrom => get_standard_option('pve-node',{ optional => 1 }),
c6bb9502
DM
1289 timeout => {
1290 description => "Wait maximal timeout seconds.",
1291 type => 'integer',
1292 minimum => 0,
1293 optional => 1,
254575e9
DM
1294 },
1295 keepActive => {
1296 description => "Do not decativate storage volumes.",
1297 type => 'boolean',
1298 optional => 1,
1299 default => 0,
c6bb9502 1300 }
5fdbe4f0
DM
1301 },
1302 },
afdb31d5 1303 returns => {
5fdbe4f0
DM
1304 type => 'string',
1305 },
1306 code => sub {
1307 my ($param) = @_;
1308
1309 my $rpcenv = PVE::RPCEnvironment::get();
1310
a0d1b1a2 1311 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1312
1313 my $node = extract_param($param, 'node');
1314
1315 my $vmid = extract_param($param, 'vmid');
1316
1317 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1318 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1319 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1320
254575e9 1321 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1322 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1323 if $keepActive && $authuser ne 'root@pam';
254575e9 1324
af30308f
DM
1325 my $migratedfrom = extract_param($param, 'migratedfrom');
1326 raise_param_exc({ migratedfrom => "Only root may use this option." })
1327 if $migratedfrom && $authuser ne 'root@pam';
1328
1329
ff1a2432
DM
1330 my $storecfg = PVE::Storage::config();
1331
3be30d63 1332 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
5fdbe4f0 1333
88fc87b4
DM
1334 my $hacmd = sub {
1335 my $upid = shift;
5fdbe4f0 1336
88fc87b4 1337 my $service = "pvevm:$vmid";
c6bb9502 1338
88fc87b4
DM
1339 my $cmd = ['clusvcadm', '-d', $service];
1340
1341 print "Executing HA stop for VM $vmid\n";
1342
1343 PVE::Tools::run_command($cmd);
5fdbe4f0 1344
88fc87b4
DM
1345 return;
1346 };
1347
1348 return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
1349
1350 } else {
1351 my $realcmd = sub {
1352 my $upid = shift;
1353
1354 syslog('info', "stop VM $vmid: $upid\n");
1355
1356 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0,
af30308f 1357 $param->{timeout}, 0, 1, $keepActive, $migratedfrom);
88fc87b4
DM
1358
1359 return;
1360 };
1361
1362 return $rpcenv->fork_worker('qmstop', $vmid, $authuser, $realcmd);
1363 }
5fdbe4f0
DM
1364 }});
1365
1366__PACKAGE__->register_method({
afdb31d5 1367 name => 'vm_reset',
5fdbe4f0
DM
1368 path => '{vmid}/status/reset',
1369 method => 'POST',
1370 protected => 1,
1371 proxyto => 'node',
1372 description => "Reset virtual machine.",
a0d1b1a2
DM
1373 permissions => {
1374 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1375 },
5fdbe4f0
DM
1376 parameters => {
1377 additionalProperties => 0,
1378 properties => {
1379 node => get_standard_option('pve-node'),
1380 vmid => get_standard_option('pve-vmid'),
1381 skiplock => get_standard_option('skiplock'),
1382 },
1383 },
afdb31d5 1384 returns => {
5fdbe4f0
DM
1385 type => 'string',
1386 },
1387 code => sub {
1388 my ($param) = @_;
1389
1390 my $rpcenv = PVE::RPCEnvironment::get();
1391
a0d1b1a2 1392 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1393
1394 my $node = extract_param($param, 'node');
1395
1396 my $vmid = extract_param($param, 'vmid');
1397
1398 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1399 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1400 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1401
ff1a2432
DM
1402 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1403
5fdbe4f0
DM
1404 my $realcmd = sub {
1405 my $upid = shift;
1406
1e3baf05 1407 PVE::QemuServer::vm_reset($vmid, $skiplock);
5fdbe4f0
DM
1408
1409 return;
1410 };
1411
a0d1b1a2 1412 return $rpcenv->fork_worker('qmreset', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1413 }});
1414
1415__PACKAGE__->register_method({
afdb31d5 1416 name => 'vm_shutdown',
5fdbe4f0
DM
1417 path => '{vmid}/status/shutdown',
1418 method => 'POST',
1419 protected => 1,
1420 proxyto => 'node',
1421 description => "Shutdown virtual machine.",
a0d1b1a2
DM
1422 permissions => {
1423 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1424 },
5fdbe4f0
DM
1425 parameters => {
1426 additionalProperties => 0,
1427 properties => {
1428 node => get_standard_option('pve-node'),
1429 vmid => get_standard_option('pve-vmid'),
1430 skiplock => get_standard_option('skiplock'),
c6bb9502
DM
1431 timeout => {
1432 description => "Wait maximal timeout seconds.",
1433 type => 'integer',
1434 minimum => 0,
1435 optional => 1,
9269013a
DM
1436 },
1437 forceStop => {
1438 description => "Make sure the VM stops.",
1439 type => 'boolean',
1440 optional => 1,
1441 default => 0,
254575e9
DM
1442 },
1443 keepActive => {
1444 description => "Do not decativate storage volumes.",
1445 type => 'boolean',
1446 optional => 1,
1447 default => 0,
c6bb9502 1448 }
5fdbe4f0
DM
1449 },
1450 },
afdb31d5 1451 returns => {
5fdbe4f0
DM
1452 type => 'string',
1453 },
1454 code => sub {
1455 my ($param) = @_;
1456
1457 my $rpcenv = PVE::RPCEnvironment::get();
1458
a0d1b1a2 1459 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1460
1461 my $node = extract_param($param, 'node');
1462
1463 my $vmid = extract_param($param, 'vmid');
1464
1465 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1466 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1467 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1468
254575e9 1469 my $keepActive = extract_param($param, 'keepActive');
afdb31d5 1470 raise_param_exc({ keepActive => "Only root may use this option." })
a0d1b1a2 1471 if $keepActive && $authuser ne 'root@pam';
254575e9 1472
02d07cf5
DM
1473 my $storecfg = PVE::Storage::config();
1474
5fdbe4f0
DM
1475 my $realcmd = sub {
1476 my $upid = shift;
1477
1478 syslog('info', "shutdown VM $vmid: $upid\n");
1479
afdb31d5 1480 PVE::QemuServer::vm_stop($storecfg, $vmid, $skiplock, 0, $param->{timeout},
254575e9 1481 1, $param->{forceStop}, $keepActive);
c6bb9502 1482
5fdbe4f0
DM
1483 return;
1484 };
1485
a0d1b1a2 1486 return $rpcenv->fork_worker('qmshutdown', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1487 }});
1488
1489__PACKAGE__->register_method({
afdb31d5 1490 name => 'vm_suspend',
5fdbe4f0
DM
1491 path => '{vmid}/status/suspend',
1492 method => 'POST',
1493 protected => 1,
1494 proxyto => 'node',
1495 description => "Suspend virtual machine.",
a0d1b1a2
DM
1496 permissions => {
1497 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1498 },
5fdbe4f0
DM
1499 parameters => {
1500 additionalProperties => 0,
1501 properties => {
1502 node => get_standard_option('pve-node'),
1503 vmid => get_standard_option('pve-vmid'),
1504 skiplock => get_standard_option('skiplock'),
1505 },
1506 },
afdb31d5 1507 returns => {
5fdbe4f0
DM
1508 type => 'string',
1509 },
1510 code => sub {
1511 my ($param) = @_;
1512
1513 my $rpcenv = PVE::RPCEnvironment::get();
1514
a0d1b1a2 1515 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1516
1517 my $node = extract_param($param, 'node');
1518
1519 my $vmid = extract_param($param, 'vmid');
1520
1521 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1522 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1523 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1524
ff1a2432
DM
1525 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
1526
5fdbe4f0
DM
1527 my $realcmd = sub {
1528 my $upid = shift;
1529
1530 syslog('info', "suspend VM $vmid: $upid\n");
1531
1e3baf05 1532 PVE::QemuServer::vm_suspend($vmid, $skiplock);
5fdbe4f0
DM
1533
1534 return;
1535 };
1536
a0d1b1a2 1537 return $rpcenv->fork_worker('qmsuspend', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1538 }});
1539
1540__PACKAGE__->register_method({
afdb31d5 1541 name => 'vm_resume',
5fdbe4f0
DM
1542 path => '{vmid}/status/resume',
1543 method => 'POST',
1544 protected => 1,
1545 proxyto => 'node',
1546 description => "Resume virtual machine.",
a0d1b1a2
DM
1547 permissions => {
1548 check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
1549 },
5fdbe4f0
DM
1550 parameters => {
1551 additionalProperties => 0,
1552 properties => {
1553 node => get_standard_option('pve-node'),
1554 vmid => get_standard_option('pve-vmid'),
1555 skiplock => get_standard_option('skiplock'),
1556 },
1557 },
afdb31d5 1558 returns => {
5fdbe4f0
DM
1559 type => 'string',
1560 },
1561 code => sub {
1562 my ($param) = @_;
1563
1564 my $rpcenv = PVE::RPCEnvironment::get();
1565
a0d1b1a2 1566 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1567
1568 my $node = extract_param($param, 'node');
1569
1570 my $vmid = extract_param($param, 'vmid');
1571
1572 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1573 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1574 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0 1575
b7eeab21 1576 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
ff1a2432 1577
5fdbe4f0
DM
1578 my $realcmd = sub {
1579 my $upid = shift;
1580
1581 syslog('info', "resume VM $vmid: $upid\n");
1582
1e3baf05 1583 PVE::QemuServer::vm_resume($vmid, $skiplock);
1e3baf05 1584
5fdbe4f0
DM
1585 return;
1586 };
1587
a0d1b1a2 1588 return $rpcenv->fork_worker('qmresume', $vmid, $authuser, $realcmd);
5fdbe4f0
DM
1589 }});
1590
1591__PACKAGE__->register_method({
afdb31d5 1592 name => 'vm_sendkey',
5fdbe4f0
DM
1593 path => '{vmid}/sendkey',
1594 method => 'PUT',
1595 protected => 1,
1596 proxyto => 'node',
1597 description => "Send key event to virtual machine.",
a0d1b1a2
DM
1598 permissions => {
1599 check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
1600 },
5fdbe4f0
DM
1601 parameters => {
1602 additionalProperties => 0,
1603 properties => {
1604 node => get_standard_option('pve-node'),
1605 vmid => get_standard_option('pve-vmid'),
1606 skiplock => get_standard_option('skiplock'),
1607 key => {
1608 description => "The key (qemu monitor encoding).",
1609 type => 'string'
1610 }
1611 },
1612 },
1613 returns => { type => 'null'},
1614 code => sub {
1615 my ($param) = @_;
1616
1617 my $rpcenv = PVE::RPCEnvironment::get();
1618
a0d1b1a2 1619 my $authuser = $rpcenv->get_user();
5fdbe4f0
DM
1620
1621 my $node = extract_param($param, 'node');
1622
1623 my $vmid = extract_param($param, 'vmid');
1624
1625 my $skiplock = extract_param($param, 'skiplock');
afdb31d5 1626 raise_param_exc({ skiplock => "Only root may use this option." })
a0d1b1a2 1627 if $skiplock && $authuser ne 'root@pam';
5fdbe4f0
DM
1628
1629 PVE::QemuServer::vm_sendkey($vmid, $skiplock, $param->{key});
1630
1631 return;
1e3baf05
DM
1632 }});
1633
3ea94c60 1634__PACKAGE__->register_method({
afdb31d5 1635 name => 'migrate_vm',
3ea94c60
DM
1636 path => '{vmid}/migrate',
1637 method => 'POST',
1638 protected => 1,
1639 proxyto => 'node',
1640 description => "Migrate virtual machine. Creates a new migration task.",
a0d1b1a2
DM
1641 permissions => {
1642 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
1643 },
3ea94c60
DM
1644 parameters => {
1645 additionalProperties => 0,
1646 properties => {
1647 node => get_standard_option('pve-node'),
1648 vmid => get_standard_option('pve-vmid'),
1649 target => get_standard_option('pve-node', { description => "Target node." }),
1650 online => {
1651 type => 'boolean',
1652 description => "Use online/live migration.",
1653 optional => 1,
1654 },
1655 force => {
1656 type => 'boolean',
1657 description => "Allow to migrate VMs which use local devices. Only root may use this option.",
1658 optional => 1,
1659 },
1660 },
1661 },
afdb31d5 1662 returns => {
3ea94c60
DM
1663 type => 'string',
1664 description => "the task ID.",
1665 },
1666 code => sub {
1667 my ($param) = @_;
1668
1669 my $rpcenv = PVE::RPCEnvironment::get();
1670
a0d1b1a2 1671 my $authuser = $rpcenv->get_user();
3ea94c60
DM
1672
1673 my $target = extract_param($param, 'target');
1674
1675 my $localnode = PVE::INotify::nodename();
1676 raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
1677
1678 PVE::Cluster::check_cfs_quorum();
1679
1680 PVE::Cluster::check_node_exists($target);
1681
1682 my $targetip = PVE::Cluster::remote_node_ip($target);
1683
1684 my $vmid = extract_param($param, 'vmid');
1685
afdb31d5 1686 raise_param_exc({ force => "Only root may use this option." })
a0d1b1a2 1687 if $param->{force} && $authuser ne 'root@pam';
3ea94c60
DM
1688
1689 # test if VM exists
a5ed42d3 1690 my $conf = PVE::QemuServer::load_config($vmid);
3ea94c60
DM
1691
1692 # try to detect errors early
a5ed42d3
DM
1693
1694 PVE::QemuServer::check_lock($conf);
1695
3ea94c60 1696 if (PVE::QemuServer::check_running($vmid)) {
afdb31d5 1697 die "cant migrate running VM without --online\n"
3ea94c60
DM
1698 if !$param->{online};
1699 }
1700
47152e2e 1701 my $storecfg = PVE::Storage::config();
22d646a7 1702 PVE::QemuServer::check_storage_availability($storecfg, $conf, $target);
47152e2e 1703
3be30d63 1704 if (&$vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
3ea94c60 1705
88fc87b4
DM
1706 my $hacmd = sub {
1707 my $upid = shift;
3ea94c60 1708
88fc87b4
DM
1709 my $service = "pvevm:$vmid";
1710
1711 my $cmd = ['clusvcadm', '-M', $service, '-m', $target];
1712
1713 print "Executing HA migrate for VM $vmid to node $target\n";
1714
1715 PVE::Tools::run_command($cmd);
1716
1717 return;
1718 };
1719
1720 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
1721
1722 } else {
1723
1724 my $realcmd = sub {
1725 my $upid = shift;
1726
1727 PVE::QemuMigrate->migrate($target, $targetip, $vmid, $param);
1728 };
1729
1730 return $rpcenv->fork_worker('qmigrate', $vmid, $authuser, $realcmd);
1731 }
3ea94c60 1732
3ea94c60 1733 }});
1e3baf05 1734
91c94f0a 1735__PACKAGE__->register_method({
afdb31d5
DM
1736 name => 'monitor',
1737 path => '{vmid}/monitor',
91c94f0a
DM
1738 method => 'POST',
1739 protected => 1,
1740 proxyto => 'node',
1741 description => "Execute Qemu monitor commands.",
a0d1b1a2
DM
1742 permissions => {
1743 check => ['perm', '/vms/{vmid}', [ 'VM.Monitor' ]],
1744 },
91c94f0a
DM
1745 parameters => {
1746 additionalProperties => 0,
1747 properties => {
1748 node => get_standard_option('pve-node'),
1749 vmid => get_standard_option('pve-vmid'),
1750 command => {
1751 type => 'string',
1752 description => "The monitor command.",
1753 }
1754 },
1755 },
1756 returns => { type => 'string'},
1757 code => sub {
1758 my ($param) = @_;
1759
1760 my $vmid = $param->{vmid};
1761
1762 my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
1763
1764 my $res = '';
1765 eval {
7b7c6d1b 1766 $res = PVE::QemuServer::vm_human_monitor_command($vmid, $param->{command});
91c94f0a
DM
1767 };
1768 $res = "ERROR: $@" if $@;
1769
1770 return $res;
1771 }});
1772
0d02881c
AD
1773__PACKAGE__->register_method({
1774 name => 'resize_vm',
614e3941 1775 path => '{vmid}/resize',
0d02881c
AD
1776 method => 'PUT',
1777 protected => 1,
1778 proxyto => 'node',
2f48a4f5 1779 description => "Extend volume size.",
0d02881c 1780 permissions => {
3b2773f6 1781 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Disk' ]],
0d02881c
AD
1782 },
1783 parameters => {
1784 additionalProperties => 0,
2f48a4f5
DM
1785 properties => {
1786 node => get_standard_option('pve-node'),
1787 vmid => get_standard_option('pve-vmid'),
1788 skiplock => get_standard_option('skiplock'),
1789 disk => {
1790 type => 'string',
1791 description => "The disk you want to resize.",
1792 enum => [PVE::QemuServer::disknames()],
1793 },
1794 size => {
1795 type => 'string',
f91b2e45 1796 pattern => '\+?\d+(\.\d+)?[KMGT]?',
2f48a4f5
DM
1797 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.",
1798 },
1799 digest => {
1800 type => 'string',
1801 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
1802 maxLength => 40,
1803 optional => 1,
1804 },
1805 },
0d02881c
AD
1806 },
1807 returns => { type => 'null'},
1808 code => sub {
1809 my ($param) = @_;
1810
1811 my $rpcenv = PVE::RPCEnvironment::get();
1812
1813 my $authuser = $rpcenv->get_user();
1814
1815 my $node = extract_param($param, 'node');
1816
1817 my $vmid = extract_param($param, 'vmid');
1818
1819 my $digest = extract_param($param, 'digest');
1820
2f48a4f5
DM
1821 my $disk = extract_param($param, 'disk');
1822
1823 my $sizestr = extract_param($param, 'size');
0d02881c 1824
f91b2e45 1825 my $skiplock = extract_param($param, 'skiplock');
0d02881c
AD
1826 raise_param_exc({ skiplock => "Only root may use this option." })
1827 if $skiplock && $authuser ne 'root@pam';
1828
0d02881c
AD
1829 my $storecfg = PVE::Storage::config();
1830
0d02881c
AD
1831 my $updatefn = sub {
1832
1833 my $conf = PVE::QemuServer::load_config($vmid);
1834
1835 die "checksum missmatch (file change by other user?)\n"
1836 if $digest && $digest ne $conf->{digest};
1837 PVE::QemuServer::check_lock($conf) if !$skiplock;
1838
f91b2e45
DM
1839 die "disk '$disk' does not exist\n" if !$conf->{$disk};
1840
1841 my $drive = PVE::QemuServer::parse_drive($disk, $conf->{$disk});
1842
1843 my $volid = $drive->{file};
1844
1845 die "disk '$disk' has no associated volume\n" if !$volid;
1846
1847 die "you can't resize a cdrom\n" if PVE::QemuServer::drive_is_cdrom($drive);
1848
1849 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
1850
1851 $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
1852
1853 my $size = PVE::Storage::volume_size_info($storecfg, $volid, 5);
1854
1855 die "internal error" if $sizestr !~ m/^(\+)?(\d+(\.\d+)?)([KMGT])?$/;
1856 my ($ext, $newsize, $unit) = ($1, $2, $4);
1857 if ($unit) {
1858 if ($unit eq 'K') {
1859 $newsize = $newsize * 1024;
1860 } elsif ($unit eq 'M') {
1861 $newsize = $newsize * 1024 * 1024;
1862 } elsif ($unit eq 'G') {
1863 $newsize = $newsize * 1024 * 1024 * 1024;
1864 } elsif ($unit eq 'T') {
1865 $newsize = $newsize * 1024 * 1024 * 1024 * 1024;
1866 }
1867 }
1868 $newsize += $size if $ext;
1869 $newsize = int($newsize);
1870
1871 die "unable to skrink disk size\n" if $newsize < $size;
1872
1873 return if $size == $newsize;
1874
2f48a4f5 1875 PVE::Cluster::log_msg('info', $authuser, "update VM $vmid: resize --disk $disk --size $sizestr");
0d02881c 1876
f91b2e45
DM
1877 PVE::QemuServer::qemu_block_resize($vmid, "drive-$disk", $storecfg, $volid, $newsize);
1878
1879 $drive->{size} = $newsize;
1880 $conf->{$disk} = PVE::QemuServer::print_drive($vmid, $drive);
1881
1882 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
1883 };
0d02881c
AD
1884
1885 PVE::QemuServer::lock_config($vmid, $updatefn);
1886 return undef;
1887 }});
1888
9dbd1ee4 1889__PACKAGE__->register_method({
7e7d7b61 1890 name => 'snapshot_list',
9dbd1ee4 1891 path => '{vmid}/snapshot',
7e7d7b61
DM
1892 method => 'GET',
1893 description => "List all snapshots.",
1894 permissions => {
1895 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1896 },
1897 proxyto => 'node',
1898 protected => 1, # qemu pid files are only readable by root
1899 parameters => {
1900 additionalProperties => 0,
1901 properties => {
1902 vmid => get_standard_option('pve-vmid'),
1903 node => get_standard_option('pve-node'),
1904 },
1905 },
1906 returns => {
1907 type => 'array',
1908 items => {
1909 type => "object",
1910 properties => {},
1911 },
1912 links => [ { rel => 'child', href => "{name}" } ],
1913 },
1914 code => sub {
1915 my ($param) = @_;
1916
6aa4651b
DM
1917 my $vmid = $param->{vmid};
1918
1919 my $conf = PVE::QemuServer::load_config($vmid);
7e7d7b61
DM
1920 my $snaphash = $conf->{snapshots} || {};
1921
1922 my $res = [];
1923
1924 foreach my $name (keys %$snaphash) {
0ea6bc69 1925 my $d = $snaphash->{$name};
982c7f12
DM
1926 my $item = {
1927 name => $name,
1928 snaptime => $d->{snaptime} || 0,
6aa4651b 1929 vmstate => $d->{vmstate} ? 1 : 0,
982c7f12
DM
1930 description => $d->{description} || '',
1931 };
0ea6bc69 1932 $item->{parent} = $d->{parent} if $d->{parent};
3ee28e38 1933 $item->{snapstate} = $d->{snapstate} if $d->{snapstate};
0ea6bc69
DM
1934 push @$res, $item;
1935 }
1936
6aa4651b
DM
1937 my $running = PVE::QemuServer::check_running($vmid, 1) ? 1 : 0;
1938 my $current = { name => 'current', digest => $conf->{digest}, running => $running };
d1914468
DM
1939 $current->{parent} = $conf->{parent} if $conf->{parent};
1940
1941 push @$res, $current;
7e7d7b61
DM
1942
1943 return $res;
1944 }});
1945
1946__PACKAGE__->register_method({
1947 name => 'snapshot',
1948 path => '{vmid}/snapshot',
1949 method => 'POST',
9dbd1ee4
AD
1950 protected => 1,
1951 proxyto => 'node',
1952 description => "Snapshot a VM.",
1953 permissions => {
f1baf1df 1954 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
9dbd1ee4
AD
1955 },
1956 parameters => {
1957 additionalProperties => 0,
1958 properties => {
1959 node => get_standard_option('pve-node'),
1960 vmid => get_standard_option('pve-vmid'),
8abd398b 1961 snapname => get_standard_option('pve-snapshot-name'),
9dbd1ee4
AD
1962 vmstate => {
1963 optional => 1,
1964 type => 'boolean',
1965 description => "Save the vmstate",
1966 },
1967 freezefs => {
1968 optional => 1,
1969 type => 'boolean',
1970 description => "Freeze the filesystem",
1971 },
782f4f75
DM
1972 description => {
1973 optional => 1,
1974 type => 'string',
1975 description => "A textual description or comment.",
1976 },
9dbd1ee4
AD
1977 },
1978 },
7e7d7b61
DM
1979 returns => {
1980 type => 'string',
1981 description => "the task ID.",
1982 },
9dbd1ee4
AD
1983 code => sub {
1984 my ($param) = @_;
1985
1986 my $rpcenv = PVE::RPCEnvironment::get();
1987
1988 my $authuser = $rpcenv->get_user();
1989
1990 my $node = extract_param($param, 'node');
1991
1992 my $vmid = extract_param($param, 'vmid');
1993
9dbd1ee4
AD
1994 my $snapname = extract_param($param, 'snapname');
1995
d1914468
DM
1996 die "unable to use snapshot name 'current' (reserved name)\n"
1997 if $snapname eq 'current';
1998
7e7d7b61 1999 my $realcmd = sub {
22c377f0 2000 PVE::Cluster::log_msg('info', $authuser, "snapshot VM $vmid: $snapname");
782f4f75
DM
2001 PVE::QemuServer::snapshot_create($vmid, $snapname, $param->{vmstate},
2002 $param->{freezefs}, $param->{description});
7e7d7b61
DM
2003 };
2004
2005 return $rpcenv->fork_worker('qmsnapshot', $vmid, $authuser, $realcmd);
2006 }});
2007
154ccdcd
DM
2008__PACKAGE__->register_method({
2009 name => 'snapshot_cmd_idx',
2010 path => '{vmid}/snapshot/{snapname}',
2011 description => '',
2012 method => 'GET',
2013 permissions => {
2014 user => 'all',
2015 },
2016 parameters => {
2017 additionalProperties => 0,
2018 properties => {
2019 vmid => get_standard_option('pve-vmid'),
2020 node => get_standard_option('pve-node'),
8abd398b 2021 snapname => get_standard_option('pve-snapshot-name'),
154ccdcd
DM
2022 },
2023 },
2024 returns => {
2025 type => 'array',
2026 items => {
2027 type => "object",
2028 properties => {},
2029 },
2030 links => [ { rel => 'child', href => "{cmd}" } ],
2031 },
2032 code => sub {
2033 my ($param) = @_;
2034
2035 my $res = [];
2036
2037 push @$res, { cmd => 'rollback' };
d788cea6 2038 push @$res, { cmd => 'config' };
154ccdcd
DM
2039
2040 return $res;
2041 }});
2042
d788cea6
DM
2043__PACKAGE__->register_method({
2044 name => 'update_snapshot_config',
2045 path => '{vmid}/snapshot/{snapname}/config',
2046 method => 'PUT',
2047 protected => 1,
2048 proxyto => 'node',
2049 description => "Update snapshot metadata.",
2050 permissions => {
2051 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2052 },
2053 parameters => {
2054 additionalProperties => 0,
2055 properties => {
2056 node => get_standard_option('pve-node'),
2057 vmid => get_standard_option('pve-vmid'),
2058 snapname => get_standard_option('pve-snapshot-name'),
2059 description => {
2060 optional => 1,
2061 type => 'string',
2062 description => "A textual description or comment.",
2063 },
2064 },
2065 },
2066 returns => { type => 'null' },
2067 code => sub {
2068 my ($param) = @_;
2069
2070 my $rpcenv = PVE::RPCEnvironment::get();
2071
2072 my $authuser = $rpcenv->get_user();
2073
2074 my $vmid = extract_param($param, 'vmid');
2075
2076 my $snapname = extract_param($param, 'snapname');
2077
2078 return undef if !defined($param->{description});
2079
2080 my $updatefn = sub {
2081
2082 my $conf = PVE::QemuServer::load_config($vmid);
2083
2084 PVE::QemuServer::check_lock($conf);
2085
2086 my $snap = $conf->{snapshots}->{$snapname};
2087
2088 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2089
2090 $snap->{description} = $param->{description} if defined($param->{description});
2091
2092 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
2093 };
2094
2095 PVE::QemuServer::lock_config($vmid, $updatefn);
2096
2097 return undef;
2098 }});
2099
2100__PACKAGE__->register_method({
2101 name => 'get_snapshot_config',
2102 path => '{vmid}/snapshot/{snapname}/config',
2103 method => 'GET',
2104 proxyto => 'node',
2105 description => "Get snapshot configuration",
2106 permissions => {
2107 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
2108 },
2109 parameters => {
2110 additionalProperties => 0,
2111 properties => {
2112 node => get_standard_option('pve-node'),
2113 vmid => get_standard_option('pve-vmid'),
2114 snapname => get_standard_option('pve-snapshot-name'),
2115 },
2116 },
2117 returns => { type => "object" },
2118 code => sub {
2119 my ($param) = @_;
2120
2121 my $rpcenv = PVE::RPCEnvironment::get();
2122
2123 my $authuser = $rpcenv->get_user();
2124
2125 my $vmid = extract_param($param, 'vmid');
2126
2127 my $snapname = extract_param($param, 'snapname');
2128
2129 my $conf = PVE::QemuServer::load_config($vmid);
2130
2131 my $snap = $conf->{snapshots}->{$snapname};
2132
2133 die "snapshot '$snapname' does not exist\n" if !defined($snap);
2134
2135 return $snap;
2136 }});
2137
7e7d7b61
DM
2138__PACKAGE__->register_method({
2139 name => 'rollback',
154ccdcd 2140 path => '{vmid}/snapshot/{snapname}/rollback',
7e7d7b61
DM
2141 method => 'POST',
2142 protected => 1,
2143 proxyto => 'node',
2144 description => "Rollback VM state to specified snapshot.",
2145 permissions => {
f1baf1df 2146 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2147 },
2148 parameters => {
2149 additionalProperties => 0,
2150 properties => {
2151 node => get_standard_option('pve-node'),
2152 vmid => get_standard_option('pve-vmid'),
8abd398b 2153 snapname => get_standard_option('pve-snapshot-name'),
7e7d7b61
DM
2154 },
2155 },
2156 returns => {
2157 type => 'string',
2158 description => "the task ID.",
2159 },
2160 code => sub {
2161 my ($param) = @_;
2162
2163 my $rpcenv = PVE::RPCEnvironment::get();
2164
2165 my $authuser = $rpcenv->get_user();
2166
2167 my $node = extract_param($param, 'node');
2168
2169 my $vmid = extract_param($param, 'vmid');
2170
2171 my $snapname = extract_param($param, 'snapname');
2172
7e7d7b61 2173 my $realcmd = sub {
22c377f0
DM
2174 PVE::Cluster::log_msg('info', $authuser, "rollback snapshot VM $vmid: $snapname");
2175 PVE::QemuServer::snapshot_rollback($vmid, $snapname);
7e7d7b61
DM
2176 };
2177
2178 return $rpcenv->fork_worker('qmrollback', $vmid, $authuser, $realcmd);
2179 }});
2180
2181__PACKAGE__->register_method({
2182 name => 'delsnapshot',
2183 path => '{vmid}/snapshot/{snapname}',
2184 method => 'DELETE',
2185 protected => 1,
2186 proxyto => 'node',
2187 description => "Delete a VM snapshot.",
2188 permissions => {
f1baf1df 2189 check => ['perm', '/vms/{vmid}', [ 'VM.Snapshot' ]],
7e7d7b61
DM
2190 },
2191 parameters => {
2192 additionalProperties => 0,
2193 properties => {
2194 node => get_standard_option('pve-node'),
2195 vmid => get_standard_option('pve-vmid'),
8abd398b 2196 snapname => get_standard_option('pve-snapshot-name'),
3ee28e38
DM
2197 force => {
2198 optional => 1,
2199 type => 'boolean',
2200 description => "For removal from config file, even if removing disk snapshots fails.",
2201 },
7e7d7b61
DM
2202 },
2203 },
2204 returns => {
2205 type => 'string',
2206 description => "the task ID.",
2207 },
2208 code => sub {
2209 my ($param) = @_;
2210
2211 my $rpcenv = PVE::RPCEnvironment::get();
2212
2213 my $authuser = $rpcenv->get_user();
2214
2215 my $node = extract_param($param, 'node');
2216
2217 my $vmid = extract_param($param, 'vmid');
2218
2219 my $snapname = extract_param($param, 'snapname');
2220
7e7d7b61 2221 my $realcmd = sub {
22c377f0 2222 PVE::Cluster::log_msg('info', $authuser, "delete snapshot VM $vmid: $snapname");
3ee28e38 2223 PVE::QemuServer::snapshot_delete($vmid, $snapname, $param->{force});
7e7d7b61 2224 };
9dbd1ee4 2225
7b2257a8 2226 return $rpcenv->fork_worker('qmdelsnapshot', $vmid, $authuser, $realcmd);
9dbd1ee4
AD
2227 }});
2228
1e3baf05 22291;