jsonrpc: Add logging for messages sent and received, at DBG level.
[sliver-openvswitch.git] / lib / jsonrpc.c
1 /*
2  * Copyright (c) 2009 Nicira Networks.
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 "json.h"
26 #include "list.h"
27 #include "ofpbuf.h"
28 #include "poll-loop.h"
29 #include "queue.h"
30 #include "stream.h"
31
32 #define THIS_MODULE VLM_jsonrpc
33 #include "vlog.h"
34 \f
35 struct jsonrpc {
36     struct stream *stream;
37     char *name;
38     int status;
39
40     /* Input. */
41     struct byteq input;
42     struct json_parser *parser;
43     struct jsonrpc_msg *received;
44
45     /* Output. */
46     struct ovs_queue output;
47     size_t backlog;
48 };
49
50 /* Rate limit for error messages. */
51 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
52
53 static void jsonrpc_received(struct jsonrpc *);
54 static void jsonrpc_cleanup(struct jsonrpc *);
55
56 struct jsonrpc *
57 jsonrpc_open(struct stream *stream)
58 {
59     struct jsonrpc *rpc;
60
61     assert(stream != NULL);
62
63     rpc = xzalloc(sizeof *rpc);
64     rpc->name = xstrdup(stream_get_name(stream));
65     rpc->stream = stream;
66     byteq_init(&rpc->input);
67     queue_init(&rpc->output);
68
69     return rpc;
70 }
71
72 void
73 jsonrpc_close(struct jsonrpc *rpc)
74 {
75     if (rpc) {
76         jsonrpc_cleanup(rpc);
77         free(rpc->name);
78         free(rpc);
79     }
80 }
81
82 void
83 jsonrpc_run(struct jsonrpc *rpc)
84 {
85     if (rpc->status) {
86         return;
87     }
88
89     while (!queue_is_empty(&rpc->output)) {
90         struct ofpbuf *buf = rpc->output.head;
91         int retval;
92
93         retval = stream_send(rpc->stream, buf->data, buf->size);
94         if (retval >= 0) {
95             rpc->backlog -= retval;
96             ofpbuf_pull(buf, retval);
97             if (!buf->size) {
98                 ofpbuf_delete(queue_pop_head(&rpc->output));
99             }
100         } else {
101             if (retval != -EAGAIN) {
102                 VLOG_WARN_RL(&rl, "%s: send error: %s",
103                              rpc->name, strerror(-retval));
104                 jsonrpc_error(rpc, -retval);
105             }
106             break;
107         }
108     }
109 }
110
111 void
112 jsonrpc_wait(struct jsonrpc *rpc)
113 {
114     if (!rpc->status && !queue_is_empty(&rpc->output)) {
115         stream_send_wait(rpc->stream);
116     }
117 }
118
119 int
120 jsonrpc_get_status(const struct jsonrpc *rpc)
121 {
122     return rpc->status;
123 }
124
125 size_t
126 jsonrpc_get_backlog(const struct jsonrpc *rpc)
127 {
128     return rpc->status ? 0 : rpc->backlog;
129 }
130
131 const char *
132 jsonrpc_get_name(const struct jsonrpc *rpc)
133 {
134     return rpc->name;
135 }
136
137 static void
138 jsonrpc_log_msg(const struct jsonrpc *rpc, const char *title,
139                 const struct jsonrpc_msg *msg)
140 {
141     if (VLOG_IS_DBG_ENABLED()) {
142         struct ds s = DS_EMPTY_INITIALIZER;
143         if (msg->method) {
144             ds_put_format(&s, ", method=\"%s\"", msg->method);
145         }
146         if (msg->params) {
147             ds_put_cstr(&s, ", params=");
148             ds_put_and_free_cstr(&s, json_to_string(msg->params, 0));
149         }
150         if (msg->result) {
151             ds_put_cstr(&s, ", result=");
152             ds_put_and_free_cstr(&s, json_to_string(msg->result, 0));
153         }
154         if (msg->error) {
155             ds_put_cstr(&s, ", error=");
156             ds_put_and_free_cstr(&s, json_to_string(msg->error, 0));
157         }
158         if (msg->id) {
159             ds_put_cstr(&s, ", id=");
160             ds_put_and_free_cstr(&s, json_to_string(msg->id, 0));
161         }
162         VLOG_DBG("%s: %s %s%s", rpc->name, title,
163                  jsonrpc_msg_type_to_string(msg->type), ds_cstr(&s));
164         ds_destroy(&s);
165     }
166 }
167
168 int
169 jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
170 {
171     struct ofpbuf *buf;
172     struct json *json;
173     size_t length;
174     char *s;
175
176     if (rpc->status) {
177         jsonrpc_msg_destroy(msg);
178         return rpc->status;
179     }
180
181     jsonrpc_log_msg(rpc, "send", msg);
182
183     json = jsonrpc_msg_to_json(msg);
184     s = json_to_string(json, 0);
185     length = strlen(s);
186     json_destroy(json);
187
188     buf = xmalloc(sizeof *buf);
189     ofpbuf_use(buf, s, length);
190     buf->size = length;
191     queue_push_tail(&rpc->output, buf);
192     rpc->backlog += length;
193
194     if (rpc->output.n == 1) {
195         jsonrpc_run(rpc);
196     }
197     return rpc->status;
198 }
199
200 int
201 jsonrpc_recv(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
202 {
203     *msgp = NULL;
204     if (rpc->status) {
205         return rpc->status;
206     }
207
208     while (!rpc->received) {
209         if (byteq_is_empty(&rpc->input)) {
210             size_t chunk;
211             int retval;
212
213             chunk = byteq_headroom(&rpc->input);
214             retval = stream_recv(rpc->stream, byteq_head(&rpc->input), chunk);
215             if (retval < 0) {
216                 if (retval == -EAGAIN) {
217                     return EAGAIN;
218                 } else {
219                     VLOG_WARN_RL(&rl, "%s: receive error: %s",
220                                  rpc->name, strerror(-retval));
221                     jsonrpc_error(rpc, -retval);
222                     return rpc->status;
223                 }
224             } else if (retval == 0) {
225                 VLOG_INFO_RL(&rl, "%s: connection closed", rpc->name);
226                 jsonrpc_error(rpc, EOF);
227                 return EOF;
228             }
229             byteq_advance_head(&rpc->input, retval);
230         } else {
231             size_t n, used;
232
233             if (!rpc->parser) {
234                 rpc->parser = json_parser_create(0);
235             }
236             n = byteq_tailroom(&rpc->input);
237             used = json_parser_feed(rpc->parser,
238                                     (char *) byteq_tail(&rpc->input), n);
239             byteq_advance_tail(&rpc->input, used);
240             if (json_parser_is_done(rpc->parser)) {
241                 jsonrpc_received(rpc);
242                 if (rpc->status) {
243                     return rpc->status;
244                 }
245             }
246         }
247     }
248
249     *msgp = rpc->received;
250     rpc->received = NULL;
251     return 0;
252 }
253
254 void
255 jsonrpc_recv_wait(struct jsonrpc *rpc)
256 {
257     if (rpc->status || rpc->received || !byteq_is_empty(&rpc->input)) {
258         poll_immediate_wake();
259     } else {
260         stream_recv_wait(rpc->stream);
261     }
262 }
263
264 int
265 jsonrpc_send_block(struct jsonrpc *rpc, struct jsonrpc_msg *msg)
266 {
267     int error;
268
269     error = jsonrpc_send(rpc, msg);
270     if (error) {
271         return error;
272     }
273
274     while (!queue_is_empty(&rpc->output) && !rpc->status) {
275         jsonrpc_run(rpc);
276         jsonrpc_wait(rpc);
277         poll_block();
278     }
279     return rpc->status;
280 }
281
282 int
283 jsonrpc_recv_block(struct jsonrpc *rpc, struct jsonrpc_msg **msgp)
284 {
285     for (;;) {
286         int error = jsonrpc_recv(rpc, msgp);
287         if (error != EAGAIN) {
288             return error;
289         }
290
291         jsonrpc_run(rpc);
292         jsonrpc_wait(rpc);
293         jsonrpc_recv_wait(rpc);
294         poll_block();
295     }
296 }
297
298 int
299 jsonrpc_transact_block(struct jsonrpc *rpc, struct jsonrpc_msg *request,
300                        struct jsonrpc_msg **replyp)
301 {
302     struct jsonrpc_msg *reply = NULL;
303     struct json *id;
304     int error;
305
306     id = json_clone(request->id);
307     error = jsonrpc_send_block(rpc, request);
308     if (!error) {
309         for (;;) {
310             error = jsonrpc_recv_block(rpc, &reply);
311             if (error
312                 || (reply->type == JSONRPC_REPLY
313                     && json_equal(id, reply->id))) {
314                 break;
315             }
316             jsonrpc_msg_destroy(reply);
317         }
318     }
319     *replyp = error ? NULL : reply;
320     json_destroy(id);
321     return error;
322 }
323
324 static void
325 jsonrpc_received(struct jsonrpc *rpc)
326 {
327     struct jsonrpc_msg *msg;
328     struct json *json;
329     char *error;
330
331     json = json_parser_finish(rpc->parser);
332     rpc->parser = NULL;
333     if (json->type == JSON_STRING) {
334         VLOG_WARN_RL(&rl, "%s: error parsing stream: %s",
335                      rpc->name, json_string(json));
336         jsonrpc_error(rpc, EPROTO);
337         json_destroy(json);
338         return;
339     }
340
341     error = jsonrpc_msg_from_json(json, &msg);
342     if (error) {
343         VLOG_WARN_RL(&rl, "%s: received bad JSON-RPC message: %s",
344                      rpc->name, error);
345         free(error);
346         jsonrpc_error(rpc, EPROTO);
347         return;
348     }
349
350     jsonrpc_log_msg(rpc, "received", msg);
351     rpc->received = msg;
352 }
353
354 void
355 jsonrpc_error(struct jsonrpc *rpc, int error)
356 {
357     assert(error);
358     if (!rpc->status) {
359         rpc->status = error;
360         jsonrpc_cleanup(rpc);
361     }
362 }
363
364 static void
365 jsonrpc_cleanup(struct jsonrpc *rpc)
366 {
367     stream_close(rpc->stream);
368     rpc->stream = NULL;
369
370     json_parser_abort(rpc->parser);
371     rpc->parser = NULL;
372
373     jsonrpc_msg_destroy(rpc->received);
374     rpc->received = NULL;
375
376     queue_clear(&rpc->output);
377     rpc->backlog = 0;
378 }
379 \f
380 static struct jsonrpc_msg *
381 jsonrpc_create(enum jsonrpc_msg_type type, const char *method,
382                 struct json *params, struct json *result, struct json *error,
383                 struct json *id)
384 {
385     struct jsonrpc_msg *msg = xmalloc(sizeof *msg);
386     msg->type = type;
387     msg->method = method ? xstrdup(method) : NULL;
388     msg->params = params;
389     msg->result = result;
390     msg->error = error;
391     msg->id = id;
392     return msg;
393 }
394
395 static struct json *
396 jsonrpc_create_id(void)
397 {
398     static unsigned int id;
399     return json_integer_create(id++);
400 }
401
402 struct jsonrpc_msg *
403 jsonrpc_create_request(const char *method, struct json *params)
404 {
405     return jsonrpc_create(JSONRPC_REQUEST, method, params, NULL, NULL,
406                            jsonrpc_create_id());
407 }
408
409 struct jsonrpc_msg *
410 jsonrpc_create_notify(const char *method, struct json *params)
411 {
412     return jsonrpc_create(JSONRPC_NOTIFY, method, params, NULL, NULL, NULL);
413 }
414
415 struct jsonrpc_msg *
416 jsonrpc_create_reply(struct json *result, const struct json *id)
417 {
418     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, result, NULL,
419                            json_clone(id));
420 }
421
422 struct jsonrpc_msg *
423 jsonrpc_create_error(struct json *error, const struct json *id)
424 {
425     return jsonrpc_create(JSONRPC_REPLY, NULL, NULL, NULL, error,
426                            json_clone(id));
427 }
428
429 const char *
430 jsonrpc_msg_type_to_string(enum jsonrpc_msg_type type)
431 {
432     switch (type) {
433     case JSONRPC_REQUEST:
434         return "request";
435
436     case JSONRPC_NOTIFY:
437         return "notification";
438
439     case JSONRPC_REPLY:
440         return "reply";
441
442     case JSONRPC_ERROR:
443         return "error";
444     }
445     return "(null)";
446 }
447
448 char *
449 jsonrpc_msg_is_valid(const struct jsonrpc_msg *m)
450 {
451     const char *type_name;
452     unsigned int pattern;
453
454     if (m->params && m->params->type != JSON_ARRAY) {
455         return xstrdup("\"params\" must be JSON array");
456     }
457
458     switch (m->type) {
459     case JSONRPC_REQUEST:
460         pattern = 0x11001;
461         break;
462
463     case JSONRPC_NOTIFY:
464         pattern = 0x11000;
465         break;
466
467     case JSONRPC_REPLY:
468         pattern = 0x00101;
469         break;
470
471     case JSONRPC_ERROR:
472         pattern = 0x00011;
473         break;
474
475     default:
476         return xasprintf("invalid JSON-RPC message type %d", m->type);
477     }
478
479     type_name = jsonrpc_msg_type_to_string(m->type);
480     if ((m->method != NULL) != ((pattern & 0x10000) != 0)) {
481         return xasprintf("%s must%s have \"method\"",
482                          type_name, (pattern & 0x10000) ? "" : " not");
483
484     }
485     if ((m->params != NULL) != ((pattern & 0x1000) != 0)) {
486         return xasprintf("%s must%s have \"params\"",
487                          type_name, (pattern & 0x1000) ? "" : " not");
488
489     }
490     if ((m->result != NULL) != ((pattern & 0x100) != 0)) {
491         return xasprintf("%s must%s have \"result\"",
492                          type_name, (pattern & 0x100) ? "" : " not");
493
494     }
495     if ((m->error != NULL) != ((pattern & 0x10) != 0)) {
496         return xasprintf("%s must%s have \"error\"",
497                          type_name, (pattern & 0x10) ? "" : " not");
498
499     }
500     if ((m->id != NULL) != ((pattern & 0x1) != 0)) {
501         return xasprintf("%s must%s have \"id\"",
502                          type_name, (pattern & 0x1) ? "" : " not");
503
504     }
505     return NULL;
506 }
507
508 void
509 jsonrpc_msg_destroy(struct jsonrpc_msg *m)
510 {
511     if (m) {
512         free(m->method);
513         json_destroy(m->params);
514         json_destroy(m->result);
515         json_destroy(m->error);
516         json_destroy(m->id);
517         free(m);
518     }
519 }
520
521 static struct json *
522 null_from_json_null(struct json *json)
523 {
524     if (json && json->type == JSON_NULL) {
525         json_destroy(json);
526         return NULL;
527     }
528     return json;
529 }
530
531 char *
532 jsonrpc_msg_from_json(struct json *json, struct jsonrpc_msg **msgp)
533 {
534     struct json *method = NULL;
535     struct jsonrpc_msg *msg = NULL;
536     struct shash *object;
537     char *error;
538
539     if (json->type != JSON_OBJECT) {
540         error = xstrdup("message is not a JSON object");
541         goto exit;
542     }
543     object = json_object(json);
544
545     method = shash_find_and_delete(object, "method");
546     if (method && method->type != JSON_STRING) {
547         error = xstrdup("method is not a JSON string");
548         goto exit;
549     }
550
551     msg = xzalloc(sizeof *msg);
552     msg->method = method ? xstrdup(method->u.string) : NULL;
553     msg->params = null_from_json_null(shash_find_and_delete(object, "params"));
554     msg->result = null_from_json_null(shash_find_and_delete(object, "result"));
555     msg->error = null_from_json_null(shash_find_and_delete(object, "error"));
556     msg->id = null_from_json_null(shash_find_and_delete(object, "id"));
557     msg->type = (msg->result ? JSONRPC_REPLY
558                  : msg->error ? JSONRPC_ERROR
559                  : msg->id ? JSONRPC_REQUEST
560                  : JSONRPC_NOTIFY);
561     if (!shash_is_empty(object)) {
562         error = xasprintf("message has unexpected member \"%s\"",
563                           shash_first(object)->name);
564         goto exit;
565     }
566     error = jsonrpc_msg_is_valid(msg);
567     if (error) {
568         goto exit;
569     }
570
571 exit:
572     json_destroy(method);
573     json_destroy(json);
574     if (error) {
575         jsonrpc_msg_destroy(msg);
576         msg = NULL;
577     }
578     *msgp = msg;
579     return error;
580 }
581
582 struct json *
583 jsonrpc_msg_to_json(struct jsonrpc_msg *m)
584 {
585     struct json *json = json_object_create();
586
587     if (m->method) {
588         json_object_put(json, "method", json_string_create_nocopy(m->method));
589     }
590
591     if (m->params) {
592         json_object_put(json, "params", m->params);
593     }
594
595     if (m->result) {
596         json_object_put(json, "result", m->result);
597     } else if (m->type == JSONRPC_ERROR) {
598         json_object_put(json, "result", json_null_create());
599     }
600
601     if (m->error) {
602         json_object_put(json, "error", m->error);
603     } else if (m->type == JSONRPC_REPLY) {
604         json_object_put(json, "error", json_null_create());
605     }
606
607     if (m->id) {
608         json_object_put(json, "id", m->id);
609     } else if (m->type == JSONRPC_NOTIFY) {
610         json_object_put(json, "id", json_null_create());
611     }
612
613     free(m);
614
615     return json;
616 }