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