jsonrpc: Don't swallow errors in jsonrpc_transact_block().
[cascardo/ovs.git] / lib / jsonrpc.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "jsonrpc.h"
20
21 #include <assert.h>
22 #include <errno.h>
23
24 #include "byteq.h"
25 #include "dynamic-string.h"
26 #include "fatal-signal.h"
27 #include "json.h"
28 #include "list.h"
29 #include "ofpbuf.h"
30 #include "poll-loop.h"
31 #include "reconnect.h"
32 #include "stream.h"
33 #include "timeval.h"
34 #include "vlog.h"
35
36 VLOG_DEFINE_THIS_MODULE(jsonrpc);
37 \f
38 struct jsonrpc {
39     struct stream *stream;
40     char *name;
41     int status;
42
43     /* Input. */
44     struct byteq input;
45     struct json_parser *parser;
46     struct jsonrpc_msg *received;
47
48     /* Output. */
49     struct list output;         /* Contains "struct ofpbuf"s. */
50     size_t backlog;
51 };
52
53 /* Rate limit for error messages. */
54 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
55
56 static void jsonrpc_received(struct jsonrpc *);
57 static void jsonrpc_cleanup(struct jsonrpc *);
58 static void jsonrpc_error(struct jsonrpc *, int error);
59
60 /* This is just the same as stream_open() except that it uses the default
61  * JSONRPC ports if none is specified. */
62 int
63 jsonrpc_stream_open(const char *name, struct stream **streamp)
64 {
65     return stream_open_with_default_ports(name, JSONRPC_TCP_PORT,
66                                           JSONRPC_SSL_PORT, streamp);
67 }
68
69 /* This is just the same as pstream_open() except that it uses the default
70  * JSONRPC ports if none is specified. */
71 int
72 jsonrpc_pstream_open(const char *name, struct pstream **pstreamp)
73 {
74     return pstream_open_with_default_ports(name, JSONRPC_TCP_PORT,
75                                            JSONRPC_SSL_PORT, pstreamp);
76 }
77
78 /* Returns a new JSON-RPC stream that uses 'stream' for input and output.  The
79  * new jsonrpc object takes ownership of 'stream'. */
80 struct jsonrpc *
81 jsonrpc_open(struct stream *stream)
82 {
83     struct jsonrpc *rpc;
84
85     assert(stream != NULL);
86
87     rpc = xzalloc(sizeof *rpc);
88     rpc->name = xstrdup(stream_get_name(stream));
89     rpc->stream = stream;
90     byteq_init(&rpc->input);
91     list_init(&rpc->output);
92
93     return rpc;
94 }
95
96 /* Destroys 'rpc', closing the stream on which it is based, and frees its
97  * memory. */
98 void
99 jsonrpc_close(struct jsonrpc *rpc)
100 {
101     if (rpc) {
102         jsonrpc_cleanup(rpc);
103         free(rpc->name);
104         free(rpc);
105     }
106 }
107
108 /* Performs periodic maintenance on 'rpc', such as flushing output buffers. */
109 void
110 jsonrpc_run(struct jsonrpc *rpc)
111 {
112     if (rpc->status) {
113         return;
114     }
115
116     stream_run(rpc->stream);
117     while (!list_is_empty(&rpc->output)) {
118         struct ofpbuf *buf = ofpbuf_from_list(rpc->output.next);
119         int retval;
120
121         retval = stream_send(rpc->stream, buf->data, buf->size);
122         if (retval >= 0) {
123             rpc->backlog -= retval;
124             ofpbuf_pull(buf, retval);
125             if (!buf->size) {
126                 list_remove(&buf->list_node);
127                 ofpbuf_delete(buf);
128             }
129         } else {
130             if (retval != -EAGAIN) {
131                 VLOG_WARN_RL(&rl, "%s: send error: %s",
132                              rpc->name, strerror(-retval));
133                 jsonrpc_error(rpc, -retval);
134             }
135             break;
136         }
137     }
138 }
139
140 /* Arranges for the poll loop to wake up when 'rpc' needs to perform
141  * maintenance activities. */
142 void
143 jsonrpc_wait(struct jsonrpc *rpc)
144 {
145     if (!rpc->status) {
146         stream_run_wait(rpc->stream);
147         if (!list_is_empty(&rpc->output)) {
148             stream_send_wait(rpc->stream);
149         }
150     }
151 }
152
153 /*
154  * Returns the current status of 'rpc'.  The possible return values are:
155  * - 0: no error yet
156  * - >0: errno value
157  * - EOF: end of file (remote end closed connection; not necessarily an error).
158  *
159  * When this functions nonzero, 'rpc' is effectively out of commission.  'rpc'
160  * will not receive any more messages and any further messages that one
161  * attempts to send with 'rpc' will be discarded.  The caller can keep 'rpc'
162  * around as long as it wants, but it's not going to provide any more useful
163  * services.
164  */
165 int
166 jsonrpc_get_status(const struct jsonrpc *rpc)
167 {
168     return rpc->status;
169 }
170
171 /* Returns the number of bytes buffered by 'rpc' to be written to the
172  * underlying stream.  Always returns 0 if 'rpc' has encountered an error or if
173  * the remote end closed the connection. */
174 size_t
175 jsonrpc_get_backlog(const struct jsonrpc *rpc)
176 {
177     return rpc->status ? 0 : rpc->backlog;
178 }
179
180 /* Returns 'rpc''s name, that is, the name returned by stream_get_name() for
181  * the stream underlying 'rpc' when 'rpc' was created. */
182 const char *
183 jsonrpc_get_name(const struct jsonrpc *rpc)
184 {
185     return rpc->name;
186 }
187
188 static void
189 jsonrpc_log_msg(const struct jsonrpc *rpc, const char *title,
190                 const struct jsonrpc_msg *msg)
191 {
192     if (VLOG_IS_DBG_ENABLED()) {
193         struct ds s = DS_EMPTY_INITIALIZER;
194         if (msg->method) {
195             ds_put_format(&s, ", method=\"%s\"", msg->method);
196         }
197         if (msg->params) {
198             ds_put_cstr(&s, ", params=");
199             json_to_ds(msg->params, 0, &s);
200         }
201         if (msg->result) {
202             ds_put_cstr(&s, ", result=");
203             json_to_ds(msg->result, 0, &s);
204         }
205         if (msg->error) {
206             ds_put_cstr(&s, ", error=");
207             json_to_ds(msg->error, 0, &s);
208         }
209         if (msg->id) {
210             ds_put_cstr(&s, ", id=");
211             json_to_ds(msg->id, 0, &s);
212         }
213         VLOG_DBG("%s: %s %s%s", rpc->name, title,
214                  jsonrpc_msg_type_to_string(msg->type), ds_cstr(&s));
215         ds_destroy(&s);
216     }
217 }
218
219 /* Schedules 'msg' to be sent on 'rpc' and returns 'rpc''s status (as with
220  * jsonrpc_get_status()).
221  *
222  * If 'msg' cannot be sent immediately, it is appended to a buffer.  The caller
223  * is responsible for ensuring that the amount of buffered data is somehow
224  * limited.  (jsonrpc_get_backlog() returns the amount of data currently
225  * buffered in 'rpc'.)
226  *
227  * Always takes ownership of 'msg', regardless of success. */
228 int
229 jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
230 {
231     struct ofpbuf *buf;
232     struct json *json;
233     size_t length;
234     char *s;
235
236     if (rpc->status) {
237         jsonrpc_msg_destroy(msg);
238         return rpc->status;
239     }
240
241     jsonrpc_log_msg(rpc, "send", msg);
242
243     json = jsonrpc_msg_to_json(msg);
244     s = json_to_string(json, 0);
245     length = strlen(s);
246     json_destroy(json);
247
248     buf = xmalloc(sizeof *buf);
249     ofpbuf_use(buf, s, length);
250     buf->size = length;
251     list_push_back(&rpc->output, &buf->list_node);
252     rpc->backlog += length;
253
254     if (rpc->backlog == length) {
255         jsonrpc_run(rpc);
256     }
257     return rpc->status;
258 }
259
260 /* Attempts to receive a message from 'rpc'.
261  *
262  * If successful, stores the received message in '*msgp' and returns 0.  The
263  * caller takes ownership of '*msgp' and must eventually destroy it with
264  * jsonrpc_msg_destroy().
265  *
266  * Otherwise, stores NULL in '*msgp' and returns one of the following:
267  *
268  *   - EAGAIN: No message has been received.
269  *
270  *   - EOF: The remote end closed the connection gracefully.
271  *
272  *   - Otherwise an errno value that represents a JSON-RPC protocol violation
273  *     or another error fatal to the connection.  'rpc' will not send or
274  *     receive any more messages.
275  */
276 int
277 jsonrpc_recv(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
278 {
279     *msgp = NULL;
280     if (rpc->status) {
281         return rpc->status;
282     }
283
284     while (!rpc->received) {
285         if (byteq_is_empty(&rpc->input)) {
286             size_t chunk;
287             int retval;
288
289             chunk = byteq_headroom(&rpc->input);
290             retval = stream_recv(rpc->stream, byteq_head(&rpc->input), chunk);
291             if (retval < 0) {
292                 if (retval == -EAGAIN) {
293                     return EAGAIN;
294                 } else {
295                     VLOG_WARN_RL(&rl, "%s: receive error: %s",
296                                  rpc->name, strerror(-retval));
297                     jsonrpc_error(rpc, -retval);
298                     return rpc->status;
299                 }
300             } else if (retval == 0) {
301                 jsonrpc_error(rpc, EOF);
302                 return EOF;
303             }
304             byteq_advance_head(&rpc->input, retval);
305         } else {
306             size_t n, used;
307
308             if (!rpc->parser) {
309                 rpc->parser = json_parser_create(0);
310             }
311             n = byteq_tailroom(&rpc->input);
312             used = json_parser_feed(rpc->parser,
313                                     (char *) byteq_tail(&rpc->input), n);
314             byteq_advance_tail(&rpc->input, used);
315             if (json_parser_is_done(rpc->parser)) {
316                 jsonrpc_received(rpc);
317                 if (rpc->status) {
318                     const struct byteq *q = &rpc->input;
319                     if (q->head <= BYTEQ_SIZE) {
320                         stream_report_content(q->buffer, q->head,
321                                               STREAM_JSONRPC,
322                                               THIS_MODULE, rpc->name);
323                     }
324                     return rpc->status;
325                 }
326             }
327         }
328     }
329
330     *msgp = rpc->received;
331     rpc->received = NULL;
332     return 0;
333 }
334
335 /* Causes the poll loop to wake up when jsonrpc_recv() may return a value other
336  * than EAGAIN. */
337 void
338 jsonrpc_recv_wait(struct jsonrpc *rpc)
339 {
340     if (rpc->status || rpc->received || !byteq_is_empty(&rpc->input)) {
341         (poll_immediate_wake)(rpc->name);
342     } else {
343         stream_recv_wait(rpc->stream);
344     }
345 }
346
347 /* Sends 'msg' on 'rpc' and waits for it to be successfully queued to the
348  * underlying stream.  Returns 0 if 'msg' was sent successfully, otherwise a
349  * status value (see jsonrpc_get_status()).
350  *
351  * Always takes ownership of 'msg', regardless of success. */
352 int
353 jsonrpc_send_block(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
354 {
355     int error;
356
357     fatal_signal_run();
358
359     error = jsonrpc_send(rpc, msg);
360     if (error) {
361         return error;
362     }
363
364     for (;;) {
365         jsonrpc_run(rpc);
366         if (list_is_empty(&rpc->output) || rpc->status) {
367             return rpc->status;
368         }
369         jsonrpc_wait(rpc);
370         poll_block();
371     }
372 }
373
374 /* Waits for a message to be received on 'rpc'.  Same semantics as
375  * jsonrpc_recv() except that EAGAIN will never be returned. */
376 int
377 jsonrpc_recv_block(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
378 {
379     for (;;) {
380         int error = jsonrpc_recv(rpc, msgp);
381         if (error != EAGAIN) {
382             fatal_signal_run();
383             return error;
384         }
385
386         jsonrpc_run(rpc);
387         jsonrpc_wait(rpc);
388         jsonrpc_recv_wait(rpc);
389         poll_block();
390     }
391 }
392
393 /* Sends 'request' to 'rpc' then waits for a reply.  The return value is 0 if
394  * successful, in which case '*replyp' is set to the reply, which the caller
395  * must eventually free with jsonrpc_msg_destroy().  Otherwise returns a status
396  * value (see jsonrpc_get_status()).
397  *
398  * Discards any message received on 'rpc' that is not a reply to 'request'
399  * (based on message id).
400  *
401  * Always takes ownership of 'request', regardless of success. */
402 int
403 jsonrpc_transact_block(struct jsonrpc *rpc, struct jsonrpc_msg *request,
404                        struct jsonrpc_msg **replyp)
405 {
406     struct jsonrpc_msg *reply = NULL;
407     struct json *id;
408     int error;
409
410     id = json_clone(request->id);
411     error = jsonrpc_send_block(rpc, request);
412     if (!error) {
413         for (;;) {
414             error = jsonrpc_recv_block(rpc, &reply);
415             if (error) {
416                 break;
417             }
418             if ((reply->type == JSONRPC_REPLY || reply->type == JSONRPC_ERROR)
419                 && json_equal(id, reply->id)) {
420                 break;
421             }
422             jsonrpc_msg_destroy(reply);
423         }
424     }
425     *replyp = error ? NULL : reply;
426     json_destroy(id);
427     return error;
428 }
429
430 static void
431 jsonrpc_received(struct jsonrpc *rpc)
432 {
433     struct jsonrpc_msg *msg;
434     struct json *json;
435     char *error;
436
437     json = json_parser_finish(rpc->parser);
438     rpc->parser = NULL;
439     if (json->type == JSON_STRING) {
440         VLOG_WARN_RL(&rl, "%s: error parsing stream: %s",
441                      rpc->name, json_string(json));
442         jsonrpc_error(rpc, EPROTO);
443         json_destroy(json);
444         return;
445     }
446
447     error = jsonrpc_msg_from_json(json, &msg);
448     if (error) {
449         VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
450                      rpc->name, error);
451         free(error);
452         jsonrpc_error(rpc, EPROTO);
453         return;
454     }
455
456     jsonrpc_log_msg(rpc, "received", msg);
457     rpc->received = msg;
458 }
459
460 static void
461 jsonrpc_error(struct jsonrpc *rpc, int error)
462 {
463     assert(error);
464     if (!rpc->status) {
465         rpc->status = error;
466         jsonrpc_cleanup(rpc);
467     }
468 }
469
470 static void
471 jsonrpc_cleanup(struct jsonrpc *rpc)
472 {
473     stream_close(rpc->stream);
474     rpc->stream = NULL;
475
476     json_parser_abort(rpc->parser);
477     rpc->parser = NULL;
478
479     jsonrpc_msg_destroy(rpc->received);
480     rpc->received = NULL;
481
482     ofpbuf_list_delete(&rpc->output);
483     rpc->backlog = 0;
484 }
485 \f
486 static struct jsonrpc_msg *
487 jsonrpc_create(enum jsonrpc_msg_type type, const char *method,
488                 struct json *params, struct json *result, struct json *error,
489                 struct json *id)
490 {
491     struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
492     msg->type = type;
493     msg->method = method ? xstrdup(method) : NULL;
494     msg->params = params;
495     msg->result = result;
496     msg->error = error;
497     msg->id = id;
498     return msg;
499 }
500
501 static struct json *
502 jsonrpc_create_id(void)
503 {
504     static unsigned int id;
505     return json_integer_create(id++);
506 }
507
508 struct jsonrpc_msg *
509 jsonrpc_create_request(const char *method, struct json *params,
510                        struct json **idp)
511 {
512     struct json *id = jsonrpc_create_id();
513     if (idp) {
514         *idp = json_clone(id);
515     }
516     return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL, id);
517 }
518
519 struct jsonrpc_msg *
520 jsonrpc_create_notify(const char *method, struct json *params)
521 {
522     return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
523 }
524
525 struct jsonrpc_msg *
526 jsonrpc_create_reply(struct json *result, const struct json *id)
527 {
528     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
529                            json_clone(id));
530 }
531
532 struct jsonrpc_msg *
533 jsonrpc_create_error(struct json *error, const struct json *id)
534 {
535     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
536                            json_clone(id));
537 }
538
539 const char *
540 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
541 {
542     switch (type) {
543     case JSONRPC_REQUEST:
544         return "request";
545
546     case JSONRPC_NOTIFY:
547         return "notification";
548
549     case JSONRPC_REPLY:
550         return "reply";
551
552     case JSONRPC_ERROR:
553         return "error";
554     }
555     return "(null)";
556 }
557
558 char *
559 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
560 {
561     const char *type_name;
562     unsigned int pattern;
563
564     if (m->params && m->params->type != JSON_ARRAY) {
565         return xstrdup("\"params\" must be JSON array");
566     }
567
568     switch (m->type) {
569     case JSONRPC_REQUEST:
570         pattern = 0x11001;
571         break;
572
573     case JSONRPC_NOTIFY:
574         pattern = 0x11000;
575         break;
576
577     case JSONRPC_REPLY:
578         pattern = 0x00101;
579         break;
580
581     case JSONRPC_ERROR:
582         pattern = 0x00011;
583         break;
584
585     default:
586         return xasprintf("invalid JSON-RPC message type %d", m->type);
587     }
588
589     type_name = jsonrpc_msg_type_to_string(m->type);
590     if ((m->method != NULL) != ((pattern & 0x10000) != 0)) {
591         return xasprintf("%s must%s have \"method\"",
592                          type_name, (pattern & 0x10000) ? "" : " not");
593
594     }
595     if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
596         return xasprintf("%s must%s have \"params\"",
597                          type_name, (pattern & 0x1000) ? "" : " not");
598
599     }
600     if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
601         return xasprintf("%s must%s have \"result\"",
602                          type_name, (pattern & 0x100) ? "" : " not");
603
604     }
605     if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
606         return xasprintf("%s must%s have \"error\"",
607                          type_name, (pattern & 0x10) ? "" : " not");
608
609     }
610     if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
611         return xasprintf("%s must%s have \"id\"",
612                          type_name, (pattern & 0x1) ? "" : " not");
613
614     }
615     return NULL;
616 }
617
618 void
619 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
620 {
621     if (m) {
622         free(m->method);
623         json_destroy(m->params);
624         json_destroy(m->result);
625         json_destroy(m->error);
626         json_destroy(m->id);
627         free(m);
628     }
629 }
630
631 static struct json *
632 null_from_json_null(struct json *json)
633 {
634     if (json && json->type == JSON_NULL) {
635         json_destroy(json);
636         return NULL;
637     }
638     return json;
639 }
640
641 char *
642 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
643 {
644     struct json *method = NULL;
645     struct jsonrpc_msg *msg = NULL;
646     struct shash *object;
647     char *error;
648
649     if (json->type != JSON_OBJECT) {
650         error = xstrdup("message is not a JSON object");
651         goto exit;
652     }
653     object = json_object(json);
654
655     method = shash_find_and_delete(object, "method");
656     if (method && method->type != JSON_STRING) {
657         error = xstrdup("method is not a JSON string");
658         goto exit;
659     }
660
661     msg = xzalloc(sizeof *msg);
662     msg->method = method ? xstrdup(method->u.string) : NULL;
663     msg->params = null_from_json_null(shash_find_and_delete(object, "params"));
664     msg->result = null_from_json_null(shash_find_and_delete(object, "result"));
665     msg->error = null_from_json_null(shash_find_and_delete(object, "error"));
666     msg->id = null_from_json_null(shash_find_and_delete(object, "id"));
667     msg->type = (msg->result ? JSONRPC_REPLY
668                  : msg->error ? JSONRPC_ERROR
669                  : msg->id ? JSONRPC_REQUEST
670                  : JSONRPC_NOTIFY);
671     if (!shash_is_empty(object)) {
672         error = xasprintf("message has unexpected member \"%s\"",
673                           shash_first(object)->name);
674         goto exit;
675     }
676     error = jsonrpc_msg_is_valid(msg);
677     if (error) {
678         goto exit;
679     }
680
681 exit:
682     json_destroy(method);
683     json_destroy(json);
684     if (error) {
685         jsonrpc_msg_destroy(msg);
686         msg = NULL;
687     }
688     *msgp = msg;
689     return error;
690 }
691
692 struct json *
693 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
694 {
695     struct json *json = json_object_create();
696
697     if (m->method) {
698         json_object_put(json, "method", json_string_create_nocopy(m->method));
699     }
700
701     if (m->params) {
702         json_object_put(json, "params", m->params);
703     }
704
705     if (m->result) {
706         json_object_put(json, "result", m->result);
707     } else if (m->type == JSONRPC_ERROR) {
708         json_object_put(json, "result", json_null_create());
709     }
710
711     if (m->error) {
712         json_object_put(json, "error", m->error);
713     } else if (m->type == JSONRPC_REPLY) {
714         json_object_put(json, "error", json_null_create());
715     }
716
717     if (m->id) {
718         json_object_put(json, "id", m->id);
719     } else if (m->type == JSONRPC_NOTIFY) {
720         json_object_put(json, "id", json_null_create());
721     }
722
723     free(m);
724
725     return json;
726 }
727 \f
728 /* A JSON-RPC session with reconnection. */
729
730 struct jsonrpc_session {
731     struct reconnect *reconnect;
732     struct jsonrpc *rpc;
733     struct stream *stream;
734     struct pstream *pstream;
735     unsigned int seqno;
736 };
737
738 /* Creates and returns a jsonrpc_session to 'name', which should be a string
739  * acceptable to stream_open() or pstream_open().
740  *
741  * If 'name' is an active connection method, e.g. "tcp:127.1.2.3", the new
742  * jsonrpc_session connects and reconnects, with back-off, to 'name'.
743  *
744  * If 'name' is a passive connection method, e.g. "ptcp:", the new
745  * jsonrpc_session listens for connections to 'name'.  It maintains at most one
746  * connection at any given time.  Any new connection causes the previous one
747  * (if any) to be dropped. */
748 struct jsonrpc_session *
749 jsonrpc_session_open(const char *name)
750 {
751     struct jsonrpc_session *s;
752
753     s = xmalloc(sizeof *s);
754     s->reconnect = reconnect_create(time_msec());
755     reconnect_set_name(s->reconnect, name);
756     reconnect_enable(s->reconnect, time_msec());
757     s->rpc = NULL;
758     s->stream = NULL;
759     s->pstream = NULL;
760     s->seqno = 0;
761
762     if (!pstream_verify_name(name)) {
763         reconnect_set_passive(s->reconnect, true, time_msec());
764     }
765
766     return s;
767 }
768
769 /* Creates and returns a jsonrpc_session that is initially connected to
770  * 'jsonrpc'.  If the connection is dropped, it will not be reconnected.
771  *
772  * On the assumption that such connections are likely to be short-lived
773  * (e.g. from ovs-vsctl), informational logging for them is suppressed. */
774 struct jsonrpc_session *
775 jsonrpc_session_open_unreliably(struct jsonrpc *jsonrpc)
776 {
777     struct jsonrpc_session *s;
778
779     s = xmalloc(sizeof *s);
780     s->reconnect = reconnect_create(time_msec());
781     reconnect_set_quiet(s->reconnect, true);
782     reconnect_set_name(s->reconnect, jsonrpc_get_name(jsonrpc));
783     reconnect_set_max_tries(s->reconnect, 0);
784     reconnect_connected(s->reconnect, time_msec());
785     s->rpc = jsonrpc;
786     s->stream = NULL;
787     s->pstream = NULL;
788     s->seqno = 0;
789
790     return s;
791 }
792
793 void
794 jsonrpc_session_close(struct jsonrpc_session *s)
795 {
796     if (s) {
797         jsonrpc_close(s->rpc);
798         reconnect_destroy(s->reconnect);
799         stream_close(s->stream);
800         pstream_close(s->pstream);
801         free(s);
802     }
803 }
804
805 static void
806 jsonrpc_session_disconnect(struct jsonrpc_session *s)
807 {
808     if (s->rpc) {
809         jsonrpc_error(s->rpc, EOF);
810         jsonrpc_close(s->rpc);
811         s->rpc = NULL;
812         s->seqno++;
813     } else if (s->stream) {
814         stream_close(s->stream);
815         s->stream = NULL;
816         s->seqno++;
817     }
818 }
819
820 static void
821 jsonrpc_session_connect(struct jsonrpc_session *s)
822 {
823     const char *name = reconnect_get_name(s->reconnect);
824     int error;
825
826     jsonrpc_session_disconnect(s);
827     if (!reconnect_is_passive(s->reconnect)) {
828         error = jsonrpc_stream_open(name, &s->stream);
829         if (!error) {
830             reconnect_connecting(s->reconnect, time_msec());
831         }
832     } else {
833         error = s->pstream ? 0 : jsonrpc_pstream_open(name, &s->pstream);
834         if (!error) {
835             reconnect_listening(s->reconnect, time_msec());
836         }
837     }
838
839     if (error) {
840         reconnect_connect_failed(s->reconnect, time_msec(), error);
841     }
842     s->seqno++;
843 }
844
845 void
846 jsonrpc_session_run(struct jsonrpc_session *s)
847 {
848     if (s->pstream) {
849         struct stream *stream;
850         int error;
851
852         error = pstream_accept(s->pstream, &stream);
853         if (!error) {
854             if (s->rpc || s->stream) {
855                 VLOG_INFO_RL(&rl,
856                              "%s: new connection replacing active connection",
857                              reconnect_get_name(s->reconnect));
858                 jsonrpc_session_disconnect(s);
859             }
860             reconnect_connected(s->reconnect, time_msec());
861             s->rpc = jsonrpc_open(stream);
862         } else if (error != EAGAIN) {
863             reconnect_listen_error(s->reconnect, time_msec(), error);
864             pstream_close(s->pstream);
865             s->pstream = NULL;
866         }
867     }
868
869     if (s->rpc) {
870         int error;
871
872         jsonrpc_run(s->rpc);
873         error = jsonrpc_get_status(s->rpc);
874         if (error) {
875             reconnect_disconnected(s->reconnect, time_msec(), error);
876             jsonrpc_session_disconnect(s);
877         }
878     } else if (s->stream) {
879         int error;
880
881         stream_run(s->stream);
882         error = stream_connect(s->stream);
883         if (!error) {
884             reconnect_connected(s->reconnect, time_msec());
885             s->rpc = jsonrpc_open(s->stream);
886             s->stream = NULL;
887         } else if (error != EAGAIN) {
888             reconnect_connect_failed(s->reconnect, time_msec(), error);
889             stream_close(s->stream);
890             s->stream = NULL;
891         }
892     }
893
894     switch (reconnect_run(s->reconnect, time_msec())) {
895     case RECONNECT_CONNECT:
896         jsonrpc_session_connect(s);
897         break;
898
899     case RECONNECT_DISCONNECT:
900         reconnect_disconnected(s->reconnect, time_msec(), 0);
901         jsonrpc_session_disconnect(s);
902         break;
903
904     case RECONNECT_PROBE:
905         if (s->rpc) {
906             struct json *params;
907             struct jsonrpc_msg *request;
908
909             params = json_array_create_empty();
910             request = jsonrpc_create_request("echo", params, NULL);
911             json_destroy(request->id);
912             request->id = json_string_create("echo");
913             jsonrpc_send(s->rpc, request);
914         }
915         break;
916     }
917 }
918
919 void
920 jsonrpc_session_wait(struct jsonrpc_session *s)
921 {
922     if (s->rpc) {
923         jsonrpc_wait(s->rpc);
924     } else if (s->stream) {
925         stream_run_wait(s->stream);
926         stream_connect_wait(s->stream);
927     }
928     if (s->pstream) {
929         pstream_wait(s->pstream);
930     }
931     reconnect_wait(s->reconnect, time_msec());
932 }
933
934 size_t
935 jsonrpc_session_get_backlog(const struct jsonrpc_session *s)
936 {
937     return s->rpc ? jsonrpc_get_backlog(s->rpc) : 0;
938 }
939
940 /* Always returns a pointer to a valid C string, assuming 's' was initialized
941  * correctly. */
942 const char *
943 jsonrpc_session_get_name(const struct jsonrpc_session *s)
944 {
945     return reconnect_get_name(s->reconnect);
946 }
947
948 /* Always takes ownership of 'msg', regardless of success. */
949 int
950 jsonrpc_session_send(struct jsonrpc_session *s, struct jsonrpc_msg *msg)
951 {
952     if (s->rpc) {
953         return jsonrpc_send(s->rpc, msg);
954     } else {
955         jsonrpc_msg_destroy(msg);
956         return ENOTCONN;
957     }
958 }
959
960 struct jsonrpc_msg *
961 jsonrpc_session_recv(struct jsonrpc_session *s)
962 {
963     if (s->rpc) {
964         struct jsonrpc_msg *msg;
965         jsonrpc_recv(s->rpc, &msg);
966         if (msg) {
967             reconnect_received(s->reconnect, time_msec());
968             if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
969                 /* Echo request.  Send reply. */
970                 struct jsonrpc_msg *reply;
971
972                 reply = jsonrpc_create_reply(json_clone(msg->params), msg->id);
973                 jsonrpc_session_send(s, reply);
974             } else if (msg->type == JSONRPC_REPLY
975                        && msg->id && msg->id->type == JSON_STRING
976                        && !strcmp(msg->id->u.string, "echo")) {
977                 /* It's a reply to our echo request.  Suppress it. */
978             } else {
979                 return msg;
980             }
981             jsonrpc_msg_destroy(msg);
982         }
983     }
984     return NULL;
985 }
986
987 void
988 jsonrpc_session_recv_wait(struct jsonrpc_session *s)
989 {
990     if (s->rpc) {
991         jsonrpc_recv_wait(s->rpc);
992     }
993 }
994
995 bool
996 jsonrpc_session_is_alive(const struct jsonrpc_session *s)
997 {
998     return s->rpc || s->stream || reconnect_get_max_tries(s->reconnect);
999 }
1000
1001 bool
1002 jsonrpc_session_is_connected(const struct jsonrpc_session *s)
1003 {
1004     return s->rpc != NULL;
1005 }
1006
1007 unsigned int
1008 jsonrpc_session_get_seqno(const struct jsonrpc_session *s)
1009 {
1010     return s->seqno;
1011 }
1012
1013 int
1014 jsonrpc_session_get_status(const struct jsonrpc_session *s)
1015 {
1016     return s && s->rpc ? jsonrpc_get_status(s->rpc) : 0;
1017 }
1018
1019 void
1020 jsonrpc_session_get_reconnect_stats(const struct jsonrpc_session *s,
1021                                     struct reconnect_stats *stats)
1022 {
1023     reconnect_get_stats(s->reconnect, time_msec(), stats);
1024 }
1025
1026 void
1027 jsonrpc_session_force_reconnect(struct jsonrpc_session *s)
1028 {
1029     reconnect_force_reconnect(s->reconnect, time_msec());
1030 }
1031
1032 void
1033 jsonrpc_session_set_max_backoff(struct jsonrpc_session *s, int max_backoff)
1034 {
1035     reconnect_set_backoff(s->reconnect, 0, max_backoff);
1036 }
1037
1038 void
1039 jsonrpc_session_set_probe_interval(struct jsonrpc_session *s,
1040                                    int probe_interval)
1041 {
1042     reconnect_set_probe_interval(s->reconnect, probe_interval);
1043 }