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