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