2 * Copyright (c) 2009, 2010, 2011 Nicira Networks.
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.
25 #include "dynamic-string.h"
26 #include "fatal-signal.h"
30 #include "poll-loop.h"
31 #include "reconnect.h"
36 VLOG_DEFINE_THIS_MODULE(jsonrpc);
39 struct stream *stream;
45 struct json_parser *parser;
46 struct jsonrpc_msg *received;
49 struct list output; /* Contains "struct ofpbuf"s. */
53 /* Rate limit for error messages. */
54 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
56 static void jsonrpc_received(struct jsonrpc *);
57 static void jsonrpc_cleanup(struct jsonrpc *);
59 /* This is just the same as stream_open() except that it uses the default
60 * JSONRPC ports if none is specified. */
62 jsonrpc_stream_open(const char *name, struct stream **streamp)
64 return stream_open_with_default_ports(name, JSONRPC_TCP_PORT,
65 JSONRPC_SSL_PORT, streamp);
68 /* This is just the same as pstream_open() except that it uses the default
69 * JSONRPC ports if none is specified. */
71 jsonrpc_pstream_open(const char *name, struct pstream **pstreamp)
73 return pstream_open_with_default_ports(name, JSONRPC_TCP_PORT,
74 JSONRPC_SSL_PORT, pstreamp);
78 jsonrpc_open(struct stream *stream)
82 assert(stream != NULL);
84 rpc = xzalloc(sizeof *rpc);
85 rpc->name = xstrdup(stream_get_name(stream));
87 byteq_init(&rpc->input);
88 list_init(&rpc->output);
94 jsonrpc_close(struct jsonrpc *rpc)
104 jsonrpc_run(struct jsonrpc *rpc)
110 stream_run(rpc->stream);
111 while (!list_is_empty(&rpc->output)) {
112 struct ofpbuf *buf = ofpbuf_from_list(rpc->output.next);
115 retval = stream_send(rpc->stream, buf->data, buf->size);
117 rpc->backlog -= retval;
118 ofpbuf_pull(buf, retval);
120 list_remove(&buf->list_node);
124 if (retval != -EAGAIN) {
125 VLOG_WARN_RL(&rl, "%s: send error: %s",
126 rpc->name, strerror(-retval));
127 jsonrpc_error(rpc, -retval);
135 jsonrpc_wait(struct jsonrpc *rpc)
138 stream_run_wait(rpc->stream);
139 if (!list_is_empty(&rpc->output)) {
140 stream_send_wait(rpc->stream);
146 * Possible status values:
149 * - EOF: end of file (remote end closed connection; not necessarily an error)
152 jsonrpc_get_status(const struct jsonrpc *rpc)
158 jsonrpc_get_backlog(const struct jsonrpc *rpc)
160 return rpc->status ? 0 : rpc->backlog;
164 jsonrpc_get_name(const struct jsonrpc *rpc)
170 jsonrpc_log_msg(const struct jsonrpc *rpc, const char *title,
171 const struct jsonrpc_msg *msg)
173 if (VLOG_IS_DBG_ENABLED()) {
174 struct ds s = DS_EMPTY_INITIALIZER;
176 ds_put_format(&s, ", method=\"%s\"", msg->method);
179 ds_put_cstr(&s, ", params=");
180 json_to_ds(msg->params, 0, &s);
183 ds_put_cstr(&s, ", result=");
184 json_to_ds(msg->result, 0, &s);
187 ds_put_cstr(&s, ", error=");
188 json_to_ds(msg->error, 0, &s);
191 ds_put_cstr(&s, ", id=");
192 json_to_ds(msg->id, 0, &s);
194 VLOG_DBG("%s: %s %s%s", rpc->name, title,
195 jsonrpc_msg_type_to_string(msg->type), ds_cstr(&s));
200 /* Always takes ownership of 'msg', regardless of success. */
202 jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
210 jsonrpc_msg_destroy(msg);
214 jsonrpc_log_msg(rpc, "send", msg);
216 json = jsonrpc_msg_to_json(msg);
217 s = json_to_string(json, 0);
221 buf = xmalloc(sizeof *buf);
222 ofpbuf_use(buf, s, length);
224 list_push_back(&rpc->output, &buf->list_node);
225 rpc->backlog += length;
227 if (rpc->backlog == length) {
234 jsonrpc_recv(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
241 while (!rpc->received) {
242 if (byteq_is_empty(&rpc->input)) {
246 chunk = byteq_headroom(&rpc->input);
247 retval = stream_recv(rpc->stream, byteq_head(&rpc->input), chunk);
249 if (retval == -EAGAIN) {
252 VLOG_WARN_RL(&rl, "%s: receive error: %s",
253 rpc->name, strerror(-retval));
254 jsonrpc_error(rpc, -retval);
257 } else if (retval == 0) {
258 jsonrpc_error(rpc, EOF);
261 byteq_advance_head(&rpc->input, retval);
266 rpc->parser = json_parser_create(0);
268 n = byteq_tailroom(&rpc->input);
269 used = json_parser_feed(rpc->parser,
270 (char *) byteq_tail(&rpc->input), n);
271 byteq_advance_tail(&rpc->input, used);
272 if (json_parser_is_done(rpc->parser)) {
273 jsonrpc_received(rpc);
275 const struct byteq *q = &rpc->input;
276 if (q->head <= BYTEQ_SIZE) {
277 stream_report_content(q->buffer, q->head,
279 THIS_MODULE, rpc->name);
287 *msgp = rpc->received;
288 rpc->received = NULL;
293 jsonrpc_recv_wait(struct jsonrpc *rpc)
295 if (rpc->status || rpc->received || !byteq_is_empty(&rpc->input)) {
296 (poll_immediate_wake)(rpc->name);
298 stream_recv_wait(rpc->stream);
302 /* Always takes ownership of 'msg', regardless of success. */
304 jsonrpc_send_block(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
310 error = jsonrpc_send(rpc, msg);
317 if (list_is_empty(&rpc->output) || rpc->status) {
326 jsonrpc_recv_block(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
329 int error = jsonrpc_recv(rpc, msgp);
330 if (error != EAGAIN) {
337 jsonrpc_recv_wait(rpc);
342 /* Always takes ownership of 'request', regardless of success. */
344 jsonrpc_transact_block(struct jsonrpc *rpc, struct jsonrpc_msg *request,
345 struct jsonrpc_msg **replyp)
347 struct jsonrpc_msg *reply = NULL;
351 id = json_clone(request->id);
352 error = jsonrpc_send_block(rpc, request);
355 error = jsonrpc_recv_block(rpc, &reply);
359 if ((reply->type == JSONRPC_REPLY || reply->type == JSONRPC_ERROR)
360 && json_equal(id, reply->id)) {
363 jsonrpc_msg_destroy(reply);
366 *replyp = error ? NULL : reply;
372 jsonrpc_received(struct jsonrpc *rpc)
374 struct jsonrpc_msg *msg;
378 json = json_parser_finish(rpc->parser);
380 if (json->type == JSON_STRING) {
381 VLOG_WARN_RL(&rl, "%s: error parsing stream: %s",
382 rpc->name, json_string(json));
383 jsonrpc_error(rpc, EPROTO);
388 error = jsonrpc_msg_from_json(json, &msg);
390 VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
393 jsonrpc_error(rpc, EPROTO);
397 jsonrpc_log_msg(rpc, "received", msg);
402 jsonrpc_error(struct jsonrpc *rpc, int error)
407 jsonrpc_cleanup(rpc);
412 jsonrpc_cleanup(struct jsonrpc *rpc)
414 stream_close(rpc->stream);
417 json_parser_abort(rpc->parser);
420 jsonrpc_msg_destroy(rpc->received);
421 rpc->received = NULL;
423 ofpbuf_list_delete(&rpc->output);
427 static struct jsonrpc_msg *
428 jsonrpc_create(enum jsonrpc_msg_type type, const char *method,
429 struct json *params, struct json *result, struct json *error,
432 struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
434 msg->method = method ? xstrdup(method) : NULL;
435 msg->params = params;
436 msg->result = result;
443 jsonrpc_create_id(void)
445 static unsigned int id;
446 return json_integer_create(id++);
450 jsonrpc_create_request(const char *method, struct json *params,
453 struct json *id = jsonrpc_create_id();
455 *idp = json_clone(id);
457 return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL, id);
461 jsonrpc_create_notify(const char *method, struct json *params)
463 return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
467 jsonrpc_create_reply(struct json *result, const struct json *id)
469 return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
474 jsonrpc_create_error(struct json *error, const struct json *id)
476 return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
481 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
484 case JSONRPC_REQUEST:
488 return "notification";
500 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
502 const char *type_name;
503 unsigned int pattern;
505 if (m->params && m->params->type != JSON_ARRAY) {
506 return xstrdup("\"params\" must be JSON array");
510 case JSONRPC_REQUEST:
527 return xasprintf("invalid JSON-RPC message type %d", m->type);
530 type_name = jsonrpc_msg_type_to_string(m->type);
531 if ((m->method != NULL) != ((pattern & 0x10000) != 0)) {
532 return xasprintf("%s must%s have \"method\"",
533 type_name, (pattern & 0x10000) ? "" : " not");
536 if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
537 return xasprintf("%s must%s have \"params\"",
538 type_name, (pattern & 0x1000) ? "" : " not");
541 if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
542 return xasprintf("%s must%s have \"result\"",
543 type_name, (pattern & 0x100) ? "" : " not");
546 if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
547 return xasprintf("%s must%s have \"error\"",
548 type_name, (pattern & 0x10) ? "" : " not");
551 if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
552 return xasprintf("%s must%s have \"id\"",
553 type_name, (pattern & 0x1) ? "" : " not");
560 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
564 json_destroy(m->params);
565 json_destroy(m->result);
566 json_destroy(m->error);
573 null_from_json_null(struct json *json)
575 if (json && json->type == JSON_NULL) {
583 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
585 struct json *method = NULL;
586 struct jsonrpc_msg *msg = NULL;
587 struct shash *object;
590 if (json->type != JSON_OBJECT) {
591 error = xstrdup("message is not a JSON object");
594 object = json_object(json);
596 method = shash_find_and_delete(object, "method");
597 if (method && method->type != JSON_STRING) {
598 error = xstrdup("method is not a JSON string");
602 msg = xzalloc(sizeof *msg);
603 msg->method = method ? xstrdup(method->u.string) : NULL;
604 msg->params = null_from_json_null(shash_find_and_delete(object, "params"));
605 msg->result = null_from_json_null(shash_find_and_delete(object, "result"));
606 msg->error = null_from_json_null(shash_find_and_delete(object, "error"));
607 msg->id = null_from_json_null(shash_find_and_delete(object, "id"));
608 msg->type = (msg->result ? JSONRPC_REPLY
609 : msg->error ? JSONRPC_ERROR
610 : msg->id ? JSONRPC_REQUEST
612 if (!shash_is_empty(object)) {
613 error = xasprintf("message has unexpected member \"%s\"",
614 shash_first(object)->name);
617 error = jsonrpc_msg_is_valid(msg);
623 json_destroy(method);
626 jsonrpc_msg_destroy(msg);
634 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
636 struct json *json = json_object_create();
639 json_object_put(json, "method", json_string_create_nocopy(m->method));
643 json_object_put(json, "params", m->params);
647 json_object_put(json, "result", m->result);
648 } else if (m->type == JSONRPC_ERROR) {
649 json_object_put(json, "result", json_null_create());
653 json_object_put(json, "error", m->error);
654 } else if (m->type == JSONRPC_REPLY) {
655 json_object_put(json, "error", json_null_create());
659 json_object_put(json, "id", m->id);
660 } else if (m->type == JSONRPC_NOTIFY) {
661 json_object_put(json, "id", json_null_create());
669 /* A JSON-RPC session with reconnection. */
671 struct jsonrpc_session {
672 struct reconnect *reconnect;
674 struct stream *stream;
675 struct pstream *pstream;
679 /* Creates and returns a jsonrpc_session to 'name', which should be a string
680 * acceptable to stream_open() or pstream_open().
682 * If 'name' is an active connection method, e.g. "tcp:127.1.2.3", the new
683 * jsonrpc_session connects and reconnects, with back-off, to 'name'.
685 * If 'name' is a passive connection method, e.g. "ptcp:", the new
686 * jsonrpc_session listens for connections to 'name'. It maintains at most one
687 * connection at any given time. Any new connection causes the previous one
688 * (if any) to be dropped. */
689 struct jsonrpc_session *
690 jsonrpc_session_open(const char *name)
692 struct jsonrpc_session *s;
694 s = xmalloc(sizeof *s);
695 s->reconnect = reconnect_create(time_msec());
696 reconnect_set_name(s->reconnect, name);
697 reconnect_enable(s->reconnect, time_msec());
703 if (!pstream_verify_name(name)) {
704 reconnect_set_passive(s->reconnect, true, time_msec());
710 /* Creates and returns a jsonrpc_session that is initially connected to
711 * 'jsonrpc'. If the connection is dropped, it will not be reconnected.
713 * On the assumption that such connections are likely to be short-lived
714 * (e.g. from ovs-vsctl), informational logging for them is suppressed. */
715 struct jsonrpc_session *
716 jsonrpc_session_open_unreliably(struct jsonrpc *jsonrpc)
718 struct jsonrpc_session *s;
720 s = xmalloc(sizeof *s);
721 s->reconnect = reconnect_create(time_msec());
722 reconnect_set_quiet(s->reconnect, true);
723 reconnect_set_name(s->reconnect, jsonrpc_get_name(jsonrpc));
724 reconnect_set_max_tries(s->reconnect, 0);
725 reconnect_connected(s->reconnect, time_msec());
735 jsonrpc_session_close(struct jsonrpc_session *s)
738 jsonrpc_close(s->rpc);
739 reconnect_destroy(s->reconnect);
740 stream_close(s->stream);
741 pstream_close(s->pstream);
747 jsonrpc_session_disconnect(struct jsonrpc_session *s)
750 jsonrpc_error(s->rpc, EOF);
751 jsonrpc_close(s->rpc);
754 } else if (s->stream) {
755 stream_close(s->stream);
762 jsonrpc_session_connect(struct jsonrpc_session *s)
764 const char *name = reconnect_get_name(s->reconnect);
767 jsonrpc_session_disconnect(s);
768 if (!reconnect_is_passive(s->reconnect)) {
769 error = jsonrpc_stream_open(name, &s->stream);
771 reconnect_connecting(s->reconnect, time_msec());
774 error = s->pstream ? 0 : jsonrpc_pstream_open(name, &s->pstream);
776 reconnect_listening(s->reconnect, time_msec());
781 reconnect_connect_failed(s->reconnect, time_msec(), error);
787 jsonrpc_session_run(struct jsonrpc_session *s)
790 struct stream *stream;
793 error = pstream_accept(s->pstream, &stream);
795 if (s->rpc || s->stream) {
797 "%s: new connection replacing active connection",
798 reconnect_get_name(s->reconnect));
799 jsonrpc_session_disconnect(s);
801 reconnect_connected(s->reconnect, time_msec());
802 s->rpc = jsonrpc_open(stream);
803 } else if (error != EAGAIN) {
804 reconnect_listen_error(s->reconnect, time_msec(), error);
805 pstream_close(s->pstream);
814 error = jsonrpc_get_status(s->rpc);
816 reconnect_disconnected(s->reconnect, time_msec(), error);
817 jsonrpc_session_disconnect(s);
819 } else if (s->stream) {
822 stream_run(s->stream);
823 error = stream_connect(s->stream);
825 reconnect_connected(s->reconnect, time_msec());
826 s->rpc = jsonrpc_open(s->stream);
828 } else if (error != EAGAIN) {
829 reconnect_connect_failed(s->reconnect, time_msec(), error);
830 stream_close(s->stream);
835 switch (reconnect_run(s->reconnect, time_msec())) {
836 case RECONNECT_CONNECT:
837 jsonrpc_session_connect(s);
840 case RECONNECT_DISCONNECT:
841 reconnect_disconnected(s->reconnect, time_msec(), 0);
842 jsonrpc_session_disconnect(s);
845 case RECONNECT_PROBE:
848 struct jsonrpc_msg *request;
850 params = json_array_create_empty();
851 request = jsonrpc_create_request("echo", params, NULL);
852 json_destroy(request->id);
853 request->id = json_string_create("echo");
854 jsonrpc_send(s->rpc, request);
861 jsonrpc_session_wait(struct jsonrpc_session *s)
864 jsonrpc_wait(s->rpc);
865 } else if (s->stream) {
866 stream_run_wait(s->stream);
867 stream_connect_wait(s->stream);
870 pstream_wait(s->pstream);
872 reconnect_wait(s->reconnect, time_msec());
876 jsonrpc_session_get_backlog(const struct jsonrpc_session *s)
878 return s->rpc ? jsonrpc_get_backlog(s->rpc) : 0;
881 /* Always returns a pointer to a valid C string, assuming 's' was initialized
884 jsonrpc_session_get_name(const struct jsonrpc_session *s)
886 return reconnect_get_name(s->reconnect);
889 /* Always takes ownership of 'msg', regardless of success. */
891 jsonrpc_session_send(struct jsonrpc_session *s, struct jsonrpc_msg *msg)
894 return jsonrpc_send(s->rpc, msg);
896 jsonrpc_msg_destroy(msg);
902 jsonrpc_session_recv(struct jsonrpc_session *s)
905 struct jsonrpc_msg *msg;
906 jsonrpc_recv(s->rpc, &msg);
908 reconnect_received(s->reconnect, time_msec());
909 if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
910 /* Echo request. Send reply. */
911 struct jsonrpc_msg *reply;
913 reply = jsonrpc_create_reply(json_clone(msg->params), msg->id);
914 jsonrpc_session_send(s, reply);
915 } else if (msg->type == JSONRPC_REPLY
916 && msg->id && msg->id->type == JSON_STRING
917 && !strcmp(msg->id->u.string, "echo")) {
918 /* It's a reply to our echo request. Suppress it. */
922 jsonrpc_msg_destroy(msg);
929 jsonrpc_session_recv_wait(struct jsonrpc_session *s)
932 jsonrpc_recv_wait(s->rpc);
937 jsonrpc_session_is_alive(const struct jsonrpc_session *s)
939 return s->rpc || s->stream || reconnect_get_max_tries(s->reconnect);
943 jsonrpc_session_is_connected(const struct jsonrpc_session *s)
945 return s->rpc != NULL;
949 jsonrpc_session_get_seqno(const struct jsonrpc_session *s)
955 jsonrpc_session_get_status(const struct jsonrpc_session *s)
957 return s && s->rpc ? jsonrpc_get_status(s->rpc) : 0;
961 jsonrpc_session_get_reconnect_stats(const struct jsonrpc_session *s,
962 struct reconnect_stats *stats)
964 reconnect_get_stats(s->reconnect, time_msec(), stats);
968 jsonrpc_session_force_reconnect(struct jsonrpc_session *s)
970 reconnect_force_reconnect(s->reconnect, time_msec());
974 jsonrpc_session_set_max_backoff(struct jsonrpc_session *s, int max_backoff)
976 reconnect_set_backoff(s->reconnect, 0, max_backoff);
980 jsonrpc_session_set_probe_interval(struct jsonrpc_session *s,
983 reconnect_set_probe_interval(s->reconnect, probe_interval);