3e4e71ec7b187eb66422ea4d221b6ba788fafdd8
[sliver-openvswitch.git] / ovsdb / jsonrpc-server.c
1 /* Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
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 <errno.h>
21
22 #include "bitmap.h"
23 #include "column.h"
24 #include "dynamic-string.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 "server.h"
33 #include "simap.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_get_memory_usage_all(
55     const struct ovsdb_jsonrpc_remote *, struct simap *usage);
56 static void ovsdb_jsonrpc_session_close_all(struct ovsdb_jsonrpc_remote *);
57 static void ovsdb_jsonrpc_session_reconnect_all(struct ovsdb_jsonrpc_remote *);
58 static void ovsdb_jsonrpc_session_set_all_options(
59     struct ovsdb_jsonrpc_remote *, const struct ovsdb_jsonrpc_options *);
60 static bool ovsdb_jsonrpc_session_get_status(
61     const struct ovsdb_jsonrpc_remote *,
62     struct ovsdb_jsonrpc_remote_status *);
63 static void ovsdb_jsonrpc_session_unlock_all(struct ovsdb_jsonrpc_session *);
64 static void ovsdb_jsonrpc_session_unlock__(struct ovsdb_lock_waiter *);
65
66 /* Triggers. */
67 static void ovsdb_jsonrpc_trigger_create(struct ovsdb_jsonrpc_session *,
68                                          struct ovsdb *,
69                                          struct json *id, struct json *params);
70 static struct ovsdb_jsonrpc_trigger *ovsdb_jsonrpc_trigger_find(
71     struct ovsdb_jsonrpc_session *, const struct json *id, size_t hash);
72 static void ovsdb_jsonrpc_trigger_complete(struct ovsdb_jsonrpc_trigger *);
73 static void ovsdb_jsonrpc_trigger_complete_all(struct ovsdb_jsonrpc_session *);
74 static void ovsdb_jsonrpc_trigger_complete_done(
75     struct ovsdb_jsonrpc_session *);
76
77 /* Monitors. */
78 static struct json *ovsdb_jsonrpc_monitor_create(
79     struct ovsdb_jsonrpc_session *, struct ovsdb *, struct json *params);
80 static struct jsonrpc_msg *ovsdb_jsonrpc_monitor_cancel(
81     struct ovsdb_jsonrpc_session *,
82     struct json_array *params,
83     const struct json *request_id);
84 static void ovsdb_jsonrpc_monitor_remove_all(struct ovsdb_jsonrpc_session *);
85 \f
86 /* JSON-RPC database server. */
87
88 struct ovsdb_jsonrpc_server {
89     struct ovsdb_server up;
90     unsigned int n_sessions, max_sessions;
91     struct shash remotes;      /* Contains "struct ovsdb_jsonrpc_remote *"s. */
92 };
93
94 /* A configured remote.  This is either a passive stream listener plus a list
95  * of the currently connected sessions, or a list of exactly one active
96  * session. */
97 struct ovsdb_jsonrpc_remote {
98     struct ovsdb_jsonrpc_server *server;
99     struct pstream *listener;   /* Listener, if passive. */
100     struct list sessions;       /* List of "struct ovsdb_jsonrpc_session"s. */
101     uint8_t dscp;
102 };
103
104 static struct ovsdb_jsonrpc_remote *ovsdb_jsonrpc_server_add_remote(
105     struct ovsdb_jsonrpc_server *, const char *name,
106     const struct ovsdb_jsonrpc_options *options
107 );
108 static void ovsdb_jsonrpc_server_del_remote(struct shash_node *);
109
110 /* Creates and returns a new server to provide JSON-RPC access to an OVSDB.
111  *
112  * The caller must call ovsdb_jsonrpc_server_add_db() for each database to
113  * which 'server' should provide access. */
114 struct ovsdb_jsonrpc_server *
115 ovsdb_jsonrpc_server_create(void)
116 {
117     struct ovsdb_jsonrpc_server *server = xzalloc(sizeof *server);
118     ovsdb_server_init(&server->up);
119     server->max_sessions = 64;
120     shash_init(&server->remotes);
121     return server;
122 }
123
124 /* Adds 'db' to the set of databases served out by 'svr'.  Returns true if
125  * successful, false if 'db''s name is the same as some database already in
126  * 'server'. */
127 bool
128 ovsdb_jsonrpc_server_add_db(struct ovsdb_jsonrpc_server *svr, struct ovsdb *db)
129 {
130     /* The OVSDB protocol doesn't have a way to notify a client that a
131      * database has been added.  If some client tried to use the database
132      * that we're adding and failed, then forcing it to reconnect seems like
133      * a reasonable way to make it try again.
134      *
135      * If this is too big of a hammer in practice, we could be more selective,
136      * e.g. disconnect only connections that actually tried to use a database
137      * with 'db''s name. */
138     ovsdb_jsonrpc_server_reconnect(svr);
139
140     return ovsdb_server_add_db(&svr->up, db);
141 }
142
143 /* Removes 'db' from the set of databases served out by 'svr'.  Returns
144  * true if successful, false if there is no database associated with 'db'. */
145 bool
146 ovsdb_jsonrpc_server_remove_db(struct ovsdb_jsonrpc_server *svr,
147                                struct ovsdb *db)
148 {
149     /* There might be pointers to 'db' from 'svr', such as monitors or
150      * outstanding transactions.  Disconnect all JSON-RPC connections to avoid
151      * accesses to freed memory.
152      *
153      * If this is too big of a hammer in practice, we could be more selective,
154      * e.g. disconnect only connections that actually reference 'db'. */
155     ovsdb_jsonrpc_server_reconnect(svr);
156
157     return ovsdb_server_remove_db(&svr->up, db);
158 }
159
160 void
161 ovsdb_jsonrpc_server_destroy(struct ovsdb_jsonrpc_server *svr)
162 {
163     struct shash_node *node, *next;
164
165     SHASH_FOR_EACH_SAFE (node, next, &svr->remotes) {
166         ovsdb_jsonrpc_server_del_remote(node);
167     }
168     shash_destroy(&svr->remotes);
169     ovsdb_server_destroy(&svr->up);
170     free(svr);
171 }
172
173 struct ovsdb_jsonrpc_options *
174 ovsdb_jsonrpc_default_options(const char *target)
175 {
176     struct ovsdb_jsonrpc_options *options = xzalloc(sizeof *options);
177     options->max_backoff = RECONNECT_DEFAULT_MAX_BACKOFF;
178     options->probe_interval = (stream_or_pstream_needs_probes(target)
179                                ? RECONNECT_DEFAULT_PROBE_INTERVAL
180                                : 0);
181     return options;
182 }
183
184 /* Sets 'svr''s current set of remotes to the names in 'new_remotes', with
185  * options in the struct ovsdb_jsonrpc_options supplied as the data values.
186  *
187  * A remote is an active or passive stream connection method, e.g. "pssl:" or
188  * "tcp:1.2.3.4". */
189 void
190 ovsdb_jsonrpc_server_set_remotes(struct ovsdb_jsonrpc_server *svr,
191                                  const struct shash *new_remotes)
192 {
193     struct shash_node *node, *next;
194
195     SHASH_FOR_EACH_SAFE (node, next, &svr->remotes) {
196         if (!shash_find(new_remotes, node->name)) {
197             VLOG_INFO("%s: remote deconfigured", node->name);
198             ovsdb_jsonrpc_server_del_remote(node);
199         }
200     }
201     SHASH_FOR_EACH (node, new_remotes) {
202         const struct ovsdb_jsonrpc_options *options = node->data;
203         struct ovsdb_jsonrpc_remote *remote;
204
205         remote = shash_find_data(&svr->remotes, node->name);
206         if (!remote) {
207             remote = ovsdb_jsonrpc_server_add_remote(svr, node->name, options);
208             if (!remote) {
209                 continue;
210             }
211         }
212
213         ovsdb_jsonrpc_session_set_all_options(remote, options);
214     }
215 }
216
217 static struct ovsdb_jsonrpc_remote *
218 ovsdb_jsonrpc_server_add_remote(struct ovsdb_jsonrpc_server *svr,
219                                 const char *name,
220                                 const struct ovsdb_jsonrpc_options *options)
221 {
222     struct ovsdb_jsonrpc_remote *remote;
223     struct pstream *listener;
224     int error;
225
226     error = jsonrpc_pstream_open(name, &listener, options->dscp);
227     if (error && error != EAFNOSUPPORT) {
228         VLOG_ERR_RL(&rl, "%s: listen failed: %s", name, ovs_strerror(error));
229         return NULL;
230     }
231
232     remote = xmalloc(sizeof *remote);
233     remote->server = svr;
234     remote->listener = listener;
235     list_init(&remote->sessions);
236     remote->dscp = options->dscp;
237     shash_add(&svr->remotes, name, remote);
238
239     if (!listener) {
240         ovsdb_jsonrpc_session_create(remote, jsonrpc_session_open(name, true));
241     }
242     return remote;
243 }
244
245 static void
246 ovsdb_jsonrpc_server_del_remote(struct shash_node *node)
247 {
248     struct ovsdb_jsonrpc_remote *remote = node->data;
249
250     ovsdb_jsonrpc_session_close_all(remote);
251     pstream_close(remote->listener);
252     shash_delete(&remote->server->remotes, node);
253     free(remote);
254 }
255
256 /* Stores status information for the remote named 'target', which should have
257  * been configured on 'svr' with a call to ovsdb_jsonrpc_server_set_remotes(),
258  * into '*status'.  On success returns true, on failure (if 'svr' doesn't have
259  * a remote named 'target' or if that remote is an inbound remote that has no
260  * active connections) returns false.  On failure, 'status' will be zeroed.
261  */
262 bool
263 ovsdb_jsonrpc_server_get_remote_status(
264     const struct ovsdb_jsonrpc_server *svr, const char *target,
265     struct ovsdb_jsonrpc_remote_status *status)
266 {
267     const struct ovsdb_jsonrpc_remote *remote;
268
269     memset(status, 0, sizeof *status);
270
271     remote = shash_find_data(&svr->remotes, target);
272     return remote && ovsdb_jsonrpc_session_get_status(remote, status);
273 }
274
275 void
276 ovsdb_jsonrpc_server_free_remote_status(
277     struct ovsdb_jsonrpc_remote_status *status)
278 {
279     free(status->locks_held);
280     free(status->locks_waiting);
281     free(status->locks_lost);
282 }
283
284 /* Forces all of the JSON-RPC sessions managed by 'svr' to disconnect and
285  * reconnect. */
286 void
287 ovsdb_jsonrpc_server_reconnect(struct ovsdb_jsonrpc_server *svr)
288 {
289     struct shash_node *node;
290
291     SHASH_FOR_EACH (node, &svr->remotes) {
292         struct ovsdb_jsonrpc_remote *remote = node->data;
293
294         ovsdb_jsonrpc_session_reconnect_all(remote);
295     }
296 }
297
298 void
299 ovsdb_jsonrpc_server_run(struct ovsdb_jsonrpc_server *svr)
300 {
301     struct shash_node *node;
302
303     SHASH_FOR_EACH (node, &svr->remotes) {
304         struct ovsdb_jsonrpc_remote *remote = node->data;
305
306         if (remote->listener && svr->n_sessions < svr->max_sessions) {
307             struct stream *stream;
308             int error;
309
310             error = pstream_accept(remote->listener, &stream);
311             if (!error) {
312                 struct jsonrpc_session *js;
313                 js = jsonrpc_session_open_unreliably(jsonrpc_open(stream),
314                                                      remote->dscp);
315                 ovsdb_jsonrpc_session_create(remote, js);
316             } else if (error != EAGAIN) {
317                 VLOG_WARN_RL(&rl, "%s: accept failed: %s",
318                              pstream_get_name(remote->listener),
319                              ovs_strerror(error));
320             }
321         }
322
323         ovsdb_jsonrpc_session_run_all(remote);
324     }
325 }
326
327 void
328 ovsdb_jsonrpc_server_wait(struct ovsdb_jsonrpc_server *svr)
329 {
330     struct shash_node *node;
331
332     SHASH_FOR_EACH (node, &svr->remotes) {
333         struct ovsdb_jsonrpc_remote *remote = node->data;
334
335         if (remote->listener && svr->n_sessions < svr->max_sessions) {
336             pstream_wait(remote->listener);
337         }
338
339         ovsdb_jsonrpc_session_wait_all(remote);
340     }
341 }
342
343 /* Adds some memory usage statistics for 'svr' into 'usage', for use with
344  * memory_report(). */
345 void
346 ovsdb_jsonrpc_server_get_memory_usage(const struct ovsdb_jsonrpc_server *svr,
347                                       struct simap *usage)
348 {
349     struct shash_node *node;
350
351     simap_increase(usage, "sessions", svr->n_sessions);
352     SHASH_FOR_EACH (node, &svr->remotes) {
353         struct ovsdb_jsonrpc_remote *remote = node->data;
354
355         ovsdb_jsonrpc_session_get_memory_usage_all(remote, usage);
356     }
357 }
358 \f
359 /* JSON-RPC database server session. */
360
361 struct ovsdb_jsonrpc_session {
362     struct list node;           /* Element in remote's sessions list. */
363     struct ovsdb_session up;
364     struct ovsdb_jsonrpc_remote *remote;
365
366     /* Triggers. */
367     struct hmap triggers;       /* Hmap of "struct ovsdb_jsonrpc_trigger"s. */
368
369     /* Monitors. */
370     struct hmap monitors;       /* Hmap of "struct ovsdb_jsonrpc_monitor"s. */
371
372     /* Network connectivity. */
373     struct jsonrpc_session *js;  /* JSON-RPC session. */
374     unsigned int js_seqno;       /* Last jsonrpc_session_get_seqno() value. */
375 };
376
377 static void ovsdb_jsonrpc_session_close(struct ovsdb_jsonrpc_session *);
378 static int ovsdb_jsonrpc_session_run(struct ovsdb_jsonrpc_session *);
379 static void ovsdb_jsonrpc_session_wait(struct ovsdb_jsonrpc_session *);
380 static void ovsdb_jsonrpc_session_get_memory_usage(
381     const struct ovsdb_jsonrpc_session *, struct simap *usage);
382 static void ovsdb_jsonrpc_session_set_options(
383     struct ovsdb_jsonrpc_session *, const struct ovsdb_jsonrpc_options *);
384 static void ovsdb_jsonrpc_session_got_request(struct ovsdb_jsonrpc_session *,
385                                              struct jsonrpc_msg *);
386 static void ovsdb_jsonrpc_session_got_notify(struct ovsdb_jsonrpc_session *,
387                                              struct jsonrpc_msg *);
388
389 static struct ovsdb_jsonrpc_session *
390 ovsdb_jsonrpc_session_create(struct ovsdb_jsonrpc_remote *remote,
391                              struct jsonrpc_session *js)
392 {
393     struct ovsdb_jsonrpc_session *s;
394
395     s = xzalloc(sizeof *s);
396     ovsdb_session_init(&s->up, &remote->server->up);
397     s->remote = remote;
398     list_push_back(&remote->sessions, &s->node);
399     hmap_init(&s->triggers);
400     hmap_init(&s->monitors);
401     s->js = js;
402     s->js_seqno = jsonrpc_session_get_seqno(js);
403
404     remote->server->n_sessions++;
405
406     return s;
407 }
408
409 static void
410 ovsdb_jsonrpc_session_close(struct ovsdb_jsonrpc_session *s)
411 {
412     ovsdb_jsonrpc_monitor_remove_all(s);
413     ovsdb_jsonrpc_session_unlock_all(s);
414     ovsdb_jsonrpc_trigger_complete_all(s);
415
416     hmap_destroy(&s->monitors);
417     hmap_destroy(&s->triggers);
418
419     jsonrpc_session_close(s->js);
420     list_remove(&s->node);
421     s->remote->server->n_sessions--;
422     ovsdb_session_destroy(&s->up);
423     free(s);
424 }
425
426 static int
427 ovsdb_jsonrpc_session_run(struct ovsdb_jsonrpc_session *s)
428 {
429     jsonrpc_session_run(s->js);
430     if (s->js_seqno != jsonrpc_session_get_seqno(s->js)) {
431         s->js_seqno = jsonrpc_session_get_seqno(s->js);
432         ovsdb_jsonrpc_trigger_complete_all(s);
433         ovsdb_jsonrpc_monitor_remove_all(s);
434         ovsdb_jsonrpc_session_unlock_all(s);
435     }
436
437     ovsdb_jsonrpc_trigger_complete_done(s);
438
439     if (!jsonrpc_session_get_backlog(s->js)) {
440         struct jsonrpc_msg *msg = jsonrpc_session_recv(s->js);
441         if (msg) {
442             if (msg->type == JSONRPC_REQUEST) {
443                 ovsdb_jsonrpc_session_got_request(s, msg);
444             } else if (msg->type == JSONRPC_NOTIFY) {
445                 ovsdb_jsonrpc_session_got_notify(s, msg);
446             } else {
447                 VLOG_WARN("%s: received unexpected %s message",
448                           jsonrpc_session_get_name(s->js),
449                           jsonrpc_msg_type_to_string(msg->type));
450                 jsonrpc_session_force_reconnect(s->js);
451                 jsonrpc_msg_destroy(msg);
452             }
453         }
454     }
455     return jsonrpc_session_is_alive(s->js) ? 0 : ETIMEDOUT;
456 }
457
458 static void
459 ovsdb_jsonrpc_session_set_options(struct ovsdb_jsonrpc_session *session,
460                                   const struct ovsdb_jsonrpc_options *options)
461 {
462     jsonrpc_session_set_max_backoff(session->js, options->max_backoff);
463     jsonrpc_session_set_probe_interval(session->js, options->probe_interval);
464     jsonrpc_session_set_dscp(session->js, options->dscp);
465 }
466
467 static void
468 ovsdb_jsonrpc_session_run_all(struct ovsdb_jsonrpc_remote *remote)
469 {
470     struct ovsdb_jsonrpc_session *s, *next;
471
472     LIST_FOR_EACH_SAFE (s, next, node, &remote->sessions) {
473         int error = ovsdb_jsonrpc_session_run(s);
474         if (error) {
475             ovsdb_jsonrpc_session_close(s);
476         }
477     }
478 }
479
480 static void
481 ovsdb_jsonrpc_session_wait(struct ovsdb_jsonrpc_session *s)
482 {
483     jsonrpc_session_wait(s->js);
484     if (!jsonrpc_session_get_backlog(s->js)) {
485         jsonrpc_session_recv_wait(s->js);
486     }
487 }
488
489 static void
490 ovsdb_jsonrpc_session_wait_all(struct ovsdb_jsonrpc_remote *remote)
491 {
492     struct ovsdb_jsonrpc_session *s;
493
494     LIST_FOR_EACH (s, node, &remote->sessions) {
495         ovsdb_jsonrpc_session_wait(s);
496     }
497 }
498
499 static void
500 ovsdb_jsonrpc_session_get_memory_usage(const struct ovsdb_jsonrpc_session *s,
501                                        struct simap *usage)
502 {
503     simap_increase(usage, "triggers", hmap_count(&s->triggers));
504     simap_increase(usage, "monitors", hmap_count(&s->monitors));
505     simap_increase(usage, "backlog", jsonrpc_session_get_backlog(s->js));
506 }
507
508 static void
509 ovsdb_jsonrpc_session_get_memory_usage_all(
510     const struct ovsdb_jsonrpc_remote *remote,
511     struct simap *usage)
512 {
513     struct ovsdb_jsonrpc_session *s;
514
515     LIST_FOR_EACH (s, node, &remote->sessions) {
516         ovsdb_jsonrpc_session_get_memory_usage(s, usage);
517     }
518 }
519
520 static void
521 ovsdb_jsonrpc_session_close_all(struct ovsdb_jsonrpc_remote *remote)
522 {
523     struct ovsdb_jsonrpc_session *s, *next;
524
525     LIST_FOR_EACH_SAFE (s, next, node, &remote->sessions) {
526         ovsdb_jsonrpc_session_close(s);
527     }
528 }
529
530 /* Forces all of the JSON-RPC sessions managed by 'remote' to disconnect and
531  * reconnect. */
532 static void
533 ovsdb_jsonrpc_session_reconnect_all(struct ovsdb_jsonrpc_remote *remote)
534 {
535     struct ovsdb_jsonrpc_session *s, *next;
536
537     LIST_FOR_EACH_SAFE (s, next, node, &remote->sessions) {
538         jsonrpc_session_force_reconnect(s->js);
539         if (!jsonrpc_session_is_alive(s->js)) {
540             ovsdb_jsonrpc_session_close(s);
541         }
542     }
543 }
544
545 /* Sets the options for all of the JSON-RPC sessions managed by 'remote' to
546  * 'options'. */
547 static void
548 ovsdb_jsonrpc_session_set_all_options(
549     struct ovsdb_jsonrpc_remote *remote,
550     const struct ovsdb_jsonrpc_options *options)
551 {
552     struct ovsdb_jsonrpc_session *s;
553
554     if (remote->listener) {
555         int error;
556
557         error = pstream_set_dscp(remote->listener, options->dscp);
558         if (error) {
559             VLOG_ERR("%s: set_dscp failed %s",
560                      pstream_get_name(remote->listener), ovs_strerror(error));
561         } else {
562             remote->dscp = options->dscp;
563         }
564         /*
565          * XXX race window between setting dscp to listening socket
566          * and accepting socket. Accepted socket may have old dscp value.
567          * Ignore this race window for now.
568          */
569     }
570     LIST_FOR_EACH (s, node, &remote->sessions) {
571         ovsdb_jsonrpc_session_set_options(s, options);
572     }
573 }
574
575 static bool
576 ovsdb_jsonrpc_session_get_status(const struct ovsdb_jsonrpc_remote *remote,
577                                  struct ovsdb_jsonrpc_remote_status *status)
578 {
579     const struct ovsdb_jsonrpc_session *s;
580     const struct jsonrpc_session *js;
581     struct ovsdb_lock_waiter *waiter;
582     struct reconnect_stats rstats;
583     struct ds locks_held, locks_waiting, locks_lost;
584
585     status->bound_port = (remote->listener
586                           ? pstream_get_bound_port(remote->listener)
587                           : htons(0));
588
589     if (list_is_empty(&remote->sessions)) {
590         return false;
591     }
592     s = CONTAINER_OF(remote->sessions.next, struct ovsdb_jsonrpc_session, node);
593     js = s->js;
594
595     status->is_connected = jsonrpc_session_is_connected(js);
596     status->last_error = jsonrpc_session_get_status(js);
597
598     jsonrpc_session_get_reconnect_stats(js, &rstats);
599     status->state = rstats.state;
600     status->sec_since_connect = rstats.msec_since_connect == UINT_MAX
601         ? UINT_MAX : rstats.msec_since_connect / 1000;
602     status->sec_since_disconnect = rstats.msec_since_disconnect == UINT_MAX
603         ? UINT_MAX : rstats.msec_since_disconnect / 1000;
604
605     ds_init(&locks_held);
606     ds_init(&locks_waiting);
607     ds_init(&locks_lost);
608     HMAP_FOR_EACH (waiter, session_node, &s->up.waiters) {
609         struct ds *string;
610
611         string = (ovsdb_lock_waiter_is_owner(waiter) ? &locks_held
612                   : waiter->mode == OVSDB_LOCK_WAIT ? &locks_waiting
613                   : &locks_lost);
614         if (string->length) {
615             ds_put_char(string, ' ');
616         }
617         ds_put_cstr(string, waiter->lock_name);
618     }
619     status->locks_held = ds_steal_cstr(&locks_held);
620     status->locks_waiting = ds_steal_cstr(&locks_waiting);
621     status->locks_lost = ds_steal_cstr(&locks_lost);
622
623     status->n_connections = list_size(&remote->sessions);
624
625     return true;
626 }
627
628 /* Examines 'request' to determine the database to which it relates, and then
629  * searches 's' to find that database:
630  *
631  *    - If successful, returns the database and sets '*replyp' to NULL.
632  *
633  *    - If no such database exists, returns NULL and sets '*replyp' to an
634  *      appropriate JSON-RPC error reply, owned by the caller. */
635 static struct ovsdb *
636 ovsdb_jsonrpc_lookup_db(const struct ovsdb_jsonrpc_session *s,
637                         const struct jsonrpc_msg *request,
638                         struct jsonrpc_msg **replyp)
639 {
640     struct json_array *params;
641     struct ovsdb_error *error;
642     const char *db_name;
643     struct ovsdb *db;
644
645     params = json_array(request->params);
646     if (!params->n || params->elems[0]->type != JSON_STRING) {
647         error = ovsdb_syntax_error(
648             request->params, NULL,
649             "%s request params must begin with <db-name>", request->method);
650         goto error;
651     }
652
653     db_name = params->elems[0]->u.string;
654     db = shash_find_data(&s->up.server->dbs, db_name);
655     if (!db) {
656         error = ovsdb_syntax_error(
657             request->params, "unknown database",
658             "%s request specifies unknown database %s",
659             request->method, db_name);
660         goto error;
661     }
662
663     *replyp = NULL;
664     return db;
665
666 error:
667     *replyp = jsonrpc_create_reply(ovsdb_error_to_json(error), request->id);
668     ovsdb_error_destroy(error);
669     return NULL;
670 }
671
672 static struct ovsdb_error *
673 ovsdb_jsonrpc_session_parse_lock_name(const struct jsonrpc_msg *request,
674                                       const char **lock_namep)
675 {
676     const struct json_array *params;
677
678     params = json_array(request->params);
679     if (params->n != 1 || params->elems[0]->type != JSON_STRING ||
680         !ovsdb_parser_is_id(json_string(params->elems[0]))) {
681         *lock_namep = NULL;
682         return ovsdb_syntax_error(request->params, NULL,
683                                   "%s request params must be <id>",
684                                   request->method);
685     }
686
687     *lock_namep = json_string(params->elems[0]);
688     return NULL;
689 }
690
691 static void
692 ovsdb_jsonrpc_session_notify(struct ovsdb_session *session,
693                              const char *lock_name,
694                              const char *method)
695 {
696     struct ovsdb_jsonrpc_session *s;
697     struct json *params;
698
699     s = CONTAINER_OF(session, struct ovsdb_jsonrpc_session, up);
700     params = json_array_create_1(json_string_create(lock_name));
701     jsonrpc_session_send(s->js, jsonrpc_create_notify(method, params));
702 }
703
704 static struct jsonrpc_msg *
705 ovsdb_jsonrpc_session_lock(struct ovsdb_jsonrpc_session *s,
706                            struct jsonrpc_msg *request,
707                            enum ovsdb_lock_mode mode)
708 {
709     struct ovsdb_lock_waiter *waiter;
710     struct jsonrpc_msg *reply;
711     struct ovsdb_error *error;
712     struct ovsdb_session *victim;
713     const char *lock_name;
714     struct json *result;
715
716     error = ovsdb_jsonrpc_session_parse_lock_name(request, &lock_name);
717     if (error) {
718         goto error;
719     }
720
721     /* Report error if this session has issued a "lock" or "steal" without a
722      * matching "unlock" for this lock. */
723     waiter = ovsdb_session_get_lock_waiter(&s->up, lock_name);
724     if (waiter) {
725         error = ovsdb_syntax_error(
726             request->params, NULL,
727             "must issue \"unlock\" before new \"%s\"", request->method);
728         goto error;
729     }
730
731     /* Get the lock, add us as a waiter. */
732     waiter = ovsdb_server_lock(&s->remote->server->up, &s->up, lock_name, mode,
733                                &victim);
734     if (victim) {
735         ovsdb_jsonrpc_session_notify(victim, lock_name, "stolen");
736     }
737
738     result = json_object_create();
739     json_object_put(result, "locked",
740                     json_boolean_create(ovsdb_lock_waiter_is_owner(waiter)));
741
742     return jsonrpc_create_reply(result, request->id);
743
744 error:
745     reply = jsonrpc_create_reply(ovsdb_error_to_json(error), request->id);
746     ovsdb_error_destroy(error);
747     return reply;
748 }
749
750 static void
751 ovsdb_jsonrpc_session_unlock_all(struct ovsdb_jsonrpc_session *s)
752 {
753     struct ovsdb_lock_waiter *waiter, *next;
754
755     HMAP_FOR_EACH_SAFE (waiter, next, session_node, &s->up.waiters) {
756         ovsdb_jsonrpc_session_unlock__(waiter);
757     }
758 }
759
760 static void
761 ovsdb_jsonrpc_session_unlock__(struct ovsdb_lock_waiter *waiter)
762 {
763     struct ovsdb_lock *lock = waiter->lock;
764
765     if (lock) {
766         struct ovsdb_session *new_owner = ovsdb_lock_waiter_remove(waiter);
767         if (new_owner) {
768             ovsdb_jsonrpc_session_notify(new_owner, lock->name, "locked");
769         } else {
770             /* ovsdb_server_lock() might have freed 'lock'. */
771         }
772     }
773
774     ovsdb_lock_waiter_destroy(waiter);
775 }
776
777 static struct jsonrpc_msg *
778 ovsdb_jsonrpc_session_unlock(struct ovsdb_jsonrpc_session *s,
779                              struct jsonrpc_msg *request)
780 {
781     struct ovsdb_lock_waiter *waiter;
782     struct jsonrpc_msg *reply;
783     struct ovsdb_error *error;
784     const char *lock_name;
785
786     error = ovsdb_jsonrpc_session_parse_lock_name(request, &lock_name);
787     if (error) {
788         goto error;
789     }
790
791     /* Report error if this session has not issued a "lock" or "steal" for this
792      * lock. */
793     waiter = ovsdb_session_get_lock_waiter(&s->up, lock_name);
794     if (!waiter) {
795         error = ovsdb_syntax_error(
796             request->params, NULL, "\"unlock\" without \"lock\" or \"steal\"");
797         goto error;
798     }
799
800     ovsdb_jsonrpc_session_unlock__(waiter);
801
802     return jsonrpc_create_reply(json_object_create(), request->id);
803
804 error:
805     reply = jsonrpc_create_reply(ovsdb_error_to_json(error), request->id);
806     ovsdb_error_destroy(error);
807     return reply;
808 }
809
810 static struct jsonrpc_msg *
811 execute_transaction(struct ovsdb_jsonrpc_session *s, struct ovsdb *db,
812                     struct jsonrpc_msg *request)
813 {
814     ovsdb_jsonrpc_trigger_create(s, db, request->id, request->params);
815     request->id = NULL;
816     request->params = NULL;
817     jsonrpc_msg_destroy(request);
818     return NULL;
819 }
820
821 static void
822 ovsdb_jsonrpc_session_got_request(struct ovsdb_jsonrpc_session *s,
823                                   struct jsonrpc_msg *request)
824 {
825     struct jsonrpc_msg *reply;
826
827     if (!strcmp(request->method, "transact")) {
828         struct ovsdb *db = ovsdb_jsonrpc_lookup_db(s, request, &reply);
829         if (!reply) {
830             reply = execute_transaction(s, db, request);
831         }
832     } else if (!strcmp(request->method, "monitor")) {
833         struct ovsdb *db = ovsdb_jsonrpc_lookup_db(s, request, &reply);
834         if (!reply) {
835             reply = jsonrpc_create_reply(
836                 ovsdb_jsonrpc_monitor_create(s, db, request->params),
837                 request->id);
838         }
839     } else if (!strcmp(request->method, "monitor_cancel")) {
840         reply = ovsdb_jsonrpc_monitor_cancel(s, json_array(request->params),
841                                              request->id);
842     } else if (!strcmp(request->method, "get_schema")) {
843         struct ovsdb *db = ovsdb_jsonrpc_lookup_db(s, request, &reply);
844         if (!reply) {
845             reply = jsonrpc_create_reply(ovsdb_schema_to_json(db->schema),
846                                          request->id);
847         }
848     } else if (!strcmp(request->method, "list_dbs")) {
849         size_t n_dbs = shash_count(&s->up.server->dbs);
850         struct shash_node *node;
851         struct json **dbs;
852         size_t i;
853
854         dbs = xmalloc(n_dbs * sizeof *dbs);
855         i = 0;
856         SHASH_FOR_EACH (node, &s->up.server->dbs) {
857             dbs[i++] = json_string_create(node->name);
858         }
859         reply = jsonrpc_create_reply(json_array_create(dbs, n_dbs),
860                                      request->id);
861     } else if (!strcmp(request->method, "lock")) {
862         reply = ovsdb_jsonrpc_session_lock(s, request, OVSDB_LOCK_WAIT);
863     } else if (!strcmp(request->method, "steal")) {
864         reply = ovsdb_jsonrpc_session_lock(s, request, OVSDB_LOCK_STEAL);
865     } else if (!strcmp(request->method, "unlock")) {
866         reply = ovsdb_jsonrpc_session_unlock(s, request);
867     } else if (!strcmp(request->method, "echo")) {
868         reply = jsonrpc_create_reply(json_clone(request->params), request->id);
869     } else {
870         reply = jsonrpc_create_error(json_string_create("unknown method"),
871                                      request->id);
872     }
873
874     if (reply) {
875         jsonrpc_msg_destroy(request);
876         jsonrpc_session_send(s->js, reply);
877     }
878 }
879
880 static void
881 execute_cancel(struct ovsdb_jsonrpc_session *s, struct jsonrpc_msg *request)
882 {
883     if (json_array(request->params)->n == 1) {
884         struct ovsdb_jsonrpc_trigger *t;
885         struct json *id;
886
887         id = request->params->u.array.elems[0];
888         t = ovsdb_jsonrpc_trigger_find(s, id, json_hash(id, 0));
889         if (t) {
890             ovsdb_jsonrpc_trigger_complete(t);
891         }
892     }
893 }
894
895 static void
896 ovsdb_jsonrpc_session_got_notify(struct ovsdb_jsonrpc_session *s,
897                                  struct jsonrpc_msg *request)
898 {
899     if (!strcmp(request->method, "cancel")) {
900         execute_cancel(s, request);
901     }
902     jsonrpc_msg_destroy(request);
903 }
904 \f
905 /* JSON-RPC database server triggers.
906  *
907  * (Every transaction is treated as a trigger even if it doesn't actually have
908  * any "wait" operations.) */
909
910 struct ovsdb_jsonrpc_trigger {
911     struct ovsdb_trigger trigger;
912     struct hmap_node hmap_node; /* In session's "triggers" hmap. */
913     struct json *id;
914 };
915
916 static void
917 ovsdb_jsonrpc_trigger_create(struct ovsdb_jsonrpc_session *s, struct ovsdb *db,
918                              struct json *id, struct json *params)
919 {
920     struct ovsdb_jsonrpc_trigger *t;
921     size_t hash;
922
923     /* Check for duplicate ID. */
924     hash = json_hash(id, 0);
925     t = ovsdb_jsonrpc_trigger_find(s, id, hash);
926     if (t) {
927         struct jsonrpc_msg *msg;
928
929         msg = jsonrpc_create_error(json_string_create("duplicate request ID"),
930                                    id);
931         jsonrpc_session_send(s->js, msg);
932         json_destroy(id);
933         json_destroy(params);
934         return;
935     }
936
937     /* Insert into trigger table. */
938     t = xmalloc(sizeof *t);
939     ovsdb_trigger_init(&s->up, db, &t->trigger, params, time_msec());
940     t->id = id;
941     hmap_insert(&s->triggers, &t->hmap_node, hash);
942
943     /* Complete early if possible. */
944     if (ovsdb_trigger_is_complete(&t->trigger)) {
945         ovsdb_jsonrpc_trigger_complete(t);
946     }
947 }
948
949 static struct ovsdb_jsonrpc_trigger *
950 ovsdb_jsonrpc_trigger_find(struct ovsdb_jsonrpc_session *s,
951                            const struct json *id, size_t hash)
952 {
953     struct ovsdb_jsonrpc_trigger *t;
954
955     HMAP_FOR_EACH_WITH_HASH (t, hmap_node, hash, &s->triggers) {
956         if (json_equal(t->id, id)) {
957             return t;
958         }
959     }
960
961     return NULL;
962 }
963
964 static void
965 ovsdb_jsonrpc_trigger_complete(struct ovsdb_jsonrpc_trigger *t)
966 {
967     struct ovsdb_jsonrpc_session *s;
968
969     s = CONTAINER_OF(t->trigger.session, struct ovsdb_jsonrpc_session, up);
970
971     if (jsonrpc_session_is_connected(s->js)) {
972         struct jsonrpc_msg *reply;
973         struct json *result;
974
975         result = ovsdb_trigger_steal_result(&t->trigger);
976         if (result) {
977             reply = jsonrpc_create_reply(result, t->id);
978         } else {
979             reply = jsonrpc_create_error(json_string_create("canceled"),
980                                          t->id);
981         }
982         jsonrpc_session_send(s->js, reply);
983     }
984
985     json_destroy(t->id);
986     ovsdb_trigger_destroy(&t->trigger);
987     hmap_remove(&s->triggers, &t->hmap_node);
988     free(t);
989 }
990
991 static void
992 ovsdb_jsonrpc_trigger_complete_all(struct ovsdb_jsonrpc_session *s)
993 {
994     struct ovsdb_jsonrpc_trigger *t, *next;
995     HMAP_FOR_EACH_SAFE (t, next, hmap_node, &s->triggers) {
996         ovsdb_jsonrpc_trigger_complete(t);
997     }
998 }
999
1000 static void
1001 ovsdb_jsonrpc_trigger_complete_done(struct ovsdb_jsonrpc_session *s)
1002 {
1003     while (!list_is_empty(&s->up.completions)) {
1004         struct ovsdb_jsonrpc_trigger *t
1005             = CONTAINER_OF(s->up.completions.next,
1006                            struct ovsdb_jsonrpc_trigger, trigger.node);
1007         ovsdb_jsonrpc_trigger_complete(t);
1008     }
1009 }
1010 \f
1011 /* JSON-RPC database table monitors. */
1012
1013 enum ovsdb_jsonrpc_monitor_selection {
1014     OJMS_INITIAL = 1 << 0,      /* All rows when monitor is created. */
1015     OJMS_INSERT = 1 << 1,       /* New rows. */
1016     OJMS_DELETE = 1 << 2,       /* Deleted rows. */
1017     OJMS_MODIFY = 1 << 3        /* Modified rows. */
1018 };
1019
1020 /* A particular column being monitored. */
1021 struct ovsdb_jsonrpc_monitor_column {
1022     const struct ovsdb_column *column;
1023     enum ovsdb_jsonrpc_monitor_selection select;
1024 };
1025
1026 /* A row that has changed in a monitored table. */
1027 struct ovsdb_jsonrpc_monitor_row {
1028     struct hmap_node hmap_node; /* In ovsdb_jsonrpc_monitor_table.changes. */
1029     struct uuid uuid;           /* UUID of row that changed. */
1030     struct ovsdb_datum *old;    /* Old data, NULL for an inserted row. */
1031     struct ovsdb_datum *new;    /* New data, NULL for a deleted row. */
1032 };
1033
1034 /* A particular table being monitored. */
1035 struct ovsdb_jsonrpc_monitor_table {
1036     const struct ovsdb_table *table;
1037
1038     /* This is the union (bitwise-OR) of the 'select' values in all of the
1039      * members of 'columns' below. */
1040     enum ovsdb_jsonrpc_monitor_selection select;
1041
1042     /* Columns being monitored. */
1043     struct ovsdb_jsonrpc_monitor_column *columns;
1044     size_t n_columns;
1045
1046     /* Contains 'struct ovsdb_jsonrpc_monitor_row's for rows that have been
1047      * updated but not yet flushed to the jsonrpc connection. */
1048     struct hmap changes;
1049 };
1050
1051 /* A collection of tables being monitored. */
1052 struct ovsdb_jsonrpc_monitor {
1053     struct ovsdb_replica replica;
1054     struct ovsdb_jsonrpc_session *session;
1055     struct ovsdb *db;
1056     struct hmap_node node;      /* In ovsdb_jsonrpc_session's "monitors". */
1057
1058     struct json *monitor_id;
1059     struct shash tables;     /* Holds "struct ovsdb_jsonrpc_monitor_table"s. */
1060 };
1061
1062 static const struct ovsdb_replica_class ovsdb_jsonrpc_replica_class;
1063
1064 struct ovsdb_jsonrpc_monitor *ovsdb_jsonrpc_monitor_find(
1065     struct ovsdb_jsonrpc_session *, const struct json *monitor_id);
1066 static void ovsdb_jsonrpc_monitor_destroy(struct ovsdb_replica *);
1067 static struct json *ovsdb_jsonrpc_monitor_get_initial(
1068     const struct ovsdb_jsonrpc_monitor *);
1069
1070 static bool
1071 parse_bool(struct ovsdb_parser *parser, const char *name, bool default_value)
1072 {
1073     const struct json *json;
1074
1075     json = ovsdb_parser_member(parser, name, OP_BOOLEAN | OP_OPTIONAL);
1076     return json ? json_boolean(json) : default_value;
1077 }
1078
1079 struct ovsdb_jsonrpc_monitor *
1080 ovsdb_jsonrpc_monitor_find(struct ovsdb_jsonrpc_session *s,
1081                            const struct json *monitor_id)
1082 {
1083     struct ovsdb_jsonrpc_monitor *m;
1084
1085     HMAP_FOR_EACH_WITH_HASH (m, node, json_hash(monitor_id, 0), &s->monitors) {
1086         if (json_equal(m->monitor_id, monitor_id)) {
1087             return m;
1088         }
1089     }
1090
1091     return NULL;
1092 }
1093
1094 static void
1095 ovsdb_jsonrpc_add_monitor_column(struct ovsdb_jsonrpc_monitor_table *mt,
1096                                  const struct ovsdb_column *column,
1097                                  enum ovsdb_jsonrpc_monitor_selection select,
1098                                  size_t *allocated_columns)
1099 {
1100     struct ovsdb_jsonrpc_monitor_column *c;
1101
1102     if (mt->n_columns >= *allocated_columns) {
1103         mt->columns = x2nrealloc(mt->columns, allocated_columns,
1104                                  sizeof *mt->columns);
1105     }
1106
1107     c = &mt->columns[mt->n_columns++];
1108     c->column = column;
1109     c->select = select;
1110 }
1111
1112 static int
1113 compare_ovsdb_jsonrpc_monitor_column(const void *a_, const void *b_)
1114 {
1115     const struct ovsdb_jsonrpc_monitor_column *a = a_;
1116     const struct ovsdb_jsonrpc_monitor_column *b = b_;
1117
1118     return a->column < b->column ? -1 : a->column > b->column;
1119 }
1120
1121 static struct ovsdb_error * WARN_UNUSED_RESULT
1122 ovsdb_jsonrpc_parse_monitor_request(struct ovsdb_jsonrpc_monitor_table *mt,
1123                                     const struct json *monitor_request,
1124                                     size_t *allocated_columns)
1125 {
1126     const struct ovsdb_table_schema *ts = mt->table->schema;
1127     enum ovsdb_jsonrpc_monitor_selection select;
1128     const struct json *columns, *select_json;
1129     struct ovsdb_parser parser;
1130     struct ovsdb_error *error;
1131
1132     ovsdb_parser_init(&parser, monitor_request, "table %s", ts->name);
1133     columns = ovsdb_parser_member(&parser, "columns", OP_ARRAY | OP_OPTIONAL);
1134     select_json = ovsdb_parser_member(&parser, "select",
1135                                       OP_OBJECT | OP_OPTIONAL);
1136     error = ovsdb_parser_finish(&parser);
1137     if (error) {
1138         return error;
1139     }
1140
1141     if (select_json) {
1142         select = 0;
1143         ovsdb_parser_init(&parser, select_json, "table %s select", ts->name);
1144         if (parse_bool(&parser, "initial", true)) {
1145             select |= OJMS_INITIAL;
1146         }
1147         if (parse_bool(&parser, "insert", true)) {
1148             select |= OJMS_INSERT;
1149         }
1150         if (parse_bool(&parser, "delete", true)) {
1151             select |= OJMS_DELETE;
1152         }
1153         if (parse_bool(&parser, "modify", true)) {
1154             select |= OJMS_MODIFY;
1155         }
1156         error = ovsdb_parser_finish(&parser);
1157         if (error) {
1158             return error;
1159         }
1160     } else {
1161         select = OJMS_INITIAL | OJMS_INSERT | OJMS_DELETE | OJMS_MODIFY;
1162     }
1163     mt->select |= select;
1164
1165     if (columns) {
1166         size_t i;
1167
1168         if (columns->type != JSON_ARRAY) {
1169             return ovsdb_syntax_error(columns, NULL,
1170                                       "array of column names expected");
1171         }
1172
1173         for (i = 0; i < columns->u.array.n; i++) {
1174             const struct ovsdb_column *column;
1175             const char *s;
1176
1177             if (columns->u.array.elems[i]->type != JSON_STRING) {
1178                 return ovsdb_syntax_error(columns, NULL,
1179                                           "array of column names expected");
1180             }
1181
1182             s = columns->u.array.elems[i]->u.string;
1183             column = shash_find_data(&mt->table->schema->columns, s);
1184             if (!column) {
1185                 return ovsdb_syntax_error(columns, NULL, "%s is not a valid "
1186                                           "column name", s);
1187             }
1188             ovsdb_jsonrpc_add_monitor_column(mt, column, select,
1189                                              allocated_columns);
1190         }
1191     } else {
1192         struct shash_node *node;
1193
1194         SHASH_FOR_EACH (node, &ts->columns) {
1195             const struct ovsdb_column *column = node->data;
1196             if (column->index != OVSDB_COL_UUID) {
1197                 ovsdb_jsonrpc_add_monitor_column(mt, column, select,
1198                                                  allocated_columns);
1199             }
1200         }
1201     }
1202
1203     return NULL;
1204 }
1205
1206 static struct json *
1207 ovsdb_jsonrpc_monitor_create(struct ovsdb_jsonrpc_session *s, struct ovsdb *db,
1208                              struct json *params)
1209 {
1210     struct ovsdb_jsonrpc_monitor *m = NULL;
1211     struct json *monitor_id, *monitor_requests;
1212     struct ovsdb_error *error = NULL;
1213     struct shash_node *node;
1214     struct json *json;
1215
1216     if (json_array(params)->n != 3) {
1217         error = ovsdb_syntax_error(params, NULL, "invalid parameters");
1218         goto error;
1219     }
1220     monitor_id = params->u.array.elems[1];
1221     monitor_requests = params->u.array.elems[2];
1222     if (monitor_requests->type != JSON_OBJECT) {
1223         error = ovsdb_syntax_error(monitor_requests, NULL,
1224                                    "monitor-requests must be object");
1225         goto error;
1226     }
1227
1228     if (ovsdb_jsonrpc_monitor_find(s, monitor_id)) {
1229         error = ovsdb_syntax_error(monitor_id, NULL, "duplicate monitor ID");
1230         goto error;
1231     }
1232
1233     m = xzalloc(sizeof *m);
1234     ovsdb_replica_init(&m->replica, &ovsdb_jsonrpc_replica_class);
1235     ovsdb_add_replica(db, &m->replica);
1236     m->session = s;
1237     m->db = db;
1238     hmap_insert(&s->monitors, &m->node, json_hash(monitor_id, 0));
1239     m->monitor_id = json_clone(monitor_id);
1240     shash_init(&m->tables);
1241
1242     SHASH_FOR_EACH (node, json_object(monitor_requests)) {
1243         const struct ovsdb_table *table;
1244         struct ovsdb_jsonrpc_monitor_table *mt;
1245         size_t allocated_columns;
1246         const struct json *mr_value;
1247         size_t i;
1248
1249         table = ovsdb_get_table(m->db, node->name);
1250         if (!table) {
1251             error = ovsdb_syntax_error(NULL, NULL,
1252                                        "no table named %s", node->name);
1253             goto error;
1254         }
1255
1256         mt = xzalloc(sizeof *mt);
1257         mt->table = table;
1258         hmap_init(&mt->changes);
1259         shash_add(&m->tables, table->schema->name, mt);
1260
1261         /* Parse columns. */
1262         mr_value = node->data;
1263         allocated_columns = 0;
1264         if (mr_value->type == JSON_ARRAY) {
1265             const struct json_array *array = &mr_value->u.array;
1266
1267             for (i = 0; i < array->n; i++) {
1268                 error = ovsdb_jsonrpc_parse_monitor_request(
1269                     mt, array->elems[i], &allocated_columns);
1270                 if (error) {
1271                     goto error;
1272                 }
1273             }
1274         } else {
1275             error = ovsdb_jsonrpc_parse_monitor_request(
1276                 mt, mr_value, &allocated_columns);
1277             if (error) {
1278                 goto error;
1279             }
1280         }
1281
1282         /* Check for duplicate columns. */
1283         qsort(mt->columns, mt->n_columns, sizeof *mt->columns,
1284               compare_ovsdb_jsonrpc_monitor_column);
1285         for (i = 1; i < mt->n_columns; i++) {
1286             if (mt->columns[i].column == mt->columns[i - 1].column) {
1287                 error = ovsdb_syntax_error(mr_value, NULL, "column %s "
1288                                            "mentioned more than once",
1289                                            mt->columns[i].column->name);
1290                 goto error;
1291             }
1292         }
1293     }
1294
1295     return ovsdb_jsonrpc_monitor_get_initial(m);
1296
1297 error:
1298     if (m) {
1299         ovsdb_remove_replica(m->db, &m->replica);
1300     }
1301
1302     json = ovsdb_error_to_json(error);
1303     ovsdb_error_destroy(error);
1304     return json;
1305 }
1306
1307 static struct jsonrpc_msg *
1308 ovsdb_jsonrpc_monitor_cancel(struct ovsdb_jsonrpc_session *s,
1309                              struct json_array *params,
1310                              const struct json *request_id)
1311 {
1312     if (params->n != 1) {
1313         return jsonrpc_create_error(json_string_create("invalid parameters"),
1314                                     request_id);
1315     } else {
1316         struct ovsdb_jsonrpc_monitor *m;
1317
1318         m = ovsdb_jsonrpc_monitor_find(s, params->elems[0]);
1319         if (!m) {
1320             return jsonrpc_create_error(json_string_create("unknown monitor"),
1321                                         request_id);
1322         } else {
1323             ovsdb_remove_replica(m->db, &m->replica);
1324             return jsonrpc_create_reply(json_object_create(), request_id);
1325         }
1326     }
1327 }
1328
1329 static void
1330 ovsdb_jsonrpc_monitor_remove_all(struct ovsdb_jsonrpc_session *s)
1331 {
1332     struct ovsdb_jsonrpc_monitor *m, *next;
1333
1334     HMAP_FOR_EACH_SAFE (m, next, node, &s->monitors) {
1335         ovsdb_remove_replica(m->db, &m->replica);
1336     }
1337 }
1338
1339 static struct ovsdb_jsonrpc_monitor *
1340 ovsdb_jsonrpc_monitor_cast(struct ovsdb_replica *replica)
1341 {
1342     ovs_assert(replica->class == &ovsdb_jsonrpc_replica_class);
1343     return CONTAINER_OF(replica, struct ovsdb_jsonrpc_monitor, replica);
1344 }
1345
1346 struct ovsdb_jsonrpc_monitor_aux {
1347     const struct ovsdb_jsonrpc_monitor *monitor;
1348     struct ovsdb_jsonrpc_monitor_table *mt;
1349 };
1350
1351 /* Finds and returns the ovsdb_jsonrpc_monitor_row in 'mt->changes' for the
1352  * given 'uuid', or NULL if there is no such row. */
1353 static struct ovsdb_jsonrpc_monitor_row *
1354 ovsdb_jsonrpc_monitor_row_find(const struct ovsdb_jsonrpc_monitor_table *mt,
1355                                const struct uuid *uuid)
1356 {
1357     struct ovsdb_jsonrpc_monitor_row *row;
1358
1359     HMAP_FOR_EACH_WITH_HASH (row, hmap_node, uuid_hash(uuid), &mt->changes) {
1360         if (uuid_equals(uuid, &row->uuid)) {
1361             return row;
1362         }
1363     }
1364     return NULL;
1365 }
1366
1367 /* Allocates an array of 'mt->n_columns' ovsdb_datums and initializes them as
1368  * copies of the data in 'row' drawn from the columns represented by
1369  * mt->columns[].  Returns the array.
1370  *
1371  * If 'row' is NULL, returns NULL. */
1372 static struct ovsdb_datum *
1373 clone_monitor_row_data(const struct ovsdb_jsonrpc_monitor_table *mt,
1374                        const struct ovsdb_row *row)
1375 {
1376     struct ovsdb_datum *data;
1377     size_t i;
1378
1379     if (!row) {
1380         return NULL;
1381     }
1382
1383     data = xmalloc(mt->n_columns * sizeof *data);
1384     for (i = 0; i < mt->n_columns; i++) {
1385         const struct ovsdb_column *c = mt->columns[i].column;
1386         const struct ovsdb_datum *src = &row->fields[c->index];
1387         struct ovsdb_datum *dst = &data[i];
1388         const struct ovsdb_type *type = &c->type;
1389
1390         ovsdb_datum_clone(dst, src, type);
1391     }
1392     return data;
1393 }
1394
1395 /* Replaces the mt->n_columns ovsdb_datums in row[] by copies of the data from
1396  * in 'row' drawn from the columns represented by mt->columns[]. */
1397 static void
1398 update_monitor_row_data(const struct ovsdb_jsonrpc_monitor_table *mt,
1399                         const struct ovsdb_row *row,
1400                         struct ovsdb_datum *data)
1401 {
1402     size_t i;
1403
1404     for (i = 0; i < mt->n_columns; i++) {
1405         const struct ovsdb_column *c = mt->columns[i].column;
1406         const struct ovsdb_datum *src = &row->fields[c->index];
1407         struct ovsdb_datum *dst = &data[i];
1408         const struct ovsdb_type *type = &c->type;
1409
1410         if (!ovsdb_datum_equals(src, dst, type)) {
1411             ovsdb_datum_destroy(dst, type);
1412             ovsdb_datum_clone(dst, src, type);
1413         }
1414     }
1415 }
1416
1417 /* Frees all of the mt->n_columns ovsdb_datums in data[], using the types taken
1418  * from mt->columns[], plus 'data' itself. */
1419 static void
1420 free_monitor_row_data(const struct ovsdb_jsonrpc_monitor_table *mt,
1421                       struct ovsdb_datum *data)
1422 {
1423     if (data) {
1424         size_t i;
1425
1426         for (i = 0; i < mt->n_columns; i++) {
1427             const struct ovsdb_column *c = mt->columns[i].column;
1428
1429             ovsdb_datum_destroy(&data[i], &c->type);
1430         }
1431         free(data);
1432     }
1433 }
1434
1435 /* Frees 'row', which must have been created from 'mt'. */
1436 static void
1437 ovsdb_jsonrpc_monitor_row_destroy(const struct ovsdb_jsonrpc_monitor_table *mt,
1438                                   struct ovsdb_jsonrpc_monitor_row *row)
1439 {
1440     if (row) {
1441         free_monitor_row_data(mt, row->old);
1442         free_monitor_row_data(mt, row->new);
1443         free(row);
1444     }
1445 }
1446
1447 static bool
1448 ovsdb_jsonrpc_monitor_change_cb(const struct ovsdb_row *old,
1449                                 const struct ovsdb_row *new,
1450                                 const unsigned long int *changed OVS_UNUSED,
1451                                 void *aux_)
1452 {
1453     struct ovsdb_jsonrpc_monitor_aux *aux = aux_;
1454     const struct ovsdb_jsonrpc_monitor *m = aux->monitor;
1455     struct ovsdb_table *table = new ? new->table : old->table;
1456     const struct uuid *uuid = ovsdb_row_get_uuid(new ? new : old);
1457     struct ovsdb_jsonrpc_monitor_row *change;
1458     struct ovsdb_jsonrpc_monitor_table *mt;
1459
1460     if (!aux->mt || table != aux->mt->table) {
1461         aux->mt = shash_find_data(&m->tables, table->schema->name);
1462         if (!aux->mt) {
1463             /* We don't care about rows in this table at all.  Tell the caller
1464              * to skip it.  */
1465             return false;
1466         }
1467     }
1468     mt = aux->mt;
1469
1470     change = ovsdb_jsonrpc_monitor_row_find(mt, uuid);
1471     if (!change) {
1472         change = xmalloc(sizeof *change);
1473         hmap_insert(&mt->changes, &change->hmap_node, uuid_hash(uuid));
1474         change->uuid = *uuid;
1475         change->old = clone_monitor_row_data(mt, old);
1476         change->new = clone_monitor_row_data(mt, new);
1477     } else {
1478         if (new) {
1479             update_monitor_row_data(mt, new, change->new);
1480         } else {
1481             free_monitor_row_data(mt, change->new);
1482             change->new = NULL;
1483
1484             if (!change->old) {
1485                 /* This row was added then deleted.  Forget about it. */
1486                 hmap_remove(&mt->changes, &change->hmap_node);
1487                 free(change);
1488             }
1489         }
1490     }
1491     return true;
1492 }
1493
1494 /* Returns JSON for a <row-update> (as described in ovsdb/SPECS) for 'row'
1495  * within 'mt', or NULL if no row update should be sent.
1496  *
1497  * The caller should specify 'initial' as true if the returned JSON is going to
1498  * be used as part of the initial reply to a "monitor" request, false if it is
1499  * going to be used as part of an "update" notification.
1500  *
1501  * 'changed' must be a scratch buffer for internal use that is at least
1502  * bitmap_n_bytes(mt->n_columns) bytes long. */
1503 static struct json *
1504 ovsdb_jsonrpc_monitor_compose_row_update(
1505     const struct ovsdb_jsonrpc_monitor_table *mt,
1506     const struct ovsdb_jsonrpc_monitor_row *row,
1507     bool initial, unsigned long int *changed)
1508 {
1509     enum ovsdb_jsonrpc_monitor_selection type;
1510     struct json *old_json, *new_json;
1511     struct json *row_json;
1512     size_t i;
1513
1514     type = (initial ? OJMS_INITIAL
1515             : !row->old ? OJMS_INSERT
1516             : !row->new ? OJMS_DELETE
1517             : OJMS_MODIFY);
1518     if (!(mt->select & type)) {
1519         return NULL;
1520     }
1521
1522     if (type == OJMS_MODIFY) {
1523         size_t n_changes;
1524
1525         n_changes = 0;
1526         memset(changed, 0, bitmap_n_bytes(mt->n_columns));
1527         for (i = 0; i < mt->n_columns; i++) {
1528             const struct ovsdb_column *c = mt->columns[i].column;
1529             if (!ovsdb_datum_equals(&row->old[i], &row->new[i], &c->type)) {
1530                 bitmap_set1(changed, i);
1531                 n_changes++;
1532             }
1533         }
1534         if (!n_changes) {
1535             /* No actual changes: presumably a row changed and then
1536              * changed back later. */
1537             return NULL;
1538         }
1539     }
1540
1541     row_json = json_object_create();
1542     old_json = new_json = NULL;
1543     if (type & (OJMS_DELETE | OJMS_MODIFY)) {
1544         old_json = json_object_create();
1545         json_object_put(row_json, "old", old_json);
1546     }
1547     if (type & (OJMS_INITIAL | OJMS_INSERT | OJMS_MODIFY)) {
1548         new_json = json_object_create();
1549         json_object_put(row_json, "new", new_json);
1550     }
1551     for (i = 0; i < mt->n_columns; i++) {
1552         const struct ovsdb_jsonrpc_monitor_column *c = &mt->columns[i];
1553
1554         if (!(type & c->select)) {
1555             /* We don't care about this type of change for this
1556              * particular column (but we will care about it for some
1557              * other column). */
1558             continue;
1559         }
1560
1561         if ((type == OJMS_MODIFY && bitmap_is_set(changed, i))
1562             || type == OJMS_DELETE) {
1563             json_object_put(old_json, c->column->name,
1564                             ovsdb_datum_to_json(&row->old[i],
1565                                                 &c->column->type));
1566         }
1567         if (type & (OJMS_INITIAL | OJMS_INSERT | OJMS_MODIFY)) {
1568             json_object_put(new_json, c->column->name,
1569                             ovsdb_datum_to_json(&row->new[i],
1570                                                 &c->column->type));
1571         }
1572     }
1573
1574     return row_json;
1575 }
1576
1577 /* Constructs and returns JSON for a <table-updates> object (as described in
1578  * ovsdb/SPECS) for all the outstanding changes within 'monitor', and deletes
1579  * all the outstanding changes from 'monitor'.  Returns NULL if no update needs
1580  * to be sent.
1581  *
1582  * The caller should specify 'initial' as true if the returned JSON is going to
1583  * be used as part of the initial reply to a "monitor" request, false if it is
1584  * going to be used as part of an "update" notification. */
1585 static struct json *
1586 ovsdb_jsonrpc_monitor_compose_table_update(
1587     const struct ovsdb_jsonrpc_monitor *monitor, bool initial)
1588 {
1589     struct shash_node *node;
1590     unsigned long int *changed;
1591     struct json *json;
1592     size_t max_columns;
1593
1594     max_columns = 0;
1595     SHASH_FOR_EACH (node, &monitor->tables) {
1596         struct ovsdb_jsonrpc_monitor_table *mt = node->data;
1597
1598         max_columns = MAX(max_columns, mt->n_columns);
1599     }
1600     changed = xmalloc(bitmap_n_bytes(max_columns));
1601
1602     json = NULL;
1603     SHASH_FOR_EACH (node, &monitor->tables) {
1604         struct ovsdb_jsonrpc_monitor_table *mt = node->data;
1605         struct ovsdb_jsonrpc_monitor_row *row, *next;
1606         struct json *table_json = NULL;
1607
1608         HMAP_FOR_EACH_SAFE (row, next, hmap_node, &mt->changes) {
1609             struct json *row_json;
1610
1611             row_json = ovsdb_jsonrpc_monitor_compose_row_update(
1612                 mt, row, initial, changed);
1613             if (row_json) {
1614                 char uuid[UUID_LEN + 1];
1615
1616                 /* Create JSON object for transaction overall. */
1617                 if (!json) {
1618                     json = json_object_create();
1619                 }
1620
1621                 /* Create JSON object for transaction on this table. */
1622                 if (!table_json) {
1623                     table_json = json_object_create();
1624                     json_object_put(json, mt->table->schema->name, table_json);
1625                 }
1626
1627                 /* Add JSON row to JSON table. */
1628                 snprintf(uuid, sizeof uuid, UUID_FMT, UUID_ARGS(&row->uuid));
1629                 json_object_put(table_json, uuid, row_json);
1630             }
1631
1632             hmap_remove(&mt->changes, &row->hmap_node);
1633             ovsdb_jsonrpc_monitor_row_destroy(mt, row);
1634         }
1635     }
1636
1637     free(changed);
1638
1639     return json;
1640 }
1641
1642 static void
1643 ovsdb_jsonrpc_monitor_init_aux(struct ovsdb_jsonrpc_monitor_aux *aux,
1644                                const struct ovsdb_jsonrpc_monitor *m)
1645 {
1646     aux->monitor = m;
1647     aux->mt = NULL;
1648 }
1649
1650 static struct ovsdb_error *
1651 ovsdb_jsonrpc_monitor_commit(struct ovsdb_replica *replica,
1652                              const struct ovsdb_txn *txn,
1653                              bool durable OVS_UNUSED)
1654 {
1655     struct ovsdb_jsonrpc_monitor *m = ovsdb_jsonrpc_monitor_cast(replica);
1656     struct ovsdb_jsonrpc_monitor_aux aux;
1657     struct json *json;
1658
1659     ovsdb_jsonrpc_monitor_init_aux(&aux, m);
1660     ovsdb_txn_for_each_change(txn, ovsdb_jsonrpc_monitor_change_cb, &aux);
1661     json = ovsdb_jsonrpc_monitor_compose_table_update(m, false);
1662     if (json) {
1663         struct jsonrpc_msg *msg;
1664         struct json *params;
1665
1666         params = json_array_create_2(json_clone(aux.monitor->monitor_id),
1667                                      json);
1668         msg = jsonrpc_create_notify("update", params);
1669         jsonrpc_session_send(aux.monitor->session->js, msg);
1670     }
1671
1672     return NULL;
1673 }
1674
1675 static struct json *
1676 ovsdb_jsonrpc_monitor_get_initial(const struct ovsdb_jsonrpc_monitor *m)
1677 {
1678     struct ovsdb_jsonrpc_monitor_aux aux;
1679     struct shash_node *node;
1680     struct json *json;
1681
1682     ovsdb_jsonrpc_monitor_init_aux(&aux, m);
1683     SHASH_FOR_EACH (node, &m->tables) {
1684         struct ovsdb_jsonrpc_monitor_table *mt = node->data;
1685
1686         if (mt->select & OJMS_INITIAL) {
1687             struct ovsdb_row *row;
1688
1689             HMAP_FOR_EACH (row, hmap_node, &mt->table->rows) {
1690                 ovsdb_jsonrpc_monitor_change_cb(NULL, row, NULL, &aux);
1691             }
1692         }
1693     }
1694     json = ovsdb_jsonrpc_monitor_compose_table_update(m, true);
1695     return json ? json : json_object_create();
1696 }
1697
1698 static void
1699 ovsdb_jsonrpc_monitor_destroy(struct ovsdb_replica *replica)
1700 {
1701     struct ovsdb_jsonrpc_monitor *m = ovsdb_jsonrpc_monitor_cast(replica);
1702     struct shash_node *node;
1703
1704     json_destroy(m->monitor_id);
1705     SHASH_FOR_EACH (node, &m->tables) {
1706         struct ovsdb_jsonrpc_monitor_table *mt = node->data;
1707         struct ovsdb_jsonrpc_monitor_row *row, *next;
1708
1709         HMAP_FOR_EACH_SAFE (row, next, hmap_node, &mt->changes) {
1710             hmap_remove(&mt->changes, &row->hmap_node);
1711             ovsdb_jsonrpc_monitor_row_destroy(mt, row);
1712         }
1713         hmap_destroy(&mt->changes);
1714
1715         free(mt->columns);
1716         free(mt);
1717     }
1718     shash_destroy(&m->tables);
1719     hmap_remove(&m->session->monitors, &m->node);
1720     free(m);
1721 }
1722
1723 static const struct ovsdb_replica_class ovsdb_jsonrpc_replica_class = {
1724     ovsdb_jsonrpc_monitor_commit,
1725     ovsdb_jsonrpc_monitor_destroy
1726 };