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