]> git.proxmox.com Git - qemu-server.git/blame - PVE/CLI/qm.pm
cli: qm: change move_disk to move-disk
[qemu-server.git] / PVE / CLI / qm.pm
CommitLineData
f3e76e36
DM
1package PVE::CLI::qm;
2
3use strict;
4use warnings;
5
6# Note: disable '+' prefix for Getopt::Long (for resize command)
7use Getopt::Long qw(:config no_getopt_compat);
8
9use Fcntl ':flock';
10use File::Path;
f3e76e36 11use IO::Select;
7c2d9b40
TL
12use IO::Socket::UNIX;
13use JSON;
5f1dc9af 14use POSIX qw(strftime);
7c2d9b40
TL
15use Term::ReadLine;
16use URI::Escape;
f3e76e36 17
f3e76e36 18use PVE::Cluster;
520884de 19use PVE::Exception qw(raise_param_exc);
9e784b11 20use PVE::GuestHelpers;
7c2d9b40
TL
21use PVE::INotify;
22use PVE::JSONSchema qw(get_standard_option);
23use PVE::Network;
24use PVE::RPCEnvironment;
25use PVE::SafeSyslog;
26use PVE::Tools qw(extract_param);
27
28use PVE::API2::Qemu::Agent;
29use PVE::API2::Qemu;
0a13e08e 30use PVE::QemuConfig;
e0fd2b2f 31use PVE::QemuServer::Drive;
d036e418 32use PVE::QemuServer::Helpers;
7c2d9b40 33use PVE::QemuServer::Agent qw(agent_available);
8653feeb 34use PVE::QemuServer::ImportDisk;
0a13e08e 35use PVE::QemuServer::Monitor qw(mon_cmd);
7cd9f6d7 36use PVE::QemuServer::OVF;
7c2d9b40 37use PVE::QemuServer;
f3e76e36
DM
38
39use PVE::CLIHandler;
f3e76e36
DM
40use base qw(PVE::CLIHandler);
41
42my $upid_exit = sub {
43 my $upid = shift;
44 my $status = PVE::Tools::upid_read_status($upid);
831ad442 45 exit(PVE::Tools::upid_status_is_error($status) ? -1 : 0);
f3e76e36
DM
46};
47
48my $nodename = PVE::INotify::nodename();
49
5e4035c7
DM
50sub setup_environment {
51 PVE::RPCEnvironment->setup_default_cli_env();
52}
53
f3e76e36
DM
54sub run_vnc_proxy {
55 my ($path) = @_;
56
57 my $c;
58 while ( ++$c < 10 && !-e $path ) { sleep(1); }
59
60 my $s = IO::Socket::UNIX->new(Peer => $path, Timeout => 120);
61
62 die "unable to connect to socket '$path' - $!" if !$s;
63
f7d1505b 64 my $select = IO::Select->new();
f3e76e36
DM
65
66 $select->add(\*STDIN);
67 $select->add($s);
68
69 my $timeout = 60*15; # 15 minutes
70
71 my @handles;
72 while ($select->count &&
73 scalar(@handles = $select->can_read ($timeout))) {
74 foreach my $h (@handles) {
75 my $buf;
76 my $n = $h->sysread($buf, 4096);
77
78 if ($h == \*STDIN) {
79 if ($n) {
80 syswrite($s, $buf);
81 } else {
82 exit(0);
83 }
84 } elsif ($h == $s) {
85 if ($n) {
86 syswrite(\*STDOUT, $buf);
87 } else {
88 exit(0);
89 }
90 }
91 }
92 }
93 exit(0);
94}
95
81fff836
DC
96sub print_recursive_hash {
97 my ($prefix, $hash, $key) = @_;
98
99 if (ref($hash) eq 'HASH') {
100 if (defined($key)) {
101 print "$prefix$key:\n";
102 }
7f0285e1 103 for my $itemkey (sort keys %$hash) {
81fff836
DC
104 print_recursive_hash("\t$prefix", $hash->{$itemkey}, $itemkey);
105 }
106 } elsif (ref($hash) eq 'ARRAY') {
107 if (defined($key)) {
108 print "$prefix$key:\n";
109 }
7f0285e1 110 for my $item (@$hash) {
81fff836
DC
111 print_recursive_hash("\t$prefix", $item);
112 }
6891fd70 113 } elsif ((!ref($hash) && defined($hash)) || ref($hash) eq 'JSON::PP::Boolean') {
81fff836
DC
114 if (defined($key)) {
115 print "$prefix$key: $hash\n";
116 } else {
117 print "$prefix$hash\n";
118 }
119 }
120}
121
f3e76e36
DM
122__PACKAGE__->register_method ({
123 name => 'showcmd',
124 path => 'showcmd',
125 method => 'GET',
126 description => "Show command line which is used to start the VM (debug info).",
127 parameters => {
128 additionalProperties => 0,
129 properties => {
335af808 130 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
16a01738
TL
131 pretty => {
132 description => "Puts each option on a new line to enhance human readability",
133 type => 'boolean',
134 optional => 1,
135 default => 0,
b14477e7
RV
136 },
137 snapshot => get_standard_option('pve-snapshot-name', {
138 description => "Fetch config values from given snapshot.",
139 optional => 1,
140 completion => sub {
141 my ($cmd, $pname, $cur, $args) = @_;
142 PVE::QemuConfig->snapshot_list($args->[0]);
143 }
144 }),
f3e76e36
DM
145 },
146 },
147 returns => { type => 'null'},
148 code => sub {
149 my ($param) = @_;
150
151 my $storecfg = PVE::Storage::config();
b14477e7 152 my $cmdline = PVE::QemuServer::vm_commandline($storecfg, $param->{vmid}, $param->{snapshot});
16a01738 153
108899b4 154 $cmdline =~ s/ -/ \\\n -/g if $param->{pretty};
16a01738
TL
155
156 print "$cmdline\n";
f3e76e36 157
d1c1af4b 158 return;
f3e76e36
DM
159 }});
160
161__PACKAGE__->register_method ({
162 name => 'status',
163 path => 'status',
164 method => 'GET',
165 description => "Show VM status.",
166 parameters => {
167 additionalProperties => 0,
168 properties => {
335af808 169 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
f3e76e36
DM
170 verbose => {
171 description => "Verbose output format",
172 type => 'boolean',
173 optional => 1,
174 }
175 },
176 },
177 returns => { type => 'null'},
178 code => sub {
179 my ($param) = @_;
180
181 # test if VM exists
ffda963f 182 my $conf = PVE::QemuConfig->load_config ($param->{vmid});
f3e76e36 183
12612b09 184 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
f3e76e36
DM
185 my $stat = $vmstatus->{$param->{vmid}};
186 if ($param->{verbose}) {
187 foreach my $k (sort (keys %$stat)) {
188 next if $k eq 'cpu' || $k eq 'relcpu'; # always 0
189 my $v = $stat->{$k};
81fff836 190 print_recursive_hash("", $v, $k);
f3e76e36
DM
191 }
192 } else {
12612b09 193 my $status = $stat->{qmpstatus} || 'unknown';
f3e76e36
DM
194 print "status: $status\n";
195 }
196
d1c1af4b 197 return;
f3e76e36
DM
198 }});
199
200__PACKAGE__->register_method ({
201 name => 'vncproxy',
202 path => 'vncproxy',
203 method => 'PUT',
204 description => "Proxy VM VNC traffic to stdin/stdout",
205 parameters => {
206 additionalProperties => 0,
207 properties => {
335af808 208 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
209 },
210 },
211 returns => { type => 'null'},
212 code => sub {
213 my ($param) = @_;
214
215 my $vmid = $param->{vmid};
0a13e08e 216 PVE::QemuConfig::assert_config_exists_on_node($vmid);
d036e418 217 my $vnc_socket = PVE::QemuServer::Helpers::vnc_socket($vmid);
f3e76e36
DM
218
219 if (my $ticket = $ENV{LC_PVE_TICKET}) { # NOTE: ssh on debian only pass LC_* variables
0a13e08e
SR
220 mon_cmd($vmid, "set_password", protocol => 'vnc', password => $ticket);
221 mon_cmd($vmid, "expire_password", protocol => 'vnc', time => "+30");
f3e76e36 222 } else {
2dc0eb61 223 die "LC_PVE_TICKET not set, VNC proxy without password is forbidden\n";
f3e76e36
DM
224 }
225
226 run_vnc_proxy($vnc_socket);
227
d1c1af4b 228 return;
f3e76e36
DM
229 }});
230
231__PACKAGE__->register_method ({
232 name => 'unlock',
233 path => 'unlock',
234 method => 'PUT',
235 description => "Unlock the VM.",
236 parameters => {
237 additionalProperties => 0,
238 properties => {
335af808 239 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
f3e76e36
DM
240 },
241 },
242 returns => { type => 'null'},
243 code => sub {
244 my ($param) = @_;
245
246 my $vmid = $param->{vmid};
247
04096e7b 248 PVE::QemuConfig->lock_config ($vmid, sub {
ffda963f 249 my $conf = PVE::QemuConfig->load_config($vmid);
f3e76e36
DM
250 delete $conf->{lock};
251 delete $conf->{pending}->{lock} if $conf->{pending}; # just to be sure
ffda963f 252 PVE::QemuConfig->write_config($vmid, $conf);
f3e76e36
DM
253 });
254
d1c1af4b 255 return;
f3e76e36
DM
256 }});
257
63a09370
AD
258__PACKAGE__->register_method ({
259 name => 'nbdstop',
260 path => 'nbdstop',
261 method => 'PUT',
262 description => "Stop embedded nbd server.",
263 parameters => {
264 additionalProperties => 0,
265 properties => {
266 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
267 },
268 },
269 returns => { type => 'null'},
270 code => sub {
271 my ($param) = @_;
272
273 my $vmid = $param->{vmid};
274
aa6ebf6a
TL
275 eval { PVE::QemuServer::nbd_stop($vmid) };
276 warn $@ if $@;
63a09370 277
d1c1af4b 278 return;
63a09370
AD
279 }});
280
f3e76e36
DM
281__PACKAGE__->register_method ({
282 name => 'mtunnel',
283 path => 'mtunnel',
284 method => 'POST',
285 description => "Used by qmigrate - do not use manually.",
286 parameters => {
287 additionalProperties => 0,
288 properties => {},
289 },
290 returns => { type => 'null'},
291 code => sub {
292 my ($param) = @_;
293
294 if (!PVE::Cluster::check_cfs_quorum(1)) {
295 print "no quorum\n";
d1c1af4b 296 return;
f3e76e36
DM
297 }
298
79c9e079
FG
299 my $tunnel_write = sub {
300 my $text = shift;
301 chomp $text;
302 print "$text\n";
303 *STDOUT->flush();
304 };
305
306 $tunnel_write->("tunnel online");
307 $tunnel_write->("ver 1");
d8518469 308
e5caa02e 309 while (my $line = <STDIN>) {
f3e76e36 310 chomp $line;
bcb51ae8
FG
311 if ($line =~ /^quit$/) {
312 $tunnel_write->("OK");
313 last;
1d5aaa1d
FG
314 } elsif ($line =~ /^resume (\d+)$/) {
315 my $vmid = $1;
316 if (PVE::QemuServer::check_running($vmid, 1)) {
317 eval { PVE::QemuServer::vm_resume($vmid, 1, 1); };
318 if ($@) {
319 $tunnel_write->("ERR: resume failed - $@");
320 } else {
321 $tunnel_write->("OK");
322 }
323 } else {
324 $tunnel_write->("ERR: resume failed - VM $vmid not running");
325 }
bcb51ae8 326 }
f3e76e36
DM
327 }
328
d1c1af4b 329 return;
f3e76e36
DM
330 }});
331
332__PACKAGE__->register_method ({
333 name => 'wait',
334 path => 'wait',
335 method => 'GET',
336 description => "Wait until the VM is stopped.",
337 parameters => {
338 additionalProperties => 0,
339 properties => {
335af808 340 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
341 timeout => {
342 description => "Timeout in seconds. Default is to wait forever.",
343 type => 'integer',
344 minimum => 1,
345 optional => 1,
346 }
347 },
348 },
349 returns => { type => 'null'},
350 code => sub {
351 my ($param) = @_;
352
353 my $vmid = $param->{vmid};
354 my $timeout = $param->{timeout};
355
356 my $pid = PVE::QemuServer::check_running ($vmid);
357 return if !$pid;
358
359 print "waiting until VM $vmid stopps (PID $pid)\n";
360
361 my $count = 0;
362 while ((!$timeout || ($count < $timeout)) && PVE::QemuServer::check_running ($vmid)) {
363 $count++;
364 sleep 1;
365 }
366
367 die "wait failed - got timeout\n" if PVE::QemuServer::check_running ($vmid);
368
d1c1af4b 369 return;
f3e76e36
DM
370 }});
371
372__PACKAGE__->register_method ({
373 name => 'monitor',
374 path => 'monitor',
375 method => 'POST',
376 description => "Enter Qemu Monitor interface.",
377 parameters => {
378 additionalProperties => 0,
379 properties => {
335af808 380 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
381 },
382 },
383 returns => { type => 'null'},
384 code => sub {
385 my ($param) = @_;
386
387 my $vmid = $param->{vmid};
388
ffda963f 389 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
f3e76e36
DM
390
391 print "Entering Qemu Monitor for VM $vmid - type 'help' for help\n";
392
f7d1505b 393 my $term = Term::ReadLine->new('qm');
f3e76e36 394
f7d1505b 395 while (defined(my $input = $term->readline('qm> '))) {
f3e76e36 396 chomp $input;
f3e76e36 397 next if $input =~ m/^\s*$/;
f3e76e36
DM
398 last if $input =~ m/^\s*q(uit)?\s*$/;
399
f7d1505b 400 eval { print PVE::QemuServer::Monitor::hmp_cmd($vmid, $input) };
f3e76e36
DM
401 print "ERROR: $@" if $@;
402 }
403
d1c1af4b 404 return;
f3e76e36
DM
405
406 }});
407
408__PACKAGE__->register_method ({
409 name => 'rescan',
410 path => 'rescan',
411 method => 'POST',
412 description => "Rescan all storages and update disk sizes and unused disk images.",
413 parameters => {
414 additionalProperties => 0,
415 properties => {
335af808
DM
416 vmid => get_standard_option('pve-vmid', {
417 optional => 1,
418 completion => \&PVE::QemuServer::complete_vmid,
419 }),
9224dcee
TL
420 dryrun => {
421 type => 'boolean',
422 optional => 1,
423 default => 0,
dc02254e 424 description => 'Do not actually write changes out to VM config(s).',
9224dcee 425 },
f3e76e36
DM
426 },
427 },
428 returns => { type => 'null'},
429 code => sub {
430 my ($param) = @_;
431
9224dcee
TL
432 my $dryrun = $param->{dryrun};
433
434 print "NOTE: running in dry-run mode, won't write changes out!\n" if $dryrun;
435
436 PVE::QemuServer::rescan($param->{vmid}, 0, $dryrun);
f3e76e36 437
d1c1af4b 438 return;
f3e76e36
DM
439 }});
440
8653feeb
EK
441__PACKAGE__->register_method ({
442 name => 'importdisk',
443 path => 'importdisk',
444 method => 'POST',
445 description => "Import an external disk image as an unused disk in a VM. The
446 image format has to be supported by qemu-img(1).",
447 parameters => {
448 additionalProperties => 0,
449 properties => {
450 vmid => get_standard_option('pve-vmid', {completion => \&PVE::QemuServer::complete_vmid}),
451 source => {
452 description => 'Path to the disk image to import',
453 type => 'string',
454 optional => 0,
455 },
456 storage => get_standard_option('pve-storage-id', {
457 description => 'Target storage ID',
458 completion => \&PVE::QemuServer::complete_storage,
459 optional => 0,
460 }),
461 format => {
462 type => 'string',
463 description => 'Target format',
464 enum => [ 'raw', 'qcow2', 'vmdk' ],
465 optional => 1,
466 },
467 },
468 },
469 returns => { type => 'null'},
470 code => sub {
471 my ($param) = @_;
472
473 my $vmid = extract_param($param, 'vmid');
474 my $source = extract_param($param, 'source');
475 my $storeid = extract_param($param, 'storage');
476 my $format = extract_param($param, 'format');
477
478 my $vm_conf = PVE::QemuConfig->load_config($vmid);
479 PVE::QemuConfig->check_lock($vm_conf);
480 die "$source: non-existent or non-regular file\n" if (! -f $source);
c7db1e40 481
8653feeb
EK
482 my $storecfg = PVE::Storage::config();
483 PVE::Storage::storage_check_enabled($storecfg, $storeid);
484
c75bf161 485 my $target_storage_config = PVE::Storage::storage_config($storecfg, $storeid);
c7db1e40
EK
486 die "storage $storeid does not support vm images\n"
487 if !$target_storage_config->{content}->{images};
488
c75bf161
TL
489 print "importing disk '$source' to VM $vmid ...\n";
490 my ($drive_id, $volid) = PVE::QemuServer::ImportDisk::do_import($source, $vmid, $storeid, { format => $format });
491 print "Successfully imported disk as '$drive_id:$volid'\n";
8653feeb 492
d1c1af4b 493 return;
8653feeb
EK
494 }});
495
f3e76e36
DM
496__PACKAGE__->register_method ({
497 name => 'terminal',
498 path => 'terminal',
499 method => 'POST',
500 description => "Open a terminal using a serial device (The VM need to have a serial device configured, for example 'serial0: socket')",
501 parameters => {
502 additionalProperties => 0,
503 properties => {
335af808 504 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
505 iface => {
506 description => "Select the serial device. By default we simply use the first suitable device.",
507 type => 'string',
508 optional => 1,
509 enum => [qw(serial0 serial1 serial2 serial3)],
aa320bcd
WB
510 },
511 escape => {
512 description => "Escape character.",
513 type => 'string',
514 optional => 1,
515 default => '^O',
516 },
f3e76e36
DM
517 },
518 },
519 returns => { type => 'null'},
520 code => sub {
521 my ($param) = @_;
522
523 my $vmid = $param->{vmid};
524
aa320bcd
WB
525 my $escape = $param->{escape} // '^O';
526 if ($escape =~ /^\^([\x40-\x7a])$/) {
527 $escape = ord($1) & 0x1F;
528 } elsif ($escape =~ /^0x[0-9a-f]+$/i) {
529 $escape = hex($escape);
530 } elsif ($escape =~ /^[0-9]+$/) {
531 $escape = int($escape);
532 } else {
533 die "invalid escape character definition: $escape\n";
534 }
535 my $escapemsg = '';
536 if ($escape) {
537 $escapemsg = sprintf(' (press Ctrl+%c to exit)', $escape+0x40);
538 $escape = sprintf(',escape=0x%x', $escape);
539 } else {
540 $escape = '';
541 }
542
ffda963f 543 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
f3e76e36
DM
544
545 my $iface = $param->{iface};
546
547 if ($iface) {
548 die "serial interface '$iface' is not configured\n" if !$conf->{$iface};
549 die "wrong serial type on interface '$iface'\n" if $conf->{$iface} ne 'socket';
550 } else {
551 foreach my $opt (qw(serial0 serial1 serial2 serial3)) {
552 if ($conf->{$opt} && ($conf->{$opt} eq 'socket')) {
553 $iface = $opt;
554 last;
555 }
556 }
557 die "unable to find a serial interface\n" if !$iface;
558 }
559
560 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
561
562 my $socket = "/var/run/qemu-server/${vmid}.$iface";
563
aa320bcd 564 my $cmd = "socat UNIX-CONNECT:$socket STDIO,raw,echo=0$escape";
f3e76e36 565
aa320bcd 566 print "starting serial terminal on interface ${iface}${escapemsg}\n";
f3e76e36
DM
567
568 system($cmd);
569
d1c1af4b 570 return;
f3e76e36
DM
571 }});
572
7cd9f6d7
EK
573__PACKAGE__->register_method ({
574 name => 'importovf',
575 path => 'importovf',
576 description => "Create a new VM using parameters read from an OVF manifest",
577 parameters => {
578 additionalProperties => 0,
579 properties => {
580 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
581 manifest => {
582 type => 'string',
583 description => 'path to the ovf file',
584 },
585 storage => get_standard_option('pve-storage-id', {
586 description => 'Target storage ID',
587 completion => \&PVE::QemuServer::complete_storage,
588 optional => 0,
589 }),
590 format => {
591 type => 'string',
592 description => 'Target format',
593 enum => [ 'raw', 'qcow2', 'vmdk' ],
594 optional => 1,
595 },
596 dryrun => {
597 type => 'boolean',
598 description => 'Print a parsed representation of the extracted OVF parameters, but do not create a VM',
599 optional => 1,
f6306646 600 }
7cd9f6d7
EK
601 },
602 },
b533b995 603 returns => { type => 'null' },
7cd9f6d7
EK
604 code => sub {
605 my ($param) = @_;
606
607 my $vmid = PVE::Tools::extract_param($param, 'vmid');
608 my $ovf_file = PVE::Tools::extract_param($param, 'manifest');
609 my $storeid = PVE::Tools::extract_param($param, 'storage');
610 my $format = PVE::Tools::extract_param($param, 'format');
611 my $dryrun = PVE::Tools::extract_param($param, 'dryrun');
612
613 die "$ovf_file: non-existent or non-regular file\n" if (! -f $ovf_file);
614 my $storecfg = PVE::Storage::config();
615 PVE::Storage::storage_check_enabled($storecfg, $storeid);
616
617 my $parsed = PVE::QemuServer::OVF::parse_ovf($ovf_file);
618
619 if ($dryrun) {
0f80f1ab
WB
620 print to_json($parsed, { pretty => 1, canonical => 1});
621 return;
7cd9f6d7
EK
622 }
623
73a4470a
TL
624 eval { PVE::QemuConfig->create_and_lock_config($vmid) };
625 die "Reserving empty config for OVF import to VM $vmid failed: $@" if $@;
7cd9f6d7 626
439390e8
DJ
627 my $conf = PVE::QemuConfig->load_config($vmid);
628 die "Internal error: Expected 'create' lock in config of VM $vmid!"
629 if !PVE::QemuConfig->has_lock($conf, "create");
7cd9f6d7 630
439390e8
DJ
631 $conf->{name} = $parsed->{qm}->{name} if defined($parsed->{qm}->{name});
632 $conf->{memory} = $parsed->{qm}->{memory} if defined($parsed->{qm}->{memory});
633 $conf->{cores} = $parsed->{qm}->{cores} if defined($parsed->{qm}->{cores});
7cd9f6d7 634
4405703d 635 my $imported_disks = [];
439390e8
DJ
636 eval {
637 # order matters, as do_import() will load_config() internally
638 $conf->{vmgenid} = PVE::QemuServer::generate_uuid();
639 $conf->{smbios1} = PVE::QemuServer::generate_smbios1_uuid();
640 PVE::QemuConfig->write_config($vmid, $conf);
7cd9f6d7 641
439390e8
DJ
642 foreach my $disk (@{ $parsed->{disks} }) {
643 my ($file, $drive) = ($disk->{backing_file}, $disk->{disk_address});
4405703d 644 my ($name, $volid) = PVE::QemuServer::ImportDisk::do_import($file, $vmid, $storeid, {
5600c5b2
TL
645 drive_name => $drive,
646 format => $format,
647 skiplock => 1,
648 });
4405703d
TL
649 # for cleanup on (later) error
650 push @$imported_disks, $volid;
7cd9f6d7 651 }
439390e8
DJ
652
653 # reload after disks entries have been created
654 $conf = PVE::QemuConfig->load_config($vmid);
2141a802
SR
655 my $devs = PVE::QemuServer::get_default_bootdevices($conf);
656 $conf->{boot} = PVE::QemuServer::print_bootorder($devs);
439390e8 657 PVE::QemuConfig->write_config($vmid, $conf);
7cd9f6d7
EK
658 };
659
4405703d 660 if (my $err = $@) {
439390e8 661 my $skiplock = 1;
4405703d
TL
662 warn "error during import, cleaning up created resources...\n";
663 for my $volid (@$imported_disks) {
664 eval { PVE::Storage::vdisk_free($storecfg, $volid) };
665 warn "cleanup of $volid failed: $@\n" if $@;
666 }
b04ea584 667 eval { PVE::QemuServer::destroy_vm($storecfg, $vmid, $skiplock) };
439390e8
DJ
668 warn "Could not destroy VM $vmid: $@" if "$@";
669 die "import failed - $err";
670 }
73a4470a
TL
671
672 PVE::QemuConfig->remove_lock($vmid, "create");
5d942f5a 673
d1c1af4b 674 return;
7cd9f6d7
EK
675
676 }
677});
788a6a35 678
520884de
DC
679__PACKAGE__->register_method({
680 name => 'exec',
681 path => 'exec',
682 method => 'POST',
683 protected => 1,
684 description => "Executes the given command via the guest agent",
685 parameters => {
686 additionalProperties => 0,
687 properties => {
688 node => get_standard_option('pve-node'),
689 vmid => get_standard_option('pve-vmid', {
690 completion => \&PVE::QemuServer::complete_vmid_running }),
691 synchronous => {
692 type => 'boolean',
693 optional => 1,
694 default => 1,
695 description => "If set to off, returns the pid immediately instead of waiting for the commmand to finish or the timeout.",
696 },
697 'timeout' => {
698 type => 'integer',
699 description => "The maximum time to wait synchronously for the command to finish. If reached, the pid gets returned. Set to 0 to deactivate",
700 minimum => 0,
701 optional => 1,
702 default => 30,
703 },
d8f61794
SR
704 'pass-stdin' => {
705 type => 'boolean',
109a0950 706 description => "When set, read STDIN until EOF and forward to guest agent via 'input-data' (usually treated as STDIN to process launched by guest agent). Allows maximal 1 MiB.",
d8f61794
SR
707 optional => 1,
708 default => 0,
709 },
520884de
DC
710 'extra-args' => get_standard_option('extra-args'),
711 },
712 },
713 returns => {
714 type => 'object',
715 },
716 code => sub {
717 my ($param) = @_;
718
719 my $vmid = $param->{vmid};
720 my $sync = $param->{synchronous} // 1;
d8f61794 721 my $pass_stdin = $param->{'pass-stdin'};
520884de
DC
722 if (defined($param->{timeout}) && !$sync) {
723 raise_param_exc({ synchronous => "needs to be set for 'timeout'"});
724 }
725
d8f61794
SR
726 my $input_data = undef;
727 if ($pass_stdin) {
728 $input_data = '';
729 while (my $line = <STDIN>) {
730 $input_data .= $line;
731 if (length($input_data) > 1024*1024) {
732 # not sure how QEMU handles large amounts of data being
733 # passed into the QMP socket, so limit to be safe
734 die "'input-data' (STDIN) is limited to 1 MiB, aborting\n";
735 }
736 }
737 }
738
739 my $args = $param->{'extra-args'};
740 $args = undef if !$args || !@$args;
741
742 my $res = PVE::QemuServer::Agent::qemu_exec($vmid, $input_data, $args);
520884de
DC
743
744 if ($sync) {
745 my $pid = $res->{pid};
746 my $timeout = $param->{timeout} // 30;
747 my $starttime = time();
748
749 while ($timeout == 0 || (time() - $starttime) < $timeout) {
750 my $out = PVE::QemuServer::Agent::qemu_exec_status($vmid, $pid);
751 if ($out->{exited}) {
752 $res = $out;
753 last;
754 }
755 sleep 1;
756 }
757
758 if (!$res->{exited}) {
759 warn "timeout reached, returning pid\n";
760 }
761 }
762
763 return { result => $res };
764 }});
765
3ea84aeb
DC
766__PACKAGE__->register_method({
767 name => 'cleanup',
768 path => 'cleanup',
769 method => 'POST',
770 protected => 1,
771 description => "Cleans up resources like tap devices, vgpus, etc. Called after a vm shuts down, crashes, etc.",
772 parameters => {
773 additionalProperties => 0,
774 properties => {
775 node => get_standard_option('pve-node'),
776 vmid => get_standard_option('pve-vmid', {
777 completion => \&PVE::QemuServer::complete_vmid_running }),
778 'clean-shutdown' => {
779 type => 'boolean',
780 description => "Indicates if qemu shutdown cleanly.",
781 },
782 'guest-requested' => {
783 type => 'boolean',
784 description => "Indicates if the shutdown was requested by the guest or via qmp.",
785 },
786 },
787 },
788 returns => { type => 'null', },
789 code => sub {
790 my ($param) = @_;
791
792 my $vmid = $param->{vmid};
793 my $clean = $param->{'clean-shutdown'};
794 my $guest = $param->{'guest-requested'};
64457ed4 795 my $restart = 0;
3ea84aeb 796
0f56fff2
DC
797 # return if we do not have the config anymore
798 return if !-f PVE::QemuConfig->config_file($vmid);
799
3ea84aeb
DC
800 my $storecfg = PVE::Storage::config();
801 warn "Starting cleanup for $vmid\n";
802
803 PVE::QemuConfig->lock_config($vmid, sub {
804 my $conf = PVE::QemuConfig->load_config ($vmid);
805 my $pid = PVE::QemuServer::check_running ($vmid);
806 die "vm still running\n" if $pid;
807
808 if (!$clean) {
809 # we have to cleanup the tap devices after a crash
810
811 foreach my $opt (keys %$conf) {
812 next if $opt !~ m/^net(\d)+$/;
813 my $interface = $1;
814 PVE::Network::tap_unplug("tap${vmid}i${interface}");
815 }
816 }
817
818 if (!$clean || $guest) {
819 # vm was shutdown from inside the guest or crashed, doing api cleanup
820 PVE::QemuServer::vm_stop_cleanup($storecfg, $vmid, $conf, 0, 0);
821 }
9e784b11 822 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-stop');
64457ed4
DC
823
824 $restart = eval { PVE::QemuServer::clear_reboot_request($vmid) };
825 warn $@ if $@;
3ea84aeb
DC
826 });
827
828 warn "Finished cleanup for $vmid\n";
829
64457ed4
DC
830 if ($restart) {
831 warn "Restarting VM $vmid\n";
832 PVE::API2::Qemu->vm_start({
833 vmid => $vmid,
834 node => $nodename,
835 });
836 }
837
d1c1af4b 838 return;
3ea84aeb
DC
839 }});
840
788a6a35
DM
841my $print_agent_result = sub {
842 my ($data) = @_;
843
520884de 844 my $result = $data->{result} // $data;
788a6a35
DM
845 return if !defined($result);
846
847 my $class = ref($result);
848
849 if (!$class) {
850 chomp $result;
851 return if $result =~ m/^\s*$/;
852 print "$result\n";
853 return;
854 }
855
856 if (($class eq 'HASH') && !scalar(keys %$result)) { # empty hash
857 return;
858 }
859
860 print to_json($result, { pretty => 1, canonical => 1});
861};
862
3351aacc
WB
863sub param_mapping {
864 my ($name) = @_;
865
866 my $ssh_key_map = ['sshkeys', sub {
867 return URI::Escape::uri_escape(PVE::Tools::file_get_contents($_[0]));
868 }];
3dba118c 869 my $cipassword_map = PVE::CLIHandler::get_standard_mapping('pve-password', { name => 'cipassword' });
8593cbe4 870 my $password_map = PVE::CLIHandler::get_standard_mapping('pve-password');
3351aacc 871 my $mapping = {
29d1f147
WB
872 'update_vm' => [$ssh_key_map, $cipassword_map],
873 'create_vm' => [$ssh_key_map, $cipassword_map],
8593cbe4 874 'set-user-password' => [$password_map],
3351aacc
WB
875 };
876
877 return $mapping->{$name};
878}
879
f3e76e36
DM
880our $cmddef = {
881 list => [ "PVE::API2::Qemu", 'vmlist', [],
882 { node => $nodename }, sub {
883 my $vmlist = shift;
884
885 exit 0 if (!scalar(@$vmlist));
886
887 printf "%10s %-20s %-10s %-10s %12s %-10s\n",
888 qw(VMID NAME STATUS MEM(MB) BOOTDISK(GB) PID);
889
890 foreach my $rec (sort { $a->{vmid} <=> $b->{vmid} } @$vmlist) {
891 printf "%10s %-20s %-10s %-10s %12.2f %-10s\n", $rec->{vmid}, $rec->{name},
12612b09 892 $rec->{qmpstatus} || $rec->{status},
f3e76e36
DM
893 ($rec->{maxmem} || 0)/(1024*1024),
894 ($rec->{maxdisk} || 0)/(1024*1024*1024),
895 $rec->{pid}||0;
896 }
897
898
899 } ],
900
901 create => [ "PVE::API2::Qemu", 'create_vm', ['vmid'], { node => $nodename }, $upid_exit ],
902
903 destroy => [ "PVE::API2::Qemu", 'destroy_vm', ['vmid'], { node => $nodename }, $upid_exit ],
904
905 clone => [ "PVE::API2::Qemu", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
906
907 migrate => [ "PVE::API2::Qemu", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit ],
908
909 set => [ "PVE::API2::Qemu", 'update_vm', ['vmid'], { node => $nodename } ],
910
911 resize => [ "PVE::API2::Qemu", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
912
2817091d
AL
913 'move-disk' => [ "PVE::API2::Qemu", 'move_vm_disk', ['vmid', 'disk', 'storage'], { node => $nodename }, $upid_exit ],
914 move_disk => { alias => 'move-disk' },
f3e76e36
DM
915
916 unlink => [ "PVE::API2::Qemu", 'unlink', ['vmid'], { node => $nodename } ],
917
918 config => [ "PVE::API2::Qemu", 'vm_config', ['vmid'],
919 { node => $nodename }, sub {
920 my $config = shift;
921 foreach my $k (sort (keys %$config)) {
922 next if $k eq 'digest';
923 my $v = $config->{$k};
924 if ($k eq 'description') {
925 $v = PVE::Tools::encode_text($v);
926 }
927 print "$k: $v\n";
928 }
929 }],
930
5c39708e 931 pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::format_pending ],
f3e76e36
DM
932 showcmd => [ __PACKAGE__, 'showcmd', ['vmid']],
933
934 status => [ __PACKAGE__, 'status', ['vmid']],
935
936 snapshot => [ "PVE::API2::Qemu", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
937
938 delsnapshot => [ "PVE::API2::Qemu", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
939
90ec74ea 940 listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::print_snapshot_tree],
265db461 941
f3e76e36
DM
942 rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
943
944 template => [ "PVE::API2::Qemu", 'template', ['vmid'], { node => $nodename }],
945
946 start => [ "PVE::API2::Qemu", 'vm_start', ['vmid'], { node => $nodename } , $upid_exit ],
947
948 stop => [ "PVE::API2::Qemu", 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit ],
949
950 reset => [ "PVE::API2::Qemu", 'vm_reset', ['vmid'], { node => $nodename }, $upid_exit ],
951
952 shutdown => [ "PVE::API2::Qemu", 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit ],
953
165411f0
DC
954 reboot => [ "PVE::API2::Qemu", 'vm_reboot', ['vmid'], { node => $nodename }, $upid_exit ],
955
f3e76e36
DM
956 suspend => [ "PVE::API2::Qemu", 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit ],
957
958 resume => [ "PVE::API2::Qemu", 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit ],
959
960 sendkey => [ "PVE::API2::Qemu", 'vm_sendkey', ['vmid', 'key'], { node => $nodename } ],
961
962 vncproxy => [ __PACKAGE__, 'vncproxy', ['vmid']],
963
964 wait => [ __PACKAGE__, 'wait', ['vmid']],
965
966 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
967
968 rescan => [ __PACKAGE__, 'rescan', []],
969
970 monitor => [ __PACKAGE__, 'monitor', ['vmid']],
971
bf744e94 972 agent => { alias => 'guest cmd' },
d1a47427 973
34e4c0aa 974 guest => {
bf744e94 975 cmd => [ "PVE::API2::Qemu::Agent", 'agent', ['vmid', 'command'], { node => $nodename }, $print_agent_result ],
8593cbe4 976 passwd => [ "PVE::API2::Qemu::Agent", 'set-user-password', [ 'vmid', 'username' ], { node => $nodename }],
520884de
DC
977 exec => [ __PACKAGE__, 'exec', [ 'vmid', 'extra-args' ], { node => $nodename }, $print_agent_result],
978 'exec-status' => [ "PVE::API2::Qemu::Agent", 'exec-status', [ 'vmid', 'pid' ], { node => $nodename }, $print_agent_result],
8593cbe4
DC
979 },
980
f3e76e36
DM
981 mtunnel => [ __PACKAGE__, 'mtunnel', []],
982
63a09370
AD
983 nbdstop => [ __PACKAGE__, 'nbdstop', ['vmid']],
984
f3e76e36 985 terminal => [ __PACKAGE__, 'terminal', ['vmid']],
8653feeb
EK
986
987 importdisk => [ __PACKAGE__, 'importdisk', ['vmid', 'source', 'storage']],
7cd9f6d7
EK
988
989 importovf => [ __PACKAGE__, 'importovf', ['vmid', 'manifest', 'storage']],
990
3ea84aeb
DC
991 cleanup => [ __PACKAGE__, 'cleanup', ['vmid', 'clean-shutdown', 'guest-requested'], { node => $nodename }],
992
1e1763e9
ML
993 cloudinit => {
994 dump => [ "PVE::API2::Qemu", 'cloudinit_generated_config_dump', ['vmid', 'type'], { node => $nodename }, sub {
995 my $data = shift;
996 print "$data\n";
997 }],
998 },
999
f3e76e36
DM
1000};
1001
10021;