]> git.proxmox.com Git - qemu-server.git/blob - PVE/QMPClient.pm
snapshot_list: add bash completion for vmid
[qemu-server.git] / PVE / QMPClient.pm
1 package PVE::QMPClient;
2
3 use strict;
4 use warnings;
5 use PVE::QemuServer;
6 use IO::Multiplex;
7 use POSIX qw(EINTR EAGAIN);
8 use JSON;
9 use Time::HiRes qw(usleep gettimeofday tv_interval);
10 use Scalar::Util qw(weaken);
11 use PVE::IPCC;
12
13 use Data::Dumper;
14
15 # Qemu Monitor Protocol (QMP) client.
16 #
17 # This implementation uses IO::Multiplex (libio-multiplex-perl) and
18 # allows you to issue qmp and qga commands to different VMs in parallel.
19
20 # Note: qemu can onyl handle 1 connection, so we close connections asap
21
22 sub new {
23 my ($class, $eventcb) = @_;
24
25 my $mux = new IO::Multiplex;
26
27 my $self = bless {
28 mux => $mux,
29 queue_lookup => {}, # $fh => $queue_info
30 queue_info => {},
31 }, $class;
32
33 $self->{eventcb} = $eventcb if $eventcb;
34
35 $mux->set_callback_object($self);
36
37 # make sure perl doesn't believe this is a circular reference as we
38 # delete mux in DESTROY
39 weaken($mux->{_object});
40
41 return $self;
42 }
43
44 # Note: List of special QGA command. Those commands can close the connection
45 # without sending a response.
46
47 my $qga_allow_close_cmds = {
48 'guest-shutdown' => 1,
49 'guest-suspend-ram' => 1,
50 'guest-suspend-disk' => 1,
51 'guest-suspend-hybrid' => 1,
52 };
53
54 my $push_cmd_to_queue = sub {
55 my ($self, $vmid, $cmd) = @_;
56
57 my $execute = $cmd->{execute} || die "no command name specified";
58
59 my $qga = ($execute =~ /^guest\-+/) ? 1 : 0;
60
61 my $sname = PVE::QemuServer::qmp_socket($vmid, $qga);
62
63 $self->{queue_info}->{$sname} = { qga => $qga, vmid => $vmid, sname => $sname, cmds => [] }
64 if !$self->{queue_info}->{$sname};
65
66 push @{$self->{queue_info}->{$sname}->{cmds}}, $cmd;
67
68 return $self->{queue_info}->{$sname};
69 };
70
71 # add a single command to the queue for later execution
72 # with queue_execute()
73 sub queue_cmd {
74 my ($self, $vmid, $callback, $execute, %params) = @_;
75
76 my $cmd = {};
77 $cmd->{execute} = $execute;
78 $cmd->{arguments} = \%params;
79 $cmd->{callback} = $callback;
80
81 &$push_cmd_to_queue($self, $vmid, $cmd);
82
83 return undef;
84 }
85
86 # execute a single command
87 sub cmd {
88 my ($self, $vmid, $cmd, $timeout) = @_;
89
90 my $result;
91
92 my $callback = sub {
93 my ($vmid, $resp) = @_;
94 $result = $resp->{'return'};
95 };
96
97 die "no command specified" if !($cmd && $cmd->{execute});
98
99 $cmd->{callback} = $callback;
100 $cmd->{arguments} = {} if !defined($cmd->{arguments});
101
102 my $queue_info = &$push_cmd_to_queue($self, $vmid, $cmd);
103
104 if (!$timeout) {
105 # hack: monitor sometime blocks
106 if ($cmd->{execute} eq 'query-migrate') {
107 $timeout = 60*60; # 1 hour
108 } elsif ($cmd->{execute} =~ m/^(eject|change)/) {
109 $timeout = 60; # note: cdrom mount command is slow
110 } elsif ($cmd->{execute} eq 'guest-fsfreeze-freeze' ||
111 $cmd->{execute} eq 'guest-fsfreeze-thaw') {
112 $timeout = 10;
113 } elsif ($cmd->{execute} eq 'savevm-start' ||
114 $cmd->{execute} eq 'savevm-end' ||
115 $cmd->{execute} eq 'query-backup' ||
116 $cmd->{execute} eq 'query-block-jobs' ||
117 $cmd->{execute} eq 'backup-cancel' ||
118 $cmd->{execute} eq 'query-savevm' ||
119 $cmd->{execute} eq 'delete-drive-snapshot' ||
120 $cmd->{execute} eq 'guest-shutdown' ||
121 $cmd->{execute} eq 'snapshot-drive' ) {
122 $timeout = 10*60; # 10 mins ?
123 } else {
124 $timeout = 3; # default
125 }
126 }
127
128 $self->queue_execute($timeout, 2);
129
130 die "VM $vmid qmp command '$cmd->{execute}' failed - $queue_info->{error}"
131 if defined($queue_info->{error});
132
133 return $result;
134 };
135
136 my $cmdid_seq = 0;
137 my $cmdid_seq_qga = 0;
138
139 my $next_cmdid = sub {
140 my ($qga) = @_;
141
142 if($qga){
143 $cmdid_seq_qga++;
144 return "$$"."0".$cmdid_seq_qga;
145 } else {
146 $cmdid_seq++;
147 return "$$:$cmdid_seq";
148 }
149 };
150
151 my $lookup_queue_info = sub {
152 my ($self, $fh, $noerr) = @_;
153
154 my $queue_info = $self->{queue_lookup}->{$fh};
155 if (!$queue_info) {
156 warn "internal error - unable to lookup queue info" if !$noerr;
157 return undef;
158 }
159 return $queue_info;
160 };
161
162 my $close_connection = sub {
163 my ($self, $queue_info) = @_;
164
165 if (my $fh = delete $queue_info->{fh}) {
166 delete $self->{queue_lookup}->{$fh};
167 $self->{mux}->close($fh);
168 }
169 };
170
171 my $open_connection = sub {
172 my ($self, $queue_info, $timeout) = @_;
173
174 die "duplicate call to open" if defined($queue_info->{fh});
175
176 my $vmid = $queue_info->{vmid};
177 my $qga = $queue_info->{qga};
178
179 my $sname = PVE::QemuServer::qmp_socket($vmid, $qga);
180
181 $timeout = 1 if !$timeout;
182
183 my $fh;
184 my $starttime = [gettimeofday];
185 my $count = 0;
186
187 my $sotype = $qga ? 'qga' : 'qmp';
188
189 for (;;) {
190 $count++;
191 $fh = IO::Socket::UNIX->new(Peer => $sname, Blocking => 0, Timeout => 1);
192 last if $fh;
193 if ($! != EINTR && $! != EAGAIN) {
194 die "unable to connect to VM $vmid $sotype socket - $!\n";
195 }
196 my $elapsed = tv_interval($starttime, [gettimeofday]);
197 if ($elapsed >= $timeout) {
198 die "unable to connect to VM $vmid $sotype socket - timeout after $count retries\n";
199 }
200 usleep(100000);
201 }
202
203 $queue_info->{fh} = $fh;
204
205 $self->{queue_lookup}->{$fh} = $queue_info;
206
207 $self->{mux}->add($fh);
208 $self->{mux}->set_timeout($fh, $timeout);
209
210 return $fh;
211 };
212
213 my $check_queue = sub {
214 my ($self) = @_;
215
216 my $running = 0;
217
218 foreach my $sname (keys %{$self->{queue_info}}) {
219 my $queue_info = $self->{queue_info}->{$sname};
220 my $fh = $queue_info->{fh};
221 next if !$fh;
222
223 my $qga = $queue_info->{qga};
224
225 if ($queue_info->{error}) {
226 &$close_connection($self, $queue_info);
227 next;
228 }
229
230 if ($queue_info->{current}) { # command running, waiting for response
231 $running++;
232 next;
233 }
234
235 if (!scalar(@{$queue_info->{cmds}})) { # no more commands
236 &$close_connection($self, $queue_info);
237 next;
238 }
239
240 eval {
241
242 my $cmd = $queue_info->{current} = shift @{$queue_info->{cmds}};
243 $cmd->{id} = &$next_cmdid($qga);
244
245 my $fd = -1;
246 if ($cmd->{execute} eq 'add-fd' || $cmd->{execute} eq 'getfd') {
247 $fd = $cmd->{arguments}->{fd};
248 delete $cmd->{arguments}->{fd};
249 }
250
251 my $qmpcmd;
252
253 if ($qga) {
254
255 $qmpcmd = to_json({ execute => 'guest-sync-delimited',
256 arguments => { id => int($cmd->{id})}}) .
257 to_json({ execute => $cmd->{execute}, arguments => $cmd->{arguments}});
258
259 } else {
260
261 $qmpcmd = to_json({
262 execute => $cmd->{execute},
263 arguments => $cmd->{arguments},
264 id => $cmd->{id}});
265 }
266
267 if ($fd >= 0) {
268 my $ret = PVE::IPCC::sendfd(fileno($fh), $fd, $qmpcmd);
269 die "sendfd failed" if $ret < 0;
270 } else {
271 $self->{mux}->write($fh, $qmpcmd);
272 }
273 };
274 if (my $err = $@) {
275 $queue_info->{error} = $err;
276 } else {
277 $running++;
278 }
279 }
280
281 $self->{mux}->endloop() if !$running;
282
283 return $running;
284 };
285
286 # execute all queued command
287
288 sub queue_execute {
289 my ($self, $timeout, $noerr) = @_;
290
291 $timeout = 3 if !$timeout;
292
293 # open all necessary connections
294 foreach my $sname (keys %{$self->{queue_info}}) {
295 my $queue_info = $self->{queue_info}->{$sname};
296 next if !scalar(@{$queue_info->{cmds}}); # no commands
297
298 $queue_info->{error} = undef;
299 $queue_info->{current} = undef;
300
301 eval {
302 &$open_connection($self, $queue_info, $timeout);
303
304 if (!$queue_info->{qga}) {
305 my $cap_cmd = { execute => 'qmp_capabilities', arguments => {} };
306 unshift @{$queue_info->{cmds}}, $cap_cmd;
307 }
308 };
309 if (my $err = $@) {
310 $queue_info->{error} = $err;
311 }
312 }
313
314 my $running;
315
316 for (;;) {
317
318 $running = &$check_queue($self);
319
320 last if !$running;
321
322 $self->{mux}->loop;
323 }
324
325 # make sure we close everything
326 my $errors = '';
327 foreach my $sname (keys %{$self->{queue_info}}) {
328 my $queue_info = $self->{queue_info}->{$sname};
329 &$close_connection($self, $queue_info);
330 if ($queue_info->{error}) {
331 if ($noerr) {
332 warn $queue_info->{error} if $noerr < 2;
333 } else {
334 $errors .= $queue_info->{error}
335 }
336 }
337 }
338
339 $self->{queue_info} = $self->{queue_lookup} = {};
340
341 die $errors if $errors;
342 }
343
344 sub mux_close {
345 my ($self, $mux, $fh) = @_;
346
347 my $queue_info = &$lookup_queue_info($self, $fh, 1);
348 return if !$queue_info;
349
350 $queue_info->{error} = "client closed connection\n"
351 if !$queue_info->{error};
352 }
353
354 # mux_input is called when input is available on one of the descriptors.
355 sub mux_input {
356 my ($self, $mux, $fh, $input) = @_;
357
358 my $queue_info = &$lookup_queue_info($self, $fh);
359 return if !$queue_info;
360
361 my $sname = $queue_info->{sname};
362 my $vmid = $queue_info->{vmid};
363 my $qga = $queue_info->{qga};
364
365 my $curcmd = $queue_info->{current};
366 die "unable to lookup current command for VM $vmid ($sname)\n" if !$curcmd;
367
368 my $raw;
369
370 if ($qga) {
371 return if $$input !~ s/^.*\xff([^\n]+}\r?\n[^\n]+})\r?\n(.*)$/$2/so;
372 $raw = $1;
373 } else {
374 return if $$input !~ s/^(.*})\r?\n(.*)$/$2/so;
375 $raw = $1;
376 }
377
378 eval {
379 my @jsons = split("\n", $raw);
380
381 if ($qga) {
382
383 die "response is not complete" if @jsons != 2 ;
384
385 my $obj = from_json($jsons[0]);
386
387 my $cmdid = $obj->{'return'};
388 die "received responsed without command id\n" if !$cmdid;
389
390 # skip results fro previous commands
391 return if $cmdid < $curcmd->{id};
392
393 if ($curcmd->{id} ne $cmdid) {
394 die "got wrong command id '$cmdid' (expected $curcmd->{id})\n";
395 }
396
397 delete $queue_info->{current};
398
399 $obj = from_json($jsons[1]);
400
401 if (my $callback = $curcmd->{callback}) {
402 &$callback($vmid, $obj);
403 }
404
405 return;
406 }
407
408 foreach my $json (@jsons) {
409 my $obj = from_json($json);
410 next if defined($obj->{QMP}); # skip monitor greeting
411
412 if (exists($obj->{error}->{desc})) {
413 my $desc = $obj->{error}->{desc};
414 chomp $desc;
415 die "$desc\n" if $desc !~ m/Connection can not be completed immediately/;
416 next;
417 }
418
419 if (defined($obj->{event})) {
420 if (my $eventcb = $self->{eventcb}) {
421 &$eventcb($obj);
422 }
423 next;
424 }
425
426 my $cmdid = $obj->{id};
427 die "received responsed without command id\n" if !$cmdid;
428
429 if ($curcmd->{id} ne $cmdid) {
430 die "got wrong command id '$cmdid' (expected $curcmd->{id})\n";
431 }
432
433 delete $queue_info->{current};
434
435 if (my $callback = $curcmd->{callback}) {
436 &$callback($vmid, $obj);
437 }
438 }
439 };
440 if (my $err = $@) {
441 $queue_info->{error} = $err;
442 }
443
444 &$check_queue($self);
445 }
446
447 # This gets called every second to update player info, etc...
448 sub mux_timeout {
449 my ($self, $mux, $fh) = @_;
450
451 if (my $queue_info = &$lookup_queue_info($self, $fh)) {
452 $queue_info->{error} = "got timeout\n";
453 $self->{mux}->inbuffer($fh, ''); # clear to avoid warnings
454 }
455
456 &$check_queue($self);
457 }
458
459 sub mux_eof {
460 my ($self, $mux, $fh, $input) = @_;
461
462 my $queue_info = &$lookup_queue_info($self, $fh);
463 return if !$queue_info;
464
465 my $sname = $queue_info->{sname};
466 my $vmid = $queue_info->{vmid};
467 my $qga = $queue_info->{qga};
468
469 my $curcmd = $queue_info->{current};
470 die "unable to lookup current command for VM $vmid ($sname)\n" if !$curcmd;
471
472 if ($qga && $qga_allow_close_cmds->{$curcmd->{execute}}) {
473
474 return if $$input !~ s/^.*\xff([^\n]+})\r?\n(.*)$/$2/so;
475
476 my $raw = $1;
477
478 eval {
479 my $obj = from_json($raw);
480
481 my $cmdid = $obj->{'return'};
482 die "received responsed without command id\n" if !$cmdid;
483
484 delete $queue_info->{current};
485
486 if (my $callback = $curcmd->{callback}) {
487 &$callback($vmid, undef);
488 }
489 };
490 if (my $err = $@) {
491 $queue_info->{error} = $err;
492 }
493
494 &$close_connection($self, $queue_info);
495
496 if (scalar(@{$queue_info->{cmds}}) && !$queue_info->{error}) {
497 $queue_info->{error} = "Got EOF but command queue is not empty.\n";
498 }
499 }
500 }
501
502 1;