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