f15adcaa1323bf68a6584e4ed1f01dc92f02f524
[cascardo/ovs.git] / lib / jsonrpc.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 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 "openvswitch/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
48     /* Output. */
49     struct ovs_list output;     /* Contains "struct ofpbuf"s. */
50     size_t output_count;        /* Number of elements in "output". */
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 struct jsonrpc_msg *jsonrpc_parse_received_message(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 port 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_port(name, OVSDB_OLD_PORT,
67                                          streamp, dscp);
68 }
69
70 /* This is just the same as pstream_open() except that it uses the default
71  * JSONRPC port 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_port(name, OVSDB_OLD_PORT,
76                                           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     ovs_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, rpc->input_buffer, sizeof rpc->input_buffer);
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, ofpbuf_data(buf), ofpbuf_size(buf));
123         if (retval >= 0) {
124             rpc->backlog -= retval;
125             ofpbuf_pull(buf, retval);
126             if (!ofpbuf_size(buf)) {
127                 list_remove(&buf->list_node);
128                 rpc->output_count--;
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     ofpbuf_set_size(buf, length);
261     list_push_back(&rpc->output, &buf->list_node);
262     rpc->output_count++;
263     rpc->backlog += length;
264
265     if (rpc->output_count >= 50) {
266         VLOG_INFO_RL(&rl, "excessive sending backlog, jsonrpc: %s, num of"
267                      " msgs: %"PRIuSIZE", backlog: %"PRIuSIZE".", rpc->name,
268                      rpc->output_count, rpc->backlog);
269     }
270
271     if (rpc->backlog == length) {
272         jsonrpc_run(rpc);
273     }
274     return rpc->status;
275 }
276
277 /* Attempts to receive a message from 'rpc'.
278  *
279  * If successful, stores the received message in '*msgp' and returns 0.  The
280  * caller takes ownership of '*msgp' and must eventually destroy it with
281  * jsonrpc_msg_destroy().
282  *
283  * Otherwise, stores NULL in '*msgp' and returns one of the following:
284  *
285  *   - EAGAIN: No message has been received.
286  *
287  *   - EOF: The remote end closed the connection gracefully.
288  *
289  *   - Otherwise an errno value that represents a JSON-RPC protocol violation
290  *     or another error fatal to the connection.  'rpc' will not send or
291  *     receive any more messages.
292  */
293 int
294 jsonrpc_recv(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
295 {
296     int i;
297
298     *msgp = NULL;
299     if (rpc->status) {
300         return rpc->status;
301     }
302
303     for (i = 0; i < 50; i++) {
304         size_t n, used;
305
306         /* Fill our input buffer if it's empty. */
307         if (byteq_is_empty(&rpc->input)) {
308             size_t chunk;
309             int retval;
310
311             chunk = byteq_headroom(&rpc->input);
312             retval = stream_recv(rpc->stream, byteq_head(&rpc->input), chunk);
313             if (retval < 0) {
314                 if (retval == -EAGAIN) {
315                     return EAGAIN;
316                 } else {
317                     VLOG_WARN_RL(&rl, "%s: receive error: %s",
318                                  rpc->name, ovs_strerror(-retval));
319                     jsonrpc_error(rpc, -retval);
320                     return rpc->status;
321                 }
322             } else if (retval == 0) {
323                 jsonrpc_error(rpc, EOF);
324                 return EOF;
325             }
326             byteq_advance_head(&rpc->input, retval);
327         }
328
329         /* We have some input.  Feed it into the JSON parser. */
330         if (!rpc->parser) {
331             rpc->parser = json_parser_create(0);
332         }
333         n = byteq_tailroom(&rpc->input);
334         used = json_parser_feed(rpc->parser,
335                                 (char *) byteq_tail(&rpc->input), n);
336         byteq_advance_tail(&rpc->input, used);
337
338         /* If we have complete JSON, attempt to parse it as JSON-RPC. */
339         if (json_parser_is_done(rpc->parser)) {
340             *msgp = jsonrpc_parse_received_message(rpc);
341             if (*msgp) {
342                 return 0;
343             }
344
345             if (rpc->status) {
346                 const struct byteq *q = &rpc->input;
347                 if (q->head <= q->size) {
348                     stream_report_content(q->buffer, q->head, STREAM_JSONRPC,
349                                           THIS_MODULE, rpc->name);
350                 }
351                 return rpc->status;
352             }
353         }
354     }
355
356     return EAGAIN;
357 }
358
359 /* Causes the poll loop to wake up when jsonrpc_recv() may return a value other
360  * than EAGAIN. */
361 void
362 jsonrpc_recv_wait(struct jsonrpc *rpc)
363 {
364     if (rpc->status || !byteq_is_empty(&rpc->input)) {
365         poll_immediate_wake_at(rpc->name);
366     } else {
367         stream_recv_wait(rpc->stream);
368     }
369 }
370
371 /* Sends 'msg' on 'rpc' and waits for it to be successfully queued to the
372  * underlying stream.  Returns 0 if 'msg' was sent successfully, otherwise a
373  * status value (see jsonrpc_get_status()).
374  *
375  * Always takes ownership of 'msg', regardless of success. */
376 int
377 jsonrpc_send_block(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
378 {
379     int error;
380
381     fatal_signal_run();
382
383     error = jsonrpc_send(rpc, msg);
384     if (error) {
385         return error;
386     }
387
388     for (;;) {
389         jsonrpc_run(rpc);
390         if (list_is_empty(&rpc->output) || rpc->status) {
391             return rpc->status;
392         }
393         jsonrpc_wait(rpc);
394         poll_block();
395     }
396 }
397
398 /* Waits for a message to be received on 'rpc'.  Same semantics as
399  * jsonrpc_recv() except that EAGAIN will never be returned. */
400 int
401 jsonrpc_recv_block(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
402 {
403     for (;;) {
404         int error = jsonrpc_recv(rpc, msgp);
405         if (error != EAGAIN) {
406             fatal_signal_run();
407             return error;
408         }
409
410         jsonrpc_run(rpc);
411         jsonrpc_wait(rpc);
412         jsonrpc_recv_wait(rpc);
413         poll_block();
414     }
415 }
416
417 /* Sends 'request' to 'rpc' then waits for a reply.  The return value is 0 if
418  * successful, in which case '*replyp' is set to the reply, which the caller
419  * must eventually free with jsonrpc_msg_destroy().  Otherwise returns a status
420  * value (see jsonrpc_get_status()).
421  *
422  * Discards any message received on 'rpc' that is not a reply to 'request'
423  * (based on message id).
424  *
425  * Always takes ownership of 'request', regardless of success. */
426 int
427 jsonrpc_transact_block(struct jsonrpc *rpc, struct jsonrpc_msg *request,
428                        struct jsonrpc_msg **replyp)
429 {
430     struct jsonrpc_msg *reply = NULL;
431     struct json *id;
432     int error;
433
434     id = json_clone(request->id);
435     error = jsonrpc_send_block(rpc, request);
436     if (!error) {
437         for (;;) {
438             error = jsonrpc_recv_block(rpc, &reply);
439             if (error) {
440                 break;
441             }
442             if ((reply->type == JSONRPC_REPLY || reply->type == JSONRPC_ERROR)
443                 && json_equal(id, reply->id)) {
444                 break;
445             }
446             jsonrpc_msg_destroy(reply);
447         }
448     }
449     *replyp = error ? NULL : reply;
450     json_destroy(id);
451     return error;
452 }
453
454 /* Attempts to parse the content of 'rpc->parser' (which is complete JSON) as a
455  * JSON-RPC message.  If successful, returns the JSON-RPC message.  On failure,
456  * signals an error on 'rpc' with jsonrpc_error() and returns NULL. */
457 static struct jsonrpc_msg *
458 jsonrpc_parse_received_message(struct jsonrpc *rpc)
459 {
460     struct jsonrpc_msg *msg;
461     struct json *json;
462     char *error;
463
464     json = json_parser_finish(rpc->parser);
465     rpc->parser = NULL;
466     if (json->type == JSON_STRING) {
467         VLOG_WARN_RL(&rl, "%s: error parsing stream: %s",
468                      rpc->name, json_string(json));
469         jsonrpc_error(rpc, EPROTO);
470         json_destroy(json);
471         return NULL;
472     }
473
474     error = jsonrpc_msg_from_json(json, &msg);
475     if (error) {
476         VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
477                      rpc->name, error);
478         free(error);
479         jsonrpc_error(rpc, EPROTO);
480         return NULL;
481     }
482
483     jsonrpc_log_msg(rpc, "received", msg);
484     return msg;
485 }
486
487 static void
488 jsonrpc_error(struct jsonrpc *rpc, int error)
489 {
490     ovs_assert(error);
491     if (!rpc->status) {
492         rpc->status = error;
493         jsonrpc_cleanup(rpc);
494     }
495 }
496
497 static void
498 jsonrpc_cleanup(struct jsonrpc *rpc)
499 {
500     stream_close(rpc->stream);
501     rpc->stream = NULL;
502
503     json_parser_abort(rpc->parser);
504     rpc->parser = NULL;
505
506     ofpbuf_list_delete(&rpc->output);
507     rpc->backlog = 0;
508     rpc->output_count = 0;
509 }
510 \f
511 static struct jsonrpc_msg *
512 jsonrpc_create(enum jsonrpc_msg_type type, const char *method,
513                 struct json *params, struct json *result, struct json *error,
514                 struct json *id)
515 {
516     struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
517     msg->type = type;
518     msg->method = method ? xstrdup(method) : NULL;
519     msg->params = params;
520     msg->result = result;
521     msg->error = error;
522     msg->id = id;
523     return msg;
524 }
525
526 static struct json *
527 jsonrpc_create_id(void)
528 {
529     static atomic_count next_id = ATOMIC_COUNT_INIT(0);
530     unsigned int id;
531
532     id = atomic_count_inc(&next_id);
533     return json_integer_create(id);
534 }
535
536 struct jsonrpc_msg *
537 jsonrpc_create_request(const char *method, struct json *params,
538                        struct json **idp)
539 {
540     struct json *id = jsonrpc_create_id();
541     if (idp) {
542         *idp = json_clone(id);
543     }
544     return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL, id);
545 }
546
547 struct jsonrpc_msg *
548 jsonrpc_create_notify(const char *method, struct json *params)
549 {
550     return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
551 }
552
553 struct jsonrpc_msg *
554 jsonrpc_create_reply(struct json *result, const struct json *id)
555 {
556     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
557                            json_clone(id));
558 }
559
560 struct jsonrpc_msg *
561 jsonrpc_create_error(struct json *error, const struct json *id)
562 {
563     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
564                            json_clone(id));
565 }
566
567 const char *
568 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
569 {
570     switch (type) {
571     case JSONRPC_REQUEST:
572         return "request";
573
574     case JSONRPC_NOTIFY:
575         return "notification";
576
577     case JSONRPC_REPLY:
578         return "reply";
579
580     case JSONRPC_ERROR:
581         return "error";
582     }
583     return "(null)";
584 }
585
586 char *
587 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
588 {
589     const char *type_name;
590     unsigned int pattern;
591
592     if (m->params && m->params->type != JSON_ARRAY) {
593         return xstrdup("\"params\" must be JSON array");
594     }
595
596     switch (m->type) {
597     case JSONRPC_REQUEST:
598         pattern = 0x11001;
599         break;
600
601     case JSONRPC_NOTIFY:
602         pattern = 0x11000;
603         break;
604
605     case JSONRPC_REPLY:
606         pattern = 0x00101;
607         break;
608
609     case JSONRPC_ERROR:
610         pattern = 0x00011;
611         break;
612
613     default:
614         return xasprintf("invalid JSON-RPC message type %d", m->type);
615     }
616
617     type_name = jsonrpc_msg_type_to_string(m->type);
618     if ((m->method != NULL) != ((pattern & 0x10000) != 0)) {
619         return xasprintf("%s must%s have \"method\"",
620                          type_name, (pattern & 0x10000) ? "" : " not");
621
622     }
623     if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
624         return xasprintf("%s must%s have \"params\"",
625                          type_name, (pattern & 0x1000) ? "" : " not");
626
627     }
628     if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
629         return xasprintf("%s must%s have \"result\"",
630                          type_name, (pattern & 0x100) ? "" : " not");
631
632     }
633     if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
634         return xasprintf("%s must%s have \"error\"",
635                          type_name, (pattern & 0x10) ? "" : " not");
636
637     }
638     if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
639         return xasprintf("%s must%s have \"id\"",
640                          type_name, (pattern & 0x1) ? "" : " not");
641
642     }
643     return NULL;
644 }
645
646 void
647 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
648 {
649     if (m) {
650         free(m->method);
651         json_destroy(m->params);
652         json_destroy(m->result);
653         json_destroy(m->error);
654         json_destroy(m->id);
655         free(m);
656     }
657 }
658
659 static struct json *
660 null_from_json_null(struct json *json)
661 {
662     if (json && json->type == JSON_NULL) {
663         json_destroy(json);
664         return NULL;
665     }
666     return json;
667 }
668
669 char *
670 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
671 {
672     struct json *method = NULL;
673     struct jsonrpc_msg *msg = NULL;
674     struct shash *object;
675     char *error;
676
677     if (json->type != JSON_OBJECT) {
678         error = xstrdup("message is not a JSON object");
679         goto exit;
680     }
681     object = json_object(json);
682
683     method = shash_find_and_delete(object, "method");
684     if (method && method->type != JSON_STRING) {
685         error = xstrdup("method is not a JSON string");
686         goto exit;
687     }
688
689     msg = xzalloc(sizeof *msg);
690     msg->method = method ? xstrdup(method->u.string) : NULL;
691     msg->params = null_from_json_null(shash_find_and_delete(object, "params"));
692     msg->result = null_from_json_null(shash_find_and_delete(object, "result"));
693     msg->error = null_from_json_null(shash_find_and_delete(object, "error"));
694     msg->id = null_from_json_null(shash_find_and_delete(object, "id"));
695     msg->type = (msg->result ? JSONRPC_REPLY
696                  : msg->error ? JSONRPC_ERROR
697                  : msg->id ? JSONRPC_REQUEST
698                  : JSONRPC_NOTIFY);
699     if (!shash_is_empty(object)) {
700         error = xasprintf("message has unexpected member \"%s\"",
701                           shash_first(object)->name);
702         goto exit;
703     }
704     error = jsonrpc_msg_is_valid(msg);
705     if (error) {
706         goto exit;
707     }
708
709 exit:
710     json_destroy(method);
711     json_destroy(json);
712     if (error) {
713         jsonrpc_msg_destroy(msg);
714         msg = NULL;
715     }
716     *msgp = msg;
717     return error;
718 }
719
720 struct json *
721 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
722 {
723     struct json *json = json_object_create();
724
725     if (m->method) {
726         json_object_put(json, "method", json_string_create_nocopy(m->method));
727     }
728
729     if (m->params) {
730         json_object_put(json, "params", m->params);
731     }
732
733     if (m->result) {
734         json_object_put(json, "result", m->result);
735     } else if (m->type == JSONRPC_ERROR) {
736         json_object_put(json, "result", json_null_create());
737     }
738
739     if (m->error) {
740         json_object_put(json, "error", m->error);
741     } else if (m->type == JSONRPC_REPLY) {
742         json_object_put(json, "error", json_null_create());
743     }
744
745     if (m->id) {
746         json_object_put(json, "id", m->id);
747     } else if (m->type == JSONRPC_NOTIFY) {
748         json_object_put(json, "id", json_null_create());
749     }
750
751     free(m);
752
753     return json;
754 }
755 \f
756 /* A JSON-RPC session with reconnection. */
757
758 struct jsonrpc_session {
759     struct reconnect *reconnect;
760     struct jsonrpc *rpc;
761     struct stream *stream;
762     struct pstream *pstream;
763     int last_error;
764     unsigned int seqno;
765     uint8_t dscp;
766 };
767
768 /* Creates and returns a jsonrpc_session to 'name', which should be a string
769  * acceptable to stream_open() or pstream_open().
770  *
771  * If 'name' is an active connection method, e.g. "tcp:127.1.2.3", the new
772  * jsonrpc_session connects to 'name'.  If 'retry' is true, then the new
773  * session connects and reconnects to 'name', with backoff.  If 'retry' is
774  * false, the new session will only try to connect once and after a connection
775  * failure or a disconnection jsonrpc_session_is_alive() will return false for
776  * the new session.
777  *
778  * If 'name' is a passive connection method, e.g. "ptcp:", the new
779  * jsonrpc_session listens for connections to 'name'.  It maintains at most one
780  * connection at any given time.  Any new connection causes the previous one
781  * (if any) to be dropped. */
782 struct jsonrpc_session *
783 jsonrpc_session_open(const char *name, bool retry)
784 {
785     struct jsonrpc_session *s;
786
787     s = xmalloc(sizeof *s);
788     s->reconnect = reconnect_create(time_msec());
789     reconnect_set_name(s->reconnect, name);
790     reconnect_enable(s->reconnect, time_msec());
791     s->rpc = NULL;
792     s->stream = NULL;
793     s->pstream = NULL;
794     s->seqno = 0;
795     s->dscp = 0;
796     s->last_error = 0;
797
798     if (!pstream_verify_name(name)) {
799         reconnect_set_passive(s->reconnect, true, time_msec());
800     } else if (!retry) {
801         reconnect_set_max_tries(s->reconnect, 1);
802         reconnect_set_backoff(s->reconnect, INT_MAX, INT_MAX);
803     }
804
805     if (!stream_or_pstream_needs_probes(name)) {
806         reconnect_set_probe_interval(s->reconnect, 0);
807     }
808
809     return s;
810 }
811
812 /* Creates and returns a jsonrpc_session that is initially connected to
813  * 'jsonrpc'.  If the connection is dropped, it will not be reconnected.
814  *
815  * On the assumption that such connections are likely to be short-lived
816  * (e.g. from ovs-vsctl), informational logging for them is suppressed. */
817 struct jsonrpc_session *
818 jsonrpc_session_open_unreliably(struct jsonrpc *jsonrpc, uint8_t dscp)
819 {
820     struct jsonrpc_session *s;
821
822     s = xmalloc(sizeof *s);
823     s->reconnect = reconnect_create(time_msec());
824     reconnect_set_quiet(s->reconnect, true);
825     reconnect_set_name(s->reconnect, jsonrpc_get_name(jsonrpc));
826     reconnect_set_max_tries(s->reconnect, 0);
827     reconnect_connected(s->reconnect, time_msec());
828     s->dscp = dscp;
829     s->rpc = jsonrpc;
830     s->stream = NULL;
831     s->pstream = NULL;
832     s->seqno = 0;
833
834     return s;
835 }
836
837 void
838 jsonrpc_session_close(struct jsonrpc_session *s)
839 {
840     if (s) {
841         jsonrpc_close(s->rpc);
842         reconnect_destroy(s->reconnect);
843         stream_close(s->stream);
844         pstream_close(s->pstream);
845         free(s);
846     }
847 }
848
849 static void
850 jsonrpc_session_disconnect(struct jsonrpc_session *s)
851 {
852     if (s->rpc) {
853         jsonrpc_error(s->rpc, EOF);
854         jsonrpc_close(s->rpc);
855         s->rpc = NULL;
856         s->seqno++;
857     } else if (s->stream) {
858         stream_close(s->stream);
859         s->stream = NULL;
860         s->seqno++;
861     }
862 }
863
864 static void
865 jsonrpc_session_connect(struct jsonrpc_session *s)
866 {
867     const char *name = reconnect_get_name(s->reconnect);
868     int error;
869
870     jsonrpc_session_disconnect(s);
871     if (!reconnect_is_passive(s->reconnect)) {
872         error = jsonrpc_stream_open(name, &s->stream, s->dscp);
873         if (!error) {
874             reconnect_connecting(s->reconnect, time_msec());
875         } else {
876             s->last_error = error;
877         }
878     } else {
879         error = s->pstream ? 0 : jsonrpc_pstream_open(name, &s->pstream,
880                                                       s->dscp);
881         if (!error) {
882             reconnect_listening(s->reconnect, time_msec());
883         }
884     }
885
886     if (error) {
887         reconnect_connect_failed(s->reconnect, time_msec(), error);
888     }
889     s->seqno++;
890 }
891
892 void
893 jsonrpc_session_run(struct jsonrpc_session *s)
894 {
895     if (s->pstream) {
896         struct stream *stream;
897         int error;
898
899         error = pstream_accept(s->pstream, &stream);
900         if (!error) {
901             if (s->rpc || s->stream) {
902                 VLOG_INFO_RL(&rl,
903                              "%s: new connection replacing active connection",
904                              reconnect_get_name(s->reconnect));
905                 jsonrpc_session_disconnect(s);
906             }
907             reconnect_connected(s->reconnect, time_msec());
908             s->rpc = jsonrpc_open(stream);
909         } else if (error != EAGAIN) {
910             reconnect_listen_error(s->reconnect, time_msec(), error);
911             pstream_close(s->pstream);
912             s->pstream = NULL;
913         }
914     }
915
916     if (s->rpc) {
917         size_t backlog;
918         int error;
919
920         backlog = jsonrpc_get_backlog(s->rpc);
921         jsonrpc_run(s->rpc);
922         if (jsonrpc_get_backlog(s->rpc) < backlog) {
923             /* Data previously caught in a queue was successfully sent (or
924              * there's an error, which we'll catch below.)
925              *
926              * We don't count data that is successfully sent immediately as
927              * activity, because there's a lot of queuing downstream from us,
928              * which means that we can push a lot of data into a connection
929              * that has stalled and won't ever recover.
930              */
931             reconnect_activity(s->reconnect, time_msec());
932         }
933
934         error = jsonrpc_get_status(s->rpc);
935         if (error) {
936             reconnect_disconnected(s->reconnect, time_msec(), error);
937             jsonrpc_session_disconnect(s);
938             s->last_error = error;
939         }
940     } else if (s->stream) {
941         int error;
942
943         stream_run(s->stream);
944         error = stream_connect(s->stream);
945         if (!error) {
946             reconnect_connected(s->reconnect, time_msec());
947             s->rpc = jsonrpc_open(s->stream);
948             s->stream = NULL;
949         } else if (error != EAGAIN) {
950             reconnect_connect_failed(s->reconnect, time_msec(), error);
951             stream_close(s->stream);
952             s->stream = NULL;
953         }
954     }
955
956     switch (reconnect_run(s->reconnect, time_msec())) {
957     case RECONNECT_CONNECT:
958         jsonrpc_session_connect(s);
959         break;
960
961     case RECONNECT_DISCONNECT:
962         reconnect_disconnected(s->reconnect, time_msec(), 0);
963         jsonrpc_session_disconnect(s);
964         break;
965
966     case RECONNECT_PROBE:
967         if (s->rpc) {
968             struct json *params;
969             struct jsonrpc_msg *request;
970
971             params = json_array_create_empty();
972             request = jsonrpc_create_request("echo", params, NULL);
973             json_destroy(request->id);
974             request->id = json_string_create("echo");
975             jsonrpc_send(s->rpc, request);
976         }
977         break;
978     }
979 }
980
981 void
982 jsonrpc_session_wait(struct jsonrpc_session *s)
983 {
984     if (s->rpc) {
985         jsonrpc_wait(s->rpc);
986     } else if (s->stream) {
987         stream_run_wait(s->stream);
988         stream_connect_wait(s->stream);
989     }
990     if (s->pstream) {
991         pstream_wait(s->pstream);
992     }
993     reconnect_wait(s->reconnect, time_msec());
994 }
995
996 size_t
997 jsonrpc_session_get_backlog(const struct jsonrpc_session *s)
998 {
999     return s->rpc ? jsonrpc_get_backlog(s->rpc) : 0;
1000 }
1001
1002 /* Always returns a pointer to a valid C string, assuming 's' was initialized
1003  * correctly. */
1004 const char *
1005 jsonrpc_session_get_name(const struct jsonrpc_session *s)
1006 {
1007     return reconnect_get_name(s->reconnect);
1008 }
1009
1010 /* Always takes ownership of 'msg', regardless of success. */
1011 int
1012 jsonrpc_session_send(struct jsonrpc_session *s, struct jsonrpc_msg *msg)
1013 {
1014     if (s->rpc) {
1015         return jsonrpc_send(s->rpc, msg);
1016     } else {
1017         jsonrpc_msg_destroy(msg);
1018         return ENOTCONN;
1019     }
1020 }
1021
1022 struct jsonrpc_msg *
1023 jsonrpc_session_recv(struct jsonrpc_session *s)
1024 {
1025     if (s->rpc) {
1026         unsigned int received_bytes;
1027         struct jsonrpc_msg *msg;
1028
1029         received_bytes = jsonrpc_get_received_bytes(s->rpc);
1030         jsonrpc_recv(s->rpc, &msg);
1031         if (received_bytes != jsonrpc_get_received_bytes(s->rpc)) {
1032             /* Data was successfully received.
1033              *
1034              * Previously we only counted receiving a full message as activity,
1035              * but with large messages or a slow connection that policy could
1036              * time out the session mid-message. */
1037             reconnect_activity(s->reconnect, time_msec());
1038         }
1039
1040         if (msg) {
1041             if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
1042                 /* Echo request.  Send reply. */
1043                 struct jsonrpc_msg *reply;
1044
1045                 reply = jsonrpc_create_reply(json_clone(msg->params), msg->id);
1046                 jsonrpc_session_send(s, reply);
1047             } else if (msg->type == JSONRPC_REPLY
1048                        && msg->id && msg->id->type == JSON_STRING
1049                        && !strcmp(msg->id->u.string, "echo")) {
1050                 /* It's a reply to our echo request.  Suppress it. */
1051             } else {
1052                 return msg;
1053             }
1054             jsonrpc_msg_destroy(msg);
1055         }
1056     }
1057     return NULL;
1058 }
1059
1060 void
1061 jsonrpc_session_recv_wait(struct jsonrpc_session *s)
1062 {
1063     if (s->rpc) {
1064         jsonrpc_recv_wait(s->rpc);
1065     }
1066 }
1067
1068 bool
1069 jsonrpc_session_is_alive(const struct jsonrpc_session *s)
1070 {
1071     return s->rpc || s->stream || reconnect_get_max_tries(s->reconnect);
1072 }
1073
1074 bool
1075 jsonrpc_session_is_connected(const struct jsonrpc_session *s)
1076 {
1077     return s->rpc != NULL;
1078 }
1079
1080 unsigned int
1081 jsonrpc_session_get_seqno(const struct jsonrpc_session *s)
1082 {
1083     return s->seqno;
1084 }
1085
1086 int
1087 jsonrpc_session_get_status(const struct jsonrpc_session *s)
1088 {
1089     return s && s->rpc ? jsonrpc_get_status(s->rpc) : 0;
1090 }
1091
1092 int
1093 jsonrpc_session_get_last_error(const struct jsonrpc_session *s)
1094 {
1095     return s->last_error;
1096 }
1097
1098 void
1099 jsonrpc_session_get_reconnect_stats(const struct jsonrpc_session *s,
1100                                     struct reconnect_stats *stats)
1101 {
1102     reconnect_get_stats(s->reconnect, time_msec(), stats);
1103 }
1104
1105 void
1106 jsonrpc_session_enable_reconnect(struct jsonrpc_session *s)
1107 {
1108     reconnect_set_max_tries(s->reconnect, UINT_MAX);
1109     reconnect_set_backoff(s->reconnect, RECONNECT_DEFAULT_MIN_BACKOFF,
1110                           RECONNECT_DEFAULT_MAX_BACKOFF);
1111 }
1112
1113 void
1114 jsonrpc_session_force_reconnect(struct jsonrpc_session *s)
1115 {
1116     reconnect_force_reconnect(s->reconnect, time_msec());
1117 }
1118
1119 void
1120 jsonrpc_session_set_max_backoff(struct jsonrpc_session *s, int max_backoff)
1121 {
1122     reconnect_set_backoff(s->reconnect, 0, max_backoff);
1123 }
1124
1125 void
1126 jsonrpc_session_set_probe_interval(struct jsonrpc_session *s,
1127                                    int probe_interval)
1128 {
1129     reconnect_set_probe_interval(s->reconnect, probe_interval);
1130 }
1131
1132 void
1133 jsonrpc_session_set_dscp(struct jsonrpc_session *s,
1134                          uint8_t dscp)
1135 {
1136     if (s->dscp != dscp) {
1137         if (s->pstream) {
1138             int error;
1139
1140             error = pstream_set_dscp(s->pstream, dscp);
1141             if (error) {
1142                 VLOG_ERR("%s: failed set_dscp %s",
1143                          reconnect_get_name(s->reconnect),
1144                          ovs_strerror(error));
1145             }
1146             /*
1147              * XXX race window between setting dscp to listening socket
1148              * and accepting socket. accepted socket may have old dscp value.
1149              * Ignore this race window for now.
1150              */
1151         }
1152         s->dscp = dscp;
1153         jsonrpc_session_force_reconnect(s);
1154     }
1155 }