]> git.proxmox.com Git - qemu-server.git/blob - PVE/CLI/qm.pm
f99d4015c49d564de3f69e43b46005663d005049
[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::Drive;
32 use PVE::QemuServer::Helpers;
33 use PVE::QemuServer::Agent qw(agent_available);
34 use PVE::QemuServer::ImportDisk;
35 use PVE::QemuServer::Monitor qw(mon_cmd);
36 use PVE::QemuServer::OVF;
37 use PVE::QemuServer;
38
39 use PVE::CLIHandler;
40 use base qw(PVE::CLIHandler);
41
42 my $upid_exit = sub {
43 my $upid = shift;
44 my $status = PVE::Tools::upid_read_status($upid);
45 exit($status eq 'OK' ? 0 : -1);
46 };
47
48 my $nodename = PVE::INotify::nodename();
49
50 sub setup_environment {
51 PVE::RPCEnvironment->setup_default_cli_env();
52 }
53
54 sub 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
64 my $select = new IO::Select;
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
96 sub 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 }
103 foreach my $itemkey (keys %$hash) {
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 }
110 foreach my $item (@$hash) {
111 print_recursive_hash("\t$prefix", $item);
112 }
113 } elsif (!ref($hash) && defined($hash)) {
114 if (defined($key)) {
115 print "$prefix$key: $hash\n";
116 } else {
117 print "$prefix$hash\n";
118 }
119 }
120 }
121
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 => {
130 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
131 pretty => {
132 description => "Puts each option on a new line to enhance human readability",
133 type => 'boolean',
134 optional => 1,
135 default => 0,
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 }),
145 },
146 },
147 returns => { type => 'null'},
148 code => sub {
149 my ($param) = @_;
150
151 my $storecfg = PVE::Storage::config();
152 my $cmdline = PVE::QemuServer::vm_commandline($storecfg, $param->{vmid}, $param->{snapshot});
153
154 $cmdline =~ s/ -/ \\\n -/g if $param->{pretty};
155
156 print "$cmdline\n";
157
158 return undef;
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 => {
169 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
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
182 my $conf = PVE::QemuConfig->load_config ($param->{vmid});
183
184 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
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};
190 print_recursive_hash("", $v, $k);
191 }
192 } else {
193 my $status = $stat->{qmpstatus} || 'unknown';
194 print "status: $status\n";
195 }
196
197 return undef;
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 => {
208 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
209 },
210 },
211 returns => { type => 'null'},
212 code => sub {
213 my ($param) = @_;
214
215 my $vmid = $param->{vmid};
216 PVE::QemuConfig::assert_config_exists_on_node($vmid);
217 my $vnc_socket = PVE::QemuServer::Helpers::vnc_socket($vmid);
218
219 if (my $ticket = $ENV{LC_PVE_TICKET}) { # NOTE: ssh on debian only pass LC_* variables
220 mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
221 mon_cmd($vmid, "set_password", protocol => 'vnc', password => $ticket);
222 mon_cmd($vmid, "expire_password", protocol => 'vnc', time => "+30");
223 } else {
224 # FIXME: remove or allow to add tls-creds object, as x509 vnc param is removed with qemu 4??
225 mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
226 }
227
228 run_vnc_proxy($vnc_socket);
229
230 return undef;
231 }});
232
233 __PACKAGE__->register_method ({
234 name => 'unlock',
235 path => 'unlock',
236 method => 'PUT',
237 description => "Unlock the VM.",
238 parameters => {
239 additionalProperties => 0,
240 properties => {
241 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
242 },
243 },
244 returns => { type => 'null'},
245 code => sub {
246 my ($param) = @_;
247
248 my $vmid = $param->{vmid};
249
250 PVE::QemuConfig->lock_config ($vmid, sub {
251 my $conf = PVE::QemuConfig->load_config($vmid);
252 delete $conf->{lock};
253 delete $conf->{pending}->{lock} if $conf->{pending}; # just to be sure
254 PVE::QemuConfig->write_config($vmid, $conf);
255 });
256
257 return undef;
258 }});
259
260 __PACKAGE__->register_method ({
261 name => 'nbdstop',
262 path => 'nbdstop',
263 method => 'PUT',
264 description => "Stop embedded nbd server.",
265 parameters => {
266 additionalProperties => 0,
267 properties => {
268 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
269 },
270 },
271 returns => { type => 'null'},
272 code => sub {
273 my ($param) = @_;
274
275 my $vmid = $param->{vmid};
276
277 PVE::QemuServer::nbd_stop($vmid);
278
279 return undef;
280 }});
281
282 __PACKAGE__->register_method ({
283 name => 'mtunnel',
284 path => 'mtunnel',
285 method => 'POST',
286 description => "Used by qmigrate - do not use manually.",
287 parameters => {
288 additionalProperties => 0,
289 properties => {},
290 },
291 returns => { type => 'null'},
292 code => sub {
293 my ($param) = @_;
294
295 if (!PVE::Cluster::check_cfs_quorum(1)) {
296 print "no quorum\n";
297 return undef;
298 }
299
300 my $tunnel_write = sub {
301 my $text = shift;
302 chomp $text;
303 print "$text\n";
304 *STDOUT->flush();
305 };
306
307 $tunnel_write->("tunnel online");
308 $tunnel_write->("ver 1");
309
310 while (my $line = <STDIN>) {
311 chomp $line;
312 if ($line =~ /^quit$/) {
313 $tunnel_write->("OK");
314 last;
315 } elsif ($line =~ /^resume (\d+)$/) {
316 my $vmid = $1;
317 if (PVE::QemuServer::check_running($vmid, 1)) {
318 eval { PVE::QemuServer::vm_resume($vmid, 1, 1); };
319 if ($@) {
320 $tunnel_write->("ERR: resume failed - $@");
321 } else {
322 $tunnel_write->("OK");
323 }
324 } else {
325 $tunnel_write->("ERR: resume failed - VM $vmid not running");
326 }
327 }
328 }
329
330 return undef;
331 }});
332
333 __PACKAGE__->register_method ({
334 name => 'wait',
335 path => 'wait',
336 method => 'GET',
337 description => "Wait until the VM is stopped.",
338 parameters => {
339 additionalProperties => 0,
340 properties => {
341 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
342 timeout => {
343 description => "Timeout in seconds. Default is to wait forever.",
344 type => 'integer',
345 minimum => 1,
346 optional => 1,
347 }
348 },
349 },
350 returns => { type => 'null'},
351 code => sub {
352 my ($param) = @_;
353
354 my $vmid = $param->{vmid};
355 my $timeout = $param->{timeout};
356
357 my $pid = PVE::QemuServer::check_running ($vmid);
358 return if !$pid;
359
360 print "waiting until VM $vmid stopps (PID $pid)\n";
361
362 my $count = 0;
363 while ((!$timeout || ($count < $timeout)) && PVE::QemuServer::check_running ($vmid)) {
364 $count++;
365 sleep 1;
366 }
367
368 die "wait failed - got timeout\n" if PVE::QemuServer::check_running ($vmid);
369
370 return undef;
371 }});
372
373 __PACKAGE__->register_method ({
374 name => 'monitor',
375 path => 'monitor',
376 method => 'POST',
377 description => "Enter Qemu Monitor interface.",
378 parameters => {
379 additionalProperties => 0,
380 properties => {
381 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
382 },
383 },
384 returns => { type => 'null'},
385 code => sub {
386 my ($param) = @_;
387
388 my $vmid = $param->{vmid};
389
390 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
391
392 print "Entering Qemu Monitor for VM $vmid - type 'help' for help\n";
393
394 my $term = new Term::ReadLine ('qm');
395
396 my $input;
397 while (defined ($input = $term->readline('qm> '))) {
398 chomp $input;
399
400 next if $input =~ m/^\s*$/;
401
402 last if $input =~ m/^\s*q(uit)?\s*$/;
403
404 eval {
405 print PVE::QemuServer::Monitor::hmp_cmd($vmid, $input);
406 };
407 print "ERROR: $@" if $@;
408 }
409
410 return undef;
411
412 }});
413
414 __PACKAGE__->register_method ({
415 name => 'rescan',
416 path => 'rescan',
417 method => 'POST',
418 description => "Rescan all storages and update disk sizes and unused disk images.",
419 parameters => {
420 additionalProperties => 0,
421 properties => {
422 vmid => get_standard_option('pve-vmid', {
423 optional => 1,
424 completion => \&PVE::QemuServer::complete_vmid,
425 }),
426 dryrun => {
427 type => 'boolean',
428 optional => 1,
429 default => 0,
430 description => 'Do not actually write changes out to VM config(s).',
431 },
432 },
433 },
434 returns => { type => 'null'},
435 code => sub {
436 my ($param) = @_;
437
438 my $dryrun = $param->{dryrun};
439
440 print "NOTE: running in dry-run mode, won't write changes out!\n" if $dryrun;
441
442 PVE::QemuServer::rescan($param->{vmid}, 0, $dryrun);
443
444 return undef;
445 }});
446
447 __PACKAGE__->register_method ({
448 name => 'importdisk',
449 path => 'importdisk',
450 method => 'POST',
451 description => "Import an external disk image as an unused disk in a VM. The
452 image format has to be supported by qemu-img(1).",
453 parameters => {
454 additionalProperties => 0,
455 properties => {
456 vmid => get_standard_option('pve-vmid', {completion => \&PVE::QemuServer::complete_vmid}),
457 source => {
458 description => 'Path to the disk image to import',
459 type => 'string',
460 optional => 0,
461 },
462 storage => get_standard_option('pve-storage-id', {
463 description => 'Target storage ID',
464 completion => \&PVE::QemuServer::complete_storage,
465 optional => 0,
466 }),
467 format => {
468 type => 'string',
469 description => 'Target format',
470 enum => [ 'raw', 'qcow2', 'vmdk' ],
471 optional => 1,
472 },
473 },
474 },
475 returns => { type => 'null'},
476 code => sub {
477 my ($param) = @_;
478
479 my $vmid = extract_param($param, 'vmid');
480 my $source = extract_param($param, 'source');
481 my $storeid = extract_param($param, 'storage');
482 my $format = extract_param($param, 'format');
483
484 my $vm_conf = PVE::QemuConfig->load_config($vmid);
485 PVE::QemuConfig->check_lock($vm_conf);
486 die "$source: non-existent or non-regular file\n" if (! -f $source);
487
488 my $storecfg = PVE::Storage::config();
489 PVE::Storage::storage_check_enabled($storecfg, $storeid);
490
491 my $target_storage_config = PVE::Storage::storage_config($storecfg, $storeid);
492 die "storage $storeid does not support vm images\n"
493 if !$target_storage_config->{content}->{images};
494
495 print "importing disk '$source' to VM $vmid ...\n";
496 my ($drive_id, $volid) = PVE::QemuServer::ImportDisk::do_import($source, $vmid, $storeid, { format => $format });
497 print "Successfully imported disk as '$drive_id:$volid'\n";
498
499 return undef;
500 }});
501
502 __PACKAGE__->register_method ({
503 name => 'terminal',
504 path => 'terminal',
505 method => 'POST',
506 description => "Open a terminal using a serial device (The VM need to have a serial device configured, for example 'serial0: socket')",
507 parameters => {
508 additionalProperties => 0,
509 properties => {
510 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
511 iface => {
512 description => "Select the serial device. By default we simply use the first suitable device.",
513 type => 'string',
514 optional => 1,
515 enum => [qw(serial0 serial1 serial2 serial3)],
516 },
517 escape => {
518 description => "Escape character.",
519 type => 'string',
520 optional => 1,
521 default => '^O',
522 },
523 },
524 },
525 returns => { type => 'null'},
526 code => sub {
527 my ($param) = @_;
528
529 my $vmid = $param->{vmid};
530
531 my $escape = $param->{escape} // '^O';
532 if ($escape =~ /^\^([\x40-\x7a])$/) {
533 $escape = ord($1) & 0x1F;
534 } elsif ($escape =~ /^0x[0-9a-f]+$/i) {
535 $escape = hex($escape);
536 } elsif ($escape =~ /^[0-9]+$/) {
537 $escape = int($escape);
538 } else {
539 die "invalid escape character definition: $escape\n";
540 }
541 my $escapemsg = '';
542 if ($escape) {
543 $escapemsg = sprintf(' (press Ctrl+%c to exit)', $escape+0x40);
544 $escape = sprintf(',escape=0x%x', $escape);
545 } else {
546 $escape = '';
547 }
548
549 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
550
551 my $iface = $param->{iface};
552
553 if ($iface) {
554 die "serial interface '$iface' is not configured\n" if !$conf->{$iface};
555 die "wrong serial type on interface '$iface'\n" if $conf->{$iface} ne 'socket';
556 } else {
557 foreach my $opt (qw(serial0 serial1 serial2 serial3)) {
558 if ($conf->{$opt} && ($conf->{$opt} eq 'socket')) {
559 $iface = $opt;
560 last;
561 }
562 }
563 die "unable to find a serial interface\n" if !$iface;
564 }
565
566 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
567
568 my $socket = "/var/run/qemu-server/${vmid}.$iface";
569
570 my $cmd = "socat UNIX-CONNECT:$socket STDIO,raw,echo=0$escape";
571
572 print "starting serial terminal on interface ${iface}${escapemsg}\n";
573
574 system($cmd);
575
576 return undef;
577 }});
578
579 __PACKAGE__->register_method ({
580 name => 'importovf',
581 path => 'importovf',
582 description => "Create a new VM using parameters read from an OVF manifest",
583 parameters => {
584 additionalProperties => 0,
585 properties => {
586 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
587 manifest => {
588 type => 'string',
589 description => 'path to the ovf file',
590 },
591 storage => get_standard_option('pve-storage-id', {
592 description => 'Target storage ID',
593 completion => \&PVE::QemuServer::complete_storage,
594 optional => 0,
595 }),
596 format => {
597 type => 'string',
598 description => 'Target format',
599 enum => [ 'raw', 'qcow2', 'vmdk' ],
600 optional => 1,
601 },
602 dryrun => {
603 type => 'boolean',
604 description => 'Print a parsed representation of the extracted OVF parameters, but do not create a VM',
605 optional => 1,
606 }
607 },
608 },
609 returns => { type => 'null' },
610 code => sub {
611 my ($param) = @_;
612
613 my $vmid = PVE::Tools::extract_param($param, 'vmid');
614 my $ovf_file = PVE::Tools::extract_param($param, 'manifest');
615 my $storeid = PVE::Tools::extract_param($param, 'storage');
616 my $format = PVE::Tools::extract_param($param, 'format');
617 my $dryrun = PVE::Tools::extract_param($param, 'dryrun');
618
619 die "$ovf_file: non-existent or non-regular file\n" if (! -f $ovf_file);
620 my $storecfg = PVE::Storage::config();
621 PVE::Storage::storage_check_enabled($storecfg, $storeid);
622
623 my $parsed = PVE::QemuServer::OVF::parse_ovf($ovf_file);
624
625 if ($dryrun) {
626 print to_json($parsed, { pretty => 1, canonical => 1});
627 return;
628 }
629
630 eval { PVE::QemuConfig->create_and_lock_config($vmid) };
631 die "Reserving empty config for OVF import to VM $vmid failed: $@" if $@;
632
633 my $conf = PVE::QemuConfig->load_config($vmid);
634 die "Internal error: Expected 'create' lock in config of VM $vmid!"
635 if !PVE::QemuConfig->has_lock($conf, "create");
636
637 $conf->{name} = $parsed->{qm}->{name} if defined($parsed->{qm}->{name});
638 $conf->{memory} = $parsed->{qm}->{memory} if defined($parsed->{qm}->{memory});
639 $conf->{cores} = $parsed->{qm}->{cores} if defined($parsed->{qm}->{cores});
640
641 eval {
642 # order matters, as do_import() will load_config() internally
643 $conf->{vmgenid} = PVE::QemuServer::generate_uuid();
644 $conf->{smbios1} = PVE::QemuServer::generate_smbios1_uuid();
645 PVE::QemuConfig->write_config($vmid, $conf);
646
647 foreach my $disk (@{ $parsed->{disks} }) {
648 my ($file, $drive) = ($disk->{backing_file}, $disk->{disk_address});
649 PVE::QemuServer::ImportDisk::do_import($file, $vmid, $storeid, {
650 drive_name => $drive,
651 format => $format,
652 skiplock => 1,
653 });
654 }
655
656 # reload after disks entries have been created
657 $conf = PVE::QemuConfig->load_config($vmid);
658 my $firstdisk = PVE::QemuServer::Drive::resolve_first_disk($conf);
659 $conf->{bootdisk} = $firstdisk if $firstdisk;
660 PVE::QemuConfig->write_config($vmid, $conf);
661 };
662
663 my $err = $@;
664 if ($err) {
665 my $skiplock = 1;
666 # eval for additional safety in error path
667 eval { PVE::QemuServer::destroy_vm($storecfg, $vmid, $skiplock) };
668 warn "Could not destroy VM $vmid: $@" if "$@";
669 die "import failed - $err";
670 }
671
672 PVE::QemuConfig->remove_lock($vmid, "create");
673
674 return undef;
675
676 }
677 });
678
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 },
704 'pass-stdin' => {
705 type => 'boolean',
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.",
707 optional => 1,
708 default => 0,
709 },
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;
721 my $pass_stdin = $param->{'pass-stdin'};
722 if (defined($param->{timeout}) && !$sync) {
723 raise_param_exc({ synchronous => "needs to be set for 'timeout'"});
724 }
725
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);
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
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'};
795 my $restart = 0;
796
797 # return if we do not have the config anymore
798 return if !-f PVE::QemuConfig->config_file($vmid);
799
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 }
822 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-stop');
823
824 $restart = eval { PVE::QemuServer::clear_reboot_request($vmid) };
825 warn $@ if $@;
826 });
827
828 warn "Finished cleanup for $vmid\n";
829
830 if ($restart) {
831 warn "Restarting VM $vmid\n";
832 PVE::API2::Qemu->vm_start({
833 vmid => $vmid,
834 node => $nodename,
835 });
836 }
837
838 return undef;
839 }});
840
841 my $print_agent_result = sub {
842 my ($data) = @_;
843
844 my $result = $data->{result} // $data;
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
863 sub 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 }];
869 my $cipassword_map = PVE::CLIHandler::get_standard_mapping('pve-password', { name => 'cipassword' });
870 my $password_map = PVE::CLIHandler::get_standard_mapping('pve-password');
871 my $mapping = {
872 'update_vm' => [$ssh_key_map, $cipassword_map],
873 'create_vm' => [$ssh_key_map, $cipassword_map],
874 'set-user-password' => [$password_map],
875 };
876
877 return $mapping->{$name};
878 }
879
880 our $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},
892 $rec->{qmpstatus} || $rec->{status},
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
913 move_disk => [ "PVE::API2::Qemu", 'move_vm_disk', ['vmid', 'disk', 'storage'], { node => $nodename }, $upid_exit ],
914
915 unlink => [ "PVE::API2::Qemu", 'unlink', ['vmid'], { node => $nodename } ],
916
917 config => [ "PVE::API2::Qemu", 'vm_config', ['vmid'],
918 { node => $nodename }, sub {
919 my $config = shift;
920 foreach my $k (sort (keys %$config)) {
921 next if $k eq 'digest';
922 my $v = $config->{$k};
923 if ($k eq 'description') {
924 $v = PVE::Tools::encode_text($v);
925 }
926 print "$k: $v\n";
927 }
928 }],
929
930 pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::format_pending ],
931 showcmd => [ __PACKAGE__, 'showcmd', ['vmid']],
932
933 status => [ __PACKAGE__, 'status', ['vmid']],
934
935 snapshot => [ "PVE::API2::Qemu", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
936
937 delsnapshot => [ "PVE::API2::Qemu", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
938
939 listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::print_snapshot_tree],
940
941 rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
942
943 template => [ "PVE::API2::Qemu", 'template', ['vmid'], { node => $nodename }],
944
945 start => [ "PVE::API2::Qemu", 'vm_start', ['vmid'], { node => $nodename } , $upid_exit ],
946
947 stop => [ "PVE::API2::Qemu", 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit ],
948
949 reset => [ "PVE::API2::Qemu", 'vm_reset', ['vmid'], { node => $nodename }, $upid_exit ],
950
951 shutdown => [ "PVE::API2::Qemu", 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit ],
952
953 reboot => [ "PVE::API2::Qemu", 'vm_reboot', ['vmid'], { node => $nodename }, $upid_exit ],
954
955 suspend => [ "PVE::API2::Qemu", 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit ],
956
957 resume => [ "PVE::API2::Qemu", 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit ],
958
959 sendkey => [ "PVE::API2::Qemu", 'vm_sendkey', ['vmid', 'key'], { node => $nodename } ],
960
961 vncproxy => [ __PACKAGE__, 'vncproxy', ['vmid']],
962
963 wait => [ __PACKAGE__, 'wait', ['vmid']],
964
965 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
966
967 rescan => [ __PACKAGE__, 'rescan', []],
968
969 monitor => [ __PACKAGE__, 'monitor', ['vmid']],
970
971 agent => { alias => 'guest cmd' },
972
973 guest => {
974 cmd => [ "PVE::API2::Qemu::Agent", 'agent', ['vmid', 'command'], { node => $nodename }, $print_agent_result ],
975 passwd => [ "PVE::API2::Qemu::Agent", 'set-user-password', [ 'vmid', 'username' ], { node => $nodename }],
976 exec => [ __PACKAGE__, 'exec', [ 'vmid', 'extra-args' ], { node => $nodename }, $print_agent_result],
977 'exec-status' => [ "PVE::API2::Qemu::Agent", 'exec-status', [ 'vmid', 'pid' ], { node => $nodename }, $print_agent_result],
978 },
979
980 mtunnel => [ __PACKAGE__, 'mtunnel', []],
981
982 nbdstop => [ __PACKAGE__, 'nbdstop', ['vmid']],
983
984 terminal => [ __PACKAGE__, 'terminal', ['vmid']],
985
986 importdisk => [ __PACKAGE__, 'importdisk', ['vmid', 'source', 'storage']],
987
988 importovf => [ __PACKAGE__, 'importovf', ['vmid', 'manifest', 'storage']],
989
990 cleanup => [ __PACKAGE__, 'cleanup', ['vmid', 'clean-shutdown', 'guest-requested'], { node => $nodename }],
991
992 cloudinit => {
993 dump => [ "PVE::API2::Qemu", 'cloudinit_generated_config_dump', ['vmid', 'type'], { node => $nodename }, sub {
994 my $data = shift;
995 print "$data\n";
996 }],
997 },
998
999 };
1000
1001 1;