]> git.proxmox.com Git - mirror_ovs.git/blob - lib/jsonrpc.c
Replace most uses of assert by ovs_assert.
[mirror_ovs.git] / lib / jsonrpc.c
1 /*
2 * Copyright (c) 2009, 2010, 2011, 2012 Nicira, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <config.h>
18
19 #include "jsonrpc.h"
20
21 #include <errno.h>
22
23 #include "byteq.h"
24 #include "dynamic-string.h"
25 #include "fatal-signal.h"
26 #include "json.h"
27 #include "list.h"
28 #include "ofpbuf.h"
29 #include "poll-loop.h"
30 #include "reconnect.h"
31 #include "stream.h"
32 #include "timeval.h"
33 #include "vlog.h"
34
35 VLOG_DEFINE_THIS_MODULE(jsonrpc);
36 \f
37 struct jsonrpc {
38 struct stream *stream;
39 char *name;
40 int status;
41
42 /* Input. */
43 struct byteq input;
44 struct json_parser *parser;
45 struct jsonrpc_msg *received;
46
47 /* Output. */
48 struct list output; /* Contains "struct ofpbuf"s. */
49 size_t backlog;
50 };
51
52 /* Rate limit for error messages. */
53 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
54
55 static void jsonrpc_received(struct jsonrpc *);
56 static void jsonrpc_cleanup(struct jsonrpc *);
57 static void jsonrpc_error(struct jsonrpc *, int error);
58
59 /* This is just the same as stream_open() except that it uses the default
60 * JSONRPC ports if none is specified. */
61 int
62 jsonrpc_stream_open(const char *name, struct stream **streamp, uint8_t dscp)
63 {
64 return stream_open_with_default_ports(name, JSONRPC_TCP_PORT,
65 JSONRPC_SSL_PORT, streamp,
66 dscp);
67 }
68
69 /* This is just the same as pstream_open() except that it uses the default
70 * JSONRPC ports if none is specified. */
71 int
72 jsonrpc_pstream_open(const char *name, struct pstream **pstreamp, uint8_t dscp)
73 {
74 return pstream_open_with_default_ports(name, JSONRPC_TCP_PORT,
75 JSONRPC_SSL_PORT, pstreamp, dscp);
76 }
77
78 /* Returns a new JSON-RPC stream that uses 'stream' for input and output. The
79 * new jsonrpc object takes ownership of 'stream'. */
80 struct jsonrpc *
81 jsonrpc_open(struct stream *stream)
82 {
83 struct jsonrpc *rpc;
84
85 ovs_assert(stream != NULL);
86
87 rpc = xzalloc(sizeof *rpc);
88 rpc->name = xstrdup(stream_get_name(stream));
89 rpc->stream = stream;
90 byteq_init(&rpc->input);
91 list_init(&rpc->output);
92
93 return rpc;
94 }
95
96 /* Destroys 'rpc', closing the stream on which it is based, and frees its
97 * memory. */
98 void
99 jsonrpc_close(struct jsonrpc *rpc)
100 {
101 if (rpc) {
102 jsonrpc_cleanup(rpc);
103 free(rpc->name);
104 free(rpc);
105 }
106 }
107
108 /* Performs periodic maintenance on 'rpc', such as flushing output buffers. */
109 void
110 jsonrpc_run(struct jsonrpc *rpc)
111 {
112 if (rpc->status) {
113 return;
114 }
115
116 stream_run(rpc->stream);
117 while (!list_is_empty(&rpc->output)) {
118 struct ofpbuf *buf = ofpbuf_from_list(rpc->output.next);
119 int retval;
120
121 retval = stream_send(rpc->stream, buf->data, buf->size);
122 if (retval >= 0) {
123 rpc->backlog -= retval;
124 ofpbuf_pull(buf, retval);
125 if (!buf->size) {
126 list_remove(&buf->list_node);
127 ofpbuf_delete(buf);
128 }
129 } else {
130 if (retval != -EAGAIN) {
131 VLOG_WARN_RL(&rl, "%s: send error: %s",
132 rpc->name, strerror(-retval));
133 jsonrpc_error(rpc, -retval);
134 }
135 break;
136 }
137 }
138 }
139
140 /* Arranges for the poll loop to wake up when 'rpc' needs to perform
141 * maintenance activities. */
142 void
143 jsonrpc_wait(struct jsonrpc *rpc)
144 {
145 if (!rpc->status) {
146 stream_run_wait(rpc->stream);
147 if (!list_is_empty(&rpc->output)) {
148 stream_send_wait(rpc->stream);
149 }
150 }
151 }
152
153 /*
154 * Returns the current status of 'rpc'. The possible return values are:
155 * - 0: no error yet
156 * - >0: errno value
157 * - EOF: end of file (remote end closed connection; not necessarily an error).
158 *
159 * When this functions nonzero, 'rpc' is effectively out of commission. 'rpc'
160 * will not receive any more messages and any further messages that one
161 * attempts to send with 'rpc' will be discarded. The caller can keep 'rpc'
162 * around as long as it wants, but it's not going to provide any more useful
163 * services.
164 */
165 int
166 jsonrpc_get_status(const struct jsonrpc *rpc)
167 {
168 return rpc->status;
169 }
170
171 /* Returns the number of bytes buffered by 'rpc' to be written to the
172 * underlying stream. Always returns 0 if 'rpc' has encountered an error or if
173 * the remote end closed the connection. */
174 size_t
175 jsonrpc_get_backlog(const struct jsonrpc *rpc)
176 {
177 return rpc->status ? 0 : rpc->backlog;
178 }
179
180 /* Returns the number of bytes that have been received on 'rpc''s underlying
181 * stream. (The value wraps around if it exceeds UINT_MAX.) */
182 unsigned int
183 jsonrpc_get_received_bytes(const struct jsonrpc *rpc)
184 {
185 return rpc->input.head;
186 }
187
188 /* Returns 'rpc''s name, that is, the name returned by stream_get_name() for
189 * the stream underlying 'rpc' when 'rpc' was created. */
190 const char *
191 jsonrpc_get_name(const struct jsonrpc *rpc)
192 {
193 return rpc->name;
194 }
195
196 static void
197 jsonrpc_log_msg(const struct jsonrpc *rpc, const char *title,
198 const struct jsonrpc_msg *msg)
199 {
200 if (VLOG_IS_DBG_ENABLED()) {
201 struct ds s = DS_EMPTY_INITIALIZER;
202 if (msg->method) {
203 ds_put_format(&s, ", method=\"%s\"", msg->method);
204 }
205 if (msg->params) {
206 ds_put_cstr(&s, ", params=");
207 json_to_ds(msg->params, 0, &s);
208 }
209 if (msg->result) {
210 ds_put_cstr(&s, ", result=");
211 json_to_ds(msg->result, 0, &s);
212 }
213 if (msg->error) {
214 ds_put_cstr(&s, ", error=");
215 json_to_ds(msg->error, 0, &s);
216 }
217 if (msg->id) {
218 ds_put_cstr(&s, ", id=");
219 json_to_ds(msg->id, 0, &s);
220 }
221 VLOG_DBG("%s: %s %s%s", rpc->name, title,
222 jsonrpc_msg_type_to_string(msg->type), ds_cstr(&s));
223 ds_destroy(&s);
224 }
225 }
226
227 /* Schedules 'msg' to be sent on 'rpc' and returns 'rpc''s status (as with
228 * jsonrpc_get_status()).
229 *
230 * If 'msg' cannot be sent immediately, it is appended to a buffer. The caller
231 * is responsible for ensuring that the amount of buffered data is somehow
232 * limited. (jsonrpc_get_backlog() returns the amount of data currently
233 * buffered in 'rpc'.)
234 *
235 * Always takes ownership of 'msg', regardless of success. */
236 int
237 jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
238 {
239 struct ofpbuf *buf;
240 struct json *json;
241 size_t length;
242 char *s;
243
244 if (rpc->status) {
245 jsonrpc_msg_destroy(msg);
246 return rpc->status;
247 }
248
249 jsonrpc_log_msg(rpc, "send", msg);
250
251 json = jsonrpc_msg_to_json(msg);
252 s = json_to_string(json, 0);
253 length = strlen(s);
254 json_destroy(json);
255
256 buf = xmalloc(sizeof *buf);
257 ofpbuf_use(buf, s, length);
258 buf->size = length;
259 list_push_back(&rpc->output, &buf->list_node);
260 rpc->backlog += length;
261
262 if (rpc->backlog == length) {
263 jsonrpc_run(rpc);
264 }
265 return rpc->status;
266 }
267
268 /* Attempts to receive a message from 'rpc'.
269 *
270 * If successful, stores the received message in '*msgp' and returns 0. The
271 * caller takes ownership of '*msgp' and must eventually destroy it with
272 * jsonrpc_msg_destroy().
273 *
274 * Otherwise, stores NULL in '*msgp' and returns one of the following:
275 *
276 * - EAGAIN: No message has been received.
277 *
278 * - EOF: The remote end closed the connection gracefully.
279 *
280 * - Otherwise an errno value that represents a JSON-RPC protocol violation
281 * or another error fatal to the connection. 'rpc' will not send or
282 * receive any more messages.
283 */
284 int
285 jsonrpc_recv(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
286 {
287 int i;
288
289 *msgp = NULL;
290 if (rpc->status) {
291 return rpc->status;
292 }
293
294 for (i = 0; i < 50; i++) {
295 if (rpc->received) {
296 *msgp = rpc->received;
297 rpc->received = NULL;
298 return 0;
299 } else if (byteq_is_empty(&rpc->input)) {
300 size_t chunk;
301 int retval;
302
303 chunk = byteq_headroom(&rpc->input);
304 retval = stream_recv(rpc->stream, byteq_head(&rpc->input), chunk);
305 if (retval < 0) {
306 if (retval == -EAGAIN) {
307 return EAGAIN;
308 } else {
309 VLOG_WARN_RL(&rl, "%s: receive error: %s",
310 rpc->name, strerror(-retval));
311 jsonrpc_error(rpc, -retval);
312 return rpc->status;
313 }
314 } else if (retval == 0) {
315 jsonrpc_error(rpc, EOF);
316 return EOF;
317 }
318 byteq_advance_head(&rpc->input, retval);
319 } else {
320 size_t n, used;
321
322 if (!rpc->parser) {
323 rpc->parser = json_parser_create(0);
324 }
325 n = byteq_tailroom(&rpc->input);
326 used = json_parser_feed(rpc->parser,
327 (char *) byteq_tail(&rpc->input), n);
328 byteq_advance_tail(&rpc->input, used);
329 if (json_parser_is_done(rpc->parser)) {
330 jsonrpc_received(rpc);
331 if (rpc->status) {
332 const struct byteq *q = &rpc->input;
333 if (q->head <= BYTEQ_SIZE) {
334 stream_report_content(q->buffer, q->head,
335 STREAM_JSONRPC,
336 THIS_MODULE, rpc->name);
337 }
338 return rpc->status;
339 }
340 }
341 }
342 }
343
344 return EAGAIN;
345 }
346
347 /* Causes the poll loop to wake up when jsonrpc_recv() may return a value other
348 * than EAGAIN. */
349 void
350 jsonrpc_recv_wait(struct jsonrpc *rpc)
351 {
352 if (rpc->status || rpc->received || !byteq_is_empty(&rpc->input)) {
353 (poll_immediate_wake)(rpc->name);
354 } else {
355 stream_recv_wait(rpc->stream);
356 }
357 }
358
359 /* Sends 'msg' on 'rpc' and waits for it to be successfully queued to the
360 * underlying stream. Returns 0 if 'msg' was sent successfully, otherwise a
361 * status value (see jsonrpc_get_status()).
362 *
363 * Always takes ownership of 'msg', regardless of success. */
364 int
365 jsonrpc_send_block(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
366 {
367 int error;
368
369 fatal_signal_run();
370
371 error = jsonrpc_send(rpc, msg);
372 if (error) {
373 return error;
374 }
375
376 for (;;) {
377 jsonrpc_run(rpc);
378 if (list_is_empty(&rpc->output) || rpc->status) {
379 return rpc->status;
380 }
381 jsonrpc_wait(rpc);
382 poll_block();
383 }
384 }
385
386 /* Waits for a message to be received on 'rpc'. Same semantics as
387 * jsonrpc_recv() except that EAGAIN will never be returned. */
388 int
389 jsonrpc_recv_block(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
390 {
391 for (;;) {
392 int error = jsonrpc_recv(rpc, msgp);
393 if (error != EAGAIN) {
394 fatal_signal_run();
395 return error;
396 }
397
398 jsonrpc_run(rpc);
399 jsonrpc_wait(rpc);
400 jsonrpc_recv_wait(rpc);
401 poll_block();
402 }
403 }
404
405 /* Sends 'request' to 'rpc' then waits for a reply. The return value is 0 if
406 * successful, in which case '*replyp' is set to the reply, which the caller
407 * must eventually free with jsonrpc_msg_destroy(). Otherwise returns a status
408 * value (see jsonrpc_get_status()).
409 *
410 * Discards any message received on 'rpc' that is not a reply to 'request'
411 * (based on message id).
412 *
413 * Always takes ownership of 'request', regardless of success. */
414 int
415 jsonrpc_transact_block(struct jsonrpc *rpc, struct jsonrpc_msg *request,
416 struct jsonrpc_msg **replyp)
417 {
418 struct jsonrpc_msg *reply = NULL;
419 struct json *id;
420 int error;
421
422 id = json_clone(request->id);
423 error = jsonrpc_send_block(rpc, request);
424 if (!error) {
425 for (;;) {
426 error = jsonrpc_recv_block(rpc, &reply);
427 if (error) {
428 break;
429 }
430 if ((reply->type == JSONRPC_REPLY || reply->type == JSONRPC_ERROR)
431 && json_equal(id, reply->id)) {
432 break;
433 }
434 jsonrpc_msg_destroy(reply);
435 }
436 }
437 *replyp = error ? NULL : reply;
438 json_destroy(id);
439 return error;
440 }
441
442 static void
443 jsonrpc_received(struct jsonrpc *rpc)
444 {
445 struct jsonrpc_msg *msg;
446 struct json *json;
447 char *error;
448
449 json = json_parser_finish(rpc->parser);
450 rpc->parser = NULL;
451 if (json->type == JSON_STRING) {
452 VLOG_WARN_RL(&rl, "%s: error parsing stream: %s",
453 rpc->name, json_string(json));
454 jsonrpc_error(rpc, EPROTO);
455 json_destroy(json);
456 return;
457 }
458
459 error = jsonrpc_msg_from_json(json, &msg);
460 if (error) {
461 VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
462 rpc->name, error);
463 free(error);
464 jsonrpc_error(rpc, EPROTO);
465 return;
466 }
467
468 jsonrpc_log_msg(rpc, "received", msg);
469 rpc->received = msg;
470 }
471
472 static void
473 jsonrpc_error(struct jsonrpc *rpc, int error)
474 {
475 ovs_assert(error);
476 if (!rpc->status) {
477 rpc->status = error;
478 jsonrpc_cleanup(rpc);
479 }
480 }
481
482 static void
483 jsonrpc_cleanup(struct jsonrpc *rpc)
484 {
485 stream_close(rpc->stream);
486 rpc->stream = NULL;
487
488 json_parser_abort(rpc->parser);
489 rpc->parser = NULL;
490
491 jsonrpc_msg_destroy(rpc->received);
492 rpc->received = NULL;
493
494 ofpbuf_list_delete(&rpc->output);
495 rpc->backlog = 0;
496 }
497 \f
498 static struct jsonrpc_msg *
499 jsonrpc_create(enum jsonrpc_msg_type type, const char *method,
500 struct json *params, struct json *result, struct json *error,
501 struct json *id)
502 {
503 struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
504 msg->type = type;
505 msg->method = method ? xstrdup(method) : NULL;
506 msg->params = params;
507 msg->result = result;
508 msg->error = error;
509 msg->id = id;
510 return msg;
511 }
512
513 static struct json *
514 jsonrpc_create_id(void)
515 {
516 static unsigned int id;
517 return json_integer_create(id++);
518 }
519
520 struct jsonrpc_msg *
521 jsonrpc_create_request(const char *method, struct json *params,
522 struct json **idp)
523 {
524 struct json *id = jsonrpc_create_id();
525 if (idp) {
526 *idp = json_clone(id);
527 }
528 return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL, id);
529 }
530
531 struct jsonrpc_msg *
532 jsonrpc_create_notify(const char *method, struct json *params)
533 {
534 return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
535 }
536
537 struct jsonrpc_msg *
538 jsonrpc_create_reply(struct json *result, const struct json *id)
539 {
540 return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
541 json_clone(id));
542 }
543
544 struct jsonrpc_msg *
545 jsonrpc_create_error(struct json *error, const struct json *id)
546 {
547 return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
548 json_clone(id));
549 }
550
551 const char *
552 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
553 {
554 switch (type) {
555 case JSONRPC_REQUEST:
556 return "request";
557
558 case JSONRPC_NOTIFY:
559 return "notification";
560
561 case JSONRPC_REPLY:
562 return "reply";
563
564 case JSONRPC_ERROR:
565 return "error";
566 }
567 return "(null)";
568 }
569
570 char *
571 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
572 {
573 const char *type_name;
574 unsigned int pattern;
575
576 if (m->params && m->params->type != JSON_ARRAY) {
577 return xstrdup("\"params\" must be JSON array");
578 }
579
580 switch (m->type) {
581 case JSONRPC_REQUEST:
582 pattern = 0x11001;
583 break;
584
585 case JSONRPC_NOTIFY:
586 pattern = 0x11000;
587 break;
588
589 case JSONRPC_REPLY:
590 pattern = 0x00101;
591 break;
592
593 case JSONRPC_ERROR:
594 pattern = 0x00011;
595 break;
596
597 default:
598 return xasprintf("invalid JSON-RPC message type %d", m->type);
599 }
600
601 type_name = jsonrpc_msg_type_to_string(m->type);
602 if ((m->method != NULL) != ((pattern & 0x10000) != 0)) {
603 return xasprintf("%s must%s have \"method\"",
604 type_name, (pattern & 0x10000) ? "" : " not");
605
606 }
607 if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
608 return xasprintf("%s must%s have \"params\"",
609 type_name, (pattern & 0x1000) ? "" : " not");
610
611 }
612 if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
613 return xasprintf("%s must%s have \"result\"",
614 type_name, (pattern & 0x100) ? "" : " not");
615
616 }
617 if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
618 return xasprintf("%s must%s have \"error\"",
619 type_name, (pattern & 0x10) ? "" : " not");
620
621 }
622 if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
623 return xasprintf("%s must%s have \"id\"",
624 type_name, (pattern & 0x1) ? "" : " not");
625
626 }
627 return NULL;
628 }
629
630 void
631 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
632 {
633 if (m) {
634 free(m->method);
635 json_destroy(m->params);
636 json_destroy(m->result);
637 json_destroy(m->error);
638 json_destroy(m->id);
639 free(m);
640 }
641 }
642
643 static struct json *
644 null_from_json_null(struct json *json)
645 {
646 if (json && json->type == JSON_NULL) {
647 json_destroy(json);
648 return NULL;
649 }
650 return json;
651 }
652
653 char *
654 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
655 {
656 struct json *method = NULL;
657 struct jsonrpc_msg *msg = NULL;
658 struct shash *object;
659 char *error;
660
661 if (json->type != JSON_OBJECT) {
662 error = xstrdup("message is not a JSON object");
663 goto exit;
664 }
665 object = json_object(json);
666
667 method = shash_find_and_delete(object, "method");
668 if (method && method->type != JSON_STRING) {
669 error = xstrdup("method is not a JSON string");
670 goto exit;
671 }
672
673 msg = xzalloc(sizeof *msg);
674 msg->method = method ? xstrdup(method->u.string) : NULL;
675 msg->params = null_from_json_null(shash_find_and_delete(object, "params"));
676 msg->result = null_from_json_null(shash_find_and_delete(object, "result"));
677 msg->error = null_from_json_null(shash_find_and_delete(object, "error"));
678 msg->id = null_from_json_null(shash_find_and_delete(object, "id"));
679 msg->type = (msg->result ? JSONRPC_REPLY
680 : msg->error ? JSONRPC_ERROR
681 : msg->id ? JSONRPC_REQUEST
682 : JSONRPC_NOTIFY);
683 if (!shash_is_empty(object)) {
684 error = xasprintf("message has unexpected member \"%s\"",
685 shash_first(object)->name);
686 goto exit;
687 }
688 error = jsonrpc_msg_is_valid(msg);
689 if (error) {
690 goto exit;
691 }
692
693 exit:
694 json_destroy(method);
695 json_destroy(json);
696 if (error) {
697 jsonrpc_msg_destroy(msg);
698 msg = NULL;
699 }
700 *msgp = msg;
701 return error;
702 }
703
704 struct json *
705 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
706 {
707 struct json *json = json_object_create();
708
709 if (m->method) {
710 json_object_put(json, "method", json_string_create_nocopy(m->method));
711 }
712
713 if (m->params) {
714 json_object_put(json, "params", m->params);
715 }
716
717 if (m->result) {
718 json_object_put(json, "result", m->result);
719 } else if (m->type == JSONRPC_ERROR) {
720 json_object_put(json, "result", json_null_create());
721 }
722
723 if (m->error) {
724 json_object_put(json, "error", m->error);
725 } else if (m->type == JSONRPC_REPLY) {
726 json_object_put(json, "error", json_null_create());
727 }
728
729 if (m->id) {
730 json_object_put(json, "id", m->id);
731 } else if (m->type == JSONRPC_NOTIFY) {
732 json_object_put(json, "id", json_null_create());
733 }
734
735 free(m);
736
737 return json;
738 }
739 \f
740 /* A JSON-RPC session with reconnection. */
741
742 struct jsonrpc_session {
743 struct reconnect *reconnect;
744 struct jsonrpc *rpc;
745 struct stream *stream;
746 struct pstream *pstream;
747 unsigned int seqno;
748 uint8_t dscp;
749 };
750
751 /* Creates and returns a jsonrpc_session to 'name', which should be a string
752 * acceptable to stream_open() or pstream_open().
753 *
754 * If 'name' is an active connection method, e.g. "tcp:127.1.2.3", the new
755 * jsonrpc_session connects and reconnects, with back-off, to 'name'.
756 *
757 * If 'name' is a passive connection method, e.g. "ptcp:", the new
758 * jsonrpc_session listens for connections to 'name'. It maintains at most one
759 * connection at any given time. Any new connection causes the previous one
760 * (if any) to be dropped. */
761 struct jsonrpc_session *
762 jsonrpc_session_open(const char *name)
763 {
764 struct jsonrpc_session *s;
765
766 s = xmalloc(sizeof *s);
767 s->reconnect = reconnect_create(time_msec());
768 reconnect_set_name(s->reconnect, name);
769 reconnect_enable(s->reconnect, time_msec());
770 s->rpc = NULL;
771 s->stream = NULL;
772 s->pstream = NULL;
773 s->seqno = 0;
774 s->dscp = 0;
775
776 if (!pstream_verify_name(name)) {
777 reconnect_set_passive(s->reconnect, true, time_msec());
778 }
779
780 if (!stream_or_pstream_needs_probes(name)) {
781 reconnect_set_probe_interval(s->reconnect, 0);
782 }
783
784 return s;
785 }
786
787 /* Creates and returns a jsonrpc_session that is initially connected to
788 * 'jsonrpc'. If the connection is dropped, it will not be reconnected.
789 *
790 * On the assumption that such connections are likely to be short-lived
791 * (e.g. from ovs-vsctl), informational logging for them is suppressed. */
792 struct jsonrpc_session *
793 jsonrpc_session_open_unreliably(struct jsonrpc *jsonrpc, uint8_t dscp)
794 {
795 struct jsonrpc_session *s;
796
797 s = xmalloc(sizeof *s);
798 s->reconnect = reconnect_create(time_msec());
799 reconnect_set_quiet(s->reconnect, true);
800 reconnect_set_name(s->reconnect, jsonrpc_get_name(jsonrpc));
801 reconnect_set_max_tries(s->reconnect, 0);
802 reconnect_connected(s->reconnect, time_msec());
803 s->dscp = dscp;
804 s->rpc = jsonrpc;
805 s->stream = NULL;
806 s->pstream = NULL;
807 s->seqno = 0;
808
809 return s;
810 }
811
812 void
813 jsonrpc_session_close(struct jsonrpc_session *s)
814 {
815 if (s) {
816 jsonrpc_close(s->rpc);
817 reconnect_destroy(s->reconnect);
818 stream_close(s->stream);
819 pstream_close(s->pstream);
820 free(s);
821 }
822 }
823
824 static void
825 jsonrpc_session_disconnect(struct jsonrpc_session *s)
826 {
827 if (s->rpc) {
828 jsonrpc_error(s->rpc, EOF);
829 jsonrpc_close(s->rpc);
830 s->rpc = NULL;
831 s->seqno++;
832 } else if (s->stream) {
833 stream_close(s->stream);
834 s->stream = NULL;
835 s->seqno++;
836 }
837 }
838
839 static void
840 jsonrpc_session_connect(struct jsonrpc_session *s)
841 {
842 const char *name = reconnect_get_name(s->reconnect);
843 int error;
844
845 jsonrpc_session_disconnect(s);
846 if (!reconnect_is_passive(s->reconnect)) {
847 error = jsonrpc_stream_open(name, &s->stream, s->dscp);
848 if (!error) {
849 reconnect_connecting(s->reconnect, time_msec());
850 }
851 } else {
852 error = s->pstream ? 0 : jsonrpc_pstream_open(name, &s->pstream,
853 s->dscp);
854 if (!error) {
855 reconnect_listening(s->reconnect, time_msec());
856 }
857 }
858
859 if (error) {
860 reconnect_connect_failed(s->reconnect, time_msec(), error);
861 }
862 s->seqno++;
863 }
864
865 void
866 jsonrpc_session_run(struct jsonrpc_session *s)
867 {
868 if (s->pstream) {
869 struct stream *stream;
870 int error;
871
872 error = pstream_accept(s->pstream, &stream);
873 if (!error) {
874 if (s->rpc || s->stream) {
875 VLOG_INFO_RL(&rl,
876 "%s: new connection replacing active connection",
877 reconnect_get_name(s->reconnect));
878 jsonrpc_session_disconnect(s);
879 }
880 reconnect_connected(s->reconnect, time_msec());
881 s->rpc = jsonrpc_open(stream);
882 } else if (error != EAGAIN) {
883 reconnect_listen_error(s->reconnect, time_msec(), error);
884 pstream_close(s->pstream);
885 s->pstream = NULL;
886 }
887 }
888
889 if (s->rpc) {
890 size_t backlog;
891 int error;
892
893 backlog = jsonrpc_get_backlog(s->rpc);
894 jsonrpc_run(s->rpc);
895 if (jsonrpc_get_backlog(s->rpc) < backlog) {
896 /* Data previously caught in a queue was successfully sent (or
897 * there's an error, which we'll catch below.)
898 *
899 * We don't count data that is successfully sent immediately as
900 * activity, because there's a lot of queuing downstream from us,
901 * which means that we can push a lot of data into a connection
902 * that has stalled and won't ever recover.
903 */
904 reconnect_activity(s->reconnect, time_msec());
905 }
906
907 error = jsonrpc_get_status(s->rpc);
908 if (error) {
909 reconnect_disconnected(s->reconnect, time_msec(), error);
910 jsonrpc_session_disconnect(s);
911 }
912 } else if (s->stream) {
913 int error;
914
915 stream_run(s->stream);
916 error = stream_connect(s->stream);
917 if (!error) {
918 reconnect_connected(s->reconnect, time_msec());
919 s->rpc = jsonrpc_open(s->stream);
920 s->stream = NULL;
921 } else if (error != EAGAIN) {
922 reconnect_connect_failed(s->reconnect, time_msec(), error);
923 stream_close(s->stream);
924 s->stream = NULL;
925 }
926 }
927
928 switch (reconnect_run(s->reconnect, time_msec())) {
929 case RECONNECT_CONNECT:
930 jsonrpc_session_connect(s);
931 break;
932
933 case RECONNECT_DISCONNECT:
934 reconnect_disconnected(s->reconnect, time_msec(), 0);
935 jsonrpc_session_disconnect(s);
936 break;
937
938 case RECONNECT_PROBE:
939 if (s->rpc) {
940 struct json *params;
941 struct jsonrpc_msg *request;
942
943 params = json_array_create_empty();
944 request = jsonrpc_create_request("echo", params, NULL);
945 json_destroy(request->id);
946 request->id = json_string_create("echo");
947 jsonrpc_send(s->rpc, request);
948 }
949 break;
950 }
951 }
952
953 void
954 jsonrpc_session_wait(struct jsonrpc_session *s)
955 {
956 if (s->rpc) {
957 jsonrpc_wait(s->rpc);
958 } else if (s->stream) {
959 stream_run_wait(s->stream);
960 stream_connect_wait(s->stream);
961 }
962 if (s->pstream) {
963 pstream_wait(s->pstream);
964 }
965 reconnect_wait(s->reconnect, time_msec());
966 }
967
968 size_t
969 jsonrpc_session_get_backlog(const struct jsonrpc_session *s)
970 {
971 return s->rpc ? jsonrpc_get_backlog(s->rpc) : 0;
972 }
973
974 /* Always returns a pointer to a valid C string, assuming 's' was initialized
975 * correctly. */
976 const char *
977 jsonrpc_session_get_name(const struct jsonrpc_session *s)
978 {
979 return reconnect_get_name(s->reconnect);
980 }
981
982 /* Always takes ownership of 'msg', regardless of success. */
983 int
984 jsonrpc_session_send(struct jsonrpc_session *s, struct jsonrpc_msg *msg)
985 {
986 if (s->rpc) {
987 return jsonrpc_send(s->rpc, msg);
988 } else {
989 jsonrpc_msg_destroy(msg);
990 return ENOTCONN;
991 }
992 }
993
994 struct jsonrpc_msg *
995 jsonrpc_session_recv(struct jsonrpc_session *s)
996 {
997 if (s->rpc) {
998 unsigned int received_bytes;
999 struct jsonrpc_msg *msg;
1000
1001 received_bytes = jsonrpc_get_received_bytes(s->rpc);
1002 jsonrpc_recv(s->rpc, &msg);
1003 if (received_bytes != jsonrpc_get_received_bytes(s->rpc)) {
1004 /* Data was successfully received.
1005 *
1006 * Previously we only counted receiving a full message as activity,
1007 * but with large messages or a slow connection that policy could
1008 * time out the session mid-message. */
1009 reconnect_activity(s->reconnect, time_msec());
1010 }
1011
1012 if (msg) {
1013 if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
1014 /* Echo request. Send reply. */
1015 struct jsonrpc_msg *reply;
1016
1017 reply = jsonrpc_create_reply(json_clone(msg->params), msg->id);
1018 jsonrpc_session_send(s, reply);
1019 } else if (msg->type == JSONRPC_REPLY
1020 && msg->id && msg->id->type == JSON_STRING
1021 && !strcmp(msg->id->u.string, "echo")) {
1022 /* It's a reply to our echo request. Suppress it. */
1023 } else {
1024 return msg;
1025 }
1026 jsonrpc_msg_destroy(msg);
1027 }
1028 }
1029 return NULL;
1030 }
1031
1032 void
1033 jsonrpc_session_recv_wait(struct jsonrpc_session *s)
1034 {
1035 if (s->rpc) {
1036 jsonrpc_recv_wait(s->rpc);
1037 }
1038 }
1039
1040 bool
1041 jsonrpc_session_is_alive(const struct jsonrpc_session *s)
1042 {
1043 return s->rpc || s->stream || reconnect_get_max_tries(s->reconnect);
1044 }
1045
1046 bool
1047 jsonrpc_session_is_connected(const struct jsonrpc_session *s)
1048 {
1049 return s->rpc != NULL;
1050 }
1051
1052 unsigned int
1053 jsonrpc_session_get_seqno(const struct jsonrpc_session *s)
1054 {
1055 return s->seqno;
1056 }
1057
1058 int
1059 jsonrpc_session_get_status(const struct jsonrpc_session *s)
1060 {
1061 return s && s->rpc ? jsonrpc_get_status(s->rpc) : 0;
1062 }
1063
1064 void
1065 jsonrpc_session_get_reconnect_stats(const struct jsonrpc_session *s,
1066 struct reconnect_stats *stats)
1067 {
1068 reconnect_get_stats(s->reconnect, time_msec(), stats);
1069 }
1070
1071 void
1072 jsonrpc_session_force_reconnect(struct jsonrpc_session *s)
1073 {
1074 reconnect_force_reconnect(s->reconnect, time_msec());
1075 }
1076
1077 void
1078 jsonrpc_session_set_max_backoff(struct jsonrpc_session *s, int max_backoff)
1079 {
1080 reconnect_set_backoff(s->reconnect, 0, max_backoff);
1081 }
1082
1083 void
1084 jsonrpc_session_set_probe_interval(struct jsonrpc_session *s,
1085 int probe_interval)
1086 {
1087 reconnect_set_probe_interval(s->reconnect, probe_interval);
1088 }
1089
1090 void
1091 jsonrpc_session_set_dscp(struct jsonrpc_session *s,
1092 uint8_t dscp)
1093 {
1094 if (s->dscp != dscp) {
1095 if (s->pstream) {
1096 int error;
1097
1098 error = pstream_set_dscp(s->pstream, dscp);
1099 if (error) {
1100 VLOG_ERR("%s: failed set_dscp %s",
1101 reconnect_get_name(s->reconnect), strerror(error));
1102 }
1103 /*
1104 * XXX race window between setting dscp to listening socket
1105 * and accepting socket. accepted socket may have old dscp value.
1106 * Ignore this race window for now.
1107 */
1108 }
1109 s->dscp = dscp;
1110 jsonrpc_session_force_reconnect(s);
1111 }
1112 }