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