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
[4096];
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 size_t max_output
; /* 'output_count' disconnection threshold. */
56 size_t max_backlog
; /* 'backlog' disconnection threshold. */
59 /* Rate limit for error messages. */
60 static struct vlog_rate_limit rl
= VLOG_RATE_LIMIT_INIT(5, 5);
62 static struct jsonrpc_msg
*jsonrpc_parse_received_message(struct jsonrpc
*);
63 static void jsonrpc_cleanup(struct jsonrpc
*);
64 static void jsonrpc_error(struct jsonrpc
*, int error
);
66 /* This is just the same as stream_open() except that it uses the default
67 * JSONRPC port if none is specified. */
69 jsonrpc_stream_open(const char *name
, struct stream
**streamp
, uint8_t dscp
)
71 return stream_open_with_default_port(name
, OVSDB_PORT
, streamp
, dscp
);
74 /* This is just the same as pstream_open() except that it uses the default
75 * JSONRPC port if none is specified. */
77 jsonrpc_pstream_open(const char *name
, struct pstream
**pstreamp
, uint8_t dscp
)
79 return pstream_open_with_default_port(name
, OVSDB_PORT
, pstreamp
, dscp
);
82 /* Returns a new JSON-RPC stream that uses 'stream' for input and output. The
83 * new jsonrpc object takes ownership of 'stream'. */
85 jsonrpc_open(struct stream
*stream
)
89 ovs_assert(stream
!= NULL
);
91 rpc
= xzalloc(sizeof *rpc
);
92 rpc
->name
= xstrdup(stream_get_name(stream
));
94 byteq_init(&rpc
->input
, rpc
->input_buffer
, sizeof rpc
->input_buffer
);
95 ovs_list_init(&rpc
->output
);
100 /* Destroys 'rpc', closing the stream on which it is based, and frees its
103 jsonrpc_close(struct jsonrpc
*rpc
)
106 jsonrpc_cleanup(rpc
);
112 /* Performs periodic maintenance on 'rpc', such as flushing output buffers. */
114 jsonrpc_run(struct jsonrpc
*rpc
)
120 stream_run(rpc
->stream
);
121 while (!ovs_list_is_empty(&rpc
->output
)) {
122 struct ofpbuf
*buf
= ofpbuf_from_list(rpc
->output
.next
);
125 retval
= stream_send(rpc
->stream
, buf
->data
, buf
->size
);
127 rpc
->backlog
-= retval
;
128 ofpbuf_pull(buf
, retval
);
130 ovs_list_remove(&buf
->list_node
);
135 if (retval
!= -EAGAIN
) {
136 VLOG_WARN_RL(&rl
, "%s: send error: %s",
137 rpc
->name
, ovs_strerror(-retval
));
138 jsonrpc_error(rpc
, -retval
);
145 /* Arranges for the poll loop to wake up when 'rpc' needs to perform
146 * maintenance activities. */
148 jsonrpc_wait(struct jsonrpc
*rpc
)
151 stream_run_wait(rpc
->stream
);
152 if (!ovs_list_is_empty(&rpc
->output
)) {
153 stream_send_wait(rpc
->stream
);
159 * Returns the current status of 'rpc'. The possible return values are:
162 * - EOF: end of file (remote end closed connection; not necessarily an error).
164 * When this function returns nonzero, 'rpc' is effectively out of
165 * commission. 'rpc' will not receive any more messages and any further
166 * messages that one attempts to send with 'rpc' will be discarded. The
167 * caller can keep 'rpc' around as long as it wants, but it's not going
168 * to provide any more useful services.
171 jsonrpc_get_status(const struct jsonrpc
*rpc
)
176 /* Returns the number of bytes buffered by 'rpc' to be written to the
177 * underlying stream. Always returns 0 if 'rpc' has encountered an error or if
178 * the remote end closed the connection. */
180 jsonrpc_get_backlog(const struct jsonrpc
*rpc
)
182 return rpc
->status
? 0 : rpc
->backlog
;
185 /* Sets thresholds for send backlog. If send backlog contains more than
186 * 'max_n_msgs' messages or is larger than 'max_backlog_bytes' bytes,
187 * connection will be dropped. */
189 jsonrpc_set_backlog_threshold(struct jsonrpc
*rpc
,
190 size_t max_n_msgs
, size_t max_backlog_bytes
)
192 rpc
->max_output
= max_n_msgs
;
193 rpc
->max_backlog
= max_backlog_bytes
;
196 /* Returns the number of bytes that have been received on 'rpc''s underlying
197 * stream. (The value wraps around if it exceeds UINT_MAX.) */
199 jsonrpc_get_received_bytes(const struct jsonrpc
*rpc
)
201 return rpc
->input
.head
;
204 /* Returns 'rpc''s name, that is, the name returned by stream_get_name() for
205 * the stream underlying 'rpc' when 'rpc' was created. */
207 jsonrpc_get_name(const struct jsonrpc
*rpc
)
213 jsonrpc_log_msg(const struct jsonrpc
*rpc
, const char *title
,
214 const struct jsonrpc_msg
*msg
)
216 if (VLOG_IS_DBG_ENABLED()) {
217 struct ds s
= DS_EMPTY_INITIALIZER
;
219 ds_put_format(&s
, ", method=\"%s\"", msg
->method
);
222 ds_put_cstr(&s
, ", params=");
223 json_to_ds(msg
->params
, 0, &s
);
226 ds_put_cstr(&s
, ", result=");
227 json_to_ds(msg
->result
, 0, &s
);
230 ds_put_cstr(&s
, ", error=");
231 json_to_ds(msg
->error
, 0, &s
);
234 ds_put_cstr(&s
, ", id=");
235 json_to_ds(msg
->id
, 0, &s
);
237 VLOG_DBG("%s: %s %s%s", rpc
->name
, title
,
238 jsonrpc_msg_type_to_string(msg
->type
), ds_cstr(&s
));
243 /* Schedules 'msg' to be sent on 'rpc' and returns 'rpc''s status (as with
244 * jsonrpc_get_status()).
246 * If 'msg' cannot be sent immediately, it is appended to a buffer. The caller
247 * is responsible for ensuring that the amount of buffered data is somehow
248 * limited. (jsonrpc_get_backlog() returns the amount of data currently
249 * buffered in 'rpc'.)
251 * Always takes ownership of 'msg', regardless of success. */
253 jsonrpc_send(struct jsonrpc
*rpc
, struct jsonrpc_msg
*msg
)
257 struct ds ds
= DS_EMPTY_INITIALIZER
;
261 jsonrpc_msg_destroy(msg
);
265 jsonrpc_log_msg(rpc
, "send", msg
);
267 json
= jsonrpc_msg_to_json(msg
);
268 json_to_ds(json
, 0, &ds
);
272 buf
= xmalloc(sizeof *buf
);
273 ofpbuf_use_ds(buf
, &ds
);
274 ovs_list_push_back(&rpc
->output
, &buf
->list_node
);
276 rpc
->backlog
+= length
;
278 if (rpc
->output_count
>= 50) {
279 static struct vlog_rate_limit bl_rl
= VLOG_RATE_LIMIT_INIT(5, 5);
280 bool disconnect
= false;
282 VLOG_INFO_RL(&bl_rl
, "excessive sending backlog, jsonrpc: %s, num of"
283 " msgs: %"PRIuSIZE
", backlog: %"PRIuSIZE
".", rpc
->name
,
284 rpc
->output_count
, rpc
->backlog
);
285 if (rpc
->max_output
&& rpc
->output_count
> rpc
->max_output
) {
287 VLOG_WARN("sending backlog exceeded maximum number of messages (%"
288 PRIuSIZE
" > %"PRIuSIZE
"), disconnecting, jsonrpc: %s.",
289 rpc
->output_count
, rpc
->max_output
, rpc
->name
);
290 } else if (rpc
->max_backlog
&& rpc
->backlog
> rpc
->max_backlog
) {
292 VLOG_WARN("sending backlog exceeded maximum size (%"PRIuSIZE
" > %"
293 PRIuSIZE
" bytes), disconnecting, jsonrpc: %s.",
294 rpc
->backlog
, rpc
->max_backlog
, rpc
->name
);
297 jsonrpc_error(rpc
, E2BIG
);
301 if (rpc
->backlog
== length
) {
307 /* Attempts to receive a message from 'rpc'.
309 * If successful, stores the received message in '*msgp' and returns 0. The
310 * caller takes ownership of '*msgp' and must eventually destroy it with
311 * jsonrpc_msg_destroy().
313 * Otherwise, stores NULL in '*msgp' and returns one of the following:
315 * - EAGAIN: No message has been received.
317 * - EOF: The remote end closed the connection gracefully.
319 * - Otherwise an errno value that represents a JSON-RPC protocol violation
320 * or another error fatal to the connection. 'rpc' will not send or
321 * receive any more messages.
324 jsonrpc_recv(struct jsonrpc
*rpc
, struct jsonrpc_msg
**msgp
)
333 for (i
= 0; i
< 50; i
++) {
336 /* Fill our input buffer if it's empty. */
337 if (byteq_is_empty(&rpc
->input
)) {
341 chunk
= byteq_headroom(&rpc
->input
);
342 retval
= stream_recv(rpc
->stream
, byteq_head(&rpc
->input
), chunk
);
344 if (retval
== -EAGAIN
) {
347 VLOG_WARN_RL(&rl
, "%s: receive error: %s",
348 rpc
->name
, ovs_strerror(-retval
));
349 jsonrpc_error(rpc
, -retval
);
352 } else if (retval
== 0) {
353 jsonrpc_error(rpc
, EOF
);
356 byteq_advance_head(&rpc
->input
, retval
);
359 /* We have some input. Feed it into the JSON parser. */
361 rpc
->parser
= json_parser_create(0);
363 n
= byteq_tailroom(&rpc
->input
);
364 used
= json_parser_feed(rpc
->parser
,
365 (char *) byteq_tail(&rpc
->input
), n
);
366 byteq_advance_tail(&rpc
->input
, used
);
368 /* If we have complete JSON, attempt to parse it as JSON-RPC. */
369 if (json_parser_is_done(rpc
->parser
)) {
370 *msgp
= jsonrpc_parse_received_message(rpc
);
376 const struct byteq
*q
= &rpc
->input
;
377 if (q
->head
<= q
->size
) {
378 stream_report_content(q
->buffer
, q
->head
, STREAM_JSONRPC
,
379 &this_module
, rpc
->name
);
389 /* Causes the poll loop to wake up when jsonrpc_recv() may return a value other
392 jsonrpc_recv_wait(struct jsonrpc
*rpc
)
394 if (rpc
->status
|| !byteq_is_empty(&rpc
->input
)) {
395 poll_immediate_wake_at(rpc
->name
);
397 stream_recv_wait(rpc
->stream
);
401 /* Sends 'msg' on 'rpc' and waits for it to be successfully queued to the
402 * underlying stream. Returns 0 if 'msg' was sent successfully, otherwise a
403 * status value (see jsonrpc_get_status()).
405 * Always takes ownership of 'msg', regardless of success. */
407 jsonrpc_send_block(struct jsonrpc
*rpc
, struct jsonrpc_msg
*msg
)
413 error
= jsonrpc_send(rpc
, msg
);
420 if (ovs_list_is_empty(&rpc
->output
) || rpc
->status
) {
428 /* Waits for a message to be received on 'rpc'. Same semantics as
429 * jsonrpc_recv() except that EAGAIN will never be returned. */
431 jsonrpc_recv_block(struct jsonrpc
*rpc
, struct jsonrpc_msg
**msgp
)
434 int error
= jsonrpc_recv(rpc
, msgp
);
435 if (error
!= EAGAIN
) {
442 jsonrpc_recv_wait(rpc
);
447 /* Sends 'request' to 'rpc' then waits for a reply. The return value is 0 if
448 * successful, in which case '*replyp' is set to the reply, which the caller
449 * must eventually free with jsonrpc_msg_destroy(). Otherwise returns a status
450 * value (see jsonrpc_get_status()).
452 * Discards any message received on 'rpc' that is not a reply to 'request'
453 * (based on message id).
455 * Always takes ownership of 'request', regardless of success. */
457 jsonrpc_transact_block(struct jsonrpc
*rpc
, struct jsonrpc_msg
*request
,
458 struct jsonrpc_msg
**replyp
)
460 struct jsonrpc_msg
*reply
= NULL
;
464 id
= json_clone(request
->id
);
465 error
= jsonrpc_send_block(rpc
, request
);
468 error
= jsonrpc_recv_block(rpc
, &reply
);
472 if ((reply
->type
== JSONRPC_REPLY
|| reply
->type
== JSONRPC_ERROR
)
473 && json_equal(id
, reply
->id
)) {
476 jsonrpc_msg_destroy(reply
);
479 *replyp
= error
? NULL
: reply
;
484 /* Attempts to parse the content of 'rpc->parser' (which is complete JSON) as a
485 * JSON-RPC message. If successful, returns the JSON-RPC message. On failure,
486 * signals an error on 'rpc' with jsonrpc_error() and returns NULL. */
487 static struct jsonrpc_msg
*
488 jsonrpc_parse_received_message(struct jsonrpc
*rpc
)
490 struct jsonrpc_msg
*msg
;
494 json
= json_parser_finish(rpc
->parser
);
496 if (json
->type
== JSON_STRING
) {
497 VLOG_WARN_RL(&rl
, "%s: error parsing stream: %s",
498 rpc
->name
, json_string(json
));
499 jsonrpc_error(rpc
, EPROTO
);
504 error
= jsonrpc_msg_from_json(json
, &msg
);
506 VLOG_WARN_RL(&rl
, "%s: received bad JSON-RPC message: %s",
509 jsonrpc_error(rpc
, EPROTO
);
513 jsonrpc_log_msg(rpc
, "received", msg
);
518 jsonrpc_error(struct jsonrpc
*rpc
, int error
)
523 jsonrpc_cleanup(rpc
);
528 jsonrpc_cleanup(struct jsonrpc
*rpc
)
530 stream_close(rpc
->stream
);
533 json_parser_abort(rpc
->parser
);
536 ofpbuf_list_delete(&rpc
->output
);
538 rpc
->output_count
= 0;
541 static struct jsonrpc_msg
*
542 jsonrpc_create(enum jsonrpc_msg_type type
, const char *method
,
543 struct json
*params
, struct json
*result
, struct json
*error
,
546 struct jsonrpc_msg
*msg
= xmalloc(sizeof *msg
);
548 msg
->method
= nullable_xstrdup(method
);
549 msg
->params
= params
;
550 msg
->result
= result
;
557 jsonrpc_create_id(void)
559 static atomic_count next_id
= ATOMIC_COUNT_INIT(0);
562 id
= atomic_count_inc(&next_id
);
563 return json_integer_create(id
);
567 jsonrpc_create_request(const char *method
, struct json
*params
,
570 struct json
*id
= jsonrpc_create_id();
572 *idp
= json_clone(id
);
574 return jsonrpc_create(JSONRPC_REQUEST
, method
, params
, NULL
, NULL
, id
);
578 jsonrpc_create_notify(const char *method
, struct json
*params
)
580 return jsonrpc_create(JSONRPC_NOTIFY
, method
, params
, NULL
, NULL
, NULL
);
584 jsonrpc_create_reply(struct json
*result
, const struct json
*id
)
586 return jsonrpc_create(JSONRPC_REPLY
, NULL
, NULL
, result
, NULL
,
591 jsonrpc_create_error(struct json
*error
, const struct json
*id
)
593 return jsonrpc_create(JSONRPC_REPLY
, NULL
, NULL
, NULL
, error
,
598 jsonrpc_msg_clone(const struct jsonrpc_msg
*old
)
600 return jsonrpc_create(old
->type
, old
->method
,
601 json_nullable_clone(old
->params
),
602 json_nullable_clone(old
->result
),
603 json_nullable_clone(old
->error
),
604 json_nullable_clone(old
->id
));
608 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type
)
611 case JSONRPC_REQUEST
:
615 return "notification";
627 jsonrpc_msg_is_valid(const struct jsonrpc_msg
*m
)
629 const char *type_name
;
630 unsigned int pattern
;
632 if (m
->params
&& m
->params
->type
!= JSON_ARRAY
) {
633 return xstrdup("\"params\" must be JSON array");
637 case JSONRPC_REQUEST
:
654 return xasprintf("invalid JSON-RPC message type %d", m
->type
);
657 type_name
= jsonrpc_msg_type_to_string(m
->type
);
658 if ((m
->method
!= NULL
) != ((pattern
& 0x10000) != 0)) {
659 return xasprintf("%s must%s have \"method\"",
660 type_name
, (pattern
& 0x10000) ? "" : " not");
663 if ((m
->params
!= NULL
) != ((pattern
& 0x1000) != 0)) {
664 return xasprintf("%s must%s have \"params\"",
665 type_name
, (pattern
& 0x1000) ? "" : " not");
668 if ((m
->result
!= NULL
) != ((pattern
& 0x100) != 0)) {
669 return xasprintf("%s must%s have \"result\"",
670 type_name
, (pattern
& 0x100) ? "" : " not");
673 if ((m
->error
!= NULL
) != ((pattern
& 0x10) != 0)) {
674 return xasprintf("%s must%s have \"error\"",
675 type_name
, (pattern
& 0x10) ? "" : " not");
678 if ((m
->id
!= NULL
) != ((pattern
& 0x1) != 0)) {
679 return xasprintf("%s must%s have \"id\"",
680 type_name
, (pattern
& 0x1) ? "" : " not");
687 jsonrpc_msg_destroy(struct jsonrpc_msg
*m
)
691 json_destroy(m
->params
);
692 json_destroy(m
->result
);
693 json_destroy(m
->error
);
700 null_from_json_null(struct json
*json
)
702 if (json
&& json
->type
== JSON_NULL
) {
710 jsonrpc_msg_from_json(struct json
*json
, struct jsonrpc_msg
**msgp
)
712 struct json
*method
= NULL
;
713 struct jsonrpc_msg
*msg
= NULL
;
714 struct shash
*object
;
717 if (json
->type
!= JSON_OBJECT
) {
718 error
= xstrdup("message is not a JSON object");
721 object
= json_object(json
);
723 method
= shash_find_and_delete(object
, "method");
724 if (method
&& method
->type
!= JSON_STRING
) {
725 error
= xstrdup("method is not a JSON string");
729 msg
= xzalloc(sizeof *msg
);
730 msg
->method
= method
? xstrdup(method
->string
) : NULL
;
731 msg
->params
= null_from_json_null(shash_find_and_delete(object
, "params"));
732 msg
->result
= null_from_json_null(shash_find_and_delete(object
, "result"));
733 msg
->error
= null_from_json_null(shash_find_and_delete(object
, "error"));
734 msg
->id
= null_from_json_null(shash_find_and_delete(object
, "id"));
735 msg
->type
= (msg
->result
? JSONRPC_REPLY
736 : msg
->error
? JSONRPC_ERROR
737 : msg
->id
? JSONRPC_REQUEST
739 if (!shash_is_empty(object
)) {
740 error
= xasprintf("message has unexpected member \"%s\"",
741 shash_first(object
)->name
);
744 error
= jsonrpc_msg_is_valid(msg
);
750 json_destroy(method
);
753 jsonrpc_msg_destroy(msg
);
760 /* Returns 'm' converted to JSON suitable for sending as a JSON-RPC message.
762 * Consumes and destroys 'm'. */
764 jsonrpc_msg_to_json(struct jsonrpc_msg
*m
)
766 struct json
*json
= json_object_create();
769 json_object_put(json
, "method", json_string_create_nocopy(m
->method
));
773 json_object_put(json
, "params", m
->params
);
777 json_object_put(json
, "result", m
->result
);
778 } else if (m
->type
== JSONRPC_ERROR
) {
779 json_object_put(json
, "result", json_null_create());
783 json_object_put(json
, "error", m
->error
);
784 } else if (m
->type
== JSONRPC_REPLY
) {
785 json_object_put(json
, "error", json_null_create());
789 json_object_put(json
, "id", m
->id
);
790 } else if (m
->type
== JSONRPC_NOTIFY
) {
791 json_object_put(json
, "id", json_null_create());
800 jsonrpc_msg_to_string(const struct jsonrpc_msg
*m
)
802 struct jsonrpc_msg
*copy
= jsonrpc_msg_clone(m
);
803 struct json
*json
= jsonrpc_msg_to_json(copy
);
804 char *s
= json_to_string(json
, JSSF_SORT
);
809 /* A JSON-RPC session with reconnection. */
811 struct jsonrpc_session
{
815 struct reconnect
*reconnect
;
817 struct stream
*stream
;
818 struct pstream
*pstream
;
823 /* Limits for jsonrpc. */
825 size_t max_backlog_bytes
;
829 jsonrpc_session_pick_remote(struct jsonrpc_session
*s
)
831 reconnect_set_name(s
->reconnect
,
832 s
->remotes
.names
[s
->next_remote
++ % s
->remotes
.n
]);
835 /* Creates and returns a jsonrpc_session to 'name', which should be a string
836 * acceptable to stream_open() or pstream_open().
838 * If 'name' is an active connection method, e.g. "tcp:127.1.2.3", the new
839 * jsonrpc_session connects to 'name'. If 'retry' is true, then the new
840 * session connects and reconnects to 'name', with backoff. If 'retry' is
841 * false, the new session will only try to connect once and after a connection
842 * failure or a disconnection jsonrpc_session_is_alive() will return false for
845 * If 'name' is a passive connection method, e.g. "ptcp:", the new
846 * jsonrpc_session listens for connections to 'name'. It maintains at most one
847 * connection at any given time. Any new connection causes the previous one
848 * (if any) to be dropped. */
849 struct jsonrpc_session
*
850 jsonrpc_session_open(const char *name
, bool retry
)
852 const struct svec remotes
= { .names
= (char **) &name
, .n
= 1 };
853 return jsonrpc_session_open_multiple(&remotes
, retry
);
856 struct jsonrpc_session
*
857 jsonrpc_session_open_multiple(const struct svec
*remotes
, bool retry
)
859 struct jsonrpc_session
*s
;
861 s
= xmalloc(sizeof *s
);
863 /* Set 'n' remotes from 'names'. */
864 svec_clone(&s
->remotes
, remotes
);
866 svec_add(&s
->remotes
, "invalid:");
870 s
->reconnect
= reconnect_create(time_msec());
871 jsonrpc_session_pick_remote(s
);
872 reconnect_enable(s
->reconnect
, time_msec());
873 reconnect_set_backoff_free_tries(s
->reconnect
, remotes
->n
);
881 jsonrpc_session_set_backlog_threshold(s
, 0, 0);
883 const char *name
= reconnect_get_name(s
->reconnect
);
884 if (!pstream_verify_name(name
)) {
885 reconnect_set_passive(s
->reconnect
, true, time_msec());
887 reconnect_set_max_tries(s
->reconnect
, remotes
->n
);
888 reconnect_set_backoff(s
->reconnect
, INT_MAX
, INT_MAX
);
891 if (!stream_or_pstream_needs_probes(name
)) {
892 reconnect_set_probe_interval(s
->reconnect
, 0);
898 /* Creates and returns a jsonrpc_session that is initially connected to
899 * 'jsonrpc'. If the connection is dropped, it will not be reconnected.
901 * On the assumption that such connections are likely to be short-lived
902 * (e.g. from ovs-vsctl), informational logging for them is suppressed. */
903 struct jsonrpc_session
*
904 jsonrpc_session_open_unreliably(struct jsonrpc
*jsonrpc
, uint8_t dscp
)
906 struct jsonrpc_session
*s
;
908 s
= xmalloc(sizeof *s
);
909 svec_init(&s
->remotes
);
910 svec_add(&s
->remotes
, jsonrpc_get_name(jsonrpc
));
912 s
->reconnect
= reconnect_create(time_msec());
913 reconnect_set_quiet(s
->reconnect
, true);
914 reconnect_set_name(s
->reconnect
, jsonrpc_get_name(jsonrpc
));
915 reconnect_set_max_tries(s
->reconnect
, 0);
916 reconnect_connected(s
->reconnect
, time_msec());
923 jsonrpc_session_set_backlog_threshold(s
, 0, 0);
928 jsonrpc_session_close(struct jsonrpc_session
*s
)
931 jsonrpc_close(s
->rpc
);
932 reconnect_destroy(s
->reconnect
);
933 stream_close(s
->stream
);
934 pstream_close(s
->pstream
);
935 svec_destroy(&s
->remotes
);
941 jsonrpc_session_steal(struct jsonrpc_session
*s
)
943 struct jsonrpc
*rpc
= s
->rpc
;
945 jsonrpc_session_close(s
);
950 jsonrpc_session_disconnect(struct jsonrpc_session
*s
)
953 jsonrpc_error(s
->rpc
, EOF
);
954 jsonrpc_close(s
->rpc
);
956 } else if (s
->stream
) {
957 stream_close(s
->stream
);
964 jsonrpc_session_pick_remote(s
);
968 jsonrpc_session_connect(struct jsonrpc_session
*s
)
970 const char *name
= reconnect_get_name(s
->reconnect
);
973 jsonrpc_session_disconnect(s
);
974 if (!reconnect_is_passive(s
->reconnect
)) {
975 error
= jsonrpc_stream_open(name
, &s
->stream
, s
->dscp
);
977 reconnect_connecting(s
->reconnect
, time_msec());
979 s
->last_error
= error
;
982 error
= s
->pstream
? 0 : jsonrpc_pstream_open(name
, &s
->pstream
,
985 reconnect_listening(s
->reconnect
, time_msec());
990 reconnect_connect_failed(s
->reconnect
, time_msec(), error
);
991 jsonrpc_session_pick_remote(s
);
996 jsonrpc_session_run(struct jsonrpc_session
*s
)
999 struct stream
*stream
;
1002 error
= pstream_accept(s
->pstream
, &stream
);
1004 if (s
->rpc
|| s
->stream
) {
1006 "%s: new connection replacing active connection",
1007 reconnect_get_name(s
->reconnect
));
1008 jsonrpc_session_disconnect(s
);
1010 reconnect_connected(s
->reconnect
, time_msec());
1011 s
->rpc
= jsonrpc_open(stream
);
1012 jsonrpc_set_backlog_threshold(s
->rpc
, s
->max_n_msgs
,
1013 s
->max_backlog_bytes
);
1015 } else if (error
!= EAGAIN
) {
1016 reconnect_listen_error(s
->reconnect
, time_msec(), error
);
1017 pstream_close(s
->pstream
);
1026 backlog
= jsonrpc_get_backlog(s
->rpc
);
1027 jsonrpc_run(s
->rpc
);
1028 if (jsonrpc_get_backlog(s
->rpc
) < backlog
) {
1029 /* Data previously caught in a queue was successfully sent (or
1030 * there's an error, which we'll catch below.)
1032 * We don't count data that is successfully sent immediately as
1033 * activity, because there's a lot of queuing downstream from us,
1034 * which means that we can push a lot of data into a connection
1035 * that has stalled and won't ever recover.
1037 reconnect_activity(s
->reconnect
, time_msec());
1040 error
= jsonrpc_get_status(s
->rpc
);
1042 reconnect_disconnected(s
->reconnect
, time_msec(), error
);
1043 jsonrpc_session_disconnect(s
);
1044 s
->last_error
= error
;
1046 } else if (s
->stream
) {
1049 stream_run(s
->stream
);
1050 error
= stream_connect(s
->stream
);
1052 reconnect_connected(s
->reconnect
, time_msec());
1053 s
->rpc
= jsonrpc_open(s
->stream
);
1054 jsonrpc_set_backlog_threshold(s
->rpc
, s
->max_n_msgs
,
1055 s
->max_backlog_bytes
);
1058 } else if (error
!= EAGAIN
) {
1059 reconnect_connect_failed(s
->reconnect
, time_msec(), error
);
1060 jsonrpc_session_pick_remote(s
);
1061 stream_close(s
->stream
);
1063 s
->last_error
= error
;
1067 switch (reconnect_run(s
->reconnect
, time_msec())) {
1068 case RECONNECT_CONNECT
:
1069 jsonrpc_session_connect(s
);
1072 case RECONNECT_DISCONNECT
:
1073 reconnect_disconnected(s
->reconnect
, time_msec(), 0);
1074 jsonrpc_session_disconnect(s
);
1077 case RECONNECT_PROBE
:
1079 struct json
*params
;
1080 struct jsonrpc_msg
*request
;
1082 params
= json_array_create_empty();
1083 request
= jsonrpc_create_request("echo", params
, NULL
);
1084 json_destroy(request
->id
);
1085 request
->id
= json_string_create("echo");
1086 jsonrpc_send(s
->rpc
, request
);
1093 jsonrpc_session_wait(struct jsonrpc_session
*s
)
1096 jsonrpc_wait(s
->rpc
);
1097 } else if (s
->stream
) {
1098 stream_run_wait(s
->stream
);
1099 stream_connect_wait(s
->stream
);
1102 pstream_wait(s
->pstream
);
1104 reconnect_wait(s
->reconnect
, time_msec());
1108 jsonrpc_session_get_backlog(const struct jsonrpc_session
*s
)
1110 return s
->rpc
? jsonrpc_get_backlog(s
->rpc
) : 0;
1113 /* Always returns a pointer to a valid C string, assuming 's' was initialized
1116 jsonrpc_session_get_name(const struct jsonrpc_session
*s
)
1118 return reconnect_get_name(s
->reconnect
);
1122 jsonrpc_session_get_id(const struct jsonrpc_session
*s
)
1124 if (s
->rpc
&& s
->rpc
->stream
) {
1125 return stream_get_peer_id(s
->rpc
->stream
);
1132 jsonrpc_session_get_n_remotes(const struct jsonrpc_session
*s
)
1134 return s
->remotes
.n
;
1137 /* Always takes ownership of 'msg', regardless of success. */
1139 jsonrpc_session_send(struct jsonrpc_session
*s
, struct jsonrpc_msg
*msg
)
1142 return jsonrpc_send(s
->rpc
, msg
);
1144 jsonrpc_msg_destroy(msg
);
1149 struct jsonrpc_msg
*
1150 jsonrpc_session_recv(struct jsonrpc_session
*s
)
1153 unsigned int received_bytes
;
1154 struct jsonrpc_msg
*msg
;
1156 received_bytes
= jsonrpc_get_received_bytes(s
->rpc
);
1157 jsonrpc_recv(s
->rpc
, &msg
);
1159 long long int now
= time_msec();
1160 reconnect_receive_attempted(s
->reconnect
, now
);
1161 if (received_bytes
!= jsonrpc_get_received_bytes(s
->rpc
)) {
1162 /* Data was successfully received.
1164 * Previously we only counted receiving a full message as activity,
1165 * but with large messages or a slow connection that policy could
1166 * time out the session mid-message. */
1167 reconnect_activity(s
->reconnect
, now
);
1171 if (msg
->type
== JSONRPC_REQUEST
&& !strcmp(msg
->method
, "echo")) {
1172 /* Echo request. Send reply. */
1173 struct jsonrpc_msg
*reply
;
1175 reply
= jsonrpc_create_reply(json_clone(msg
->params
), msg
->id
);
1176 jsonrpc_session_send(s
, reply
);
1177 } else if (msg
->type
== JSONRPC_REPLY
1178 && msg
->id
&& msg
->id
->type
== JSON_STRING
1179 && !strcmp(msg
->id
->string
, "echo")) {
1180 /* It's a reply to our echo request. Suppress it. */
1184 jsonrpc_msg_destroy(msg
);
1191 jsonrpc_session_recv_wait(struct jsonrpc_session
*s
)
1194 jsonrpc_recv_wait(s
->rpc
);
1198 /* Returns true if 's' is currently connected or trying to connect. */
1200 jsonrpc_session_is_alive(const struct jsonrpc_session
*s
)
1202 return s
->rpc
|| s
->stream
|| reconnect_get_max_tries(s
->reconnect
);
1205 /* Returns true if 's' is currently connected. */
1207 jsonrpc_session_is_connected(const struct jsonrpc_session
*s
)
1209 return s
->rpc
!= NULL
;
1212 /* Returns a sequence number for 's'. The sequence number increments every
1213 * time 's' connects or disconnects. Thus, a caller can use the change (or
1214 * lack of change) in the sequence number to figure out whether the underlying
1215 * connection is the same as before. */
1217 jsonrpc_session_get_seqno(const struct jsonrpc_session
*s
)
1222 /* Returns the current status of 's'. If 's' is NULL or is disconnected, this
1223 * is 0, otherwise it is the status of the connection, as reported by
1224 * jsonrpc_get_status(). */
1226 jsonrpc_session_get_status(const struct jsonrpc_session
*s
)
1228 return s
&& s
->rpc
? jsonrpc_get_status(s
->rpc
) : 0;
1231 /* Returns the last error reported on a connection by 's'. The return value is
1232 * 0 only if no connection made by 's' has ever encountered an error. See
1233 * jsonrpc_get_status() for return value interpretation. */
1235 jsonrpc_session_get_last_error(const struct jsonrpc_session
*s
)
1237 return s
->last_error
;
1240 /* Populates 'stats' with statistics from 's'. */
1242 jsonrpc_session_get_reconnect_stats(const struct jsonrpc_session
*s
,
1243 struct reconnect_stats
*stats
)
1245 reconnect_get_stats(s
->reconnect
, time_msec(), stats
);
1248 /* Enables 's' to reconnect to the peer if the connection drops. */
1250 jsonrpc_session_enable_reconnect(struct jsonrpc_session
*s
)
1252 reconnect_set_max_tries(s
->reconnect
, UINT_MAX
);
1253 reconnect_set_backoff(s
->reconnect
, RECONNECT_DEFAULT_MIN_BACKOFF
,
1254 RECONNECT_DEFAULT_MAX_BACKOFF
);
1257 /* Forces 's' to drop its connection (if any) and reconnect. */
1259 jsonrpc_session_force_reconnect(struct jsonrpc_session
*s
)
1261 reconnect_force_reconnect(s
->reconnect
, time_msec());
1264 /* Sets 'max_backoff' as the maximum time, in milliseconds, to wait after a
1265 * connection attempt fails before attempting to connect again. */
1267 jsonrpc_session_set_max_backoff(struct jsonrpc_session
*s
, int max_backoff
)
1269 reconnect_set_backoff(s
->reconnect
, 0, max_backoff
);
1272 /* Sets the "probe interval" for 's' to 'probe_interval', in milliseconds. If
1273 * this is zero, it disables the connection keepalive feature. Otherwise, if
1274 * 's' is idle for 'probe_interval' milliseconds then 's' will send an echo
1275 * request and, if no reply is received within an additional 'probe_interval'
1276 * milliseconds, close the connection (then reconnect, if that feature is
1279 jsonrpc_session_set_probe_interval(struct jsonrpc_session
*s
,
1282 reconnect_set_probe_interval(s
->reconnect
, probe_interval
);
1285 /* Sets the DSCP value used for 's''s connection to 'dscp'. If this is
1286 * different from the DSCP value currently in use then the connection is closed
1287 * and reconnected. */
1289 jsonrpc_session_set_dscp(struct jsonrpc_session
*s
, uint8_t dscp
)
1291 if (s
->dscp
!= dscp
) {
1292 pstream_close(s
->pstream
);
1296 jsonrpc_session_force_reconnect(s
);
1300 /* Sets thresholds for send backlog. If send backlog contains more than
1301 * 'max_n_msgs' messages or is larger than 'max_backlog_bytes' bytes,
1302 * connection will be closed (then reconnected, if that feature is enabled). */
1304 jsonrpc_session_set_backlog_threshold(struct jsonrpc_session
*s
,
1306 size_t max_backlog_bytes
)
1308 s
->max_n_msgs
= max_n_msgs
;
1309 s
->max_backlog_bytes
= max_backlog_bytes
;
1311 jsonrpc_set_backlog_threshold(s
->rpc
, max_n_msgs
, max_backlog_bytes
);