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