]> git.proxmox.com Git - qemu-server.git/blob - PVE/CLI/qm.pm
bump version to 8.2.1
[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 'extra-args' => get_standard_option('extra-args'),
704 },
705 },
706 returns => {
707 type => 'object',
708 },
709 code => sub {
710 my ($param) = @_;
711
712 my $vmid = $param->{vmid};
713 my $sync = $param->{synchronous} // 1;
714 if (!$param->{'extra-args'} || !@{$param->{'extra-args'}}) {
715 raise_param_exc( { 'extra-args' => "No command given" });
716 }
717 if (defined($param->{timeout}) && !$sync) {
718 raise_param_exc({ synchronous => "needs to be set for 'timeout'"});
719 }
720
721 my $res = PVE::QemuServer::Agent::qemu_exec($vmid, $param->{'extra-args'});
722
723 if ($sync) {
724 my $pid = $res->{pid};
725 my $timeout = $param->{timeout} // 30;
726 my $starttime = time();
727
728 while ($timeout == 0 || (time() - $starttime) < $timeout) {
729 my $out = PVE::QemuServer::Agent::qemu_exec_status($vmid, $pid);
730 if ($out->{exited}) {
731 $res = $out;
732 last;
733 }
734 sleep 1;
735 }
736
737 if (!$res->{exited}) {
738 warn "timeout reached, returning pid\n";
739 }
740 }
741
742 return { result => $res };
743 }});
744
745 __PACKAGE__->register_method({
746 name => 'cleanup',
747 path => 'cleanup',
748 method => 'POST',
749 protected => 1,
750 description => "Cleans up resources like tap devices, vgpus, etc. Called after a vm shuts down, crashes, etc.",
751 parameters => {
752 additionalProperties => 0,
753 properties => {
754 node => get_standard_option('pve-node'),
755 vmid => get_standard_option('pve-vmid', {
756 completion => \&PVE::QemuServer::complete_vmid_running }),
757 'clean-shutdown' => {
758 type => 'boolean',
759 description => "Indicates if qemu shutdown cleanly.",
760 },
761 'guest-requested' => {
762 type => 'boolean',
763 description => "Indicates if the shutdown was requested by the guest or via qmp.",
764 },
765 },
766 },
767 returns => { type => 'null', },
768 code => sub {
769 my ($param) = @_;
770
771 my $vmid = $param->{vmid};
772 my $clean = $param->{'clean-shutdown'};
773 my $guest = $param->{'guest-requested'};
774 my $restart = 0;
775
776 # return if we do not have the config anymore
777 return if !-f PVE::QemuConfig->config_file($vmid);
778
779 my $storecfg = PVE::Storage::config();
780 warn "Starting cleanup for $vmid\n";
781
782 PVE::QemuConfig->lock_config($vmid, sub {
783 my $conf = PVE::QemuConfig->load_config ($vmid);
784 my $pid = PVE::QemuServer::check_running ($vmid);
785 die "vm still running\n" if $pid;
786
787 if (!$clean) {
788 # we have to cleanup the tap devices after a crash
789
790 foreach my $opt (keys %$conf) {
791 next if $opt !~ m/^net(\d)+$/;
792 my $interface = $1;
793 PVE::Network::tap_unplug("tap${vmid}i${interface}");
794 }
795 }
796
797 if (!$clean || $guest) {
798 # vm was shutdown from inside the guest or crashed, doing api cleanup
799 PVE::QemuServer::vm_stop_cleanup($storecfg, $vmid, $conf, 0, 0);
800 }
801 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-stop');
802
803 $restart = eval { PVE::QemuServer::clear_reboot_request($vmid) };
804 warn $@ if $@;
805 });
806
807 warn "Finished cleanup for $vmid\n";
808
809 if ($restart) {
810 warn "Restarting VM $vmid\n";
811 PVE::API2::Qemu->vm_start({
812 vmid => $vmid,
813 node => $nodename,
814 });
815 }
816
817 return undef;
818 }});
819
820 my $print_agent_result = sub {
821 my ($data) = @_;
822
823 my $result = $data->{result} // $data;
824 return if !defined($result);
825
826 my $class = ref($result);
827
828 if (!$class) {
829 chomp $result;
830 return if $result =~ m/^\s*$/;
831 print "$result\n";
832 return;
833 }
834
835 if (($class eq 'HASH') && !scalar(keys %$result)) { # empty hash
836 return;
837 }
838
839 print to_json($result, { pretty => 1, canonical => 1});
840 };
841
842 sub param_mapping {
843 my ($name) = @_;
844
845 my $ssh_key_map = ['sshkeys', sub {
846 return URI::Escape::uri_escape(PVE::Tools::file_get_contents($_[0]));
847 }];
848 my $cipassword_map = PVE::CLIHandler::get_standard_mapping('pve-password', { name => 'cipassword' });
849 my $password_map = PVE::CLIHandler::get_standard_mapping('pve-password');
850 my $mapping = {
851 'update_vm' => [$ssh_key_map, $cipassword_map],
852 'create_vm' => [$ssh_key_map, $cipassword_map],
853 'set-user-password' => [$password_map],
854 };
855
856 return $mapping->{$name};
857 }
858
859 our $cmddef = {
860 list => [ "PVE::API2::Qemu", 'vmlist', [],
861 { node => $nodename }, sub {
862 my $vmlist = shift;
863
864 exit 0 if (!scalar(@$vmlist));
865
866 printf "%10s %-20s %-10s %-10s %12s %-10s\n",
867 qw(VMID NAME STATUS MEM(MB) BOOTDISK(GB) PID);
868
869 foreach my $rec (sort { $a->{vmid} <=> $b->{vmid} } @$vmlist) {
870 printf "%10s %-20s %-10s %-10s %12.2f %-10s\n", $rec->{vmid}, $rec->{name},
871 $rec->{qmpstatus} || $rec->{status},
872 ($rec->{maxmem} || 0)/(1024*1024),
873 ($rec->{maxdisk} || 0)/(1024*1024*1024),
874 $rec->{pid}||0;
875 }
876
877
878 } ],
879
880 create => [ "PVE::API2::Qemu", 'create_vm', ['vmid'], { node => $nodename }, $upid_exit ],
881
882 destroy => [ "PVE::API2::Qemu", 'destroy_vm', ['vmid'], { node => $nodename }, $upid_exit ],
883
884 clone => [ "PVE::API2::Qemu", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
885
886 migrate => [ "PVE::API2::Qemu", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit ],
887
888 set => [ "PVE::API2::Qemu", 'update_vm', ['vmid'], { node => $nodename } ],
889
890 resize => [ "PVE::API2::Qemu", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
891
892 move_disk => [ "PVE::API2::Qemu", 'move_vm_disk', ['vmid', 'disk', 'storage'], { node => $nodename }, $upid_exit ],
893
894 unlink => [ "PVE::API2::Qemu", 'unlink', ['vmid'], { node => $nodename } ],
895
896 config => [ "PVE::API2::Qemu", 'vm_config', ['vmid'],
897 { node => $nodename }, sub {
898 my $config = shift;
899 foreach my $k (sort (keys %$config)) {
900 next if $k eq 'digest';
901 my $v = $config->{$k};
902 if ($k eq 'description') {
903 $v = PVE::Tools::encode_text($v);
904 }
905 print "$k: $v\n";
906 }
907 }],
908
909 pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::format_pending ],
910 showcmd => [ __PACKAGE__, 'showcmd', ['vmid']],
911
912 status => [ __PACKAGE__, 'status', ['vmid']],
913
914 snapshot => [ "PVE::API2::Qemu", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
915
916 delsnapshot => [ "PVE::API2::Qemu", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
917
918 listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::print_snapshot_tree],
919
920 rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
921
922 template => [ "PVE::API2::Qemu", 'template', ['vmid'], { node => $nodename }],
923
924 start => [ "PVE::API2::Qemu", 'vm_start', ['vmid'], { node => $nodename } , $upid_exit ],
925
926 stop => [ "PVE::API2::Qemu", 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit ],
927
928 reset => [ "PVE::API2::Qemu", 'vm_reset', ['vmid'], { node => $nodename }, $upid_exit ],
929
930 shutdown => [ "PVE::API2::Qemu", 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit ],
931
932 reboot => [ "PVE::API2::Qemu", 'vm_reboot', ['vmid'], { node => $nodename }, $upid_exit ],
933
934 suspend => [ "PVE::API2::Qemu", 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit ],
935
936 resume => [ "PVE::API2::Qemu", 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit ],
937
938 sendkey => [ "PVE::API2::Qemu", 'vm_sendkey', ['vmid', 'key'], { node => $nodename } ],
939
940 vncproxy => [ __PACKAGE__, 'vncproxy', ['vmid']],
941
942 wait => [ __PACKAGE__, 'wait', ['vmid']],
943
944 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
945
946 rescan => [ __PACKAGE__, 'rescan', []],
947
948 monitor => [ __PACKAGE__, 'monitor', ['vmid']],
949
950 agent => { alias => 'guest cmd' },
951
952 guest => {
953 cmd => [ "PVE::API2::Qemu::Agent", 'agent', ['vmid', 'command'], { node => $nodename }, $print_agent_result ],
954 passwd => [ "PVE::API2::Qemu::Agent", 'set-user-password', [ 'vmid', 'username' ], { node => $nodename }],
955 exec => [ __PACKAGE__, 'exec', [ 'vmid', 'extra-args' ], { node => $nodename }, $print_agent_result],
956 'exec-status' => [ "PVE::API2::Qemu::Agent", 'exec-status', [ 'vmid', 'pid' ], { node => $nodename }, $print_agent_result],
957 },
958
959 mtunnel => [ __PACKAGE__, 'mtunnel', []],
960
961 nbdstop => [ __PACKAGE__, 'nbdstop', ['vmid']],
962
963 terminal => [ __PACKAGE__, 'terminal', ['vmid']],
964
965 importdisk => [ __PACKAGE__, 'importdisk', ['vmid', 'source', 'storage']],
966
967 importovf => [ __PACKAGE__, 'importovf', ['vmid', 'manifest', 'storage']],
968
969 cleanup => [ __PACKAGE__, 'cleanup', ['vmid', 'clean-shutdown', 'guest-requested'], { node => $nodename }],
970
971 cloudinit => {
972 dump => [ "PVE::API2::Qemu", 'cloudinit_generated_config_dump', ['vmid', 'type'], { node => $nodename }, sub {
973 my $data = shift;
974 print "$data\n";
975 }],
976 },
977
978 };
979
980 1;