2 * Copyright (c) 2009-2017 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 #include "openvswitch/dynamic-string.h"
25 #include "fatal-signal.h"
26 #include "openvswitch/json.h"
27 #include "openvswitch/list.h"
28 #include "openvswitch/ofpbuf.h"
29 #include "ovs-thread.h"
30 #include "openvswitch/poll-loop.h"
31 #include "reconnect.h"
35 #include "openvswitch/vlog.h"
37 VLOG_DEFINE_THIS_MODULE(jsonrpc
);
40 struct stream
*stream
;
46 uint8_t input_buffer
[512];
47 struct json_parser
*parser
;
50 struct ovs_list output
; /* Contains "struct ofpbuf"s. */
51 size_t output_count
; /* Number of elements in "output". */
55 /* Rate limit for error messages. */
56 static struct vlog_rate_limit rl
= VLOG_RATE_LIMIT_INIT(5, 5);
58 static struct jsonrpc_msg
*jsonrpc_parse_received_message(struct jsonrpc
*);
59 static void jsonrpc_cleanup(struct jsonrpc
*);
60 static void jsonrpc_error(struct jsonrpc
*, int error
);
62 /* This is just the same as stream_open() except that it uses the default
63 * JSONRPC port if none is specified. */
65 jsonrpc_stream_open(const char *name
, struct stream
**streamp
, uint8_t dscp
)
67 return stream_open_with_default_port(name
, OVSDB_PORT
, streamp
, dscp
);
70 /* This is just the same as pstream_open() except that it uses the default
71 * JSONRPC port if none is specified. */
73 jsonrpc_pstream_open(const char *name
, struct pstream
**pstreamp
, uint8_t dscp
)
75 return pstream_open_with_default_port(name
, OVSDB_PORT
, pstreamp
, dscp
);
78 /* Returns a new JSON-RPC stream that uses 'stream' for input and output. The
79 * new jsonrpc object takes ownership of 'stream'. */
81 jsonrpc_open(struct stream
*stream
)
85 ovs_assert(stream
!= NULL
);
87 rpc
= xzalloc(sizeof *rpc
);
88 rpc
->name
= xstrdup(stream_get_name(stream
));
90 byteq_init(&rpc
->input
, rpc
->input_buffer
, sizeof rpc
->input_buffer
);
91 ovs_list_init(&rpc
->output
);
96 /* Destroys 'rpc', closing the stream on which it is based, and frees its
99 jsonrpc_close(struct jsonrpc
*rpc
)
102 jsonrpc_cleanup(rpc
);
108 /* Performs periodic maintenance on 'rpc', such as flushing output buffers. */
110 jsonrpc_run(struct jsonrpc
*rpc
)
116 stream_run(rpc
->stream
);
117 while (!ovs_list_is_empty(&rpc
->output
)) {
118 struct ofpbuf
*buf
= ofpbuf_from_list(rpc
->output
.next
);
121 retval
= stream_send(rpc
->stream
, buf
->data
, buf
->size
);
123 rpc
->backlog
-= retval
;
124 ofpbuf_pull(buf
, retval
);
126 ovs_list_remove(&buf
->list_node
);
131 if (retval
!= -EAGAIN
) {
132 VLOG_WARN_RL(&rl
, "%s: send error: %s",
133 rpc
->name
, ovs_strerror(-retval
));
134 jsonrpc_error(rpc
, -retval
);
141 /* Arranges for the poll loop to wake up when 'rpc' needs to perform
142 * maintenance activities. */
144 jsonrpc_wait(struct jsonrpc
*rpc
)
147 stream_run_wait(rpc
->stream
);
148 if (!ovs_list_is_empty(&rpc
->output
)) {
149 stream_send_wait(rpc
->stream
);
155 * Returns the current status of 'rpc'. The possible return values are:
158 * - EOF: end of file (remote end closed connection; not necessarily an error).
160 * When this function returns nonzero, 'rpc' is effectively out of
161 * commission. 'rpc' will not receive any more messages and any further
162 * messages that one attempts to send with 'rpc' will be discarded. The
163 * caller can keep 'rpc' around as long as it wants, but it's not going
164 * to provide any more useful services.
167 jsonrpc_get_status(const struct jsonrpc
*rpc
)
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. */
176 jsonrpc_get_backlog(const struct jsonrpc
*rpc
)
178 return rpc
->status
? 0 : rpc
->backlog
;
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.) */
184 jsonrpc_get_received_bytes(const struct jsonrpc
*rpc
)
186 return rpc
->input
.head
;
189 /* Returns 'rpc''s name, that is, the name returned by stream_get_name() for
190 * the stream underlying 'rpc' when 'rpc' was created. */
192 jsonrpc_get_name(const struct jsonrpc
*rpc
)
198 jsonrpc_log_msg(const struct jsonrpc
*rpc
, const char *title
,
199 const struct jsonrpc_msg
*msg
)
201 if (VLOG_IS_DBG_ENABLED()) {
202 struct ds s
= DS_EMPTY_INITIALIZER
;
204 ds_put_format(&s
, ", method=\"%s\"", msg
->method
);
207 ds_put_cstr(&s
, ", params=");
208 json_to_ds(msg
->params
, 0, &s
);
211 ds_put_cstr(&s
, ", result=");
212 json_to_ds(msg
->result
, 0, &s
);
215 ds_put_cstr(&s
, ", error=");
216 json_to_ds(msg
->error
, 0, &s
);
219 ds_put_cstr(&s
, ", id=");
220 json_to_ds(msg
->id
, 0, &s
);
222 VLOG_DBG("%s: %s %s%s", rpc
->name
, title
,
223 jsonrpc_msg_type_to_string(msg
->type
), ds_cstr(&s
));
228 /* Schedules 'msg' to be sent on 'rpc' and returns 'rpc''s status (as with
229 * jsonrpc_get_status()).
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'.)
236 * Always takes ownership of 'msg', regardless of success. */
238 jsonrpc_send(struct jsonrpc
*rpc
, struct jsonrpc_msg
*msg
)
242 struct ds ds
= DS_EMPTY_INITIALIZER
;
246 jsonrpc_msg_destroy(msg
);
250 jsonrpc_log_msg(rpc
, "send", msg
);
252 json
= jsonrpc_msg_to_json(msg
);
253 json_to_ds(json
, 0, &ds
);
257 buf
= xmalloc(sizeof *buf
);
258 ofpbuf_use_ds(buf
, &ds
);
259 ovs_list_push_back(&rpc
->output
, &buf
->list_node
);
261 rpc
->backlog
+= length
;
263 if (rpc
->output_count
>= 50) {
264 VLOG_INFO_RL(&rl
, "excessive sending backlog, jsonrpc: %s, num of"
265 " msgs: %"PRIuSIZE
", backlog: %"PRIuSIZE
".", rpc
->name
,
266 rpc
->output_count
, rpc
->backlog
);
269 if (rpc
->backlog
== length
) {
275 /* Attempts to receive a message from 'rpc'.
277 * If successful, stores the received message in '*msgp' and returns 0. The
278 * caller takes ownership of '*msgp' and must eventually destroy it with
279 * jsonrpc_msg_destroy().
281 * Otherwise, stores NULL in '*msgp' and returns one of the following:
283 * - EAGAIN: No message has been received.
285 * - EOF: The remote end closed the connection gracefully.
287 * - Otherwise an errno value that represents a JSON-RPC protocol violation
288 * or another error fatal to the connection. 'rpc' will not send or
289 * receive any more messages.
292 jsonrpc_recv(struct jsonrpc
*rpc
, struct jsonrpc_msg
**msgp
)
301 for (i
= 0; i
< 50; i
++) {
304 /* Fill our input buffer if it's empty. */
305 if (byteq_is_empty(&rpc
->input
)) {
309 chunk
= byteq_headroom(&rpc
->input
);
310 retval
= stream_recv(rpc
->stream
, byteq_head(&rpc
->input
), chunk
);
312 if (retval
== -EAGAIN
) {
315 VLOG_WARN_RL(&rl
, "%s: receive error: %s",
316 rpc
->name
, ovs_strerror(-retval
));
317 jsonrpc_error(rpc
, -retval
);
320 } else if (retval
== 0) {
321 jsonrpc_error(rpc
, EOF
);
324 byteq_advance_head(&rpc
->input
, retval
);
327 /* We have some input. Feed it into the JSON parser. */
329 rpc
->parser
= json_parser_create(0);
331 n
= byteq_tailroom(&rpc
->input
);
332 used
= json_parser_feed(rpc
->parser
,
333 (char *) byteq_tail(&rpc
->input
), n
);
334 byteq_advance_tail(&rpc
->input
, used
);
336 /* If we have complete JSON, attempt to parse it as JSON-RPC. */
337 if (json_parser_is_done(rpc
->parser
)) {
338 *msgp
= jsonrpc_parse_received_message(rpc
);
344 const struct byteq
*q
= &rpc
->input
;
345 if (q
->head
<= q
->size
) {
346 stream_report_content(q
->buffer
, q
->head
, STREAM_JSONRPC
,
347 &this_module
, rpc
->name
);
357 /* Causes the poll loop to wake up when jsonrpc_recv() may return a value other
360 jsonrpc_recv_wait(struct jsonrpc
*rpc
)
362 if (rpc
->status
|| !byteq_is_empty(&rpc
->input
)) {
363 poll_immediate_wake_at(rpc
->name
);
365 stream_recv_wait(rpc
->stream
);
369 /* Sends 'msg' on 'rpc' and waits for it to be successfully queued to the
370 * underlying stream. Returns 0 if 'msg' was sent successfully, otherwise a
371 * status value (see jsonrpc_get_status()).
373 * Always takes ownership of 'msg', regardless of success. */
375 jsonrpc_send_block(struct jsonrpc
*rpc
, struct jsonrpc_msg
*msg
)
381 error
= jsonrpc_send(rpc
, msg
);
388 if (ovs_list_is_empty(&rpc
->output
) || rpc
->status
) {
396 /* Waits for a message to be received on 'rpc'. Same semantics as
397 * jsonrpc_recv() except that EAGAIN will never be returned. */
399 jsonrpc_recv_block(struct jsonrpc
*rpc
, struct jsonrpc_msg
**msgp
)
402 int error
= jsonrpc_recv(rpc
, msgp
);
403 if (error
!= EAGAIN
) {
410 jsonrpc_recv_wait(rpc
);
415 /* Sends 'request' to 'rpc' then waits for a reply. The return value is 0 if
416 * successful, in which case '*replyp' is set to the reply, which the caller
417 * must eventually free with jsonrpc_msg_destroy(). Otherwise returns a status
418 * value (see jsonrpc_get_status()).
420 * Discards any message received on 'rpc' that is not a reply to 'request'
421 * (based on message id).
423 * Always takes ownership of 'request', regardless of success. */
425 jsonrpc_transact_block(struct jsonrpc
*rpc
, struct jsonrpc_msg
*request
,
426 struct jsonrpc_msg
**replyp
)
428 struct jsonrpc_msg
*reply
= NULL
;
432 id
= json_clone(request
->id
);
433 error
= jsonrpc_send_block(rpc
, request
);
436 error
= jsonrpc_recv_block(rpc
, &reply
);
440 if ((reply
->type
== JSONRPC_REPLY
|| reply
->type
== JSONRPC_ERROR
)
441 && json_equal(id
, reply
->id
)) {
444 jsonrpc_msg_destroy(reply
);
447 *replyp
= error
? NULL
: reply
;
452 /* Attempts to parse the content of 'rpc->parser' (which is complete JSON) as a
453 * JSON-RPC message. If successful, returns the JSON-RPC message. On failure,
454 * signals an error on 'rpc' with jsonrpc_error() and returns NULL. */
455 static struct jsonrpc_msg
*
456 jsonrpc_parse_received_message(struct jsonrpc
*rpc
)
458 struct jsonrpc_msg
*msg
;
462 json
= json_parser_finish(rpc
->parser
);
464 if (json
->type
== JSON_STRING
) {
465 VLOG_WARN_RL(&rl
, "%s: error parsing stream: %s",
466 rpc
->name
, json_string(json
));
467 jsonrpc_error(rpc
, EPROTO
);
472 error
= jsonrpc_msg_from_json(json
, &msg
);
474 VLOG_WARN_RL(&rl
, "%s: received bad JSON-RPC message: %s",
477 jsonrpc_error(rpc
, EPROTO
);
481 jsonrpc_log_msg(rpc
, "received", msg
);
486 jsonrpc_error(struct jsonrpc
*rpc
, int error
)
491 jsonrpc_cleanup(rpc
);
496 jsonrpc_cleanup(struct jsonrpc
*rpc
)
498 stream_close(rpc
->stream
);
501 json_parser_abort(rpc
->parser
);
504 ofpbuf_list_delete(&rpc
->output
);
506 rpc
->output_count
= 0;
509 static struct jsonrpc_msg
*
510 jsonrpc_create(enum jsonrpc_msg_type type
, const char *method
,
511 struct json
*params
, struct json
*result
, struct json
*error
,
514 struct jsonrpc_msg
*msg
= xmalloc(sizeof *msg
);
516 msg
->method
= nullable_xstrdup(method
);
517 msg
->params
= params
;
518 msg
->result
= result
;
525 jsonrpc_create_id(void)
527 static atomic_count next_id
= ATOMIC_COUNT_INIT(0);
530 id
= atomic_count_inc(&next_id
);
531 return json_integer_create(id
);
535 jsonrpc_create_request(const char *method
, struct json
*params
,
538 struct json
*id
= jsonrpc_create_id();
540 *idp
= json_clone(id
);
542 return jsonrpc_create(JSONRPC_REQUEST
, method
, params
, NULL
, NULL
, id
);
546 jsonrpc_create_notify(const char *method
, struct json
*params
)
548 return jsonrpc_create(JSONRPC_NOTIFY
, method
, params
, NULL
, NULL
, NULL
);
552 jsonrpc_create_reply(struct json
*result
, const struct json
*id
)
554 return jsonrpc_create(JSONRPC_REPLY
, NULL
, NULL
, result
, NULL
,
559 jsonrpc_create_error(struct json
*error
, const struct json
*id
)
561 return jsonrpc_create(JSONRPC_REPLY
, NULL
, NULL
, NULL
, error
,
566 jsonrpc_msg_clone(const struct jsonrpc_msg
*old
)
568 return jsonrpc_create(old
->type
, old
->method
,
569 json_nullable_clone(old
->params
),
570 json_nullable_clone(old
->result
),
571 json_nullable_clone(old
->error
),
572 json_nullable_clone(old
->id
));
576 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type
)
579 case JSONRPC_REQUEST
:
583 return "notification";
595 jsonrpc_msg_is_valid(const struct jsonrpc_msg
*m
)
597 const char *type_name
;
598 unsigned int pattern
;
600 if (m
->params
&& m
->params
->type
!= JSON_ARRAY
) {
601 return xstrdup("\"params\" must be JSON array");
605 case JSONRPC_REQUEST
:
622 return xasprintf("invalid JSON-RPC message type %d", m
->type
);
625 type_name
= jsonrpc_msg_type_to_string(m
->type
);
626 if ((m
->method
!= NULL
) != ((pattern
& 0x10000) != 0)) {
627 return xasprintf("%s must%s have \"method\"",
628 type_name
, (pattern
& 0x10000) ? "" : " not");
631 if ((m
->params
!= NULL
) != ((pattern
& 0x1000) != 0)) {
632 return xasprintf("%s must%s have \"params\"",
633 type_name
, (pattern
& 0x1000) ? "" : " not");
636 if ((m
->result
!= NULL
) != ((pattern
& 0x100) != 0)) {
637 return xasprintf("%s must%s have \"result\"",
638 type_name
, (pattern
& 0x100) ? "" : " not");
641 if ((m
->error
!= NULL
) != ((pattern
& 0x10) != 0)) {
642 return xasprintf("%s must%s have \"error\"",
643 type_name
, (pattern
& 0x10) ? "" : " not");
646 if ((m
->id
!= NULL
) != ((pattern
& 0x1) != 0)) {
647 return xasprintf("%s must%s have \"id\"",
648 type_name
, (pattern
& 0x1) ? "" : " not");
655 jsonrpc_msg_destroy(struct jsonrpc_msg
*m
)
659 json_destroy(m
->params
);
660 json_destroy(m
->result
);
661 json_destroy(m
->error
);
668 null_from_json_null(struct json
*json
)
670 if (json
&& json
->type
== JSON_NULL
) {
678 jsonrpc_msg_from_json(struct json
*json
, struct jsonrpc_msg
**msgp
)
680 struct json
*method
= NULL
;
681 struct jsonrpc_msg
*msg
= NULL
;
682 struct shash
*object
;
685 if (json
->type
!= JSON_OBJECT
) {
686 error
= xstrdup("message is not a JSON object");
689 object
= json_object(json
);
691 method
= shash_find_and_delete(object
, "method");
692 if (method
&& method
->type
!= JSON_STRING
) {
693 error
= xstrdup("method is not a JSON string");
697 msg
= xzalloc(sizeof *msg
);
698 msg
->method
= method
? xstrdup(method
->string
) : NULL
;
699 msg
->params
= null_from_json_null(shash_find_and_delete(object
, "params"));
700 msg
->result
= null_from_json_null(shash_find_and_delete(object
, "result"));
701 msg
->error
= null_from_json_null(shash_find_and_delete(object
, "error"));
702 msg
->id
= null_from_json_null(shash_find_and_delete(object
, "id"));
703 msg
->type
= (msg
->result
? JSONRPC_REPLY
704 : msg
->error
? JSONRPC_ERROR
705 : msg
->id
? JSONRPC_REQUEST
707 if (!shash_is_empty(object
)) {
708 error
= xasprintf("message has unexpected member \"%s\"",
709 shash_first(object
)->name
);
712 error
= jsonrpc_msg_is_valid(msg
);
718 json_destroy(method
);
721 jsonrpc_msg_destroy(msg
);
728 /* Returns 'm' converted to JSON suitable for sending as a JSON-RPC message.
730 * Consumes and destroys 'm'. */
732 jsonrpc_msg_to_json(struct jsonrpc_msg
*m
)
734 struct json
*json
= json_object_create();
737 json_object_put(json
, "method", json_string_create_nocopy(m
->method
));
741 json_object_put(json
, "params", m
->params
);
745 json_object_put(json
, "result", m
->result
);
746 } else if (m
->type
== JSONRPC_ERROR
) {
747 json_object_put(json
, "result", json_null_create());
751 json_object_put(json
, "error", m
->error
);
752 } else if (m
->type
== JSONRPC_REPLY
) {
753 json_object_put(json
, "error", json_null_create());
757 json_object_put(json
, "id", m
->id
);
758 } else if (m
->type
== JSONRPC_NOTIFY
) {
759 json_object_put(json
, "id", json_null_create());
768 jsonrpc_msg_to_string(const struct jsonrpc_msg
*m
)
770 struct jsonrpc_msg
*copy
= jsonrpc_msg_clone(m
);
771 struct json
*json
= jsonrpc_msg_to_json(copy
);
772 char *s
= json_to_string(json
, JSSF_SORT
);
777 /* A JSON-RPC session with reconnection. */
779 struct jsonrpc_session
{
783 struct reconnect
*reconnect
;
785 struct stream
*stream
;
786 struct pstream
*pstream
;
793 jsonrpc_session_pick_remote(struct jsonrpc_session
*s
)
795 reconnect_set_name(s
->reconnect
,
796 s
->remotes
.names
[s
->next_remote
++ % s
->remotes
.n
]);
799 /* Creates and returns a jsonrpc_session to 'name', which should be a string
800 * acceptable to stream_open() or pstream_open().
802 * If 'name' is an active connection method, e.g. "tcp:127.1.2.3", the new
803 * jsonrpc_session connects to 'name'. If 'retry' is true, then the new
804 * session connects and reconnects to 'name', with backoff. If 'retry' is
805 * false, the new session will only try to connect once and after a connection
806 * failure or a disconnection jsonrpc_session_is_alive() will return false for
809 * If 'name' is a passive connection method, e.g. "ptcp:", the new
810 * jsonrpc_session listens for connections to 'name'. It maintains at most one
811 * connection at any given time. Any new connection causes the previous one
812 * (if any) to be dropped. */
813 struct jsonrpc_session
*
814 jsonrpc_session_open(const char *name
, bool retry
)
816 const struct svec remotes
= { .names
= (char **) &name
, .n
= 1 };
817 return jsonrpc_session_open_multiple(&remotes
, retry
);
820 struct jsonrpc_session
*
821 jsonrpc_session_open_multiple(const struct svec
*remotes
, bool retry
)
823 struct jsonrpc_session
*s
;
825 s
= xmalloc(sizeof *s
);
827 /* Set 'n' remotes from 'names', shuffling them into random order. */
828 ovs_assert(remotes
->n
> 0);
829 svec_clone(&s
->remotes
, remotes
);
830 svec_shuffle(&s
->remotes
);
833 s
->reconnect
= reconnect_create(time_msec());
834 jsonrpc_session_pick_remote(s
);
835 reconnect_enable(s
->reconnect
, time_msec());
836 reconnect_set_backoff_free_tries(s
->reconnect
, remotes
->n
);
844 const char *name
= reconnect_get_name(s
->reconnect
);
845 if (!pstream_verify_name(name
)) {
846 reconnect_set_passive(s
->reconnect
, true, time_msec());
848 reconnect_set_max_tries(s
->reconnect
, remotes
->n
);
849 reconnect_set_backoff(s
->reconnect
, INT_MAX
, INT_MAX
);
852 if (!stream_or_pstream_needs_probes(name
)) {
853 reconnect_set_probe_interval(s
->reconnect
, 0);
859 /* Creates and returns a jsonrpc_session that is initially connected to
860 * 'jsonrpc'. If the connection is dropped, it will not be reconnected.
862 * On the assumption that such connections are likely to be short-lived
863 * (e.g. from ovs-vsctl), informational logging for them is suppressed. */
864 struct jsonrpc_session
*
865 jsonrpc_session_open_unreliably(struct jsonrpc
*jsonrpc
, uint8_t dscp
)
867 struct jsonrpc_session
*s
;
869 s
= xmalloc(sizeof *s
);
870 svec_init(&s
->remotes
);
871 svec_add(&s
->remotes
, jsonrpc_get_name(jsonrpc
));
873 s
->reconnect
= reconnect_create(time_msec());
874 reconnect_set_quiet(s
->reconnect
, true);
875 reconnect_set_name(s
->reconnect
, jsonrpc_get_name(jsonrpc
));
876 reconnect_set_max_tries(s
->reconnect
, 0);
877 reconnect_connected(s
->reconnect
, time_msec());
888 jsonrpc_session_close(struct jsonrpc_session
*s
)
891 jsonrpc_close(s
->rpc
);
892 reconnect_destroy(s
->reconnect
);
893 stream_close(s
->stream
);
894 pstream_close(s
->pstream
);
895 svec_destroy(&s
->remotes
);
901 jsonrpc_session_steal(struct jsonrpc_session
*s
)
903 struct jsonrpc
*rpc
= s
->rpc
;
905 jsonrpc_session_close(s
);
910 jsonrpc_session_disconnect(struct jsonrpc_session
*s
)
913 jsonrpc_error(s
->rpc
, EOF
);
914 jsonrpc_close(s
->rpc
);
916 } else if (s
->stream
) {
917 stream_close(s
->stream
);
924 jsonrpc_session_pick_remote(s
);
928 jsonrpc_session_connect(struct jsonrpc_session
*s
)
930 const char *name
= reconnect_get_name(s
->reconnect
);
933 jsonrpc_session_disconnect(s
);
934 if (!reconnect_is_passive(s
->reconnect
)) {
935 error
= jsonrpc_stream_open(name
, &s
->stream
, s
->dscp
);
937 reconnect_connecting(s
->reconnect
, time_msec());
939 s
->last_error
= error
;
942 error
= s
->pstream
? 0 : jsonrpc_pstream_open(name
, &s
->pstream
,
945 reconnect_listening(s
->reconnect
, time_msec());
950 reconnect_connect_failed(s
->reconnect
, time_msec(), error
);
951 jsonrpc_session_pick_remote(s
);
956 jsonrpc_session_run(struct jsonrpc_session
*s
)
959 struct stream
*stream
;
962 error
= pstream_accept(s
->pstream
, &stream
);
964 if (s
->rpc
|| s
->stream
) {
966 "%s: new connection replacing active connection",
967 reconnect_get_name(s
->reconnect
));
968 jsonrpc_session_disconnect(s
);
970 reconnect_connected(s
->reconnect
, time_msec());
971 s
->rpc
= jsonrpc_open(stream
);
973 } else if (error
!= EAGAIN
) {
974 reconnect_listen_error(s
->reconnect
, time_msec(), error
);
975 pstream_close(s
->pstream
);
984 backlog
= jsonrpc_get_backlog(s
->rpc
);
986 if (jsonrpc_get_backlog(s
->rpc
) < backlog
) {
987 /* Data previously caught in a queue was successfully sent (or
988 * there's an error, which we'll catch below.)
990 * We don't count data that is successfully sent immediately as
991 * activity, because there's a lot of queuing downstream from us,
992 * which means that we can push a lot of data into a connection
993 * that has stalled and won't ever recover.
995 reconnect_activity(s
->reconnect
, time_msec());
998 error
= jsonrpc_get_status(s
->rpc
);
1000 reconnect_disconnected(s
->reconnect
, time_msec(), error
);
1001 jsonrpc_session_disconnect(s
);
1002 s
->last_error
= error
;
1004 } else if (s
->stream
) {
1007 stream_run(s
->stream
);
1008 error
= stream_connect(s
->stream
);
1010 reconnect_connected(s
->reconnect
, time_msec());
1011 s
->rpc
= jsonrpc_open(s
->stream
);
1014 } else if (error
!= EAGAIN
) {
1015 reconnect_connect_failed(s
->reconnect
, time_msec(), error
);
1016 jsonrpc_session_pick_remote(s
);
1017 stream_close(s
->stream
);
1019 s
->last_error
= error
;
1023 switch (reconnect_run(s
->reconnect
, time_msec())) {
1024 case RECONNECT_CONNECT
:
1025 jsonrpc_session_connect(s
);
1028 case RECONNECT_DISCONNECT
:
1029 reconnect_disconnected(s
->reconnect
, time_msec(), 0);
1030 jsonrpc_session_disconnect(s
);
1033 case RECONNECT_PROBE
:
1035 struct json
*params
;
1036 struct jsonrpc_msg
*request
;
1038 params
= json_array_create_empty();
1039 request
= jsonrpc_create_request("echo", params
, NULL
);
1040 json_destroy(request
->id
);
1041 request
->id
= json_string_create("echo");
1042 jsonrpc_send(s
->rpc
, request
);
1049 jsonrpc_session_wait(struct jsonrpc_session
*s
)
1052 jsonrpc_wait(s
->rpc
);
1053 } else if (s
->stream
) {
1054 stream_run_wait(s
->stream
);
1055 stream_connect_wait(s
->stream
);
1058 pstream_wait(s
->pstream
);
1060 reconnect_wait(s
->reconnect
, time_msec());
1064 jsonrpc_session_get_backlog(const struct jsonrpc_session
*s
)
1066 return s
->rpc
? jsonrpc_get_backlog(s
->rpc
) : 0;
1069 /* Always returns a pointer to a valid C string, assuming 's' was initialized
1072 jsonrpc_session_get_name(const struct jsonrpc_session
*s
)
1074 return reconnect_get_name(s
->reconnect
);
1078 jsonrpc_session_get_id(const struct jsonrpc_session
*s
)
1080 if (s
->rpc
&& s
->rpc
->stream
) {
1081 return stream_get_peer_id(s
->rpc
->stream
);
1088 jsonrpc_session_get_n_remotes(const struct jsonrpc_session
*s
)
1090 return s
->remotes
.n
;
1093 /* Always takes ownership of 'msg', regardless of success. */
1095 jsonrpc_session_send(struct jsonrpc_session
*s
, struct jsonrpc_msg
*msg
)
1098 return jsonrpc_send(s
->rpc
, msg
);
1100 jsonrpc_msg_destroy(msg
);
1105 struct jsonrpc_msg
*
1106 jsonrpc_session_recv(struct jsonrpc_session
*s
)
1109 unsigned int received_bytes
;
1110 struct jsonrpc_msg
*msg
;
1112 received_bytes
= jsonrpc_get_received_bytes(s
->rpc
);
1113 jsonrpc_recv(s
->rpc
, &msg
);
1114 if (received_bytes
!= jsonrpc_get_received_bytes(s
->rpc
)) {
1115 /* Data was successfully received.
1117 * Previously we only counted receiving a full message as activity,
1118 * but with large messages or a slow connection that policy could
1119 * time out the session mid-message. */
1120 reconnect_activity(s
->reconnect
, time_msec());
1124 if (msg
->type
== JSONRPC_REQUEST
&& !strcmp(msg
->method
, "echo")) {
1125 /* Echo request. Send reply. */
1126 struct jsonrpc_msg
*reply
;
1128 reply
= jsonrpc_create_reply(json_clone(msg
->params
), msg
->id
);
1129 jsonrpc_session_send(s
, reply
);
1130 } else if (msg
->type
== JSONRPC_REPLY
1131 && msg
->id
&& msg
->id
->type
== JSON_STRING
1132 && !strcmp(msg
->id
->string
, "echo")) {
1133 /* It's a reply to our echo request. Suppress it. */
1137 jsonrpc_msg_destroy(msg
);
1144 jsonrpc_session_recv_wait(struct jsonrpc_session
*s
)
1147 jsonrpc_recv_wait(s
->rpc
);
1151 /* Returns true if 's' is currently connected or trying to connect. */
1153 jsonrpc_session_is_alive(const struct jsonrpc_session
*s
)
1155 return s
->rpc
|| s
->stream
|| reconnect_get_max_tries(s
->reconnect
);
1158 /* Returns true if 's' is currently connected. */
1160 jsonrpc_session_is_connected(const struct jsonrpc_session
*s
)
1162 return s
->rpc
!= NULL
;
1165 /* Returns a sequence number for 's'. The sequence number increments every
1166 * time 's' connects or disconnects. Thus, a caller can use the change (or
1167 * lack of change) in the sequence number to figure out whether the underlying
1168 * connection is the same as before. */
1170 jsonrpc_session_get_seqno(const struct jsonrpc_session
*s
)
1175 /* Returns the current status of 's'. If 's' is NULL or is disconnected, this
1176 * is 0, otherwise it is the status of the connection, as reported by
1177 * jsonrpc_get_status(). */
1179 jsonrpc_session_get_status(const struct jsonrpc_session
*s
)
1181 return s
&& s
->rpc
? jsonrpc_get_status(s
->rpc
) : 0;
1184 /* Returns the last error reported on a connection by 's'. The return value is
1185 * 0 only if no connection made by 's' has ever encountered an error. See
1186 * jsonrpc_get_status() for return value interpretation. */
1188 jsonrpc_session_get_last_error(const struct jsonrpc_session
*s
)
1190 return s
->last_error
;
1193 /* Populates 'stats' with statistics from 's'. */
1195 jsonrpc_session_get_reconnect_stats(const struct jsonrpc_session
*s
,
1196 struct reconnect_stats
*stats
)
1198 reconnect_get_stats(s
->reconnect
, time_msec(), stats
);
1201 /* Enables 's' to reconnect to the peer if the connection drops. */
1203 jsonrpc_session_enable_reconnect(struct jsonrpc_session
*s
)
1205 reconnect_set_max_tries(s
->reconnect
, UINT_MAX
);
1206 reconnect_set_backoff(s
->reconnect
, RECONNECT_DEFAULT_MIN_BACKOFF
,
1207 RECONNECT_DEFAULT_MAX_BACKOFF
);
1210 /* Forces 's' to drop its connection (if any) and reconnect. */
1212 jsonrpc_session_force_reconnect(struct jsonrpc_session
*s
)
1214 reconnect_force_reconnect(s
->reconnect
, time_msec());
1217 /* Sets 'max_backoff' as the maximum time, in milliseconds, to wait after a
1218 * connection attempt fails before attempting to connect again. */
1220 jsonrpc_session_set_max_backoff(struct jsonrpc_session
*s
, int max_backoff
)
1222 reconnect_set_backoff(s
->reconnect
, 0, max_backoff
);
1225 /* Sets the "probe interval" for 's' to 'probe_interval', in milliseconds. If
1226 * this is zero, it disables the connection keepalive feature. Otherwise, if
1227 * 's' is idle for 'probe_interval' milliseconds then 's' will send an echo
1228 * request and, if no reply is received within an additional 'probe_interval'
1229 * milliseconds, close the connection (then reconnect, if that feature is
1232 jsonrpc_session_set_probe_interval(struct jsonrpc_session
*s
,
1235 reconnect_set_probe_interval(s
->reconnect
, probe_interval
);
1238 /* Sets the DSCP value used for 's''s connection to 'dscp'. If this is
1239 * different from the DSCP value currently in use then the connection is closed
1240 * and reconnected. */
1242 jsonrpc_session_set_dscp(struct jsonrpc_session
*s
, uint8_t dscp
)
1244 if (s
->dscp
!= dscp
) {
1245 pstream_close(s
->pstream
);
1249 jsonrpc_session_force_reconnect(s
);