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