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