Switch many macros from using CONTAINER_OF to using OBJECT_CONTAINING.
[sliver-openvswitch.git] / ovsdb / jsonrpc-server.c
1 /* Copyright (c) 2009, 2010 Nicira Networks
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "jsonrpc-server.h"
19
20 #include <assert.h>
21 #include <errno.h>
22
23 #include "bitmap.h"
24 #include "column.h"
25 #include "json.h"
26 #include "jsonrpc.h"
27 #include "ovsdb-error.h"
28 #include "ovsdb-parser.h"
29 #include "ovsdb.h"
30 #include "reconnect.h"
31 #include "row.h"
32 #include "stream.h"
33 #include "table.h"
34 #include "timeval.h"
35 #include "transaction.h"
36 #include "trigger.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(ovsdb_jsonrpc_server)
40
41 struct ovsdb_jsonrpc_remote;
42 struct ovsdb_jsonrpc_session;
43
44 /* Message rate-limiting. */
45 struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
46
47 /* Sessions. */
48 static struct ovsdb_jsonrpc_session *ovsdb_jsonrpc_session_create(
49     struct ovsdb_jsonrpc_remote *, struct jsonrpc_session *);
50 static void ovsdb_jsonrpc_session_run_all(struct ovsdb_jsonrpc_remote *);
51 static void ovsdb_jsonrpc_session_wait_all(struct ovsdb_jsonrpc_remote *);
52 static void ovsdb_jsonrpc_session_close_all(struct ovsdb_jsonrpc_remote *);
53 static void ovsdb_jsonrpc_session_reconnect_all(struct ovsdb_jsonrpc_remote *);
54
55 /* Triggers. */
56 static void ovsdb_jsonrpc_trigger_create(struct ovsdb_jsonrpc_session *,
57                                          struct json *id, struct json *params);
58 static struct ovsdb_jsonrpc_trigger *ovsdb_jsonrpc_trigger_find(
59     struct ovsdb_jsonrpc_session *, const struct json *id, size_t hash);
60 static void ovsdb_jsonrpc_trigger_complete(struct ovsdb_jsonrpc_trigger *);
61 static void ovsdb_jsonrpc_trigger_complete_all(struct ovsdb_jsonrpc_session *);
62 static void ovsdb_jsonrpc_trigger_complete_done(
63     struct ovsdb_jsonrpc_session *);
64
65 /* Monitors. */
66 static struct json *ovsdb_jsonrpc_monitor_create(
67     struct ovsdb_jsonrpc_session *, struct json *params);
68 static struct jsonrpc_msg *ovsdb_jsonrpc_monitor_cancel(
69     struct ovsdb_jsonrpc_session *,
70     struct json_array *params,
71     const struct json *request_id);
72 static void ovsdb_jsonrpc_monitor_remove_all(struct ovsdb_jsonrpc_session *);
73 \f
74 /* JSON-RPC database server. */
75
76 struct ovsdb_jsonrpc_server {
77     struct ovsdb *db;
78     unsigned int n_sessions, max_sessions;
79     struct shash remotes;      /* Contains "struct ovsdb_jsonrpc_remote *"s. */
80 };
81
82 /* A configured remote.  This is either a passive stream listener plus a list
83  * of the currently connected sessions, or a list of exactly one active
84  * session. */
85 struct ovsdb_jsonrpc_remote {
86     struct ovsdb_jsonrpc_server *server;
87     struct pstream *listener;   /* Listener, if passive. */
88     struct list sessions;       /* List of "struct ovsdb_jsonrpc_session"s. */
89 };
90
91 static void ovsdb_jsonrpc_server_add_remote(struct ovsdb_jsonrpc_server *,
92                                             const char *name);
93 static void ovsdb_jsonrpc_server_del_remote(struct shash_node *);
94
95 struct ovsdb_jsonrpc_server *
96 ovsdb_jsonrpc_server_create(struct ovsdb *db)
97 {
98     struct ovsdb_jsonrpc_server *server = xzalloc(sizeof *server);
99     server->db = db;
100     server->max_sessions = 64;
101     shash_init(&server->remotes);
102     return server;
103 }
104
105 void
106 ovsdb_jsonrpc_server_destroy(struct ovsdb_jsonrpc_server *svr)
107 {
108     struct shash_node *node, *next;
109
110     SHASH_FOR_EACH_SAFE (node, next, &svr->remotes) {
111         ovsdb_jsonrpc_server_del_remote(node);
112     }
113     shash_destroy(&svr->remotes);
114     free(svr);
115 }
116
117 /* Sets 'svr''s current set of remotes to the names in 'new_remotes'.  The data
118  * values in 'new_remotes' are ignored.
119  *
120  * A remote is an active or passive stream connection method, e.g. "pssl:" or
121  * "tcp:1.2.3.4". */
122 void
123 ovsdb_jsonrpc_server_set_remotes(struct ovsdb_jsonrpc_server *svr,
124                                  const struct shash *new_remotes)
125 {
126     struct shash_node *node, *next;
127
128     SHASH_FOR_EACH_SAFE (node, next, &svr->remotes) {
129         if (!shash_find(new_remotes, node->name)) {
130             ovsdb_jsonrpc_server_del_remote(node);
131         }
132     }
133     SHASH_FOR_EACH (node, new_remotes) {
134         if (!shash_find(&svr->remotes, node->name)) {
135             ovsdb_jsonrpc_server_add_remote(svr, node->name);
136         }
137     }
138 }
139
140 static void
141 ovsdb_jsonrpc_server_add_remote(struct ovsdb_jsonrpc_server *svr,
142                                 const char *name)
143 {
144     struct ovsdb_jsonrpc_remote *remote;
145     struct pstream *listener;
146     int error;
147
148     error = jsonrpc_pstream_open(name, &listener);
149     if (error && error != EAFNOSUPPORT) {
150         VLOG_ERR_RL(&rl, "%s: listen failed: %s", name, strerror(error));
151         return;
152     }
153
154     remote = xmalloc(sizeof *remote);
155     remote->server = svr;
156     remote->listener = listener;
157     list_init(&remote->sessions);
158     shash_add(&svr->remotes, name, remote);
159
160     if (!listener) {
161         ovsdb_jsonrpc_session_create(remote, jsonrpc_session_open(name));
162     }
163 }
164
165 static void
166 ovsdb_jsonrpc_server_del_remote(struct shash_node *node)
167 {
168     struct ovsdb_jsonrpc_remote *remote = node->data;
169
170     ovsdb_jsonrpc_session_close_all(remote);
171     pstream_close(remote->listener);
172     shash_delete(&remote->server->remotes, node);
173     free(remote);
174 }
175
176 /* Forces all of the JSON-RPC sessions managed by 'svr' to disconnect and
177  * reconnect. */
178 void
179 ovsdb_jsonrpc_server_reconnect(struct ovsdb_jsonrpc_server *svr)
180 {
181     struct shash_node *node;
182
183     SHASH_FOR_EACH (node, &svr->remotes) {
184         struct ovsdb_jsonrpc_remote *remote = node->data;
185
186         ovsdb_jsonrpc_session_reconnect_all(remote);
187     }
188 }
189
190 void
191 ovsdb_jsonrpc_server_run(struct ovsdb_jsonrpc_server *svr)
192 {
193     struct shash_node *node;
194
195     SHASH_FOR_EACH (node, &svr->remotes) {
196         struct ovsdb_jsonrpc_remote *remote = node->data;
197
198         if (remote->listener && svr->n_sessions < svr->max_sessions) {
199             struct stream *stream;
200             int error;
201
202             error = pstream_accept(remote->listener, &stream);
203             if (!error) {
204                 struct jsonrpc_session *js;
205                 js = jsonrpc_session_open_unreliably(jsonrpc_open(stream));
206                 ovsdb_jsonrpc_session_create(remote, js);
207             } else if (error != EAGAIN) {
208                 VLOG_WARN_RL(&rl, "%s: accept failed: %s",
209                              pstream_get_name(remote->listener),
210                              strerror(error));
211             }
212         }
213
214         ovsdb_jsonrpc_session_run_all(remote);
215     }
216 }
217
218 void
219 ovsdb_jsonrpc_server_wait(struct ovsdb_jsonrpc_server *svr)
220 {
221     struct shash_node *node;
222
223     SHASH_FOR_EACH (node, &svr->remotes) {
224         struct ovsdb_jsonrpc_remote *remote = node->data;
225
226         if (remote->listener && svr->n_sessions < svr->max_sessions) {
227             pstream_wait(remote->listener);
228         }
229
230         ovsdb_jsonrpc_session_wait_all(remote);
231     }
232 }
233 \f
234 /* JSON-RPC database server session. */
235
236 struct ovsdb_jsonrpc_session {
237     struct ovsdb_jsonrpc_remote *remote;
238     struct list node;           /* Element in remote's sessions list. */
239
240     /* Triggers. */
241     struct hmap triggers;       /* Hmap of "struct ovsdb_jsonrpc_trigger"s. */
242     struct list completions;    /* Completed triggers. */
243
244     /* Monitors. */
245     struct hmap monitors;       /* Hmap of "struct ovsdb_jsonrpc_monitor"s. */
246
247     /* Network connectivity. */
248     struct jsonrpc_session *js;  /* JSON-RPC session. */
249     unsigned int js_seqno;       /* Last jsonrpc_session_get_seqno() value. */
250 };
251
252 static void ovsdb_jsonrpc_session_close(struct ovsdb_jsonrpc_session *);
253 static int ovsdb_jsonrpc_session_run(struct ovsdb_jsonrpc_session *);
254 static void ovsdb_jsonrpc_session_wait(struct ovsdb_jsonrpc_session *);
255 static void ovsdb_jsonrpc_session_got_request(struct ovsdb_jsonrpc_session *,
256                                              struct jsonrpc_msg *);
257 static void ovsdb_jsonrpc_session_got_notify(struct ovsdb_jsonrpc_session *,
258                                              struct jsonrpc_msg *);
259
260 static struct ovsdb_jsonrpc_session *
261 ovsdb_jsonrpc_session_create(struct ovsdb_jsonrpc_remote *remote,
262                              struct jsonrpc_session *js)
263 {
264     struct ovsdb_jsonrpc_session *s;
265
266     s = xzalloc(sizeof *s);
267     s->remote = remote;
268     list_push_back(&remote->sessions, &s->node);
269     hmap_init(&s->triggers);
270     hmap_init(&s->monitors);
271     list_init(&s->completions);
272     s->js = js;
273     s->js_seqno = jsonrpc_session_get_seqno(js);
274
275     remote->server->n_sessions++;
276
277     return s;
278 }
279
280 static void
281 ovsdb_jsonrpc_session_close(struct ovsdb_jsonrpc_session *s)
282 {
283     ovsdb_jsonrpc_monitor_remove_all(s);
284     jsonrpc_session_close(s->js);
285     list_remove(&s->node);
286     s->remote->server->n_sessions--;
287     free(s);
288 }
289
290 static int
291 ovsdb_jsonrpc_session_run(struct ovsdb_jsonrpc_session *s)
292 {
293     jsonrpc_session_run(s->js);
294     if (s->js_seqno != jsonrpc_session_get_seqno(s->js)) {
295         s->js_seqno = jsonrpc_session_get_seqno(s->js);
296         ovsdb_jsonrpc_trigger_complete_all(s);
297         ovsdb_jsonrpc_monitor_remove_all(s);
298     }
299
300     ovsdb_jsonrpc_trigger_complete_done(s);
301
302     if (!jsonrpc_session_get_backlog(s->js)) {
303         struct jsonrpc_msg *msg = jsonrpc_session_recv(s->js);
304         if (msg) {
305             if (msg->type == JSONRPC_REQUEST) {
306                 ovsdb_jsonrpc_session_got_request(s, msg);
307             } else if (msg->type == JSONRPC_NOTIFY) {
308                 ovsdb_jsonrpc_session_got_notify(s, msg);
309             } else {
310                 VLOG_WARN("%s: received unexpected %s message",
311                           jsonrpc_session_get_name(s->js),
312                           jsonrpc_msg_type_to_string(msg->type));
313                 jsonrpc_session_force_reconnect(s->js);
314                 jsonrpc_msg_destroy(msg);
315             }
316         }
317     }
318     return jsonrpc_session_is_alive(s->js) ? 0 : ETIMEDOUT;
319 }
320
321 static void
322 ovsdb_jsonrpc_session_run_all(struct ovsdb_jsonrpc_remote *remote)
323 {
324     struct ovsdb_jsonrpc_session *s, *next;
325
326     LIST_FOR_EACH_SAFE (s, next, node, &remote->sessions) {
327         int error = ovsdb_jsonrpc_session_run(s);
328         if (error) {
329             ovsdb_jsonrpc_session_close(s);
330         }
331     }
332 }
333
334 static void
335 ovsdb_jsonrpc_session_wait(struct ovsdb_jsonrpc_session *s)
336 {
337     jsonrpc_session_wait(s->js);
338     if (!jsonrpc_session_get_backlog(s->js)) {
339         jsonrpc_session_recv_wait(s->js);
340     }
341 }
342
343 static void
344 ovsdb_jsonrpc_session_wait_all(struct ovsdb_jsonrpc_remote *remote)
345 {
346     struct ovsdb_jsonrpc_session *s;
347
348     LIST_FOR_EACH (s, node, &remote->sessions) {
349         ovsdb_jsonrpc_session_wait(s);
350     }
351 }
352
353 static void
354 ovsdb_jsonrpc_session_close_all(struct ovsdb_jsonrpc_remote *remote)
355 {
356     struct ovsdb_jsonrpc_session *s, *next;
357
358     LIST_FOR_EACH_SAFE (s, next, node, &remote->sessions) {
359         ovsdb_jsonrpc_session_close(s);
360     }
361 }
362
363 /* Forces all of the JSON-RPC sessions managed by 'remote' to disconnect and
364  * reconnect. */
365 static void
366 ovsdb_jsonrpc_session_reconnect_all(struct ovsdb_jsonrpc_remote *remote)
367 {
368     struct ovsdb_jsonrpc_session *s, *next;
369
370     LIST_FOR_EACH_SAFE (s, next, node, &remote->sessions) {
371         jsonrpc_session_force_reconnect(s->js);
372         if (!jsonrpc_session_is_alive(s->js)) {
373             ovsdb_jsonrpc_session_close(s);
374         }
375     }
376 }
377
378 static const char *
379 get_db_name(const struct ovsdb_jsonrpc_session *s)
380 {
381     return s->remote->server->db->schema->name;
382 }
383
384 static struct jsonrpc_msg *
385 ovsdb_jsonrpc_check_db_name(const struct ovsdb_jsonrpc_session *s,
386                             const struct jsonrpc_msg *request)
387 {
388     struct json_array *params;
389     const char *want_db_name;
390     const char *have_db_name;
391     struct ovsdb_error *error;
392     struct jsonrpc_msg *reply;
393
394     params = json_array(request->params);
395     if (!params->n || params->elems[0]->type != JSON_STRING) {
396         error = ovsdb_syntax_error(
397             request->params, NULL,
398             "%s request params must begin with <db-name>", request->method);
399         goto error;
400     }
401
402     want_db_name = params->elems[0]->u.string;
403     have_db_name = get_db_name(s);
404     if (strcmp(want_db_name, have_db_name)) {
405         error = ovsdb_syntax_error(
406             request->params, "unknown database",
407             "%s request specifies unknown database %s",
408             request->method, want_db_name);
409         goto error;
410     }
411
412     return NULL;
413
414 error:
415     reply = jsonrpc_create_reply(ovsdb_error_to_json(error), request->id);
416     ovsdb_error_destroy(error);
417     return reply;
418 }
419
420 static struct jsonrpc_msg *
421 execute_transaction(struct ovsdb_jsonrpc_session *s,
422                     struct jsonrpc_msg *request)
423 {
424     ovsdb_jsonrpc_trigger_create(s, request->id, request->params);
425     request->id = NULL;
426     request->params = NULL;
427     jsonrpc_msg_destroy(request);
428     return NULL;
429 }
430
431 static void
432 ovsdb_jsonrpc_session_got_request(struct ovsdb_jsonrpc_session *s,
433                                   struct jsonrpc_msg *request)
434 {
435     struct jsonrpc_msg *reply;
436
437     if (!strcmp(request->method, "transact")) {
438         reply = ovsdb_jsonrpc_check_db_name(s, request);
439         if (!reply) {
440             reply = execute_transaction(s, request);
441         }
442     } else if (!strcmp(request->method, "monitor")) {
443         reply = ovsdb_jsonrpc_check_db_name(s, request);
444         if (!reply) {
445             reply = jsonrpc_create_reply(
446                 ovsdb_jsonrpc_monitor_create(s, request->params), request->id);
447         }
448     } else if (!strcmp(request->method, "monitor_cancel")) {
449         reply = ovsdb_jsonrpc_monitor_cancel(s, json_array(request->params),
450                                              request->id);
451     } else if (!strcmp(request->method, "get_schema")) {
452         reply = ovsdb_jsonrpc_check_db_name(s, request);
453         if (!reply) {
454             reply = jsonrpc_create_reply(
455                 ovsdb_schema_to_json(s->remote->server->db->schema),
456                 request->id);
457         }
458     } else if (!strcmp(request->method, "list_dbs")) {
459         reply = jsonrpc_create_reply(
460             json_array_create_1(json_string_create(get_db_name(s))),
461             request->id);
462     } else if (!strcmp(request->method, "echo")) {
463         reply = jsonrpc_create_reply(json_clone(request->params), request->id);
464     } else {
465         reply = jsonrpc_create_error(json_string_create("unknown method"),
466                                      request->id);
467     }
468
469     if (reply) {
470         jsonrpc_msg_destroy(request);
471         jsonrpc_session_send(s->js, reply);
472     }
473 }
474
475 static void
476 execute_cancel(struct ovsdb_jsonrpc_session *s, struct jsonrpc_msg *request)
477 {
478     if (json_array(request->params)->n == 1) {
479         struct ovsdb_jsonrpc_trigger *t;
480         struct json *id;
481
482         id = request->params->u.array.elems[0];
483         t = ovsdb_jsonrpc_trigger_find(s, id, json_hash(id, 0));
484         if (t) {
485             ovsdb_jsonrpc_trigger_complete(t);
486         }
487     }
488 }
489
490 static void
491 ovsdb_jsonrpc_session_got_notify(struct ovsdb_jsonrpc_session *s,
492                                  struct jsonrpc_msg *request)
493 {
494     if (!strcmp(request->method, "cancel")) {
495         execute_cancel(s, request);
496     }
497     jsonrpc_msg_destroy(request);
498 }
499 \f
500 /* JSON-RPC database server triggers.
501  *
502  * (Every transaction is treated as a trigger even if it doesn't actually have
503  * any "wait" operations.) */
504
505 struct ovsdb_jsonrpc_trigger {
506     struct ovsdb_trigger trigger;
507     struct ovsdb_jsonrpc_session *session;
508     struct hmap_node hmap_node; /* In session's "triggers" hmap. */
509     struct json *id;
510 };
511
512 static void
513 ovsdb_jsonrpc_trigger_create(struct ovsdb_jsonrpc_session *s,
514                              struct json *id, struct json *params)
515 {
516     struct ovsdb_jsonrpc_trigger *t;
517     size_t hash;
518
519     /* Check for duplicate ID. */
520     hash = json_hash(id, 0);
521     t = ovsdb_jsonrpc_trigger_find(s, id, hash);
522     if (t) {
523         struct jsonrpc_msg *msg;
524
525         msg = jsonrpc_create_error(json_string_create("duplicate request ID"),
526                                    id);
527         jsonrpc_session_send(s->js, msg);
528         json_destroy(id);
529         json_destroy(params);
530         return;
531     }
532
533     /* Insert into trigger table. */
534     t = xmalloc(sizeof *t);
535     ovsdb_trigger_init(s->remote->server->db,
536                        &t->trigger, params, &s->completions,
537                        time_msec());
538     t->session = s;
539     t->id = id;
540     hmap_insert(&s->triggers, &t->hmap_node, hash);
541
542     /* Complete early if possible. */
543     if (ovsdb_trigger_is_complete(&t->trigger)) {
544         ovsdb_jsonrpc_trigger_complete(t);
545     }
546 }
547
548 static struct ovsdb_jsonrpc_trigger *
549 ovsdb_jsonrpc_trigger_find(struct ovsdb_jsonrpc_session *s,
550                            const struct json *id, size_t hash)
551 {
552     struct ovsdb_jsonrpc_trigger *t;
553
554     HMAP_FOR_EACH_WITH_HASH (t, hmap_node, hash, &s->triggers) {
555         if (json_equal(t->id, id)) {
556             return t;
557         }
558     }
559
560     return NULL;
561 }
562
563 static void
564 ovsdb_jsonrpc_trigger_complete(struct ovsdb_jsonrpc_trigger *t)
565 {
566     struct ovsdb_jsonrpc_session *s = t->session;
567
568     if (jsonrpc_session_is_connected(s->js)) {
569         struct jsonrpc_msg *reply;
570         struct json *result;
571
572         result = ovsdb_trigger_steal_result(&t->trigger);
573         if (result) {
574             reply = jsonrpc_create_reply(result, t->id);
575         } else {
576             reply = jsonrpc_create_error(json_string_create("canceled"),
577                                          t->id);
578         }
579         jsonrpc_session_send(s->js, reply);
580     }
581
582     json_destroy(t->id);
583     ovsdb_trigger_destroy(&t->trigger);
584     hmap_remove(&s->triggers, &t->hmap_node);
585     free(t);
586 }
587
588 static void
589 ovsdb_jsonrpc_trigger_complete_all(struct ovsdb_jsonrpc_session *s)
590 {
591     struct ovsdb_jsonrpc_trigger *t, *next;
592     HMAP_FOR_EACH_SAFE (t, next, hmap_node, &s->triggers) {
593         ovsdb_jsonrpc_trigger_complete(t);
594     }
595 }
596
597 static void
598 ovsdb_jsonrpc_trigger_complete_done(struct ovsdb_jsonrpc_session *s)
599 {
600     while (!list_is_empty(&s->completions)) {
601         struct ovsdb_jsonrpc_trigger *t
602             = CONTAINER_OF(s->completions.next,
603                            struct ovsdb_jsonrpc_trigger, trigger.node);
604         ovsdb_jsonrpc_trigger_complete(t);
605     }
606 }
607 \f
608 /* JSON-RPC database table monitors. */
609
610 enum ovsdb_jsonrpc_monitor_selection {
611     OJMS_INITIAL = 1 << 0,      /* All rows when monitor is created. */
612     OJMS_INSERT = 1 << 1,       /* New rows. */
613     OJMS_DELETE = 1 << 2,       /* Deleted rows. */
614     OJMS_MODIFY = 1 << 3        /* Modified rows. */
615 };
616
617 /* A particular column being monitored. */
618 struct ovsdb_jsonrpc_monitor_column {
619     const struct ovsdb_column *column;
620     enum ovsdb_jsonrpc_monitor_selection select;
621 };
622
623 /* A particular table being monitored. */
624 struct ovsdb_jsonrpc_monitor_table {
625     const struct ovsdb_table *table;
626
627     /* This is the union (bitwise-OR) of the 'select' values in all of the
628      * members of 'columns' below. */
629     enum ovsdb_jsonrpc_monitor_selection select;
630
631     /* Columns being monitored. */
632     struct ovsdb_jsonrpc_monitor_column *columns;
633     size_t n_columns;
634 };
635
636 /* A collection of tables being monitored. */
637 struct ovsdb_jsonrpc_monitor {
638     struct ovsdb_replica replica;
639     struct ovsdb_jsonrpc_session *session;
640     struct hmap_node node;      /* In ovsdb_jsonrpc_session's "monitors". */
641
642     struct json *monitor_id;
643     struct shash tables;     /* Holds "struct ovsdb_jsonrpc_monitor_table"s. */
644 };
645
646 static const struct ovsdb_replica_class ovsdb_jsonrpc_replica_class;
647
648 struct ovsdb_jsonrpc_monitor *ovsdb_jsonrpc_monitor_find(
649     struct ovsdb_jsonrpc_session *, const struct json *monitor_id);
650 static void ovsdb_jsonrpc_monitor_destroy(struct ovsdb_replica *);
651 static struct json *ovsdb_jsonrpc_monitor_get_initial(
652     const struct ovsdb_jsonrpc_monitor *);
653
654 static bool
655 parse_bool(struct ovsdb_parser *parser, const char *name, bool default_value)
656 {
657     const struct json *json;
658
659     json = ovsdb_parser_member(parser, name, OP_BOOLEAN | OP_OPTIONAL);
660     return json ? json_boolean(json) : default_value;
661 }
662
663 struct ovsdb_jsonrpc_monitor *
664 ovsdb_jsonrpc_monitor_find(struct ovsdb_jsonrpc_session *s,
665                            const struct json *monitor_id)
666 {
667     struct ovsdb_jsonrpc_monitor *m;
668
669     HMAP_FOR_EACH_WITH_HASH (m, node, json_hash(monitor_id, 0), &s->monitors) {
670         if (json_equal(m->monitor_id, monitor_id)) {
671             return m;
672         }
673     }
674
675     return NULL;
676 }
677
678 static void
679 ovsdb_jsonrpc_add_monitor_column(struct ovsdb_jsonrpc_monitor_table *mt,
680                                  const struct ovsdb_column *column,
681                                  enum ovsdb_jsonrpc_monitor_selection select,
682                                  size_t *allocated_columns)
683 {
684     struct ovsdb_jsonrpc_monitor_column *c;
685
686     if (mt->n_columns >= *allocated_columns) {
687         mt->columns = x2nrealloc(mt->columns, allocated_columns,
688                                  sizeof *mt->columns);
689     }
690
691     c = &mt->columns[mt->n_columns++];
692     c->column = column;
693     c->select = select;
694 }
695
696 static int
697 compare_ovsdb_jsonrpc_monitor_column(const void *a_, const void *b_)
698 {
699     const struct ovsdb_jsonrpc_monitor_column *a = a_;
700     const struct ovsdb_jsonrpc_monitor_column *b = b_;
701
702     return a->column < b->column ? -1 : a->column > b->column;
703 }
704
705 static struct ovsdb_error * WARN_UNUSED_RESULT
706 ovsdb_jsonrpc_parse_monitor_request(struct ovsdb_jsonrpc_monitor_table *mt,
707                                     const struct json *monitor_request,
708                                     size_t *allocated_columns)
709 {
710     const struct ovsdb_table_schema *ts = mt->table->schema;
711     enum ovsdb_jsonrpc_monitor_selection select;
712     const struct json *columns, *select_json;
713     struct ovsdb_parser parser;
714     struct ovsdb_error *error;
715
716     ovsdb_parser_init(&parser, monitor_request, "table %s", ts->name);
717     columns = ovsdb_parser_member(&parser, "columns", OP_ARRAY | OP_OPTIONAL);
718     select_json = ovsdb_parser_member(&parser, "select",
719                                       OP_OBJECT | OP_OPTIONAL);
720     error = ovsdb_parser_finish(&parser);
721     if (error) {
722         return error;
723     }
724
725     if (select_json) {
726         select = 0;
727         ovsdb_parser_init(&parser, select_json, "table %s select", ts->name);
728         if (parse_bool(&parser, "initial", true)) {
729             select |= OJMS_INITIAL;
730         }
731         if (parse_bool(&parser, "insert", true)) {
732             select |= OJMS_INSERT;
733         }
734         if (parse_bool(&parser, "delete", true)) {
735             select |= OJMS_DELETE;
736         }
737         if (parse_bool(&parser, "modify", true)) {
738             select |= OJMS_MODIFY;
739         }
740         error = ovsdb_parser_finish(&parser);
741         if (error) {
742             return error;
743         }
744     } else {
745         select = OJMS_INITIAL | OJMS_INSERT | OJMS_DELETE | OJMS_MODIFY;
746     }
747     mt->select |= select;
748
749     if (columns) {
750         size_t i;
751
752         if (columns->type != JSON_ARRAY) {
753             return ovsdb_syntax_error(columns, NULL,
754                                       "array of column names expected");
755         }
756
757         for (i = 0; i < columns->u.array.n; i++) {
758             const struct ovsdb_column *column;
759             const char *s;
760
761             if (columns->u.array.elems[i]->type != JSON_STRING) {
762                 return ovsdb_syntax_error(columns, NULL,
763                                           "array of column names expected");
764             }
765
766             s = columns->u.array.elems[i]->u.string;
767             column = shash_find_data(&mt->table->schema->columns, s);
768             if (!column) {
769                 return ovsdb_syntax_error(columns, NULL, "%s is not a valid "
770                                           "column name", s);
771             }
772             ovsdb_jsonrpc_add_monitor_column(mt, column, select,
773                                              allocated_columns);
774         }
775     } else {
776         struct shash_node *node;
777
778         SHASH_FOR_EACH (node, &ts->columns) {
779             const struct ovsdb_column *column = node->data;
780             if (column->index != OVSDB_COL_UUID) {
781                 ovsdb_jsonrpc_add_monitor_column(mt, column, select,
782                                                  allocated_columns);
783             }
784         }
785     }
786
787     return NULL;
788 }
789
790 static struct json *
791 ovsdb_jsonrpc_monitor_create(struct ovsdb_jsonrpc_session *s,
792                              struct json *params)
793 {
794     struct ovsdb_jsonrpc_monitor *m = NULL;
795     struct json *monitor_id, *monitor_requests;
796     struct ovsdb_error *error = NULL;
797     struct shash_node *node;
798     struct json *json;
799
800     if (json_array(params)->n != 3) {
801         error = ovsdb_syntax_error(params, NULL, "invalid parameters");
802         goto error;
803     }
804     monitor_id = params->u.array.elems[1];
805     monitor_requests = params->u.array.elems[2];
806     if (monitor_requests->type != JSON_OBJECT) {
807         error = ovsdb_syntax_error(monitor_requests, NULL,
808                                    "monitor-requests must be object");
809         goto error;
810     }
811
812     if (ovsdb_jsonrpc_monitor_find(s, monitor_id)) {
813         error = ovsdb_syntax_error(monitor_id, NULL, "duplicate monitor ID");
814         goto error;
815     }
816
817     m = xzalloc(sizeof *m);
818     ovsdb_replica_init(&m->replica, &ovsdb_jsonrpc_replica_class);
819     ovsdb_add_replica(s->remote->server->db, &m->replica);
820     m->session = s;
821     hmap_insert(&s->monitors, &m->node, json_hash(monitor_id, 0));
822     m->monitor_id = json_clone(monitor_id);
823     shash_init(&m->tables);
824
825     SHASH_FOR_EACH (node, json_object(monitor_requests)) {
826         const struct ovsdb_table *table;
827         struct ovsdb_jsonrpc_monitor_table *mt;
828         size_t allocated_columns;
829         const struct json *mr_value;
830         size_t i;
831
832         table = ovsdb_get_table(s->remote->server->db, node->name);
833         if (!table) {
834             error = ovsdb_syntax_error(NULL, NULL,
835                                        "no table named %s", node->name);
836             goto error;
837         }
838
839         mt = xzalloc(sizeof *mt);
840         mt->table = table;
841         shash_add(&m->tables, table->schema->name, mt);
842
843         /* Parse columns. */
844         mr_value = node->data;
845         allocated_columns = 0;
846         if (mr_value->type == JSON_ARRAY) {
847             const struct json_array *array = &mr_value->u.array;
848
849             for (i = 0; i < array->n; i++) {
850                 error = ovsdb_jsonrpc_parse_monitor_request(
851                     mt, array->elems[i], &allocated_columns);
852                 if (error) {
853                     goto error;
854                 }
855             }
856         } else {
857             error = ovsdb_jsonrpc_parse_monitor_request(
858                 mt, mr_value, &allocated_columns);
859             if (error) {
860                 goto error;
861             }
862         }
863
864         /* Check for duplicate columns. */
865         qsort(mt->columns, mt->n_columns, sizeof *mt->columns,
866               compare_ovsdb_jsonrpc_monitor_column);
867         for (i = 1; i < mt->n_columns; i++) {
868             if (mt->columns[i].column == mt->columns[i - 1].column) {
869                 error = ovsdb_syntax_error(mr_value, NULL, "column %s "
870                                            "mentioned more than once",
871                                            mt->columns[i].column->name);
872                 goto error;
873             }
874         }
875     }
876
877     return ovsdb_jsonrpc_monitor_get_initial(m);
878
879 error:
880     if (m) {
881         ovsdb_remove_replica(s->remote->server->db, &m->replica);
882     }
883
884     json = ovsdb_error_to_json(error);
885     ovsdb_error_destroy(error);
886     return json;
887 }
888
889 static struct jsonrpc_msg *
890 ovsdb_jsonrpc_monitor_cancel(struct ovsdb_jsonrpc_session *s,
891                              struct json_array *params,
892                              const struct json *request_id)
893 {
894     if (params->n != 1) {
895         return jsonrpc_create_error(json_string_create("invalid parameters"),
896                                     request_id);
897     } else {
898         struct ovsdb_jsonrpc_monitor *m;
899
900         m = ovsdb_jsonrpc_monitor_find(s, params->elems[0]);
901         if (!m) {
902             return jsonrpc_create_error(json_string_create("unknown monitor"),
903                                         request_id);
904         } else {
905             ovsdb_remove_replica(s->remote->server->db, &m->replica);
906             return jsonrpc_create_reply(json_object_create(), request_id);
907         }
908     }
909 }
910
911 static void
912 ovsdb_jsonrpc_monitor_remove_all(struct ovsdb_jsonrpc_session *s)
913 {
914     struct ovsdb_jsonrpc_monitor *m, *next;
915
916     HMAP_FOR_EACH_SAFE (m, next, node, &s->monitors) {
917         ovsdb_remove_replica(s->remote->server->db, &m->replica);
918     }
919 }
920
921 static struct ovsdb_jsonrpc_monitor *
922 ovsdb_jsonrpc_monitor_cast(struct ovsdb_replica *replica)
923 {
924     assert(replica->class == &ovsdb_jsonrpc_replica_class);
925     return CONTAINER_OF(replica, struct ovsdb_jsonrpc_monitor, replica);
926 }
927
928 struct ovsdb_jsonrpc_monitor_aux {
929     bool initial;               /* Sending initial contents of table? */
930     const struct ovsdb_jsonrpc_monitor *monitor;
931     struct json *json;          /* JSON for the whole transaction. */
932
933     /* Current table.  */
934     struct ovsdb_jsonrpc_monitor_table *mt;
935     struct json *table_json;    /* JSON for table's transaction. */
936 };
937
938 static bool
939 ovsdb_jsonrpc_monitor_change_cb(const struct ovsdb_row *old,
940                                 const struct ovsdb_row *new,
941                                 const unsigned long int *changed,
942                                 void *aux_)
943 {
944     struct ovsdb_jsonrpc_monitor_aux *aux = aux_;
945     const struct ovsdb_jsonrpc_monitor *m = aux->monitor;
946     struct ovsdb_table *table = new ? new->table : old->table;
947     enum ovsdb_jsonrpc_monitor_selection type;
948     struct json *old_json, *new_json;
949     struct json *row_json;
950     char uuid[UUID_LEN + 1];
951     int n_changed;
952     size_t i;
953
954     if (!aux->mt || table != aux->mt->table) {
955         aux->mt = shash_find_data(&m->tables, table->schema->name);
956         aux->table_json = NULL;
957         if (!aux->mt) {
958             /* We don't care about rows in this table at all.  Tell the caller
959              * to skip it.  */
960             return false;
961         }
962     }
963
964     type = (aux->initial ? OJMS_INITIAL
965             : !old ? OJMS_INSERT
966             : !new ? OJMS_DELETE
967             : OJMS_MODIFY);
968     if (!(aux->mt->select & type)) {
969         /* We don't care about this type of change (but do want to be called
970          * back for changes to other rows in the same table). */
971         return true;
972     }
973
974     old_json = new_json = NULL;
975     n_changed = 0;
976     for (i = 0; i < aux->mt->n_columns; i++) {
977         const struct ovsdb_jsonrpc_monitor_column *c = &aux->mt->columns[i];
978         const struct ovsdb_column *column = c->column;
979         unsigned int idx = c->column->index;
980         bool column_changed = false;
981
982         if (!(type & c->select)) {
983             /* We don't care about this type of change for this particular
984              * column (but we will care about it for some other column). */
985             continue;
986         }
987
988         if (type == OJMS_MODIFY) {
989             column_changed = bitmap_is_set(changed, idx);
990             n_changed += column_changed;
991         }
992         if (column_changed || type == OJMS_DELETE) {
993             if (!old_json) {
994                 old_json = json_object_create();
995             }
996             json_object_put(old_json, column->name,
997                             ovsdb_datum_to_json(&old->fields[idx],
998                                                 &column->type));
999         }
1000         if (type & (OJMS_INITIAL | OJMS_INSERT | OJMS_MODIFY)) {
1001             if (!new_json) {
1002                 new_json = json_object_create();
1003             }
1004             json_object_put(new_json, column->name,
1005                             ovsdb_datum_to_json(&new->fields[idx],
1006                                                 &column->type));
1007         }
1008     }
1009     if ((type == OJMS_MODIFY && !n_changed) || (!old_json && !new_json)) {
1010         /* No reportable changes. */
1011         json_destroy(old_json);
1012         json_destroy(new_json);
1013         return true;
1014     }
1015
1016     /* Create JSON object for transaction overall. */
1017     if (!aux->json) {
1018         aux->json = json_object_create();
1019     }
1020
1021     /* Create JSON object for transaction on this table. */
1022     if (!aux->table_json) {
1023         aux->table_json = json_object_create();
1024         json_object_put(aux->json, aux->mt->table->schema->name,
1025                         aux->table_json);
1026     }
1027
1028     /* Create JSON object for transaction on this row. */
1029     row_json = json_object_create();
1030     if (old_json) {
1031         json_object_put(row_json, "old", old_json);
1032     }
1033     if (new_json) {
1034         json_object_put(row_json, "new", new_json);
1035     }
1036
1037     /* Add JSON row to JSON table. */
1038     snprintf(uuid, sizeof uuid,
1039              UUID_FMT, UUID_ARGS(ovsdb_row_get_uuid(new ? new : old)));
1040     json_object_put(aux->table_json, uuid, row_json);
1041
1042     return true;
1043 }
1044
1045 static void
1046 ovsdb_jsonrpc_monitor_init_aux(struct ovsdb_jsonrpc_monitor_aux *aux,
1047                                const struct ovsdb_jsonrpc_monitor *m,
1048                                bool initial)
1049 {
1050     aux->initial = initial;
1051     aux->monitor = m;
1052     aux->json = NULL;
1053     aux->mt = NULL;
1054     aux->table_json = NULL;
1055 }
1056
1057 static struct ovsdb_error *
1058 ovsdb_jsonrpc_monitor_commit(struct ovsdb_replica *replica,
1059                              const struct ovsdb_txn *txn,
1060                              bool durable OVS_UNUSED)
1061 {
1062     struct ovsdb_jsonrpc_monitor *m = ovsdb_jsonrpc_monitor_cast(replica);
1063     struct ovsdb_jsonrpc_monitor_aux aux;
1064
1065     ovsdb_jsonrpc_monitor_init_aux(&aux, m, false);
1066     ovsdb_txn_for_each_change(txn, ovsdb_jsonrpc_monitor_change_cb, &aux);
1067     if (aux.json) {
1068         struct jsonrpc_msg *msg;
1069         struct json *params;
1070
1071         params = json_array_create_2(json_clone(aux.monitor->monitor_id),
1072                                      aux.json);
1073         msg = jsonrpc_create_notify("update", params);
1074         jsonrpc_session_send(aux.monitor->session->js, msg);
1075     }
1076
1077     return NULL;
1078 }
1079
1080 static struct json *
1081 ovsdb_jsonrpc_monitor_get_initial(const struct ovsdb_jsonrpc_monitor *m)
1082 {
1083     struct ovsdb_jsonrpc_monitor_aux aux;
1084     struct shash_node *node;
1085
1086     ovsdb_jsonrpc_monitor_init_aux(&aux, m, true);
1087     SHASH_FOR_EACH (node, &m->tables) {
1088         struct ovsdb_jsonrpc_monitor_table *mt = node->data;
1089
1090         if (mt->select & OJMS_INITIAL) {
1091             struct ovsdb_row *row;
1092
1093             HMAP_FOR_EACH (row, hmap_node, &mt->table->rows) {
1094                 ovsdb_jsonrpc_monitor_change_cb(NULL, row, NULL, &aux);
1095             }
1096         }
1097     }
1098     return aux.json ? aux.json : json_object_create();
1099 }
1100
1101 static void
1102 ovsdb_jsonrpc_monitor_destroy(struct ovsdb_replica *replica)
1103 {
1104     struct ovsdb_jsonrpc_monitor *m = ovsdb_jsonrpc_monitor_cast(replica);
1105     struct shash_node *node;
1106
1107     json_destroy(m->monitor_id);
1108     SHASH_FOR_EACH (node, &m->tables) {
1109         struct ovsdb_jsonrpc_monitor_table *mt = node->data;
1110         free(mt->columns);
1111         free(mt);
1112     }
1113     shash_destroy(&m->tables);
1114     hmap_remove(&m->session->monitors, &m->node);
1115     free(m);
1116 }
1117
1118 static const struct ovsdb_replica_class ovsdb_jsonrpc_replica_class = {
1119     ovsdb_jsonrpc_monitor_commit,
1120     ovsdb_jsonrpc_monitor_destroy
1121 };