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