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