]> git.proxmox.com Git - qemu-server.git/blob - PVE/CLI/qm.pm
b70bb200c9461961201fc257d4fb31ee483affff
[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
14 use PVE::Tools qw(extract_param);
15 use PVE::Cluster;
16 use PVE::SafeSyslog;
17 use PVE::INotify;
18 use PVE::RPCEnvironment;
19 use PVE::QemuServer;
20 use PVE::QemuServer::ImportDisk;
21 use PVE::API2::Qemu;
22 use JSON;
23 use PVE::JSONSchema qw(get_standard_option);
24 use Term::ReadLine;
25
26 use PVE::CLIHandler;
27
28 use base qw(PVE::CLIHandler);
29
30 my $upid_exit = sub {
31 my $upid = shift;
32 my $status = PVE::Tools::upid_read_status($upid);
33 exit($status eq 'OK' ? 0 : -1);
34 };
35
36 my $nodename = PVE::INotify::nodename();
37
38 sub setup_environment {
39 PVE::RPCEnvironment->setup_default_cli_env();
40 }
41
42 sub run_vnc_proxy {
43 my ($path) = @_;
44
45 my $c;
46 while ( ++$c < 10 && !-e $path ) { sleep(1); }
47
48 my $s = IO::Socket::UNIX->new(Peer => $path, Timeout => 120);
49
50 die "unable to connect to socket '$path' - $!" if !$s;
51
52 my $select = new IO::Select;
53
54 $select->add(\*STDIN);
55 $select->add($s);
56
57 my $timeout = 60*15; # 15 minutes
58
59 my @handles;
60 while ($select->count &&
61 scalar(@handles = $select->can_read ($timeout))) {
62 foreach my $h (@handles) {
63 my $buf;
64 my $n = $h->sysread($buf, 4096);
65
66 if ($h == \*STDIN) {
67 if ($n) {
68 syswrite($s, $buf);
69 } else {
70 exit(0);
71 }
72 } elsif ($h == $s) {
73 if ($n) {
74 syswrite(\*STDOUT, $buf);
75 } else {
76 exit(0);
77 }
78 }
79 }
80 }
81 exit(0);
82 }
83
84 sub print_recursive_hash {
85 my ($prefix, $hash, $key) = @_;
86
87 if (ref($hash) eq 'HASH') {
88 if (defined($key)) {
89 print "$prefix$key:\n";
90 }
91 foreach my $itemkey (keys %$hash) {
92 print_recursive_hash("\t$prefix", $hash->{$itemkey}, $itemkey);
93 }
94 } elsif (ref($hash) eq 'ARRAY') {
95 if (defined($key)) {
96 print "$prefix$key:\n";
97 }
98 foreach my $item (@$hash) {
99 print_recursive_hash("\t$prefix", $item);
100 }
101 } elsif (!ref($hash) && defined($hash)) {
102 if (defined($key)) {
103 print "$prefix$key: $hash\n";
104 } else {
105 print "$prefix$hash\n";
106 }
107 }
108 }
109
110 __PACKAGE__->register_method ({
111 name => 'showcmd',
112 path => 'showcmd',
113 method => 'GET',
114 description => "Show command line which is used to start the VM (debug info).",
115 parameters => {
116 additionalProperties => 0,
117 properties => {
118 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
119 },
120 },
121 returns => { type => 'null'},
122 code => sub {
123 my ($param) = @_;
124
125 my $storecfg = PVE::Storage::config();
126 print PVE::QemuServer::vm_commandline($storecfg, $param->{vmid}) . "\n";
127
128 return undef;
129 }});
130
131 __PACKAGE__->register_method ({
132 name => 'status',
133 path => 'status',
134 method => 'GET',
135 description => "Show VM status.",
136 parameters => {
137 additionalProperties => 0,
138 properties => {
139 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
140 verbose => {
141 description => "Verbose output format",
142 type => 'boolean',
143 optional => 1,
144 }
145 },
146 },
147 returns => { type => 'null'},
148 code => sub {
149 my ($param) = @_;
150
151 # test if VM exists
152 my $conf = PVE::QemuConfig->load_config ($param->{vmid});
153
154 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
155 my $stat = $vmstatus->{$param->{vmid}};
156 if ($param->{verbose}) {
157 foreach my $k (sort (keys %$stat)) {
158 next if $k eq 'cpu' || $k eq 'relcpu'; # always 0
159 my $v = $stat->{$k};
160 print_recursive_hash("", $v, $k);
161 }
162 } else {
163 my $status = $stat->{qmpstatus} || 'unknown';
164 print "status: $status\n";
165 }
166
167 return undef;
168 }});
169
170 __PACKAGE__->register_method ({
171 name => 'vncproxy',
172 path => 'vncproxy',
173 method => 'PUT',
174 description => "Proxy VM VNC traffic to stdin/stdout",
175 parameters => {
176 additionalProperties => 0,
177 properties => {
178 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
179 },
180 },
181 returns => { type => 'null'},
182 code => sub {
183 my ($param) = @_;
184
185 my $vmid = $param->{vmid};
186 my $vnc_socket = PVE::QemuServer::vnc_socket($vmid);
187
188 if (my $ticket = $ENV{LC_PVE_TICKET}) { # NOTE: ssh on debian only pass LC_* variables
189 PVE::QemuServer::vm_mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
190 PVE::QemuServer::vm_mon_cmd($vmid, "set_password", protocol => 'vnc', password => $ticket);
191 PVE::QemuServer::vm_mon_cmd($vmid, "expire_password", protocol => 'vnc', time => "+30");
192 } else {
193 PVE::QemuServer::vm_mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,x509,password");
194 }
195
196 run_vnc_proxy($vnc_socket);
197
198 return undef;
199 }});
200
201 __PACKAGE__->register_method ({
202 name => 'unlock',
203 path => 'unlock',
204 method => 'PUT',
205 description => "Unlock the VM.",
206 parameters => {
207 additionalProperties => 0,
208 properties => {
209 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
210 },
211 },
212 returns => { type => 'null'},
213 code => sub {
214 my ($param) = @_;
215
216 my $vmid = $param->{vmid};
217
218 PVE::QemuConfig->lock_config ($vmid, sub {
219 my $conf = PVE::QemuConfig->load_config($vmid);
220 delete $conf->{lock};
221 delete $conf->{pending}->{lock} if $conf->{pending}; # just to be sure
222 PVE::QemuConfig->write_config($vmid, $conf);
223 });
224
225 return undef;
226 }});
227
228 __PACKAGE__->register_method ({
229 name => 'nbdstop',
230 path => 'nbdstop',
231 method => 'PUT',
232 description => "Stop embedded nbd server.",
233 parameters => {
234 additionalProperties => 0,
235 properties => {
236 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
237 },
238 },
239 returns => { type => 'null'},
240 code => sub {
241 my ($param) = @_;
242
243 my $vmid = $param->{vmid};
244
245 PVE::QemuServer::nbd_stop($vmid);
246
247 return undef;
248 }});
249
250 __PACKAGE__->register_method ({
251 name => 'mtunnel',
252 path => 'mtunnel',
253 method => 'POST',
254 description => "Used by qmigrate - do not use manually.",
255 parameters => {
256 additionalProperties => 0,
257 properties => {},
258 },
259 returns => { type => 'null'},
260 code => sub {
261 my ($param) = @_;
262
263 if (!PVE::Cluster::check_cfs_quorum(1)) {
264 print "no quorum\n";
265 return undef;
266 }
267
268 my $tunnel_write = sub {
269 my $text = shift;
270 chomp $text;
271 print "$text\n";
272 *STDOUT->flush();
273 };
274
275 $tunnel_write->("tunnel online");
276 $tunnel_write->("ver 1");
277
278 while (my $line = <>) {
279 chomp $line;
280 if ($line =~ /^quit$/) {
281 $tunnel_write->("OK");
282 last;
283 }
284 }
285
286 return undef;
287 }});
288
289 __PACKAGE__->register_method ({
290 name => 'wait',
291 path => 'wait',
292 method => 'GET',
293 description => "Wait until the VM is stopped.",
294 parameters => {
295 additionalProperties => 0,
296 properties => {
297 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
298 timeout => {
299 description => "Timeout in seconds. Default is to wait forever.",
300 type => 'integer',
301 minimum => 1,
302 optional => 1,
303 }
304 },
305 },
306 returns => { type => 'null'},
307 code => sub {
308 my ($param) = @_;
309
310 my $vmid = $param->{vmid};
311 my $timeout = $param->{timeout};
312
313 my $pid = PVE::QemuServer::check_running ($vmid);
314 return if !$pid;
315
316 print "waiting until VM $vmid stopps (PID $pid)\n";
317
318 my $count = 0;
319 while ((!$timeout || ($count < $timeout)) && PVE::QemuServer::check_running ($vmid)) {
320 $count++;
321 sleep 1;
322 }
323
324 die "wait failed - got timeout\n" if PVE::QemuServer::check_running ($vmid);
325
326 return undef;
327 }});
328
329 __PACKAGE__->register_method ({
330 name => 'monitor',
331 path => 'monitor',
332 method => 'POST',
333 description => "Enter Qemu Monitor interface.",
334 parameters => {
335 additionalProperties => 0,
336 properties => {
337 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
338 },
339 },
340 returns => { type => 'null'},
341 code => sub {
342 my ($param) = @_;
343
344 my $vmid = $param->{vmid};
345
346 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
347
348 print "Entering Qemu Monitor for VM $vmid - type 'help' for help\n";
349
350 my $term = new Term::ReadLine ('qm');
351
352 my $input;
353 while (defined ($input = $term->readline('qm> '))) {
354 chomp $input;
355
356 next if $input =~ m/^\s*$/;
357
358 last if $input =~ m/^\s*q(uit)?\s*$/;
359
360 eval {
361 print PVE::QemuServer::vm_human_monitor_command ($vmid, $input);
362 };
363 print "ERROR: $@" if $@;
364 }
365
366 return undef;
367
368 }});
369
370 __PACKAGE__->register_method ({
371 name => 'rescan',
372 path => 'rescan',
373 method => 'POST',
374 description => "Rescan all storages and update disk sizes and unused disk images.",
375 parameters => {
376 additionalProperties => 0,
377 properties => {
378 vmid => get_standard_option('pve-vmid', {
379 optional => 1,
380 completion => \&PVE::QemuServer::complete_vmid,
381 }),
382 },
383 },
384 returns => { type => 'null'},
385 code => sub {
386 my ($param) = @_;
387
388 PVE::QemuServer::rescan($param->{vmid});
389
390 return undef;
391 }});
392
393 __PACKAGE__->register_method ({
394 name => 'importdisk',
395 path => 'importdisk',
396 method => 'POST',
397 description => "Import an external disk image as an unused disk in a VM. The
398 image format has to be supported by qemu-img(1).",
399 parameters => {
400 additionalProperties => 0,
401 properties => {
402 vmid => get_standard_option('pve-vmid', {completion => \&PVE::QemuServer::complete_vmid}),
403 source => {
404 description => 'Path to the disk image to import',
405 type => 'string',
406 optional => 0,
407 },
408 storage => get_standard_option('pve-storage-id', {
409 description => 'Target storage ID',
410 completion => \&PVE::QemuServer::complete_storage,
411 optional => 0,
412 }),
413 format => {
414 type => 'string',
415 description => 'Target format',
416 enum => [ 'raw', 'qcow2', 'vmdk' ],
417 optional => 1,
418 },
419 },
420 },
421 returns => { type => 'null'},
422 code => sub {
423 my ($param) = @_;
424
425 my $vmid = extract_param($param, 'vmid');
426 my $source = extract_param($param, 'source');
427 my $storeid = extract_param($param, 'storage');
428 my $format = extract_param($param, 'format');
429
430 my $vm_conf = PVE::QemuConfig->load_config($vmid);
431 PVE::QemuConfig->check_lock($vm_conf);
432 die "$source: non-existent or non-regular file\n" if (! -f $source);
433
434 my $storecfg = PVE::Storage::config();
435 PVE::Storage::storage_check_enabled($storecfg, $storeid);
436
437 my $target_storage_config =
438 PVE::Storage::storage_config($storecfg, $storeid);
439 die "storage $storeid does not support vm images\n"
440 if !$target_storage_config->{content}->{images};
441
442 PVE::QemuServer::ImportDisk::do_import($source, $vmid, $storeid, { format => $format });
443
444 return undef;
445 }});
446
447 __PACKAGE__->register_method ({
448 name => 'terminal',
449 path => 'terminal',
450 method => 'POST',
451 description => "Open a terminal using a serial device (The VM need to have a serial device configured, for example 'serial0: socket')",
452 parameters => {
453 additionalProperties => 0,
454 properties => {
455 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
456 iface => {
457 description => "Select the serial device. By default we simply use the first suitable device.",
458 type => 'string',
459 optional => 1,
460 enum => [qw(serial0 serial1 serial2 serial3)],
461 }
462 },
463 },
464 returns => { type => 'null'},
465 code => sub {
466 my ($param) = @_;
467
468 my $vmid = $param->{vmid};
469
470 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
471
472 my $iface = $param->{iface};
473
474 if ($iface) {
475 die "serial interface '$iface' is not configured\n" if !$conf->{$iface};
476 die "wrong serial type on interface '$iface'\n" if $conf->{$iface} ne 'socket';
477 } else {
478 foreach my $opt (qw(serial0 serial1 serial2 serial3)) {
479 if ($conf->{$opt} && ($conf->{$opt} eq 'socket')) {
480 $iface = $opt;
481 last;
482 }
483 }
484 die "unable to find a serial interface\n" if !$iface;
485 }
486
487 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
488
489 my $socket = "/var/run/qemu-server/${vmid}.$iface";
490
491 my $cmd = "socat UNIX-CONNECT:$socket STDIO,raw,echo=0,escape=0x0f";
492
493 print "starting serial terminal on interface $iface (press control-O to exit)\n";
494
495 system($cmd);
496
497 return undef;
498 }});
499
500
501 my $print_agent_result = sub {
502 my ($data) = @_;
503
504 my $result = $data->{result};
505 return if !defined($result);
506
507 my $class = ref($result);
508
509 if (!$class) {
510 chomp $result;
511 return if $result =~ m/^\s*$/;
512 print "$result\n";
513 return;
514 }
515
516 if (($class eq 'HASH') && !scalar(keys %$result)) { # empty hash
517 return;
518 }
519
520 print to_json($result, { pretty => 1, canonical => 1});
521 };
522
523 our $cmddef = {
524 list => [ "PVE::API2::Qemu", 'vmlist', [],
525 { node => $nodename }, sub {
526 my $vmlist = shift;
527
528 exit 0 if (!scalar(@$vmlist));
529
530 printf "%10s %-20s %-10s %-10s %12s %-10s\n",
531 qw(VMID NAME STATUS MEM(MB) BOOTDISK(GB) PID);
532
533 foreach my $rec (sort { $a->{vmid} <=> $b->{vmid} } @$vmlist) {
534 printf "%10s %-20s %-10s %-10s %12.2f %-10s\n", $rec->{vmid}, $rec->{name},
535 $rec->{qmpstatus} || $rec->{status},
536 ($rec->{maxmem} || 0)/(1024*1024),
537 ($rec->{maxdisk} || 0)/(1024*1024*1024),
538 $rec->{pid}||0;
539 }
540
541
542 } ],
543
544 create => [ "PVE::API2::Qemu", 'create_vm', ['vmid'], { node => $nodename }, $upid_exit ],
545
546 destroy => [ "PVE::API2::Qemu", 'destroy_vm', ['vmid'], { node => $nodename }, $upid_exit ],
547
548 clone => [ "PVE::API2::Qemu", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
549
550 migrate => [ "PVE::API2::Qemu", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit ],
551
552 set => [ "PVE::API2::Qemu", 'update_vm', ['vmid'], { node => $nodename } ],
553
554 resize => [ "PVE::API2::Qemu", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
555
556 move_disk => [ "PVE::API2::Qemu", 'move_vm_disk', ['vmid', 'disk', 'storage'], { node => $nodename }, $upid_exit ],
557
558 unlink => [ "PVE::API2::Qemu", 'unlink', ['vmid'], { node => $nodename } ],
559
560 config => [ "PVE::API2::Qemu", 'vm_config', ['vmid'],
561 { node => $nodename }, sub {
562 my $config = shift;
563 foreach my $k (sort (keys %$config)) {
564 next if $k eq 'digest';
565 my $v = $config->{$k};
566 if ($k eq 'description') {
567 $v = PVE::Tools::encode_text($v);
568 }
569 print "$k: $v\n";
570 }
571 }],
572
573 pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'],
574 { node => $nodename }, sub {
575 my $data = shift;
576 foreach my $item (sort { $a->{key} cmp $b->{key}} @$data) {
577 my $k = $item->{key};
578 next if $k eq 'digest';
579 my $v = $item->{value};
580 my $p = $item->{pending};
581 if ($k eq 'description') {
582 $v = PVE::Tools::encode_text($v) if defined($v);
583 $p = PVE::Tools::encode_text($p) if defined($p);
584 }
585 if (defined($v)) {
586 if ($item->{delete}) {
587 print "del $k: $v\n";
588 } elsif (defined($p)) {
589 print "cur $k: $v\n";
590 print "new $k: $p\n";
591 } else {
592 print "cur $k: $v\n";
593 }
594 } elsif (defined($p)) {
595 print "new $k: $p\n";
596 }
597 }
598 }],
599
600 showcmd => [ __PACKAGE__, 'showcmd', ['vmid']],
601
602 status => [ __PACKAGE__, 'status', ['vmid']],
603
604 snapshot => [ "PVE::API2::Qemu", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
605
606 delsnapshot => [ "PVE::API2::Qemu", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
607
608 listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename },
609 sub {
610 my $res = shift;
611 foreach my $e (@$res) {
612 my $headline = $e->{description} || 'no-description';
613 $headline =~ s/\n.*//sg;
614 my $parent = $e->{parent} // 'no-parent';
615 printf("%-20s %-20s %s\n", $e->{name}, $parent, $headline);
616 }
617 }],
618
619 rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
620
621 template => [ "PVE::API2::Qemu", 'template', ['vmid'], { node => $nodename }],
622
623 start => [ "PVE::API2::Qemu", 'vm_start', ['vmid'], { node => $nodename } , $upid_exit ],
624
625 stop => [ "PVE::API2::Qemu", 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit ],
626
627 reset => [ "PVE::API2::Qemu", 'vm_reset', ['vmid'], { node => $nodename }, $upid_exit ],
628
629 shutdown => [ "PVE::API2::Qemu", 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit ],
630
631 suspend => [ "PVE::API2::Qemu", 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit ],
632
633 resume => [ "PVE::API2::Qemu", 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit ],
634
635 sendkey => [ "PVE::API2::Qemu", 'vm_sendkey', ['vmid', 'key'], { node => $nodename } ],
636
637 vncproxy => [ __PACKAGE__, 'vncproxy', ['vmid']],
638
639 wait => [ __PACKAGE__, 'wait', ['vmid']],
640
641 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
642
643 rescan => [ __PACKAGE__, 'rescan', []],
644
645 monitor => [ __PACKAGE__, 'monitor', ['vmid']],
646
647 agent => [ "PVE::API2::Qemu", 'agent', ['vmid', 'command'],
648 { node => $nodename }, $print_agent_result ],
649
650 mtunnel => [ __PACKAGE__, 'mtunnel', []],
651
652 nbdstop => [ __PACKAGE__, 'nbdstop', ['vmid']],
653
654 terminal => [ __PACKAGE__, 'terminal', ['vmid']],
655
656 importdisk => [ __PACKAGE__, 'importdisk', ['vmid', 'source', 'storage']],
657 };
658
659 1;