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