]> git.proxmox.com Git - qemu-server.git/blob - PVE/CLI/qm.pm
Fix #1999: cli: listsnapshot: handle multiple roots and mark orphaned as root
[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 use POSIX qw(strftime);
15
16 use PVE::Tools qw(extract_param);
17 use PVE::Cluster;
18 use PVE::SafeSyslog;
19 use PVE::INotify;
20 use PVE::RPCEnvironment;
21 use PVE::Exception qw(raise_param_exc);
22 use PVE::Network;
23 use PVE::GuestHelpers;
24 use PVE::QemuServer;
25 use PVE::QemuServer::ImportDisk;
26 use PVE::QemuServer::OVF;
27 use PVE::QemuServer::Agent qw(agent_available);
28 use PVE::API2::Qemu;
29 use PVE::API2::Qemu::Agent;
30 use JSON;
31 use PVE::JSONSchema qw(get_standard_option);
32 use Term::ReadLine;
33
34 use PVE::CLIHandler;
35
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 PVE::QemuServer::vm_mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,x509,password");
220 }
221
222 run_vnc_proxy($vnc_socket);
223
224 return undef;
225 }});
226
227 __PACKAGE__->register_method ({
228 name => 'unlock',
229 path => 'unlock',
230 method => 'PUT',
231 description => "Unlock the VM.",
232 parameters => {
233 additionalProperties => 0,
234 properties => {
235 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
236 },
237 },
238 returns => { type => 'null'},
239 code => sub {
240 my ($param) = @_;
241
242 my $vmid = $param->{vmid};
243
244 PVE::QemuConfig->lock_config ($vmid, sub {
245 my $conf = PVE::QemuConfig->load_config($vmid);
246 delete $conf->{lock};
247 delete $conf->{pending}->{lock} if $conf->{pending}; # just to be sure
248 PVE::QemuConfig->write_config($vmid, $conf);
249 });
250
251 return undef;
252 }});
253
254 __PACKAGE__->register_method ({
255 name => 'nbdstop',
256 path => 'nbdstop',
257 method => 'PUT',
258 description => "Stop embedded nbd server.",
259 parameters => {
260 additionalProperties => 0,
261 properties => {
262 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
263 },
264 },
265 returns => { type => 'null'},
266 code => sub {
267 my ($param) = @_;
268
269 my $vmid = $param->{vmid};
270
271 PVE::QemuServer::nbd_stop($vmid);
272
273 return undef;
274 }});
275
276 __PACKAGE__->register_method ({
277 name => 'mtunnel',
278 path => 'mtunnel',
279 method => 'POST',
280 description => "Used by qmigrate - do not use manually.",
281 parameters => {
282 additionalProperties => 0,
283 properties => {},
284 },
285 returns => { type => 'null'},
286 code => sub {
287 my ($param) = @_;
288
289 if (!PVE::Cluster::check_cfs_quorum(1)) {
290 print "no quorum\n";
291 return undef;
292 }
293
294 my $tunnel_write = sub {
295 my $text = shift;
296 chomp $text;
297 print "$text\n";
298 *STDOUT->flush();
299 };
300
301 $tunnel_write->("tunnel online");
302 $tunnel_write->("ver 1");
303
304 while (my $line = <STDIN>) {
305 chomp $line;
306 if ($line =~ /^quit$/) {
307 $tunnel_write->("OK");
308 last;
309 } elsif ($line =~ /^resume (\d+)$/) {
310 my $vmid = $1;
311 if (PVE::QemuServer::check_running($vmid, 1)) {
312 eval { PVE::QemuServer::vm_resume($vmid, 1, 1); };
313 if ($@) {
314 $tunnel_write->("ERR: resume failed - $@");
315 } else {
316 $tunnel_write->("OK");
317 }
318 } else {
319 $tunnel_write->("ERR: resume failed - VM $vmid not running");
320 }
321 }
322 }
323
324 return undef;
325 }});
326
327 __PACKAGE__->register_method ({
328 name => 'wait',
329 path => 'wait',
330 method => 'GET',
331 description => "Wait until the VM is stopped.",
332 parameters => {
333 additionalProperties => 0,
334 properties => {
335 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
336 timeout => {
337 description => "Timeout in seconds. Default is to wait forever.",
338 type => 'integer',
339 minimum => 1,
340 optional => 1,
341 }
342 },
343 },
344 returns => { type => 'null'},
345 code => sub {
346 my ($param) = @_;
347
348 my $vmid = $param->{vmid};
349 my $timeout = $param->{timeout};
350
351 my $pid = PVE::QemuServer::check_running ($vmid);
352 return if !$pid;
353
354 print "waiting until VM $vmid stopps (PID $pid)\n";
355
356 my $count = 0;
357 while ((!$timeout || ($count < $timeout)) && PVE::QemuServer::check_running ($vmid)) {
358 $count++;
359 sleep 1;
360 }
361
362 die "wait failed - got timeout\n" if PVE::QemuServer::check_running ($vmid);
363
364 return undef;
365 }});
366
367 __PACKAGE__->register_method ({
368 name => 'monitor',
369 path => 'monitor',
370 method => 'POST',
371 description => "Enter Qemu Monitor interface.",
372 parameters => {
373 additionalProperties => 0,
374 properties => {
375 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
376 },
377 },
378 returns => { type => 'null'},
379 code => sub {
380 my ($param) = @_;
381
382 my $vmid = $param->{vmid};
383
384 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
385
386 print "Entering Qemu Monitor for VM $vmid - type 'help' for help\n";
387
388 my $term = new Term::ReadLine ('qm');
389
390 my $input;
391 while (defined ($input = $term->readline('qm> '))) {
392 chomp $input;
393
394 next if $input =~ m/^\s*$/;
395
396 last if $input =~ m/^\s*q(uit)?\s*$/;
397
398 eval {
399 print PVE::QemuServer::vm_human_monitor_command ($vmid, $input);
400 };
401 print "ERROR: $@" if $@;
402 }
403
404 return undef;
405
406 }});
407
408 __PACKAGE__->register_method ({
409 name => 'rescan',
410 path => 'rescan',
411 method => 'POST',
412 description => "Rescan all storages and update disk sizes and unused disk images.",
413 parameters => {
414 additionalProperties => 0,
415 properties => {
416 vmid => get_standard_option('pve-vmid', {
417 optional => 1,
418 completion => \&PVE::QemuServer::complete_vmid,
419 }),
420 dryrun => {
421 type => 'boolean',
422 optional => 1,
423 default => 0,
424 description => 'Do not actually write changes out to VM config(s).',
425 },
426 },
427 },
428 returns => { type => 'null'},
429 code => sub {
430 my ($param) = @_;
431
432 my $dryrun = $param->{dryrun};
433
434 print "NOTE: running in dry-run mode, won't write changes out!\n" if $dryrun;
435
436 PVE::QemuServer::rescan($param->{vmid}, 0, $dryrun);
437
438 return undef;
439 }});
440
441 __PACKAGE__->register_method ({
442 name => 'importdisk',
443 path => 'importdisk',
444 method => 'POST',
445 description => "Import an external disk image as an unused disk in a VM. The
446 image format has to be supported by qemu-img(1).",
447 parameters => {
448 additionalProperties => 0,
449 properties => {
450 vmid => get_standard_option('pve-vmid', {completion => \&PVE::QemuServer::complete_vmid}),
451 source => {
452 description => 'Path to the disk image to import',
453 type => 'string',
454 optional => 0,
455 },
456 storage => get_standard_option('pve-storage-id', {
457 description => 'Target storage ID',
458 completion => \&PVE::QemuServer::complete_storage,
459 optional => 0,
460 }),
461 format => {
462 type => 'string',
463 description => 'Target format',
464 enum => [ 'raw', 'qcow2', 'vmdk' ],
465 optional => 1,
466 },
467 },
468 },
469 returns => { type => 'null'},
470 code => sub {
471 my ($param) = @_;
472
473 my $vmid = extract_param($param, 'vmid');
474 my $source = extract_param($param, 'source');
475 my $storeid = extract_param($param, 'storage');
476 my $format = extract_param($param, 'format');
477
478 my $vm_conf = PVE::QemuConfig->load_config($vmid);
479 PVE::QemuConfig->check_lock($vm_conf);
480 die "$source: non-existent or non-regular file\n" if (! -f $source);
481
482 my $storecfg = PVE::Storage::config();
483 PVE::Storage::storage_check_enabled($storecfg, $storeid);
484
485 my $target_storage_config =
486 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 PVE::QemuServer::ImportDisk::do_import($source, $vmid, $storeid, { format => $format });
491
492 return undef;
493 }});
494
495 __PACKAGE__->register_method ({
496 name => 'terminal',
497 path => 'terminal',
498 method => 'POST',
499 description => "Open a terminal using a serial device (The VM need to have a serial device configured, for example 'serial0: socket')",
500 parameters => {
501 additionalProperties => 0,
502 properties => {
503 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
504 iface => {
505 description => "Select the serial device. By default we simply use the first suitable device.",
506 type => 'string',
507 optional => 1,
508 enum => [qw(serial0 serial1 serial2 serial3)],
509 },
510 escape => {
511 description => "Escape character.",
512 type => 'string',
513 optional => 1,
514 default => '^O',
515 },
516 },
517 },
518 returns => { type => 'null'},
519 code => sub {
520 my ($param) = @_;
521
522 my $vmid = $param->{vmid};
523
524 my $escape = $param->{escape} // '^O';
525 if ($escape =~ /^\^([\x40-\x7a])$/) {
526 $escape = ord($1) & 0x1F;
527 } elsif ($escape =~ /^0x[0-9a-f]+$/i) {
528 $escape = hex($escape);
529 } elsif ($escape =~ /^[0-9]+$/) {
530 $escape = int($escape);
531 } else {
532 die "invalid escape character definition: $escape\n";
533 }
534 my $escapemsg = '';
535 if ($escape) {
536 $escapemsg = sprintf(' (press Ctrl+%c to exit)', $escape+0x40);
537 $escape = sprintf(',escape=0x%x', $escape);
538 } else {
539 $escape = '';
540 }
541
542 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
543
544 my $iface = $param->{iface};
545
546 if ($iface) {
547 die "serial interface '$iface' is not configured\n" if !$conf->{$iface};
548 die "wrong serial type on interface '$iface'\n" if $conf->{$iface} ne 'socket';
549 } else {
550 foreach my $opt (qw(serial0 serial1 serial2 serial3)) {
551 if ($conf->{$opt} && ($conf->{$opt} eq 'socket')) {
552 $iface = $opt;
553 last;
554 }
555 }
556 die "unable to find a serial interface\n" if !$iface;
557 }
558
559 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
560
561 my $socket = "/var/run/qemu-server/${vmid}.$iface";
562
563 my $cmd = "socat UNIX-CONNECT:$socket STDIO,raw,echo=0$escape";
564
565 print "starting serial terminal on interface ${iface}${escapemsg}\n";
566
567 system($cmd);
568
569 return undef;
570 }});
571
572 __PACKAGE__->register_method ({
573 name => 'importovf',
574 path => 'importovf',
575 description => "Create a new VM using parameters read from an OVF manifest",
576 parameters => {
577 additionalProperties => 0,
578 properties => {
579 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
580 manifest => {
581 type => 'string',
582 description => 'path to the ovf file',
583 },
584 storage => get_standard_option('pve-storage-id', {
585 description => 'Target storage ID',
586 completion => \&PVE::QemuServer::complete_storage,
587 optional => 0,
588 }),
589 format => {
590 type => 'string',
591 description => 'Target format',
592 enum => [ 'raw', 'qcow2', 'vmdk' ],
593 optional => 1,
594 },
595 dryrun => {
596 type => 'boolean',
597 description => 'Print a parsed representation of the extracted OVF parameters, but do not create a VM',
598 optional => 1,
599 }
600 },
601 },
602 returns => { type => 'null' },
603 code => sub {
604 my ($param) = @_;
605
606 my $vmid = PVE::Tools::extract_param($param, 'vmid');
607 my $ovf_file = PVE::Tools::extract_param($param, 'manifest');
608 my $storeid = PVE::Tools::extract_param($param, 'storage');
609 my $format = PVE::Tools::extract_param($param, 'format');
610 my $dryrun = PVE::Tools::extract_param($param, 'dryrun');
611
612 die "$ovf_file: non-existent or non-regular file\n" if (! -f $ovf_file);
613 my $storecfg = PVE::Storage::config();
614 PVE::Storage::storage_check_enabled($storecfg, $storeid);
615
616 my $parsed = PVE::QemuServer::OVF::parse_ovf($ovf_file);
617
618 if ($dryrun) {
619 print to_json($parsed, { pretty => 1, canonical => 1});
620 return;
621 }
622
623 $param->{name} = $parsed->{qm}->{name} if defined($parsed->{qm}->{name});
624 $param->{memory} = $parsed->{qm}->{memory} if defined($parsed->{qm}->{memory});
625 $param->{cores} = $parsed->{qm}->{cores} if defined($parsed->{qm}->{cores});
626
627 my $importfn = sub {
628
629 PVE::Cluster::check_vmid_unused($vmid);
630
631 my $conf = $param;
632
633 eval {
634 # order matters, as do_import() will load_config() internally
635 $conf->{vmgenid} = PVE::QemuServer::generate_uuid();
636 $conf->{smbios1} = PVE::QemuServer::generate_smbios1_uuid();
637 PVE::QemuConfig->write_config($vmid, $conf);
638
639 foreach my $disk (@{ $parsed->{disks} }) {
640 my ($file, $drive) = ($disk->{backing_file}, $disk->{disk_address});
641 PVE::QemuServer::ImportDisk::do_import($file, $vmid, $storeid,
642 { drive_name => $drive, format => $format });
643 }
644
645 # reload after disks entries have been created
646 $conf = PVE::QemuConfig->load_config($vmid);
647 PVE::QemuConfig->check_lock($conf);
648 my $firstdisk = PVE::QemuServer::resolve_first_disk($conf);
649 $conf->{bootdisk} = $firstdisk if $firstdisk;
650 PVE::QemuConfig->write_config($vmid, $conf);
651 };
652
653 my $err = $@;
654 if ($err) {
655 my $skiplock = 1;
656 eval { PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock); };
657 die "import failed - $err";
658 }
659 };
660
661 my $wait_for_lock = 1;
662 PVE::QemuConfig->lock_config_full($vmid, $wait_for_lock, $importfn);
663
664 return undef;
665
666 }
667 });
668
669 __PACKAGE__->register_method({
670 name => 'exec',
671 path => 'exec',
672 method => 'POST',
673 protected => 1,
674 description => "Executes the given command via the guest agent",
675 parameters => {
676 additionalProperties => 0,
677 properties => {
678 node => get_standard_option('pve-node'),
679 vmid => get_standard_option('pve-vmid', {
680 completion => \&PVE::QemuServer::complete_vmid_running }),
681 synchronous => {
682 type => 'boolean',
683 optional => 1,
684 default => 1,
685 description => "If set to off, returns the pid immediately instead of waiting for the commmand to finish or the timeout.",
686 },
687 'timeout' => {
688 type => 'integer',
689 description => "The maximum time to wait synchronously for the command to finish. If reached, the pid gets returned. Set to 0 to deactivate",
690 minimum => 0,
691 optional => 1,
692 default => 30,
693 },
694 'extra-args' => get_standard_option('extra-args'),
695 },
696 },
697 returns => {
698 type => 'object',
699 },
700 code => sub {
701 my ($param) = @_;
702
703 my $vmid = $param->{vmid};
704 my $sync = $param->{synchronous} // 1;
705 if (!$param->{'extra-args'} || !@{$param->{'extra-args'}}) {
706 raise_param_exc( { 'extra-args' => "No command given" });
707 }
708 if (defined($param->{timeout}) && !$sync) {
709 raise_param_exc({ synchronous => "needs to be set for 'timeout'"});
710 }
711
712 my $res = PVE::QemuServer::Agent::qemu_exec($vmid, $param->{'extra-args'});
713
714 if ($sync) {
715 my $pid = $res->{pid};
716 my $timeout = $param->{timeout} // 30;
717 my $starttime = time();
718
719 while ($timeout == 0 || (time() - $starttime) < $timeout) {
720 my $out = PVE::QemuServer::Agent::qemu_exec_status($vmid, $pid);
721 if ($out->{exited}) {
722 $res = $out;
723 last;
724 }
725 sleep 1;
726 }
727
728 if (!$res->{exited}) {
729 warn "timeout reached, returning pid\n";
730 }
731 }
732
733 return { result => $res };
734 }});
735
736 __PACKAGE__->register_method({
737 name => 'cleanup',
738 path => 'cleanup',
739 method => 'POST',
740 protected => 1,
741 description => "Cleans up resources like tap devices, vgpus, etc. Called after a vm shuts down, crashes, etc.",
742 parameters => {
743 additionalProperties => 0,
744 properties => {
745 node => get_standard_option('pve-node'),
746 vmid => get_standard_option('pve-vmid', {
747 completion => \&PVE::QemuServer::complete_vmid_running }),
748 'clean-shutdown' => {
749 type => 'boolean',
750 description => "Indicates if qemu shutdown cleanly.",
751 },
752 'guest-requested' => {
753 type => 'boolean',
754 description => "Indicates if the shutdown was requested by the guest or via qmp.",
755 },
756 },
757 },
758 returns => { type => 'null', },
759 code => sub {
760 my ($param) = @_;
761
762 my $vmid = $param->{vmid};
763 my $clean = $param->{'clean-shutdown'};
764 my $guest = $param->{'guest-requested'};
765
766 # return if we do not have the config anymore
767 return if !-f PVE::QemuConfig->config_file($vmid);
768
769 my $storecfg = PVE::Storage::config();
770 warn "Starting cleanup for $vmid\n";
771
772 PVE::QemuConfig->lock_config($vmid, sub {
773 my $conf = PVE::QemuConfig->load_config ($vmid);
774 my $pid = PVE::QemuServer::check_running ($vmid);
775 die "vm still running\n" if $pid;
776
777 if (!$clean) {
778 # we have to cleanup the tap devices after a crash
779
780 foreach my $opt (keys %$conf) {
781 next if $opt !~ m/^net(\d)+$/;
782 my $interface = $1;
783 PVE::Network::tap_unplug("tap${vmid}i${interface}");
784 }
785 }
786
787 if (!$clean || $guest) {
788 # vm was shutdown from inside the guest or crashed, doing api cleanup
789 PVE::QemuServer::vm_stop_cleanup($storecfg, $vmid, $conf, 0, 0);
790 }
791 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-stop');
792 });
793
794 warn "Finished cleanup for $vmid\n";
795
796 return undef;
797 }});
798
799 my $print_agent_result = sub {
800 my ($data) = @_;
801
802 my $result = $data->{result} // $data;
803 return if !defined($result);
804
805 my $class = ref($result);
806
807 if (!$class) {
808 chomp $result;
809 return if $result =~ m/^\s*$/;
810 print "$result\n";
811 return;
812 }
813
814 if (($class eq 'HASH') && !scalar(keys %$result)) { # empty hash
815 return;
816 }
817
818 print to_json($result, { pretty => 1, canonical => 1});
819 };
820
821 sub param_mapping {
822 my ($name) = @_;
823
824 my $ssh_key_map = ['sshkeys', sub {
825 return URI::Escape::uri_escape(PVE::Tools::file_get_contents($_[0]));
826 }];
827 my $cipassword_map = PVE::CLIHandler::get_standard_mapping('pve-password', { name => 'cipassword' });
828 my $password_map = PVE::CLIHandler::get_standard_mapping('pve-password');
829 my $mapping = {
830 'update_vm' => [$ssh_key_map, $cipassword_map],
831 'create_vm' => [$ssh_key_map, $cipassword_map],
832 'set-user-password' => [$password_map],
833 };
834
835 return $mapping->{$name};
836 }
837
838 our $cmddef = {
839 list => [ "PVE::API2::Qemu", 'vmlist', [],
840 { node => $nodename }, sub {
841 my $vmlist = shift;
842
843 exit 0 if (!scalar(@$vmlist));
844
845 printf "%10s %-20s %-10s %-10s %12s %-10s\n",
846 qw(VMID NAME STATUS MEM(MB) BOOTDISK(GB) PID);
847
848 foreach my $rec (sort { $a->{vmid} <=> $b->{vmid} } @$vmlist) {
849 printf "%10s %-20s %-10s %-10s %12.2f %-10s\n", $rec->{vmid}, $rec->{name},
850 $rec->{qmpstatus} || $rec->{status},
851 ($rec->{maxmem} || 0)/(1024*1024),
852 ($rec->{maxdisk} || 0)/(1024*1024*1024),
853 $rec->{pid}||0;
854 }
855
856
857 } ],
858
859 create => [ "PVE::API2::Qemu", 'create_vm', ['vmid'], { node => $nodename }, $upid_exit ],
860
861 destroy => [ "PVE::API2::Qemu", 'destroy_vm', ['vmid'], { node => $nodename }, $upid_exit ],
862
863 clone => [ "PVE::API2::Qemu", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
864
865 migrate => [ "PVE::API2::Qemu", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit ],
866
867 set => [ "PVE::API2::Qemu", 'update_vm', ['vmid'], { node => $nodename } ],
868
869 resize => [ "PVE::API2::Qemu", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
870
871 move_disk => [ "PVE::API2::Qemu", 'move_vm_disk', ['vmid', 'disk', 'storage'], { node => $nodename }, $upid_exit ],
872
873 unlink => [ "PVE::API2::Qemu", 'unlink', ['vmid'], { node => $nodename } ],
874
875 config => [ "PVE::API2::Qemu", 'vm_config', ['vmid'],
876 { node => $nodename }, sub {
877 my $config = shift;
878 foreach my $k (sort (keys %$config)) {
879 next if $k eq 'digest';
880 my $v = $config->{$k};
881 if ($k eq 'description') {
882 $v = PVE::Tools::encode_text($v);
883 }
884 print "$k: $v\n";
885 }
886 }],
887
888 pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'],
889 { node => $nodename }, sub {
890 my $data = shift;
891 foreach my $item (sort { $a->{key} cmp $b->{key}} @$data) {
892 my $k = $item->{key};
893 next if $k eq 'digest';
894 my $v = $item->{value};
895 my $p = $item->{pending};
896 if ($k eq 'description') {
897 $v = PVE::Tools::encode_text($v) if defined($v);
898 $p = PVE::Tools::encode_text($p) if defined($p);
899 }
900 if (defined($v)) {
901 if ($item->{delete}) {
902 print "del $k: $v\n";
903 } elsif (defined($p)) {
904 print "cur $k: $v\n";
905 print "new $k: $p\n";
906 } else {
907 print "cur $k: $v\n";
908 }
909 } elsif (defined($p)) {
910 print "new $k: $p\n";
911 }
912 }
913 }],
914
915 showcmd => [ __PACKAGE__, 'showcmd', ['vmid']],
916
917 status => [ __PACKAGE__, 'status', ['vmid']],
918
919 snapshot => [ "PVE::API2::Qemu", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
920
921 delsnapshot => [ "PVE::API2::Qemu", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
922
923 listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename },
924 sub {
925 my $res = shift;
926
927 my $snapshots = { map { $_->{name} => $_ } @$res };
928
929 my @roots;
930 foreach my $e (@$res) {
931 my $parent;
932 if (($parent = $e->{parent}) && defined $snapshots->{$parent}) {
933 push @{$snapshots->{$parent}->{children}}, $e->{name};
934 } else {
935 push @roots, $e->{name};
936 }
937 }
938
939 # sort the elements by snaptime - with "current" (no snaptime) highest
940 my $snaptimesort = sub {
941 return +1 if !defined $snapshots->{$a}->{snaptime};
942 return -1 if !defined $snapshots->{$b}->{snaptime};
943 return $snapshots->{$a}->{snaptime} <=> $snapshots->{$b}->{snaptime};
944 };
945
946 # recursion function for displaying the tree
947 my $snapshottree;
948 $snapshottree = sub {
949 my ($prefix, $root, $snapshots) = @_;
950 my $e = $snapshots->{$root};
951
952 my $description = $e->{description} || 'no-description';
953 ($description) = $description =~ m/(.*)$/m;
954
955 my $timestring = "";
956 if (defined $e->{snaptime}) {
957 $timestring = strftime("%F %H:%M:%S", localtime($e->{snaptime}));
958 }
959
960 my $len = 30 - length($prefix); # for aligning the description
961 printf("%s %-${len}s %-23s %s\n", $prefix, $root, $timestring, $description);
962
963 if ($e->{children}) {
964 $prefix = " $prefix";
965 foreach my $child (sort $snaptimesort @{$e->{children}}) {
966 $snapshottree->($prefix, $child, $snapshots);
967 }
968 }
969 };
970
971 foreach my $root (sort $snaptimesort @roots) {
972 $snapshottree->('`->', $root, $snapshots);
973 }
974 }],
975
976 rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
977
978 template => [ "PVE::API2::Qemu", 'template', ['vmid'], { node => $nodename }],
979
980 start => [ "PVE::API2::Qemu", 'vm_start', ['vmid'], { node => $nodename } , $upid_exit ],
981
982 stop => [ "PVE::API2::Qemu", 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit ],
983
984 reset => [ "PVE::API2::Qemu", 'vm_reset', ['vmid'], { node => $nodename }, $upid_exit ],
985
986 shutdown => [ "PVE::API2::Qemu", 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit ],
987
988 suspend => [ "PVE::API2::Qemu", 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit ],
989
990 resume => [ "PVE::API2::Qemu", 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit ],
991
992 sendkey => [ "PVE::API2::Qemu", 'vm_sendkey', ['vmid', 'key'], { node => $nodename } ],
993
994 vncproxy => [ __PACKAGE__, 'vncproxy', ['vmid']],
995
996 wait => [ __PACKAGE__, 'wait', ['vmid']],
997
998 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
999
1000 rescan => [ __PACKAGE__, 'rescan', []],
1001
1002 monitor => [ __PACKAGE__, 'monitor', ['vmid']],
1003
1004 agent => { alias => 'guest cmd' },
1005
1006 guest => {
1007 cmd => [ "PVE::API2::Qemu::Agent", 'agent', ['vmid', 'command'], { node => $nodename }, $print_agent_result ],
1008 passwd => [ "PVE::API2::Qemu::Agent", 'set-user-password', [ 'vmid', 'username' ], { node => $nodename }],
1009 exec => [ __PACKAGE__, 'exec', [ 'vmid', 'extra-args' ], { node => $nodename }, $print_agent_result],
1010 'exec-status' => [ "PVE::API2::Qemu::Agent", 'exec-status', [ 'vmid', 'pid' ], { node => $nodename }, $print_agent_result],
1011 },
1012
1013 mtunnel => [ __PACKAGE__, 'mtunnel', []],
1014
1015 nbdstop => [ __PACKAGE__, 'nbdstop', ['vmid']],
1016
1017 terminal => [ __PACKAGE__, 'terminal', ['vmid']],
1018
1019 importdisk => [ __PACKAGE__, 'importdisk', ['vmid', 'source', 'storage']],
1020
1021 importovf => [ __PACKAGE__, 'importovf', ['vmid', 'manifest', 'storage']],
1022
1023 cleanup => [ __PACKAGE__, 'cleanup', ['vmid', 'clean-shutdown', 'guest-requested'], { node => $nodename }],
1024
1025 };
1026
1027 1;