]> git.proxmox.com Git - qemu-server.git/blob - PVE/QMPClient.pm
return error from guest-agent
[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 $result = { error => $resp->{'error'} } if !defined($result) && $resp->{'error'};
96 };
97
98 die "no command specified" if !($cmd && $cmd->{execute});
99
100 $cmd->{callback} = $callback;
101 $cmd->{arguments} = {} if !defined($cmd->{arguments});
102
103 my $queue_info = &$push_cmd_to_queue($self, $vmid, $cmd);
104
105 if (!$timeout) {
106 # hack: monitor sometime blocks
107 if ($cmd->{execute} eq 'query-migrate') {
108 $timeout = 60*60; # 1 hour
109 } elsif ($cmd->{execute} =~ m/^(eject|change)/) {
110 $timeout = 60; # note: cdrom mount command is slow
111 } elsif ($cmd->{execute} eq 'guest-fsfreeze-freeze') {
112 # freeze syncs all guest FS, if we kill it it stays in an unfreezable
113 # locked state with high probability, so use an generous timeout
114 $timeout = 60*60; # 1 hour
115 } elsif ($cmd->{execute} eq 'guest-fsfreeze-thaw') {
116 # thaw has no possible long blocking actions, either it returns
117 # instantly or never (dead locked)
118 $timeout = 10;
119 } elsif ($cmd->{execute} eq 'savevm-start' ||
120 $cmd->{execute} eq 'savevm-end' ||
121 $cmd->{execute} eq 'query-backup' ||
122 $cmd->{execute} eq 'query-block-jobs' ||
123 $cmd->{execute} eq 'block-job-cancel' ||
124 $cmd->{execute} eq 'block-job-complete' ||
125 $cmd->{execute} eq 'backup-cancel' ||
126 $cmd->{execute} eq 'query-savevm' ||
127 $cmd->{execute} eq 'delete-drive-snapshot' ||
128 $cmd->{execute} eq 'guest-shutdown' ||
129 $cmd->{execute} eq 'snapshot-drive' ) {
130 $timeout = 10*60; # 10 mins ?
131 } else {
132 $timeout = 3; # default
133 }
134 }
135
136 $self->queue_execute($timeout, 2);
137
138 die "VM $vmid qmp command '$cmd->{execute}' failed - $queue_info->{error}"
139 if defined($queue_info->{error});
140
141 return $result;
142 };
143
144 my $cmdid_seq = 0;
145 my $cmdid_seq_qga = 0;
146
147 my $next_cmdid = sub {
148 my ($qga) = @_;
149
150 if($qga){
151 $cmdid_seq_qga++;
152 return "$$"."0".$cmdid_seq_qga;
153 } else {
154 $cmdid_seq++;
155 return "$$:$cmdid_seq";
156 }
157 };
158
159 my $lookup_queue_info = sub {
160 my ($self, $fh, $noerr) = @_;
161
162 my $queue_info = $self->{queue_lookup}->{$fh};
163 if (!$queue_info) {
164 warn "internal error - unable to lookup queue info" if !$noerr;
165 return undef;
166 }
167 return $queue_info;
168 };
169
170 my $close_connection = sub {
171 my ($self, $queue_info) = @_;
172
173 if (my $fh = delete $queue_info->{fh}) {
174 delete $self->{queue_lookup}->{$fh};
175 $self->{mux}->close($fh);
176 }
177 };
178
179 my $open_connection = sub {
180 my ($self, $queue_info, $timeout) = @_;
181
182 die "duplicate call to open" if defined($queue_info->{fh});
183
184 my $vmid = $queue_info->{vmid};
185 my $qga = $queue_info->{qga};
186
187 my $sname = PVE::QemuServer::qmp_socket($vmid, $qga);
188
189 $timeout = 1 if !$timeout;
190
191 my $fh;
192 my $starttime = [gettimeofday];
193 my $count = 0;
194
195 my $sotype = $qga ? 'qga' : 'qmp';
196
197 for (;;) {
198 $count++;
199 $fh = IO::Socket::UNIX->new(Peer => $sname, Blocking => 0, Timeout => 1);
200 last if $fh;
201 if ($! != EINTR && $! != EAGAIN) {
202 die "unable to connect to VM $vmid $sotype socket - $!\n";
203 }
204 my $elapsed = tv_interval($starttime, [gettimeofday]);
205 if ($elapsed >= $timeout) {
206 die "unable to connect to VM $vmid $sotype socket - timeout after $count retries\n";
207 }
208 usleep(100000);
209 }
210
211 $queue_info->{fh} = $fh;
212
213 $self->{queue_lookup}->{$fh} = $queue_info;
214
215 $self->{mux}->add($fh);
216 $self->{mux}->set_timeout($fh, $timeout);
217
218 return $fh;
219 };
220
221 my $check_queue = sub {
222 my ($self) = @_;
223
224 my $running = 0;
225
226 foreach my $sname (keys %{$self->{queue_info}}) {
227 my $queue_info = $self->{queue_info}->{$sname};
228 my $fh = $queue_info->{fh};
229 next if !$fh;
230
231 my $qga = $queue_info->{qga};
232
233 if ($queue_info->{error}) {
234 &$close_connection($self, $queue_info);
235 next;
236 }
237
238 if ($queue_info->{current}) { # command running, waiting for response
239 $running++;
240 next;
241 }
242
243 if (!scalar(@{$queue_info->{cmds}})) { # no more commands
244 &$close_connection($self, $queue_info);
245 next;
246 }
247
248 eval {
249
250 my $cmd = $queue_info->{current} = shift @{$queue_info->{cmds}};
251 $cmd->{id} = &$next_cmdid($qga);
252
253 my $fd = -1;
254 if ($cmd->{execute} eq 'add-fd' || $cmd->{execute} eq 'getfd') {
255 $fd = $cmd->{arguments}->{fd};
256 delete $cmd->{arguments}->{fd};
257 }
258
259 my $qmpcmd;
260
261 if ($qga) {
262
263 $qmpcmd = to_json({ execute => 'guest-sync-delimited',
264 arguments => { id => int($cmd->{id})}}) .
265 to_json({ execute => $cmd->{execute}, arguments => $cmd->{arguments}});
266
267 } else {
268
269 $qmpcmd = to_json({
270 execute => $cmd->{execute},
271 arguments => $cmd->{arguments},
272 id => $cmd->{id}});
273 }
274
275 if ($fd >= 0) {
276 my $ret = PVE::IPCC::sendfd(fileno($fh), $fd, $qmpcmd);
277 die "sendfd failed" if $ret < 0;
278 } else {
279 $self->{mux}->write($fh, $qmpcmd);
280 }
281 };
282 if (my $err = $@) {
283 $queue_info->{error} = $err;
284 } else {
285 $running++;
286 }
287 }
288
289 $self->{mux}->endloop() if !$running;
290
291 return $running;
292 };
293
294 # execute all queued command
295
296 sub queue_execute {
297 my ($self, $timeout, $noerr) = @_;
298
299 $timeout = 3 if !$timeout;
300
301 # open all necessary connections
302 foreach my $sname (keys %{$self->{queue_info}}) {
303 my $queue_info = $self->{queue_info}->{$sname};
304 next if !scalar(@{$queue_info->{cmds}}); # no commands
305
306 $queue_info->{error} = undef;
307 $queue_info->{current} = undef;
308
309 eval {
310 &$open_connection($self, $queue_info, $timeout);
311
312 if (!$queue_info->{qga}) {
313 my $cap_cmd = { execute => 'qmp_capabilities', arguments => {} };
314 unshift @{$queue_info->{cmds}}, $cap_cmd;
315 }
316 };
317 if (my $err = $@) {
318 $queue_info->{error} = $err;
319 }
320 }
321
322 my $running;
323
324 for (;;) {
325
326 $running = &$check_queue($self);
327
328 last if !$running;
329
330 $self->{mux}->loop;
331 }
332
333 # make sure we close everything
334 my $errors = '';
335 foreach my $sname (keys %{$self->{queue_info}}) {
336 my $queue_info = $self->{queue_info}->{$sname};
337 &$close_connection($self, $queue_info);
338 if ($queue_info->{error}) {
339 if ($noerr) {
340 warn $queue_info->{error} if $noerr < 2;
341 } else {
342 $errors .= $queue_info->{error}
343 }
344 }
345 }
346
347 $self->{queue_info} = $self->{queue_lookup} = {};
348
349 die $errors if $errors;
350 }
351
352 sub mux_close {
353 my ($self, $mux, $fh) = @_;
354
355 my $queue_info = &$lookup_queue_info($self, $fh, 1);
356 return if !$queue_info;
357
358 $queue_info->{error} = "client closed connection\n"
359 if !$queue_info->{error};
360 }
361
362 # mux_input is called when input is available on one of the descriptors.
363 sub mux_input {
364 my ($self, $mux, $fh, $input) = @_;
365
366 my $queue_info = &$lookup_queue_info($self, $fh);
367 return if !$queue_info;
368
369 my $sname = $queue_info->{sname};
370 my $vmid = $queue_info->{vmid};
371 my $qga = $queue_info->{qga};
372
373 my $curcmd = $queue_info->{current};
374 die "unable to lookup current command for VM $vmid ($sname)\n" if !$curcmd;
375
376 my $raw;
377
378 if ($qga) {
379 return if $$input !~ s/^.*\xff([^\n]+}\r?\n[^\n]+})\r?\n(.*)$/$2/so;
380 $raw = $1;
381 } else {
382 return if $$input !~ s/^(.*})\r?\n(.*)$/$2/so;
383 $raw = $1;
384 }
385
386 eval {
387 my @jsons = split("\n", $raw);
388
389 if ($qga) {
390
391 die "response is not complete" if @jsons != 2 ;
392
393 my $obj = from_json($jsons[0]);
394
395 my $cmdid = $obj->{'return'};
396 die "received responsed without command id\n" if !$cmdid;
397
398 # skip results fro previous commands
399 return if $cmdid < $curcmd->{id};
400
401 if ($curcmd->{id} ne $cmdid) {
402 die "got wrong command id '$cmdid' (expected $curcmd->{id})\n";
403 }
404
405 delete $queue_info->{current};
406
407 $obj = from_json($jsons[1]);
408
409 if (my $callback = $curcmd->{callback}) {
410 &$callback($vmid, $obj);
411 }
412
413 return;
414 }
415
416 foreach my $json (@jsons) {
417 my $obj = from_json($json);
418 next if defined($obj->{QMP}); # skip monitor greeting
419
420 if (exists($obj->{error}->{desc})) {
421 my $desc = $obj->{error}->{desc};
422 chomp $desc;
423 die "$desc\n" if $desc !~ m/Connection can not be completed immediately/;
424 next;
425 }
426
427 if (defined($obj->{event})) {
428 if (my $eventcb = $self->{eventcb}) {
429 &$eventcb($obj);
430 }
431 next;
432 }
433
434 my $cmdid = $obj->{id};
435 die "received responsed without command id\n" if !$cmdid;
436
437 if ($curcmd->{id} ne $cmdid) {
438 die "got wrong command id '$cmdid' (expected $curcmd->{id})\n";
439 }
440
441 delete $queue_info->{current};
442
443 if (my $callback = $curcmd->{callback}) {
444 &$callback($vmid, $obj);
445 }
446 }
447 };
448 if (my $err = $@) {
449 $queue_info->{error} = $err;
450 }
451
452 &$check_queue($self);
453 }
454
455 # This gets called every second to update player info, etc...
456 sub mux_timeout {
457 my ($self, $mux, $fh) = @_;
458
459 if (my $queue_info = &$lookup_queue_info($self, $fh)) {
460 $queue_info->{error} = "got timeout\n";
461 $self->{mux}->inbuffer($fh, ''); # clear to avoid warnings
462 }
463
464 &$check_queue($self);
465 }
466
467 sub mux_eof {
468 my ($self, $mux, $fh, $input) = @_;
469
470 my $queue_info = &$lookup_queue_info($self, $fh);
471 return if !$queue_info;
472
473 my $sname = $queue_info->{sname};
474 my $vmid = $queue_info->{vmid};
475 my $qga = $queue_info->{qga};
476
477 my $curcmd = $queue_info->{current};
478 die "unable to lookup current command for VM $vmid ($sname)\n" if !$curcmd;
479
480 if ($qga && $qga_allow_close_cmds->{$curcmd->{execute}}) {
481
482 return if $$input !~ s/^.*\xff([^\n]+})\r?\n(.*)$/$2/so;
483
484 my $raw = $1;
485
486 eval {
487 my $obj = from_json($raw);
488
489 my $cmdid = $obj->{'return'};
490 die "received responsed without command id\n" if !$cmdid;
491
492 delete $queue_info->{current};
493
494 if (my $callback = $curcmd->{callback}) {
495 &$callback($vmid, undef);
496 }
497 };
498 if (my $err = $@) {
499 $queue_info->{error} = $err;
500 }
501
502 &$close_connection($self, $queue_info);
503
504 if (scalar(@{$queue_info->{cmds}}) && !$queue_info->{error}) {
505 $queue_info->{error} = "Got EOF but command queue is not empty.\n";
506 }
507 }
508 }
509
510 1;