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