]> git.proxmox.com Git - mirror_ovs.git/blob - lib/jsonrpc.c
ovsdb-idl: Remove prototype for function that is not defined or used.
[mirror_ovs.git] / lib / jsonrpc.c
1 /*
2 * Copyright (c) 2009-2017 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 "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"
32 #include "stream.h"
33 #include "svec.h"
34 #include "timeval.h"
35 #include "openvswitch/vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(jsonrpc);
38 \f
39 struct jsonrpc {
40 struct stream *stream;
41 char *name;
42 int status;
43
44 /* Input. */
45 struct byteq input;
46 uint8_t input_buffer[4096];
47 struct json_parser *parser;
48
49 /* Output. */
50 struct ovs_list output; /* Contains "struct ofpbuf"s. */
51 size_t output_count; /* Number of elements in "output". */
52 size_t backlog;
53
54 /* Limits. */
55 size_t max_output; /* 'output_count' disconnection threshold. */
56 size_t max_backlog; /* 'backlog' disconnection threshold. */
57 };
58
59 /* Rate limit for error messages. */
60 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
61
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);
65
66 /* This is just the same as stream_open() except that it uses the default
67 * JSONRPC port if none is specified. */
68 int
69 jsonrpc_stream_open(const char *name, struct stream **streamp, uint8_t dscp)
70 {
71 return stream_open_with_default_port(name, OVSDB_PORT, streamp, dscp);
72 }
73
74 /* This is just the same as pstream_open() except that it uses the default
75 * JSONRPC port if none is specified. */
76 int
77 jsonrpc_pstream_open(const char *name, struct pstream **pstreamp, uint8_t dscp)
78 {
79 return pstream_open_with_default_port(name, OVSDB_PORT, pstreamp, dscp);
80 }
81
82 /* Returns a new JSON-RPC stream that uses 'stream' for input and output. The
83 * new jsonrpc object takes ownership of 'stream'. */
84 struct jsonrpc *
85 jsonrpc_open(struct stream *stream)
86 {
87 struct jsonrpc *rpc;
88
89 ovs_assert(stream != NULL);
90
91 rpc = xzalloc(sizeof *rpc);
92 rpc->name = xstrdup(stream_get_name(stream));
93 rpc->stream = stream;
94 byteq_init(&rpc->input, rpc->input_buffer, sizeof rpc->input_buffer);
95 ovs_list_init(&rpc->output);
96
97 return rpc;
98 }
99
100 /* Destroys 'rpc', closing the stream on which it is based, and frees its
101 * memory. */
102 void
103 jsonrpc_close(struct jsonrpc *rpc)
104 {
105 if (rpc) {
106 jsonrpc_cleanup(rpc);
107 free(rpc->name);
108 free(rpc);
109 }
110 }
111
112 /* Performs periodic maintenance on 'rpc', such as flushing output buffers. */
113 void
114 jsonrpc_run(struct jsonrpc *rpc)
115 {
116 if (rpc->status) {
117 return;
118 }
119
120 stream_run(rpc->stream);
121 while (!ovs_list_is_empty(&rpc->output)) {
122 struct ofpbuf *buf = ofpbuf_from_list(rpc->output.next);
123 int retval;
124
125 retval = stream_send(rpc->stream, buf->data, buf->size);
126 if (retval >= 0) {
127 rpc->backlog -= retval;
128 ofpbuf_pull(buf, retval);
129 if (!buf->size) {
130 ovs_list_remove(&buf->list_node);
131 rpc->output_count--;
132 ofpbuf_delete(buf);
133 }
134 } else {
135 if (retval != -EAGAIN) {
136 VLOG_WARN_RL(&rl, "%s: send error: %s",
137 rpc->name, ovs_strerror(-retval));
138 jsonrpc_error(rpc, -retval);
139 }
140 break;
141 }
142 }
143 }
144
145 /* Arranges for the poll loop to wake up when 'rpc' needs to perform
146 * maintenance activities. */
147 void
148 jsonrpc_wait(struct jsonrpc *rpc)
149 {
150 if (!rpc->status) {
151 stream_run_wait(rpc->stream);
152 if (!ovs_list_is_empty(&rpc->output)) {
153 stream_send_wait(rpc->stream);
154 }
155 }
156 }
157
158 /*
159 * Returns the current status of 'rpc'. The possible return values are:
160 * - 0: no error yet
161 * - >0: errno value
162 * - EOF: end of file (remote end closed connection; not necessarily an error).
163 *
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.
169 */
170 int
171 jsonrpc_get_status(const struct jsonrpc *rpc)
172 {
173 return rpc->status;
174 }
175
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. */
179 size_t
180 jsonrpc_get_backlog(const struct jsonrpc *rpc)
181 {
182 return rpc->status ? 0 : rpc->backlog;
183 }
184
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. */
188 void
189 jsonrpc_set_backlog_threshold(struct jsonrpc *rpc,
190 size_t max_n_msgs, size_t max_backlog_bytes)
191 {
192 rpc->max_output = max_n_msgs;
193 rpc->max_backlog = max_backlog_bytes;
194 }
195
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.) */
198 unsigned int
199 jsonrpc_get_received_bytes(const struct jsonrpc *rpc)
200 {
201 return rpc->input.head;
202 }
203
204 /* Returns 'rpc''s name, that is, the name returned by stream_get_name() for
205 * the stream underlying 'rpc' when 'rpc' was created. */
206 const char *
207 jsonrpc_get_name(const struct jsonrpc *rpc)
208 {
209 return rpc->name;
210 }
211
212 static void
213 jsonrpc_log_msg(const struct jsonrpc *rpc, const char *title,
214 const struct jsonrpc_msg *msg)
215 {
216 if (VLOG_IS_DBG_ENABLED()) {
217 struct ds s = DS_EMPTY_INITIALIZER;
218 if (msg->method) {
219 ds_put_format(&s, ", method=\"%s\"", msg->method);
220 }
221 if (msg->params) {
222 ds_put_cstr(&s, ", params=");
223 json_to_ds(msg->params, 0, &s);
224 }
225 if (msg->result) {
226 ds_put_cstr(&s, ", result=");
227 json_to_ds(msg->result, 0, &s);
228 }
229 if (msg->error) {
230 ds_put_cstr(&s, ", error=");
231 json_to_ds(msg->error, 0, &s);
232 }
233 if (msg->id) {
234 ds_put_cstr(&s, ", id=");
235 json_to_ds(msg->id, 0, &s);
236 }
237 VLOG_DBG("%s: %s %s%s", rpc->name, title,
238 jsonrpc_msg_type_to_string(msg->type), ds_cstr(&s));
239 ds_destroy(&s);
240 }
241 }
242
243 /* Schedules 'msg' to be sent on 'rpc' and returns 'rpc''s status (as with
244 * jsonrpc_get_status()).
245 *
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'.)
250 *
251 * Always takes ownership of 'msg', regardless of success. */
252 int
253 jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
254 {
255 struct ofpbuf *buf;
256 struct json *json;
257 struct ds ds = DS_EMPTY_INITIALIZER;
258 size_t length;
259
260 if (rpc->status) {
261 jsonrpc_msg_destroy(msg);
262 return rpc->status;
263 }
264
265 jsonrpc_log_msg(rpc, "send", msg);
266
267 json = jsonrpc_msg_to_json(msg);
268 json_to_ds(json, 0, &ds);
269 length = ds.length;
270 json_destroy(json);
271
272 buf = xmalloc(sizeof *buf);
273 ofpbuf_use_ds(buf, &ds);
274 ovs_list_push_back(&rpc->output, &buf->list_node);
275 rpc->output_count++;
276 rpc->backlog += length;
277
278 if (rpc->output_count >= 50) {
279 static struct vlog_rate_limit bl_rl = VLOG_RATE_LIMIT_INIT(5, 5);
280 bool disconnect = false;
281
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) {
286 disconnect = true;
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) {
291 disconnect = true;
292 VLOG_WARN("sending backlog exceeded maximum size (%"PRIuSIZE" > %"
293 PRIuSIZE" bytes), disconnecting, jsonrpc: %s.",
294 rpc->backlog, rpc->max_backlog, rpc->name);
295 }
296 if (disconnect) {
297 jsonrpc_error(rpc, E2BIG);
298 }
299 }
300
301 if (rpc->backlog == length) {
302 jsonrpc_run(rpc);
303 }
304 return rpc->status;
305 }
306
307 /* Attempts to receive a message from 'rpc'.
308 *
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().
312 *
313 * Otherwise, stores NULL in '*msgp' and returns one of the following:
314 *
315 * - EAGAIN: No message has been received.
316 *
317 * - EOF: The remote end closed the connection gracefully.
318 *
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.
322 */
323 int
324 jsonrpc_recv(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
325 {
326 int i;
327
328 *msgp = NULL;
329 if (rpc->status) {
330 return rpc->status;
331 }
332
333 for (i = 0; i < 50; i++) {
334 size_t n, used;
335
336 /* Fill our input buffer if it's empty. */
337 if (byteq_is_empty(&rpc->input)) {
338 size_t chunk;
339 int retval;
340
341 chunk = byteq_headroom(&rpc->input);
342 retval = stream_recv(rpc->stream, byteq_head(&rpc->input), chunk);
343 if (retval < 0) {
344 if (retval == -EAGAIN) {
345 return EAGAIN;
346 } else {
347 VLOG_WARN_RL(&rl, "%s: receive error: %s",
348 rpc->name, ovs_strerror(-retval));
349 jsonrpc_error(rpc, -retval);
350 return rpc->status;
351 }
352 } else if (retval == 0) {
353 jsonrpc_error(rpc, EOF);
354 return EOF;
355 }
356 byteq_advance_head(&rpc->input, retval);
357 }
358
359 /* We have some input. Feed it into the JSON parser. */
360 if (!rpc->parser) {
361 rpc->parser = json_parser_create(0);
362 }
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);
367
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);
371 if (*msgp) {
372 return 0;
373 }
374
375 if (rpc->status) {
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);
380 }
381 return rpc->status;
382 }
383 }
384 }
385
386 return EAGAIN;
387 }
388
389 /* Causes the poll loop to wake up when jsonrpc_recv() may return a value other
390 * than EAGAIN. */
391 void
392 jsonrpc_recv_wait(struct jsonrpc *rpc)
393 {
394 if (rpc->status || !byteq_is_empty(&rpc->input)) {
395 poll_immediate_wake_at(rpc->name);
396 } else {
397 stream_recv_wait(rpc->stream);
398 }
399 }
400
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()).
404 *
405 * Always takes ownership of 'msg', regardless of success. */
406 int
407 jsonrpc_send_block(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
408 {
409 int error;
410
411 fatal_signal_run();
412
413 error = jsonrpc_send(rpc, msg);
414 if (error) {
415 return error;
416 }
417
418 for (;;) {
419 jsonrpc_run(rpc);
420 if (ovs_list_is_empty(&rpc->output) || rpc->status) {
421 return rpc->status;
422 }
423 jsonrpc_wait(rpc);
424 poll_block();
425 }
426 }
427
428 /* Waits for a message to be received on 'rpc'. Same semantics as
429 * jsonrpc_recv() except that EAGAIN will never be returned. */
430 int
431 jsonrpc_recv_block(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
432 {
433 for (;;) {
434 int error = jsonrpc_recv(rpc, msgp);
435 if (error != EAGAIN) {
436 fatal_signal_run();
437 return error;
438 }
439
440 jsonrpc_run(rpc);
441 jsonrpc_wait(rpc);
442 jsonrpc_recv_wait(rpc);
443 poll_block();
444 }
445 }
446
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()).
451 *
452 * Discards any message received on 'rpc' that is not a reply to 'request'
453 * (based on message id).
454 *
455 * Always takes ownership of 'request', regardless of success. */
456 int
457 jsonrpc_transact_block(struct jsonrpc *rpc, struct jsonrpc_msg *request,
458 struct jsonrpc_msg **replyp)
459 {
460 struct jsonrpc_msg *reply = NULL;
461 struct json *id;
462 int error;
463
464 id = json_clone(request->id);
465 error = jsonrpc_send_block(rpc, request);
466 if (!error) {
467 for (;;) {
468 error = jsonrpc_recv_block(rpc, &reply);
469 if (error) {
470 break;
471 }
472 if ((reply->type == JSONRPC_REPLY || reply->type == JSONRPC_ERROR)
473 && json_equal(id, reply->id)) {
474 break;
475 }
476 jsonrpc_msg_destroy(reply);
477 }
478 }
479 *replyp = error ? NULL : reply;
480 json_destroy(id);
481 return error;
482 }
483
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)
489 {
490 struct jsonrpc_msg *msg;
491 struct json *json;
492 char *error;
493
494 json = json_parser_finish(rpc->parser);
495 rpc->parser = NULL;
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);
500 json_destroy(json);
501 return NULL;
502 }
503
504 error = jsonrpc_msg_from_json(json, &msg);
505 if (error) {
506 VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
507 rpc->name, error);
508 free(error);
509 jsonrpc_error(rpc, EPROTO);
510 return NULL;
511 }
512
513 jsonrpc_log_msg(rpc, "received", msg);
514 return msg;
515 }
516
517 static void
518 jsonrpc_error(struct jsonrpc *rpc, int error)
519 {
520 ovs_assert(error);
521 if (!rpc->status) {
522 rpc->status = error;
523 jsonrpc_cleanup(rpc);
524 }
525 }
526
527 static void
528 jsonrpc_cleanup(struct jsonrpc *rpc)
529 {
530 stream_close(rpc->stream);
531 rpc->stream = NULL;
532
533 json_parser_abort(rpc->parser);
534 rpc->parser = NULL;
535
536 ofpbuf_list_delete(&rpc->output);
537 rpc->backlog = 0;
538 rpc->output_count = 0;
539 }
540 \f
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,
544 struct json *id)
545 {
546 struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
547 msg->type = type;
548 msg->method = nullable_xstrdup(method);
549 msg->params = params;
550 msg->result = result;
551 msg->error = error;
552 msg->id = id;
553 return msg;
554 }
555
556 static struct json *
557 jsonrpc_create_id(void)
558 {
559 static atomic_count next_id = ATOMIC_COUNT_INIT(0);
560 unsigned int id;
561
562 id = atomic_count_inc(&next_id);
563 return json_integer_create(id);
564 }
565
566 struct jsonrpc_msg *
567 jsonrpc_create_request(const char *method, struct json *params,
568 struct json **idp)
569 {
570 struct json *id = jsonrpc_create_id();
571 if (idp) {
572 *idp = json_clone(id);
573 }
574 return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL, id);
575 }
576
577 struct jsonrpc_msg *
578 jsonrpc_create_notify(const char *method, struct json *params)
579 {
580 return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
581 }
582
583 struct jsonrpc_msg *
584 jsonrpc_create_reply(struct json *result, const struct json *id)
585 {
586 return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
587 json_clone(id));
588 }
589
590 struct jsonrpc_msg *
591 jsonrpc_create_error(struct json *error, const struct json *id)
592 {
593 return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
594 json_clone(id));
595 }
596
597 struct jsonrpc_msg *
598 jsonrpc_msg_clone(const struct jsonrpc_msg *old)
599 {
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));
605 }
606
607 const char *
608 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
609 {
610 switch (type) {
611 case JSONRPC_REQUEST:
612 return "request";
613
614 case JSONRPC_NOTIFY:
615 return "notification";
616
617 case JSONRPC_REPLY:
618 return "reply";
619
620 case JSONRPC_ERROR:
621 return "error";
622 }
623 return "(null)";
624 }
625
626 char *
627 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
628 {
629 const char *type_name;
630 unsigned int pattern;
631
632 if (m->params && m->params->type != JSON_ARRAY) {
633 return xstrdup("\"params\" must be JSON array");
634 }
635
636 switch (m->type) {
637 case JSONRPC_REQUEST:
638 pattern = 0x11001;
639 break;
640
641 case JSONRPC_NOTIFY:
642 pattern = 0x11000;
643 break;
644
645 case JSONRPC_REPLY:
646 pattern = 0x00101;
647 break;
648
649 case JSONRPC_ERROR:
650 pattern = 0x00011;
651 break;
652
653 default:
654 return xasprintf("invalid JSON-RPC message type %d", m->type);
655 }
656
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");
661
662 }
663 if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
664 return xasprintf("%s must%s have \"params\"",
665 type_name, (pattern & 0x1000) ? "" : " not");
666
667 }
668 if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
669 return xasprintf("%s must%s have \"result\"",
670 type_name, (pattern & 0x100) ? "" : " not");
671
672 }
673 if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
674 return xasprintf("%s must%s have \"error\"",
675 type_name, (pattern & 0x10) ? "" : " not");
676
677 }
678 if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
679 return xasprintf("%s must%s have \"id\"",
680 type_name, (pattern & 0x1) ? "" : " not");
681
682 }
683 return NULL;
684 }
685
686 void
687 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
688 {
689 if (m) {
690 free(m->method);
691 json_destroy(m->params);
692 json_destroy(m->result);
693 json_destroy(m->error);
694 json_destroy(m->id);
695 free(m);
696 }
697 }
698
699 static struct json *
700 null_from_json_null(struct json *json)
701 {
702 if (json && json->type == JSON_NULL) {
703 json_destroy(json);
704 return NULL;
705 }
706 return json;
707 }
708
709 char *
710 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
711 {
712 struct json *method = NULL;
713 struct jsonrpc_msg *msg = NULL;
714 struct shash *object;
715 char *error;
716
717 if (json->type != JSON_OBJECT) {
718 error = xstrdup("message is not a JSON object");
719 goto exit;
720 }
721 object = json_object(json);
722
723 method = shash_find_and_delete(object, "method");
724 if (method && method->type != JSON_STRING) {
725 error = xstrdup("method is not a JSON string");
726 goto exit;
727 }
728
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
738 : JSONRPC_NOTIFY);
739 if (!shash_is_empty(object)) {
740 error = xasprintf("message has unexpected member \"%s\"",
741 shash_first(object)->name);
742 goto exit;
743 }
744 error = jsonrpc_msg_is_valid(msg);
745 if (error) {
746 goto exit;
747 }
748
749 exit:
750 json_destroy(method);
751 json_destroy(json);
752 if (error) {
753 jsonrpc_msg_destroy(msg);
754 msg = NULL;
755 }
756 *msgp = msg;
757 return error;
758 }
759
760 /* Returns 'm' converted to JSON suitable for sending as a JSON-RPC message.
761 *
762 * Consumes and destroys 'm'. */
763 struct json *
764 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
765 {
766 struct json *json = json_object_create();
767
768 if (m->method) {
769 json_object_put(json, "method", json_string_create_nocopy(m->method));
770 }
771
772 if (m->params) {
773 json_object_put(json, "params", m->params);
774 }
775
776 if (m->result) {
777 json_object_put(json, "result", m->result);
778 } else if (m->type == JSONRPC_ERROR) {
779 json_object_put(json, "result", json_null_create());
780 }
781
782 if (m->error) {
783 json_object_put(json, "error", m->error);
784 } else if (m->type == JSONRPC_REPLY) {
785 json_object_put(json, "error", json_null_create());
786 }
787
788 if (m->id) {
789 json_object_put(json, "id", m->id);
790 } else if (m->type == JSONRPC_NOTIFY) {
791 json_object_put(json, "id", json_null_create());
792 }
793
794 free(m);
795
796 return json;
797 }
798
799 char *
800 jsonrpc_msg_to_string(const struct jsonrpc_msg *m)
801 {
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);
805 json_destroy(json);
806 return s;
807 }
808 \f
809 /* A JSON-RPC session with reconnection. */
810
811 struct jsonrpc_session {
812 struct svec remotes;
813 size_t next_remote;
814
815 struct reconnect *reconnect;
816 struct jsonrpc *rpc;
817 struct stream *stream;
818 struct pstream *pstream;
819 int last_error;
820 unsigned int seqno;
821 uint8_t dscp;
822
823 /* Limits for jsonrpc. */
824 size_t max_n_msgs;
825 size_t max_backlog_bytes;
826 };
827
828 static void
829 jsonrpc_session_pick_remote(struct jsonrpc_session *s)
830 {
831 reconnect_set_name(s->reconnect,
832 s->remotes.names[s->next_remote++ % s->remotes.n]);
833 }
834
835 /* Creates and returns a jsonrpc_session to 'name', which should be a string
836 * acceptable to stream_open() or pstream_open().
837 *
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
843 * the new session.
844 *
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)
851 {
852 const struct svec remotes = { .names = (char **) &name, .n = 1 };
853 return jsonrpc_session_open_multiple(&remotes, retry);
854 }
855
856 struct jsonrpc_session *
857 jsonrpc_session_open_multiple(const struct svec *remotes, bool retry)
858 {
859 struct jsonrpc_session *s;
860
861 s = xmalloc(sizeof *s);
862
863 /* Set 'n' remotes from 'names'. */
864 svec_clone(&s->remotes, remotes);
865 if (!s->remotes.n) {
866 svec_add(&s->remotes, "invalid:");
867 }
868 s->next_remote = 0;
869
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);
874 s->rpc = NULL;
875 s->stream = NULL;
876 s->pstream = NULL;
877 s->seqno = 0;
878 s->dscp = 0;
879 s->last_error = 0;
880
881 jsonrpc_session_set_backlog_threshold(s, 0, 0);
882
883 const char *name = reconnect_get_name(s->reconnect);
884 if (!pstream_verify_name(name)) {
885 reconnect_set_passive(s->reconnect, true, time_msec());
886 } else if (!retry) {
887 reconnect_set_max_tries(s->reconnect, remotes->n);
888 reconnect_set_backoff(s->reconnect, INT_MAX, INT_MAX);
889 }
890
891 if (!stream_or_pstream_needs_probes(name)) {
892 reconnect_set_probe_interval(s->reconnect, 0);
893 }
894
895 return s;
896 }
897
898 /* Creates and returns a jsonrpc_session that is initially connected to
899 * 'jsonrpc'. If the connection is dropped, it will not be reconnected.
900 *
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)
905 {
906 struct jsonrpc_session *s;
907
908 s = xmalloc(sizeof *s);
909 svec_init(&s->remotes);
910 svec_add(&s->remotes, jsonrpc_get_name(jsonrpc));
911 s->next_remote = 0;
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());
917 s->dscp = dscp;
918 s->rpc = jsonrpc;
919 s->stream = NULL;
920 s->pstream = NULL;
921 s->seqno = 1;
922
923 jsonrpc_session_set_backlog_threshold(s, 0, 0);
924 return s;
925 }
926
927 void
928 jsonrpc_session_close(struct jsonrpc_session *s)
929 {
930 if (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);
936 free(s);
937 }
938 }
939
940 struct jsonrpc *
941 jsonrpc_session_steal(struct jsonrpc_session *s)
942 {
943 struct jsonrpc *rpc = s->rpc;
944 s->rpc = NULL;
945 jsonrpc_session_close(s);
946 return rpc;
947 }
948
949 static void
950 jsonrpc_session_disconnect(struct jsonrpc_session *s)
951 {
952 if (s->rpc) {
953 jsonrpc_error(s->rpc, EOF);
954 jsonrpc_close(s->rpc);
955 s->rpc = NULL;
956 } else if (s->stream) {
957 stream_close(s->stream);
958 s->stream = NULL;
959 } else {
960 return;
961 }
962
963 s->seqno++;
964 jsonrpc_session_pick_remote(s);
965 }
966
967 static void
968 jsonrpc_session_connect(struct jsonrpc_session *s)
969 {
970 const char *name = reconnect_get_name(s->reconnect);
971 int error;
972
973 jsonrpc_session_disconnect(s);
974 if (!reconnect_is_passive(s->reconnect)) {
975 error = jsonrpc_stream_open(name, &s->stream, s->dscp);
976 if (!error) {
977 reconnect_connecting(s->reconnect, time_msec());
978 } else {
979 s->last_error = error;
980 }
981 } else {
982 error = s->pstream ? 0 : jsonrpc_pstream_open(name, &s->pstream,
983 s->dscp);
984 if (!error) {
985 reconnect_listening(s->reconnect, time_msec());
986 }
987 }
988
989 if (error) {
990 reconnect_connect_failed(s->reconnect, time_msec(), error);
991 jsonrpc_session_pick_remote(s);
992 }
993 }
994
995 void
996 jsonrpc_session_run(struct jsonrpc_session *s)
997 {
998 if (s->pstream) {
999 struct stream *stream;
1000 int error;
1001
1002 error = pstream_accept(s->pstream, &stream);
1003 if (!error) {
1004 if (s->rpc || s->stream) {
1005 VLOG_INFO_RL(&rl,
1006 "%s: new connection replacing active connection",
1007 reconnect_get_name(s->reconnect));
1008 jsonrpc_session_disconnect(s);
1009 }
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);
1014 s->seqno++;
1015 } else if (error != EAGAIN) {
1016 reconnect_listen_error(s->reconnect, time_msec(), error);
1017 pstream_close(s->pstream);
1018 s->pstream = NULL;
1019 }
1020 }
1021
1022 if (s->rpc) {
1023 size_t backlog;
1024 int error;
1025
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.)
1031 *
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.
1036 */
1037 reconnect_activity(s->reconnect, time_msec());
1038 }
1039
1040 error = jsonrpc_get_status(s->rpc);
1041 if (error) {
1042 reconnect_disconnected(s->reconnect, time_msec(), error);
1043 jsonrpc_session_disconnect(s);
1044 s->last_error = error;
1045 }
1046 } else if (s->stream) {
1047 int error;
1048
1049 stream_run(s->stream);
1050 error = stream_connect(s->stream);
1051 if (!error) {
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);
1056 s->stream = NULL;
1057 s->seqno++;
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);
1062 s->stream = NULL;
1063 s->last_error = error;
1064 }
1065 }
1066
1067 switch (reconnect_run(s->reconnect, time_msec())) {
1068 case RECONNECT_CONNECT:
1069 jsonrpc_session_connect(s);
1070 break;
1071
1072 case RECONNECT_DISCONNECT:
1073 reconnect_disconnected(s->reconnect, time_msec(), 0);
1074 jsonrpc_session_disconnect(s);
1075 break;
1076
1077 case RECONNECT_PROBE:
1078 if (s->rpc) {
1079 struct json *params;
1080 struct jsonrpc_msg *request;
1081
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);
1087 }
1088 break;
1089 }
1090 }
1091
1092 void
1093 jsonrpc_session_wait(struct jsonrpc_session *s)
1094 {
1095 if (s->rpc) {
1096 jsonrpc_wait(s->rpc);
1097 } else if (s->stream) {
1098 stream_run_wait(s->stream);
1099 stream_connect_wait(s->stream);
1100 }
1101 if (s->pstream) {
1102 pstream_wait(s->pstream);
1103 }
1104 reconnect_wait(s->reconnect, time_msec());
1105 }
1106
1107 size_t
1108 jsonrpc_session_get_backlog(const struct jsonrpc_session *s)
1109 {
1110 return s->rpc ? jsonrpc_get_backlog(s->rpc) : 0;
1111 }
1112
1113 /* Always returns a pointer to a valid C string, assuming 's' was initialized
1114 * correctly. */
1115 const char *
1116 jsonrpc_session_get_name(const struct jsonrpc_session *s)
1117 {
1118 return reconnect_get_name(s->reconnect);
1119 }
1120
1121 const char *
1122 jsonrpc_session_get_id(const struct jsonrpc_session *s)
1123 {
1124 if (s->rpc && s->rpc->stream) {
1125 return stream_get_peer_id(s->rpc->stream);
1126 } else {
1127 return NULL;
1128 }
1129 }
1130
1131 size_t
1132 jsonrpc_session_get_n_remotes(const struct jsonrpc_session *s)
1133 {
1134 return s->remotes.n;
1135 }
1136
1137 /* Always takes ownership of 'msg', regardless of success. */
1138 int
1139 jsonrpc_session_send(struct jsonrpc_session *s, struct jsonrpc_msg *msg)
1140 {
1141 if (s->rpc) {
1142 return jsonrpc_send(s->rpc, msg);
1143 } else {
1144 jsonrpc_msg_destroy(msg);
1145 return ENOTCONN;
1146 }
1147 }
1148
1149 struct jsonrpc_msg *
1150 jsonrpc_session_recv(struct jsonrpc_session *s)
1151 {
1152 if (s->rpc) {
1153 unsigned int received_bytes;
1154 struct jsonrpc_msg *msg;
1155
1156 received_bytes = jsonrpc_get_received_bytes(s->rpc);
1157 jsonrpc_recv(s->rpc, &msg);
1158
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.
1163 *
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);
1168 }
1169
1170 if (msg) {
1171 if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
1172 /* Echo request. Send reply. */
1173 struct jsonrpc_msg *reply;
1174
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. */
1181 } else {
1182 return msg;
1183 }
1184 jsonrpc_msg_destroy(msg);
1185 }
1186 }
1187 return NULL;
1188 }
1189
1190 void
1191 jsonrpc_session_recv_wait(struct jsonrpc_session *s)
1192 {
1193 if (s->rpc) {
1194 jsonrpc_recv_wait(s->rpc);
1195 }
1196 }
1197
1198 /* Returns true if 's' is currently connected or trying to connect. */
1199 bool
1200 jsonrpc_session_is_alive(const struct jsonrpc_session *s)
1201 {
1202 return s->rpc || s->stream || reconnect_get_max_tries(s->reconnect);
1203 }
1204
1205 /* Returns true if 's' is currently connected. */
1206 bool
1207 jsonrpc_session_is_connected(const struct jsonrpc_session *s)
1208 {
1209 return s->rpc != NULL;
1210 }
1211
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. */
1216 unsigned int
1217 jsonrpc_session_get_seqno(const struct jsonrpc_session *s)
1218 {
1219 return s->seqno;
1220 }
1221
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(). */
1225 int
1226 jsonrpc_session_get_status(const struct jsonrpc_session *s)
1227 {
1228 return s && s->rpc ? jsonrpc_get_status(s->rpc) : 0;
1229 }
1230
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. */
1234 int
1235 jsonrpc_session_get_last_error(const struct jsonrpc_session *s)
1236 {
1237 return s->last_error;
1238 }
1239
1240 /* Populates 'stats' with statistics from 's'. */
1241 void
1242 jsonrpc_session_get_reconnect_stats(const struct jsonrpc_session *s,
1243 struct reconnect_stats *stats)
1244 {
1245 reconnect_get_stats(s->reconnect, time_msec(), stats);
1246 }
1247
1248 /* Enables 's' to reconnect to the peer if the connection drops. */
1249 void
1250 jsonrpc_session_enable_reconnect(struct jsonrpc_session *s)
1251 {
1252 reconnect_set_max_tries(s->reconnect, UINT_MAX);
1253 reconnect_set_backoff(s->reconnect, RECONNECT_DEFAULT_MIN_BACKOFF,
1254 RECONNECT_DEFAULT_MAX_BACKOFF);
1255 }
1256
1257 /* Forces 's' to drop its connection (if any) and reconnect. */
1258 void
1259 jsonrpc_session_force_reconnect(struct jsonrpc_session *s)
1260 {
1261 reconnect_force_reconnect(s->reconnect, time_msec());
1262 }
1263
1264 /* Sets 'max_backoff' as the maximum time, in milliseconds, to wait after a
1265 * connection attempt fails before attempting to connect again. */
1266 void
1267 jsonrpc_session_set_max_backoff(struct jsonrpc_session *s, int max_backoff)
1268 {
1269 reconnect_set_backoff(s->reconnect, 0, max_backoff);
1270 }
1271
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
1277 * enabled). */
1278 void
1279 jsonrpc_session_set_probe_interval(struct jsonrpc_session *s,
1280 int probe_interval)
1281 {
1282 reconnect_set_probe_interval(s->reconnect, probe_interval);
1283 }
1284
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. */
1288 void
1289 jsonrpc_session_set_dscp(struct jsonrpc_session *s, uint8_t dscp)
1290 {
1291 if (s->dscp != dscp) {
1292 pstream_close(s->pstream);
1293 s->pstream = NULL;
1294
1295 s->dscp = dscp;
1296 jsonrpc_session_force_reconnect(s);
1297 }
1298 }
1299
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). */
1303 void
1304 jsonrpc_session_set_backlog_threshold(struct jsonrpc_session *s,
1305 size_t max_n_msgs,
1306 size_t max_backlog_bytes)
1307 {
1308 s->max_n_msgs = max_n_msgs;
1309 s->max_backlog_bytes = max_backlog_bytes;
1310 if (s->rpc) {
1311 jsonrpc_set_backlog_threshold(s->rpc, max_n_msgs, max_backlog_bytes);
1312 }
1313 }