ovsdb-idl: Improve ovsdb_idl_txn_increment() interface.
[sliver-openvswitch.git] / lib / ovsdb-idl.c
1 /* Copyright (c) 2009, 2010, 2011, 2012 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 "ovsdb-idl.h"
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <stdlib.h>
25
26 #include "bitmap.h"
27 #include "dynamic-string.h"
28 #include "fatal-signal.h"
29 #include "json.h"
30 #include "jsonrpc.h"
31 #include "ovsdb-data.h"
32 #include "ovsdb-error.h"
33 #include "ovsdb-idl-provider.h"
34 #include "poll-loop.h"
35 #include "shash.h"
36 #include "util.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(ovsdb_idl);
40
41 /* An arc from one idl_row to another.  When row A contains a UUID that
42  * references row B, this is represented by an arc from A (the source) to B
43  * (the destination).
44  *
45  * Arcs from a row to itself are omitted, that is, src and dst are always
46  * different.
47  *
48  * Arcs are never duplicated, that is, even if there are multiple references
49  * from A to B, there is only a single arc from A to B.
50  *
51  * Arcs are directed: an arc from A to B is the converse of an an arc from B to
52  * A.  Both an arc and its converse may both be present, if each row refers
53  * to the other circularly.
54  *
55  * The source and destination row may be in the same table or in different
56  * tables.
57  */
58 struct ovsdb_idl_arc {
59     struct list src_node;       /* In src->src_arcs list. */
60     struct list dst_node;       /* In dst->dst_arcs list. */
61     struct ovsdb_idl_row *src;  /* Source row. */
62     struct ovsdb_idl_row *dst;  /* Destination row. */
63 };
64
65 struct ovsdb_idl {
66     const struct ovsdb_idl_class *class;
67     struct jsonrpc_session *session;
68     struct shash table_by_name;
69     struct ovsdb_idl_table *tables; /* Contains "struct ovsdb_idl_table *"s.*/
70     struct json *monitor_request_id;
71     unsigned int last_monitor_request_seqno;
72     unsigned int change_seqno;
73
74     /* Database locking. */
75     char *lock_name;            /* Name of lock we need, NULL if none. */
76     bool has_lock;              /* Has db server told us we have the lock? */
77     bool is_lock_contended;     /* Has db server told us we can't get lock? */
78     struct json *lock_request_id; /* JSON-RPC ID of in-flight lock request. */
79
80     /* Transaction support. */
81     struct ovsdb_idl_txn *txn;
82     struct hmap outstanding_txns;
83 };
84
85 struct ovsdb_idl_txn {
86     struct hmap_node hmap_node;
87     struct json *request_id;
88     struct ovsdb_idl *idl;
89     struct hmap txn_rows;
90     enum ovsdb_idl_txn_status status;
91     char *error;
92     bool dry_run;
93     struct ds comment;
94     unsigned int commit_seqno;
95
96     /* Increments. */
97     const char *inc_table;
98     const char *inc_column;
99     struct uuid inc_row;
100     unsigned int inc_index;
101     int64_t inc_new_value;
102
103     /* Inserted rows. */
104     struct hmap inserted_rows;  /* Contains "struct ovsdb_idl_txn_insert"s. */
105 };
106
107 struct ovsdb_idl_txn_insert {
108     struct hmap_node hmap_node; /* In struct ovsdb_idl_txn's inserted_rows. */
109     struct uuid dummy;          /* Dummy UUID used locally. */
110     int op_index;               /* Index into transaction's operation array. */
111     struct uuid real;           /* Real UUID used by database server. */
112 };
113
114 static struct vlog_rate_limit syntax_rl = VLOG_RATE_LIMIT_INIT(1, 5);
115 static struct vlog_rate_limit semantic_rl = VLOG_RATE_LIMIT_INIT(1, 5);
116
117 static void ovsdb_idl_clear(struct ovsdb_idl *);
118 static void ovsdb_idl_send_monitor_request(struct ovsdb_idl *);
119 static void ovsdb_idl_parse_update(struct ovsdb_idl *, const struct json *);
120 static struct ovsdb_error *ovsdb_idl_parse_update__(struct ovsdb_idl *,
121                                                     const struct json *);
122 static bool ovsdb_idl_process_update(struct ovsdb_idl_table *,
123                                      const struct uuid *,
124                                      const struct json *old,
125                                      const struct json *new);
126 static void ovsdb_idl_insert_row(struct ovsdb_idl_row *, const struct json *);
127 static void ovsdb_idl_delete_row(struct ovsdb_idl_row *);
128 static bool ovsdb_idl_modify_row(struct ovsdb_idl_row *, const struct json *);
129
130 static bool ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *);
131 static struct ovsdb_idl_row *ovsdb_idl_row_create__(
132     const struct ovsdb_idl_table_class *);
133 static struct ovsdb_idl_row *ovsdb_idl_row_create(struct ovsdb_idl_table *,
134                                                   const struct uuid *);
135 static void ovsdb_idl_row_destroy(struct ovsdb_idl_row *);
136
137 static void ovsdb_idl_row_parse(struct ovsdb_idl_row *);
138 static void ovsdb_idl_row_unparse(struct ovsdb_idl_row *);
139 static void ovsdb_idl_row_clear_old(struct ovsdb_idl_row *);
140 static void ovsdb_idl_row_clear_new(struct ovsdb_idl_row *);
141
142 static void ovsdb_idl_txn_abort_all(struct ovsdb_idl *);
143 static bool ovsdb_idl_txn_process_reply(struct ovsdb_idl *,
144                                         const struct jsonrpc_msg *msg);
145
146 static void ovsdb_idl_send_lock_request(struct ovsdb_idl *);
147 static void ovsdb_idl_send_unlock_request(struct ovsdb_idl *);
148 static void ovsdb_idl_parse_lock_reply(struct ovsdb_idl *,
149                                        const struct json *);
150 static void ovsdb_idl_parse_lock_notify(struct ovsdb_idl *,
151                                         const struct json *params,
152                                         bool new_has_lock);
153
154 /* Creates and returns a connection to database 'remote', which should be in a
155  * form acceptable to jsonrpc_session_open().  The connection will maintain an
156  * in-memory replica of the remote database whose schema is described by
157  * 'class'.  (Ordinarily 'class' is compiled from an OVSDB schema automatically
158  * by ovsdb-idlc.)
159  *
160  * If 'monitor_everything_by_default' is true, then everything in the remote
161  * database will be replicated by default.  ovsdb_idl_omit() and
162  * ovsdb_idl_omit_alert() may be used to selectively drop some columns from
163  * monitoring.
164  *
165  * If 'monitor_everything_by_default' is false, then no columns or tables will
166  * be replicated by default.  ovsdb_idl_add_column() and ovsdb_idl_add_table()
167  * must be used to choose some columns or tables to replicate.
168  */
169 struct ovsdb_idl *
170 ovsdb_idl_create(const char *remote, const struct ovsdb_idl_class *class,
171                  bool monitor_everything_by_default)
172 {
173     struct ovsdb_idl *idl;
174     uint8_t default_mode;
175     size_t i;
176
177     default_mode = (monitor_everything_by_default
178                     ? OVSDB_IDL_MONITOR | OVSDB_IDL_ALERT
179                     : 0);
180
181     idl = xzalloc(sizeof *idl);
182     idl->class = class;
183     idl->session = jsonrpc_session_open(remote);
184     shash_init(&idl->table_by_name);
185     idl->tables = xmalloc(class->n_tables * sizeof *idl->tables);
186     for (i = 0; i < class->n_tables; i++) {
187         const struct ovsdb_idl_table_class *tc = &class->tables[i];
188         struct ovsdb_idl_table *table = &idl->tables[i];
189         size_t j;
190
191         shash_add_assert(&idl->table_by_name, tc->name, table);
192         table->class = tc;
193         table->modes = xmalloc(tc->n_columns);
194         memset(table->modes, default_mode, tc->n_columns);
195         table->need_table = false;
196         shash_init(&table->columns);
197         for (j = 0; j < tc->n_columns; j++) {
198             const struct ovsdb_idl_column *column = &tc->columns[j];
199
200             shash_add_assert(&table->columns, column->name, column);
201         }
202         hmap_init(&table->rows);
203         table->idl = idl;
204     }
205     idl->last_monitor_request_seqno = UINT_MAX;
206     hmap_init(&idl->outstanding_txns);
207
208     return idl;
209 }
210
211 /* Destroys 'idl' and all of the data structures that it manages. */
212 void
213 ovsdb_idl_destroy(struct ovsdb_idl *idl)
214 {
215     if (idl) {
216         size_t i;
217
218         assert(!idl->txn);
219         ovsdb_idl_clear(idl);
220         jsonrpc_session_close(idl->session);
221
222         for (i = 0; i < idl->class->n_tables; i++) {
223             struct ovsdb_idl_table *table = &idl->tables[i];
224             shash_destroy(&table->columns);
225             hmap_destroy(&table->rows);
226             free(table->modes);
227         }
228         shash_destroy(&idl->table_by_name);
229         free(idl->tables);
230         json_destroy(idl->monitor_request_id);
231         free(idl->lock_name);
232         json_destroy(idl->lock_request_id);
233         free(idl);
234     }
235 }
236
237 static void
238 ovsdb_idl_clear(struct ovsdb_idl *idl)
239 {
240     bool changed = false;
241     size_t i;
242
243     for (i = 0; i < idl->class->n_tables; i++) {
244         struct ovsdb_idl_table *table = &idl->tables[i];
245         struct ovsdb_idl_row *row, *next_row;
246
247         if (hmap_is_empty(&table->rows)) {
248             continue;
249         }
250
251         changed = true;
252         HMAP_FOR_EACH_SAFE (row, next_row, hmap_node, &table->rows) {
253             struct ovsdb_idl_arc *arc, *next_arc;
254
255             if (!ovsdb_idl_row_is_orphan(row)) {
256                 ovsdb_idl_row_unparse(row);
257             }
258             LIST_FOR_EACH_SAFE (arc, next_arc, src_node, &row->src_arcs) {
259                 free(arc);
260             }
261             /* No need to do anything with dst_arcs: some node has those arcs
262              * as forward arcs and will destroy them itself. */
263
264             ovsdb_idl_row_destroy(row);
265         }
266     }
267
268     if (changed) {
269         idl->change_seqno++;
270     }
271 }
272
273 /* Processes a batch of messages from the database server on 'idl'.  This may
274  * cause the IDL's contents to change.  The client may check for that with
275  * ovsdb_idl_get_seqno(). */
276 void
277 ovsdb_idl_run(struct ovsdb_idl *idl)
278 {
279     int i;
280
281     assert(!idl->txn);
282     jsonrpc_session_run(idl->session);
283     for (i = 0; jsonrpc_session_is_connected(idl->session) && i < 50; i++) {
284         struct jsonrpc_msg *msg;
285         unsigned int seqno;
286
287         seqno = jsonrpc_session_get_seqno(idl->session);
288         if (idl->last_monitor_request_seqno != seqno) {
289             idl->last_monitor_request_seqno = seqno;
290             ovsdb_idl_txn_abort_all(idl);
291             ovsdb_idl_send_monitor_request(idl);
292             if (idl->lock_name) {
293                 ovsdb_idl_send_lock_request(idl);
294             }
295             break;
296         }
297
298         msg = jsonrpc_session_recv(idl->session);
299         if (!msg) {
300             break;
301         }
302
303         if (msg->type == JSONRPC_NOTIFY
304             && !strcmp(msg->method, "update")
305             && msg->params->type == JSON_ARRAY
306             && msg->params->u.array.n == 2
307             && msg->params->u.array.elems[0]->type == JSON_NULL) {
308             /* Database contents changed. */
309             ovsdb_idl_parse_update(idl, msg->params->u.array.elems[1]);
310         } else if (msg->type == JSONRPC_REPLY
311                    && idl->monitor_request_id
312                    && json_equal(idl->monitor_request_id, msg->id)) {
313             /* Reply to our "monitor" request. */
314             idl->change_seqno++;
315             json_destroy(idl->monitor_request_id);
316             idl->monitor_request_id = NULL;
317             ovsdb_idl_clear(idl);
318             ovsdb_idl_parse_update(idl, msg->result);
319         } else if (msg->type == JSONRPC_REPLY
320                    && idl->lock_request_id
321                    && json_equal(idl->lock_request_id, msg->id)) {
322             /* Reply to our "lock" request. */
323             ovsdb_idl_parse_lock_reply(idl, msg->result);
324         } else if (msg->type == JSONRPC_NOTIFY
325                    && !strcmp(msg->method, "locked")) {
326             /* We got our lock. */
327             ovsdb_idl_parse_lock_notify(idl, msg->params, true);
328         } else if (msg->type == JSONRPC_NOTIFY
329                    && !strcmp(msg->method, "stolen")) {
330             /* Someone else stole our lock. */
331             ovsdb_idl_parse_lock_notify(idl, msg->params, false);
332         } else if (msg->type == JSONRPC_REPLY && msg->id->type == JSON_STRING
333                    && !strcmp(msg->id->u.string, "echo")) {
334             /* Reply to our echo request.  Ignore it. */
335         } else if ((msg->type == JSONRPC_ERROR
336                     || msg->type == JSONRPC_REPLY)
337                    && ovsdb_idl_txn_process_reply(idl, msg)) {
338             /* ovsdb_idl_txn_process_reply() did everything needful. */
339         } else {
340             /* This can happen if ovsdb_idl_txn_destroy() is called to destroy
341              * a transaction before we receive the reply, so keep the log level
342              * low. */
343             VLOG_DBG("%s: received unexpected %s message",
344                      jsonrpc_session_get_name(idl->session),
345                      jsonrpc_msg_type_to_string(msg->type));
346         }
347         jsonrpc_msg_destroy(msg);
348     }
349 }
350
351 /* Arranges for poll_block() to wake up when ovsdb_idl_run() has something to
352  * do or when activity occurs on a transaction on 'idl'. */
353 void
354 ovsdb_idl_wait(struct ovsdb_idl *idl)
355 {
356     jsonrpc_session_wait(idl->session);
357     jsonrpc_session_recv_wait(idl->session);
358 }
359
360 /* Returns a number that represents the state of 'idl'.  When 'idl' is updated
361  * (by ovsdb_idl_run()), the return value changes. */
362 unsigned int
363 ovsdb_idl_get_seqno(const struct ovsdb_idl *idl)
364 {
365     return idl->change_seqno;
366 }
367
368 /* Returns true if 'idl' successfully connected to the remote database and
369  * retrieved its contents (even if the connection subsequently dropped and is
370  * in the process of reconnecting).  If so, then 'idl' contains an atomic
371  * snapshot of the database's contents (but it might be arbitrarily old if the
372  * connection dropped).
373  *
374  * Returns false if 'idl' has never connected or retrieved the database's
375  * contents.  If so, 'idl' is empty. */
376 bool
377 ovsdb_idl_has_ever_connected(const struct ovsdb_idl *idl)
378 {
379     return ovsdb_idl_get_seqno(idl) != 0;
380 }
381
382 /* Forces 'idl' to drop its connection to the database and reconnect.  In the
383  * meantime, the contents of 'idl' will not change. */
384 void
385 ovsdb_idl_force_reconnect(struct ovsdb_idl *idl)
386 {
387     jsonrpc_session_force_reconnect(idl->session);
388 }
389 \f
390 static unsigned char *
391 ovsdb_idl_get_mode(struct ovsdb_idl *idl,
392                    const struct ovsdb_idl_column *column)
393 {
394     size_t i;
395
396     assert(!idl->change_seqno);
397
398     for (i = 0; i < idl->class->n_tables; i++) {
399         const struct ovsdb_idl_table *table = &idl->tables[i];
400         const struct ovsdb_idl_table_class *tc = table->class;
401
402         if (column >= tc->columns && column < &tc->columns[tc->n_columns]) {
403             return &table->modes[column - tc->columns];
404         }
405     }
406
407     NOT_REACHED();
408 }
409
410 static void
411 add_ref_table(struct ovsdb_idl *idl, const struct ovsdb_base_type *base)
412 {
413     if (base->type == OVSDB_TYPE_UUID && base->u.uuid.refTableName) {
414         struct ovsdb_idl_table *table;
415
416         table = shash_find_data(&idl->table_by_name,
417                                 base->u.uuid.refTableName);
418         if (table) {
419             table->need_table = true;
420         } else {
421             VLOG_WARN("%s IDL class missing referenced table %s",
422                       idl->class->database, base->u.uuid.refTableName);
423         }
424     }
425 }
426
427 /* Turns on OVSDB_IDL_MONITOR and OVSDB_IDL_ALERT for 'column' in 'idl'.  Also
428  * ensures that any tables referenced by 'column' will be replicated, even if
429  * no columns in that table are selected for replication (see
430  * ovsdb_idl_add_table() for more information).
431  *
432  * This function is only useful if 'monitor_everything_by_default' was false in
433  * the call to ovsdb_idl_create().  This function should be called between
434  * ovsdb_idl_create() and the first call to ovsdb_idl_run().
435  */
436 void
437 ovsdb_idl_add_column(struct ovsdb_idl *idl,
438                      const struct ovsdb_idl_column *column)
439 {
440     *ovsdb_idl_get_mode(idl, column) = OVSDB_IDL_MONITOR | OVSDB_IDL_ALERT;
441     add_ref_table(idl, &column->type.key);
442     add_ref_table(idl, &column->type.value);
443 }
444
445 /* Ensures that the table with class 'tc' will be replicated on 'idl' even if
446  * no columns are selected for replication.  This can be useful because it
447  * allows 'idl' to keep track of what rows in the table actually exist, which
448  * in turn allows columns that reference the table to have accurate contents.
449  * (The IDL presents the database with references to rows that do not exist
450  * removed.)
451  *
452  * This function is only useful if 'monitor_everything_by_default' was false in
453  * the call to ovsdb_idl_create().  This function should be called between
454  * ovsdb_idl_create() and the first call to ovsdb_idl_run().
455  */
456 void
457 ovsdb_idl_add_table(struct ovsdb_idl *idl,
458                     const struct ovsdb_idl_table_class *tc)
459 {
460     size_t i;
461
462     for (i = 0; i < idl->class->n_tables; i++) {
463         struct ovsdb_idl_table *table = &idl->tables[i];
464
465         if (table->class == tc) {
466             table->need_table = true;
467             return;
468         }
469     }
470
471     NOT_REACHED();
472 }
473
474 /* Turns off OVSDB_IDL_ALERT for 'column' in 'idl'.
475  *
476  * This function should be called between ovsdb_idl_create() and the first call
477  * to ovsdb_idl_run().
478  */
479 void
480 ovsdb_idl_omit_alert(struct ovsdb_idl *idl,
481                      const struct ovsdb_idl_column *column)
482 {
483     *ovsdb_idl_get_mode(idl, column) &= ~OVSDB_IDL_ALERT;
484 }
485
486 /* Sets the mode for 'column' in 'idl' to 0.  See the big comment above
487  * OVSDB_IDL_MONITOR for details.
488  *
489  * This function should be called between ovsdb_idl_create() and the first call
490  * to ovsdb_idl_run().
491  */
492 void
493 ovsdb_idl_omit(struct ovsdb_idl *idl, const struct ovsdb_idl_column *column)
494 {
495     *ovsdb_idl_get_mode(idl, column) = 0;
496 }
497 \f
498 static void
499 ovsdb_idl_send_monitor_request(struct ovsdb_idl *idl)
500 {
501     struct json *monitor_requests;
502     struct jsonrpc_msg *msg;
503     size_t i;
504
505     monitor_requests = json_object_create();
506     for (i = 0; i < idl->class->n_tables; i++) {
507         const struct ovsdb_idl_table *table = &idl->tables[i];
508         const struct ovsdb_idl_table_class *tc = table->class;
509         struct json *monitor_request, *columns;
510         size_t j;
511
512         columns = table->need_table ? json_array_create_empty() : NULL;
513         for (j = 0; j < tc->n_columns; j++) {
514             const struct ovsdb_idl_column *column = &tc->columns[j];
515             if (table->modes[j] & OVSDB_IDL_MONITOR) {
516                 if (!columns) {
517                     columns = json_array_create_empty();
518                 }
519                 json_array_add(columns, json_string_create(column->name));
520             }
521         }
522
523         if (columns) {
524             monitor_request = json_object_create();
525             json_object_put(monitor_request, "columns", columns);
526             json_object_put(monitor_requests, tc->name, monitor_request);
527         }
528     }
529
530     json_destroy(idl->monitor_request_id);
531     msg = jsonrpc_create_request(
532         "monitor",
533         json_array_create_3(json_string_create(idl->class->database),
534                             json_null_create(), monitor_requests),
535         &idl->monitor_request_id);
536     jsonrpc_session_send(idl->session, msg);
537 }
538
539 static void
540 ovsdb_idl_parse_update(struct ovsdb_idl *idl, const struct json *table_updates)
541 {
542     struct ovsdb_error *error = ovsdb_idl_parse_update__(idl, table_updates);
543     if (error) {
544         if (!VLOG_DROP_WARN(&syntax_rl)) {
545             char *s = ovsdb_error_to_string(error);
546             VLOG_WARN_RL(&syntax_rl, "%s", s);
547             free(s);
548         }
549         ovsdb_error_destroy(error);
550     }
551 }
552
553 static struct ovsdb_error *
554 ovsdb_idl_parse_update__(struct ovsdb_idl *idl,
555                          const struct json *table_updates)
556 {
557     const struct shash_node *tables_node;
558
559     if (table_updates->type != JSON_OBJECT) {
560         return ovsdb_syntax_error(table_updates, NULL,
561                                   "<table-updates> is not an object");
562     }
563     SHASH_FOR_EACH (tables_node, json_object(table_updates)) {
564         const struct json *table_update = tables_node->data;
565         const struct shash_node *table_node;
566         struct ovsdb_idl_table *table;
567
568         table = shash_find_data(&idl->table_by_name, tables_node->name);
569         if (!table) {
570             return ovsdb_syntax_error(
571                 table_updates, NULL,
572                 "<table-updates> includes unknown table \"%s\"",
573                 tables_node->name);
574         }
575
576         if (table_update->type != JSON_OBJECT) {
577             return ovsdb_syntax_error(table_update, NULL,
578                                       "<table-update> for table \"%s\" is "
579                                       "not an object", table->class->name);
580         }
581         SHASH_FOR_EACH (table_node, json_object(table_update)) {
582             const struct json *row_update = table_node->data;
583             const struct json *old_json, *new_json;
584             struct uuid uuid;
585
586             if (!uuid_from_string(&uuid, table_node->name)) {
587                 return ovsdb_syntax_error(table_update, NULL,
588                                           "<table-update> for table \"%s\" "
589                                           "contains bad UUID "
590                                           "\"%s\" as member name",
591                                           table->class->name,
592                                           table_node->name);
593             }
594             if (row_update->type != JSON_OBJECT) {
595                 return ovsdb_syntax_error(row_update, NULL,
596                                           "<table-update> for table \"%s\" "
597                                           "contains <row-update> for %s that "
598                                           "is not an object",
599                                           table->class->name,
600                                           table_node->name);
601             }
602
603             old_json = shash_find_data(json_object(row_update), "old");
604             new_json = shash_find_data(json_object(row_update), "new");
605             if (old_json && old_json->type != JSON_OBJECT) {
606                 return ovsdb_syntax_error(old_json, NULL,
607                                           "\"old\" <row> is not object");
608             } else if (new_json && new_json->type != JSON_OBJECT) {
609                 return ovsdb_syntax_error(new_json, NULL,
610                                           "\"new\" <row> is not object");
611             } else if ((old_json != NULL) + (new_json != NULL)
612                        != shash_count(json_object(row_update))) {
613                 return ovsdb_syntax_error(row_update, NULL,
614                                           "<row-update> contains unexpected "
615                                           "member");
616             } else if (!old_json && !new_json) {
617                 return ovsdb_syntax_error(row_update, NULL,
618                                           "<row-update> missing \"old\" "
619                                           "and \"new\" members");
620             }
621
622             if (ovsdb_idl_process_update(table, &uuid, old_json, new_json)) {
623                 idl->change_seqno++;
624             }
625         }
626     }
627
628     return NULL;
629 }
630
631 static struct ovsdb_idl_row *
632 ovsdb_idl_get_row(struct ovsdb_idl_table *table, const struct uuid *uuid)
633 {
634     struct ovsdb_idl_row *row;
635
636     HMAP_FOR_EACH_WITH_HASH (row, hmap_node, uuid_hash(uuid), &table->rows) {
637         if (uuid_equals(&row->uuid, uuid)) {
638             return row;
639         }
640     }
641     return NULL;
642 }
643
644 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
645  * otherwise. */
646 static bool
647 ovsdb_idl_process_update(struct ovsdb_idl_table *table,
648                          const struct uuid *uuid, const struct json *old,
649                          const struct json *new)
650 {
651     struct ovsdb_idl_row *row;
652
653     row = ovsdb_idl_get_row(table, uuid);
654     if (!new) {
655         /* Delete row. */
656         if (row && !ovsdb_idl_row_is_orphan(row)) {
657             /* XXX perhaps we should check the 'old' values? */
658             ovsdb_idl_delete_row(row);
659         } else {
660             VLOG_WARN_RL(&semantic_rl, "cannot delete missing row "UUID_FMT" "
661                          "from table %s",
662                          UUID_ARGS(uuid), table->class->name);
663             return false;
664         }
665     } else if (!old) {
666         /* Insert row. */
667         if (!row) {
668             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
669         } else if (ovsdb_idl_row_is_orphan(row)) {
670             ovsdb_idl_insert_row(row, new);
671         } else {
672             VLOG_WARN_RL(&semantic_rl, "cannot add existing row "UUID_FMT" to "
673                          "table %s", UUID_ARGS(uuid), table->class->name);
674             return ovsdb_idl_modify_row(row, new);
675         }
676     } else {
677         /* Modify row. */
678         if (row) {
679             /* XXX perhaps we should check the 'old' values? */
680             if (!ovsdb_idl_row_is_orphan(row)) {
681                 return ovsdb_idl_modify_row(row, new);
682             } else {
683                 VLOG_WARN_RL(&semantic_rl, "cannot modify missing but "
684                              "referenced row "UUID_FMT" in table %s",
685                              UUID_ARGS(uuid), table->class->name);
686                 ovsdb_idl_insert_row(row, new);
687             }
688         } else {
689             VLOG_WARN_RL(&semantic_rl, "cannot modify missing row "UUID_FMT" "
690                          "in table %s", UUID_ARGS(uuid), table->class->name);
691             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
692         }
693     }
694
695     return true;
696 }
697
698 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
699  * otherwise. */
700 static bool
701 ovsdb_idl_row_update(struct ovsdb_idl_row *row, const struct json *row_json)
702 {
703     struct ovsdb_idl_table *table = row->table;
704     struct shash_node *node;
705     bool changed = false;
706
707     SHASH_FOR_EACH (node, json_object(row_json)) {
708         const char *column_name = node->name;
709         const struct ovsdb_idl_column *column;
710         struct ovsdb_datum datum;
711         struct ovsdb_error *error;
712
713         column = shash_find_data(&table->columns, column_name);
714         if (!column) {
715             VLOG_WARN_RL(&syntax_rl, "unknown column %s updating row "UUID_FMT,
716                          column_name, UUID_ARGS(&row->uuid));
717             continue;
718         }
719
720         error = ovsdb_datum_from_json(&datum, &column->type, node->data, NULL);
721         if (!error) {
722             unsigned int column_idx = column - table->class->columns;
723             struct ovsdb_datum *old = &row->old[column_idx];
724
725             if (!ovsdb_datum_equals(old, &datum, &column->type)) {
726                 ovsdb_datum_swap(old, &datum);
727                 if (table->modes[column_idx] & OVSDB_IDL_ALERT) {
728                     changed = true;
729                 }
730             } else {
731                 /* Didn't really change but the OVSDB monitor protocol always
732                  * includes every value in a row. */
733             }
734
735             ovsdb_datum_destroy(&datum, &column->type);
736         } else {
737             char *s = ovsdb_error_to_string(error);
738             VLOG_WARN_RL(&syntax_rl, "error parsing column %s in row "UUID_FMT
739                          " in table %s: %s", column_name,
740                          UUID_ARGS(&row->uuid), table->class->name, s);
741             free(s);
742             ovsdb_error_destroy(error);
743         }
744     }
745     return changed;
746 }
747
748 /* When a row A refers to row B through a column with a "refTable" constraint,
749  * but row B does not exist, row B is called an "orphan row".  Orphan rows
750  * should not persist, because the database enforces referential integrity, but
751  * they can appear transiently as changes from the database are received (the
752  * database doesn't try to topologically sort them and circular references mean
753  * it isn't always possible anyhow).
754  *
755  * This function returns true if 'row' is an orphan row, otherwise false.
756  */
757 static bool
758 ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *row)
759 {
760     return !row->old && !row->new;
761 }
762
763 /* Returns true if 'row' is conceptually part of the database as modified by
764  * the current transaction (if any), false otherwise.
765  *
766  * This function will return true if 'row' is not an orphan (see the comment on
767  * ovsdb_idl_row_is_orphan()) and:
768  *
769  *   - 'row' exists in the database and has not been deleted within the
770  *     current transaction (if any).
771  *
772  *   - 'row' was inserted within the current transaction and has not been
773  *     deleted.  (In the latter case you should not have passed 'row' in at
774  *     all, because ovsdb_idl_txn_delete() freed it.)
775  *
776  * This function will return false if 'row' is an orphan or if 'row' was
777  * deleted within the current transaction.
778  */
779 static bool
780 ovsdb_idl_row_exists(const struct ovsdb_idl_row *row)
781 {
782     return row->new != NULL;
783 }
784
785 static void
786 ovsdb_idl_row_parse(struct ovsdb_idl_row *row)
787 {
788     const struct ovsdb_idl_table_class *class = row->table->class;
789     size_t i;
790
791     for (i = 0; i < class->n_columns; i++) {
792         const struct ovsdb_idl_column *c = &class->columns[i];
793         (c->parse)(row, &row->old[i]);
794     }
795 }
796
797 static void
798 ovsdb_idl_row_unparse(struct ovsdb_idl_row *row)
799 {
800     const struct ovsdb_idl_table_class *class = row->table->class;
801     size_t i;
802
803     for (i = 0; i < class->n_columns; i++) {
804         const struct ovsdb_idl_column *c = &class->columns[i];
805         (c->unparse)(row);
806     }
807 }
808
809 static void
810 ovsdb_idl_row_clear_old(struct ovsdb_idl_row *row)
811 {
812     assert(row->old == row->new);
813     if (!ovsdb_idl_row_is_orphan(row)) {
814         const struct ovsdb_idl_table_class *class = row->table->class;
815         size_t i;
816
817         for (i = 0; i < class->n_columns; i++) {
818             ovsdb_datum_destroy(&row->old[i], &class->columns[i].type);
819         }
820         free(row->old);
821         row->old = row->new = NULL;
822     }
823 }
824
825 static void
826 ovsdb_idl_row_clear_new(struct ovsdb_idl_row *row)
827 {
828     if (row->old != row->new) {
829         if (row->new) {
830             const struct ovsdb_idl_table_class *class = row->table->class;
831             size_t i;
832
833             if (row->written) {
834                 BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
835                     ovsdb_datum_destroy(&row->new[i], &class->columns[i].type);
836                 }
837             }
838             free(row->new);
839             free(row->written);
840             row->written = NULL;
841         }
842         row->new = row->old;
843     }
844 }
845
846 static void
847 ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
848 {
849     struct ovsdb_idl_arc *arc, *next;
850
851     /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
852      * that this causes to be unreferenced. */
853     LIST_FOR_EACH_SAFE (arc, next, src_node, &row->src_arcs) {
854         list_remove(&arc->dst_node);
855         if (destroy_dsts
856             && ovsdb_idl_row_is_orphan(arc->dst)
857             && list_is_empty(&arc->dst->dst_arcs)) {
858             ovsdb_idl_row_destroy(arc->dst);
859         }
860         free(arc);
861     }
862     list_init(&row->src_arcs);
863 }
864
865 /* Force nodes that reference 'row' to reparse. */
866 static void
867 ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
868 {
869     struct ovsdb_idl_arc *arc, *next;
870
871     /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
872      * 'arc', so we need to use the "safe" variant of list traversal.  However,
873      * calling an ovsdb_idl_column's 'parse' function will add an arc
874      * equivalent to 'arc' to row->arcs.  That could be a problem for
875      * traversal, but it adds it at the beginning of the list to prevent us
876      * from stumbling upon it again.
877      *
878      * (If duplicate arcs were possible then we would need to make sure that
879      * 'next' didn't also point into 'arc''s destination, but we forbid
880      * duplicate arcs.) */
881     LIST_FOR_EACH_SAFE (arc, next, dst_node, &row->dst_arcs) {
882         struct ovsdb_idl_row *ref = arc->src;
883
884         ovsdb_idl_row_unparse(ref);
885         ovsdb_idl_row_clear_arcs(ref, false);
886         ovsdb_idl_row_parse(ref);
887     }
888 }
889
890 static struct ovsdb_idl_row *
891 ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
892 {
893     struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
894     list_init(&row->src_arcs);
895     list_init(&row->dst_arcs);
896     hmap_node_nullify(&row->txn_node);
897     return row;
898 }
899
900 static struct ovsdb_idl_row *
901 ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
902 {
903     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class);
904     hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
905     row->uuid = *uuid;
906     row->table = table;
907     return row;
908 }
909
910 static void
911 ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
912 {
913     if (row) {
914         ovsdb_idl_row_clear_old(row);
915         hmap_remove(&row->table->rows, &row->hmap_node);
916         free(row);
917     }
918 }
919
920 static void
921 ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct json *row_json)
922 {
923     const struct ovsdb_idl_table_class *class = row->table->class;
924     size_t i;
925
926     assert(!row->old && !row->new);
927     row->old = row->new = xmalloc(class->n_columns * sizeof *row->old);
928     for (i = 0; i < class->n_columns; i++) {
929         ovsdb_datum_init_default(&row->old[i], &class->columns[i].type);
930     }
931     ovsdb_idl_row_update(row, row_json);
932     ovsdb_idl_row_parse(row);
933
934     ovsdb_idl_row_reparse_backrefs(row);
935 }
936
937 static void
938 ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
939 {
940     ovsdb_idl_row_unparse(row);
941     ovsdb_idl_row_clear_arcs(row, true);
942     ovsdb_idl_row_clear_old(row);
943     if (list_is_empty(&row->dst_arcs)) {
944         ovsdb_idl_row_destroy(row);
945     } else {
946         ovsdb_idl_row_reparse_backrefs(row);
947     }
948 }
949
950 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
951  * otherwise. */
952 static bool
953 ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct json *row_json)
954 {
955     bool changed;
956
957     ovsdb_idl_row_unparse(row);
958     ovsdb_idl_row_clear_arcs(row, true);
959     changed = ovsdb_idl_row_update(row, row_json);
960     ovsdb_idl_row_parse(row);
961
962     return changed;
963 }
964
965 static bool
966 may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
967 {
968     const struct ovsdb_idl_arc *arc;
969
970     /* No self-arcs. */
971     if (src == dst) {
972         return false;
973     }
974
975     /* No duplicate arcs.
976      *
977      * We only need to test whether the first arc in dst->dst_arcs originates
978      * at 'src', since we add all of the arcs from a given source in a clump
979      * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
980      * added at the front of the dst_arcs list. */
981     if (list_is_empty(&dst->dst_arcs)) {
982         return true;
983     }
984     arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
985     return arc->src != src;
986 }
987
988 static struct ovsdb_idl_table *
989 ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
990                            const struct ovsdb_idl_table_class *table_class)
991 {
992     return &idl->tables[table_class - idl->class->tables];
993 }
994
995 struct ovsdb_idl_row *
996 ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
997                       struct ovsdb_idl_table_class *dst_table_class,
998                       const struct uuid *dst_uuid)
999 {
1000     struct ovsdb_idl *idl = src->table->idl;
1001     struct ovsdb_idl_table *dst_table;
1002     struct ovsdb_idl_arc *arc;
1003     struct ovsdb_idl_row *dst;
1004
1005     dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
1006     dst = ovsdb_idl_get_row(dst_table, dst_uuid);
1007     if (idl->txn) {
1008         /* We're being called from ovsdb_idl_txn_write().  We must not update
1009          * any arcs, because the transaction will be backed out at commit or
1010          * abort time and we don't want our graph screwed up.
1011          *
1012          * Just return the destination row, if there is one and it has not been
1013          * deleted. */
1014         if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new)) {
1015             return dst;
1016         }
1017         return NULL;
1018     } else {
1019         /* We're being called from some other context.  Update the graph. */
1020         if (!dst) {
1021             dst = ovsdb_idl_row_create(dst_table, dst_uuid);
1022         }
1023
1024         /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
1025         if (may_add_arc(src, dst)) {
1026             /* The arc *must* be added at the front of the dst_arcs list.  See
1027              * ovsdb_idl_row_reparse_backrefs() for details. */
1028             arc = xmalloc(sizeof *arc);
1029             list_push_front(&src->src_arcs, &arc->src_node);
1030             list_push_front(&dst->dst_arcs, &arc->dst_node);
1031             arc->src = src;
1032             arc->dst = dst;
1033         }
1034
1035         return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
1036     }
1037 }
1038
1039 const struct ovsdb_idl_row *
1040 ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
1041                            const struct ovsdb_idl_table_class *tc,
1042                            const struct uuid *uuid)
1043 {
1044     return ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
1045 }
1046
1047 static struct ovsdb_idl_row *
1048 next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
1049 {
1050     for (; node; node = hmap_next(&table->rows, node)) {
1051         struct ovsdb_idl_row *row;
1052
1053         row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
1054         if (ovsdb_idl_row_exists(row)) {
1055             return row;
1056         }
1057     }
1058     return NULL;
1059 }
1060
1061 const struct ovsdb_idl_row *
1062 ovsdb_idl_first_row(const struct ovsdb_idl *idl,
1063                     const struct ovsdb_idl_table_class *table_class)
1064 {
1065     struct ovsdb_idl_table *table
1066         = ovsdb_idl_table_from_class(idl, table_class);
1067     return next_real_row(table, hmap_first(&table->rows));
1068 }
1069
1070 const struct ovsdb_idl_row *
1071 ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
1072 {
1073     struct ovsdb_idl_table *table = row->table;
1074
1075     return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
1076 }
1077
1078 /* Reads and returns the value of 'column' within 'row'.  If an ongoing
1079  * transaction has changed 'column''s value, the modified value is returned.
1080  *
1081  * The caller must not modify or free the returned value.
1082  *
1083  * Various kinds of changes can invalidate the returned value: writing to the
1084  * same 'column' in 'row' (e.g. with ovsdb_idl_txn_write()), deleting 'row'
1085  * (e.g. with ovsdb_idl_txn_delete()), or completing an ongoing transaction
1086  * (e.g. with ovsdb_idl_txn_commit() or ovsdb_idl_txn_abort()).  If the
1087  * returned value is needed for a long time, it is best to make a copy of it
1088  * with ovsdb_datum_clone(). */
1089 const struct ovsdb_datum *
1090 ovsdb_idl_read(const struct ovsdb_idl_row *row,
1091                const struct ovsdb_idl_column *column)
1092 {
1093     const struct ovsdb_idl_table_class *class;
1094     size_t column_idx;
1095
1096     assert(!ovsdb_idl_row_is_synthetic(row));
1097
1098     class = row->table->class;
1099     column_idx = column - class->columns;
1100
1101     assert(row->new != NULL);
1102     assert(column_idx < class->n_columns);
1103
1104     if (row->written && bitmap_is_set(row->written, column_idx)) {
1105         return &row->new[column_idx];
1106     } else if (row->old) {
1107         return &row->old[column_idx];
1108     } else {
1109         return ovsdb_datum_default(&column->type);
1110     }
1111 }
1112
1113 /* Same as ovsdb_idl_read(), except that it also asserts that 'column' has key
1114  * type 'key_type' and value type 'value_type'.  (Scalar and set types will
1115  * have a value type of OVSDB_TYPE_VOID.)
1116  *
1117  * This is useful in code that "knows" that a particular column has a given
1118  * type, so that it will abort if someone changes the column's type without
1119  * updating the code that uses it. */
1120 const struct ovsdb_datum *
1121 ovsdb_idl_get(const struct ovsdb_idl_row *row,
1122               const struct ovsdb_idl_column *column,
1123               enum ovsdb_atomic_type key_type OVS_UNUSED,
1124               enum ovsdb_atomic_type value_type OVS_UNUSED)
1125 {
1126     assert(column->type.key.type == key_type);
1127     assert(column->type.value.type == value_type);
1128
1129     return ovsdb_idl_read(row, column);
1130 }
1131
1132 /* Returns false if 'row' was obtained from the IDL, true if it was initialized
1133  * to all-zero-bits by some other entity.  If 'row' was set up some other way
1134  * then the return value is indeterminate. */
1135 bool
1136 ovsdb_idl_row_is_synthetic(const struct ovsdb_idl_row *row)
1137 {
1138     return row->table == NULL;
1139 }
1140 \f
1141 /* Transactions. */
1142
1143 static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1144                                    enum ovsdb_idl_txn_status);
1145
1146 const char *
1147 ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
1148 {
1149     switch (status) {
1150     case TXN_UNCOMMITTED:
1151         return "uncommitted";
1152     case TXN_UNCHANGED:
1153         return "unchanged";
1154     case TXN_INCOMPLETE:
1155         return "incomplete";
1156     case TXN_ABORTED:
1157         return "aborted";
1158     case TXN_SUCCESS:
1159         return "success";
1160     case TXN_TRY_AGAIN:
1161         return "try again";
1162     case TXN_NOT_LOCKED:
1163         return "not locked";
1164     case TXN_ERROR:
1165         return "error";
1166     }
1167     return "<unknown>";
1168 }
1169
1170 struct ovsdb_idl_txn *
1171 ovsdb_idl_txn_create(struct ovsdb_idl *idl)
1172 {
1173     struct ovsdb_idl_txn *txn;
1174
1175     assert(!idl->txn);
1176     idl->txn = txn = xmalloc(sizeof *txn);
1177     txn->request_id = NULL;
1178     txn->idl = idl;
1179     hmap_init(&txn->txn_rows);
1180     txn->status = TXN_UNCOMMITTED;
1181     txn->error = NULL;
1182     txn->dry_run = false;
1183     ds_init(&txn->comment);
1184     txn->commit_seqno = txn->idl->change_seqno;
1185
1186     txn->inc_table = NULL;
1187     txn->inc_column = NULL;
1188
1189     hmap_init(&txn->inserted_rows);
1190
1191     return txn;
1192 }
1193
1194 /* Appends 's', which is treated as a printf()-type format string, to the
1195  * comments that will be passed to the OVSDB server when 'txn' is committed.
1196  * (The comment will be committed to the OVSDB log, which "ovsdb-tool
1197  * show-log" can print in a relatively human-readable form.) */
1198 void
1199 ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s, ...)
1200 {
1201     va_list args;
1202
1203     if (txn->comment.length) {
1204         ds_put_char(&txn->comment, '\n');
1205     }
1206
1207     va_start(args, s);
1208     ds_put_format_valist(&txn->comment, s, args);
1209     va_end(args);
1210 }
1211
1212 void
1213 ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
1214 {
1215     txn->dry_run = true;
1216 }
1217
1218 /* Causes 'txn', when committed, to increment the value of 'column' within
1219  * 'row' by 1.  'column' must have an integer type.  After 'txn' commits
1220  * successfully, the client may retrieve the final (incremented) value of
1221  * 'column' with ovsdb_idl_txn_get_increment_new_value().
1222  *
1223  * The client could accomplish something similar with ovsdb_idl_read(),
1224  * ovsdb_idl_txn_verify() and ovsdb_idl_txn_write(), or with ovsdb-idlc
1225  * generated wrappers for these functions.  However, ovsdb_idl_txn_increment()
1226  * will never (by itself) fail because of a verify error.
1227  *
1228  * The intended use is for incrementing the "next_cfg" column in the
1229  * Open_vSwitch table. */
1230 void
1231 ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn,
1232                         const struct ovsdb_idl_row *row,
1233                         const struct ovsdb_idl_column *column)
1234 {
1235     assert(!txn->inc_table);
1236     assert(column->type.key.type == OVSDB_TYPE_INTEGER);
1237     assert(column->type.value.type == OVSDB_TYPE_VOID);
1238
1239     txn->inc_table = row->table->class->name;
1240     txn->inc_column = column->name;
1241     txn->inc_row = row->uuid;
1242 }
1243
1244 void
1245 ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
1246 {
1247     struct ovsdb_idl_txn_insert *insert, *next;
1248
1249     json_destroy(txn->request_id);
1250     if (txn->status == TXN_INCOMPLETE) {
1251         hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1252     }
1253     ovsdb_idl_txn_abort(txn);
1254     ds_destroy(&txn->comment);
1255     free(txn->error);
1256     HMAP_FOR_EACH_SAFE (insert, next, hmap_node, &txn->inserted_rows) {
1257         free(insert);
1258     }
1259     hmap_destroy(&txn->inserted_rows);
1260     free(txn);
1261 }
1262
1263 void
1264 ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
1265 {
1266     if (txn->status != TXN_UNCOMMITTED && txn->status != TXN_INCOMPLETE) {
1267         poll_immediate_wake();
1268     }
1269 }
1270
1271 static struct json *
1272 where_uuid_equals(const struct uuid *uuid)
1273 {
1274     return
1275         json_array_create_1(
1276             json_array_create_3(
1277                 json_string_create("_uuid"),
1278                 json_string_create("=="),
1279                 json_array_create_2(
1280                     json_string_create("uuid"),
1281                     json_string_create_nocopy(
1282                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
1283 }
1284
1285 static char *
1286 uuid_name_from_uuid(const struct uuid *uuid)
1287 {
1288     char *name;
1289     char *p;
1290
1291     name = xasprintf("row"UUID_FMT, UUID_ARGS(uuid));
1292     for (p = name; *p != '\0'; p++) {
1293         if (*p == '-') {
1294             *p = '_';
1295         }
1296     }
1297
1298     return name;
1299 }
1300
1301 static const struct ovsdb_idl_row *
1302 ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
1303 {
1304     const struct ovsdb_idl_row *row;
1305
1306     HMAP_FOR_EACH_WITH_HASH (row, txn_node, uuid_hash(uuid), &txn->txn_rows) {
1307         if (uuid_equals(&row->uuid, uuid)) {
1308             return row;
1309         }
1310     }
1311     return NULL;
1312 }
1313
1314 /* XXX there must be a cleaner way to do this */
1315 static struct json *
1316 substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
1317 {
1318     if (json->type == JSON_ARRAY) {
1319         struct uuid uuid;
1320         size_t i;
1321
1322         if (json->u.array.n == 2
1323             && json->u.array.elems[0]->type == JSON_STRING
1324             && json->u.array.elems[1]->type == JSON_STRING
1325             && !strcmp(json->u.array.elems[0]->u.string, "uuid")
1326             && uuid_from_string(&uuid, json->u.array.elems[1]->u.string)) {
1327             const struct ovsdb_idl_row *row;
1328
1329             row = ovsdb_idl_txn_get_row(txn, &uuid);
1330             if (row && !row->old && row->new) {
1331                 json_destroy(json);
1332
1333                 return json_array_create_2(
1334                     json_string_create("named-uuid"),
1335                     json_string_create_nocopy(uuid_name_from_uuid(&uuid)));
1336             }
1337         }
1338
1339         for (i = 0; i < json->u.array.n; i++) {
1340             json->u.array.elems[i] = substitute_uuids(json->u.array.elems[i],
1341                                                       txn);
1342         }
1343     } else if (json->type == JSON_OBJECT) {
1344         struct shash_node *node;
1345
1346         SHASH_FOR_EACH (node, json_object(json)) {
1347             node->data = substitute_uuids(node->data, txn);
1348         }
1349     }
1350     return json;
1351 }
1352
1353 static void
1354 ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
1355 {
1356     struct ovsdb_idl_row *row, *next;
1357
1358     /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
1359      * ovsdb_idl_column's 'parse' function, which will call
1360      * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
1361      * transaction and fail to update the graph.  */
1362     txn->idl->txn = NULL;
1363
1364     HMAP_FOR_EACH_SAFE (row, next, txn_node, &txn->txn_rows) {
1365         if (row->old) {
1366             if (row->written) {
1367                 ovsdb_idl_row_unparse(row);
1368                 ovsdb_idl_row_clear_arcs(row, false);
1369                 ovsdb_idl_row_parse(row);
1370             }
1371         } else {
1372             ovsdb_idl_row_unparse(row);
1373         }
1374         ovsdb_idl_row_clear_new(row);
1375
1376         free(row->prereqs);
1377         row->prereqs = NULL;
1378
1379         free(row->written);
1380         row->written = NULL;
1381
1382         hmap_remove(&txn->txn_rows, &row->txn_node);
1383         hmap_node_nullify(&row->txn_node);
1384         if (!row->old) {
1385             hmap_remove(&row->table->rows, &row->hmap_node);
1386             free(row);
1387         }
1388     }
1389     hmap_destroy(&txn->txn_rows);
1390     hmap_init(&txn->txn_rows);
1391 }
1392
1393 enum ovsdb_idl_txn_status
1394 ovsdb_idl_txn_commit(struct ovsdb_idl_txn *txn)
1395 {
1396     struct ovsdb_idl_row *row;
1397     struct json *operations;
1398     bool any_updates;
1399
1400     if (txn != txn->idl->txn) {
1401         return txn->status;
1402     }
1403
1404     /* If we need a lock but don't have it, give up quickly. */
1405     if (txn->idl->lock_name && !ovsdb_idl_has_lock(txn->idl)) {
1406         txn->status = TXN_NOT_LOCKED;
1407         ovsdb_idl_txn_disassemble(txn);
1408         return txn->status;
1409     }
1410
1411     operations = json_array_create_1(
1412         json_string_create(txn->idl->class->database));
1413
1414     /* Assert that we have the required lock (avoiding a race). */
1415     if (txn->idl->lock_name) {
1416         struct json *op = json_object_create();
1417         json_array_add(operations, op);
1418         json_object_put_string(op, "op", "assert");
1419         json_object_put_string(op, "lock", txn->idl->lock_name);
1420     }
1421
1422     /* Add prerequisites and declarations of new rows. */
1423     HMAP_FOR_EACH (row, txn_node, &txn->txn_rows) {
1424         /* XXX check that deleted rows exist even if no prereqs? */
1425         if (row->prereqs) {
1426             const struct ovsdb_idl_table_class *class = row->table->class;
1427             size_t n_columns = class->n_columns;
1428             struct json *op, *columns, *row_json;
1429             size_t idx;
1430
1431             op = json_object_create();
1432             json_array_add(operations, op);
1433             json_object_put_string(op, "op", "wait");
1434             json_object_put_string(op, "table", class->name);
1435             json_object_put(op, "timeout", json_integer_create(0));
1436             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1437             json_object_put_string(op, "until", "==");
1438             columns = json_array_create_empty();
1439             json_object_put(op, "columns", columns);
1440             row_json = json_object_create();
1441             json_object_put(op, "rows", json_array_create_1(row_json));
1442
1443             BITMAP_FOR_EACH_1 (idx, n_columns, row->prereqs) {
1444                 const struct ovsdb_idl_column *column = &class->columns[idx];
1445                 json_array_add(columns, json_string_create(column->name));
1446                 json_object_put(row_json, column->name,
1447                                 ovsdb_datum_to_json(&row->old[idx],
1448                                                     &column->type));
1449             }
1450         }
1451     }
1452
1453     /* Add updates. */
1454     any_updates = false;
1455     HMAP_FOR_EACH (row, txn_node, &txn->txn_rows) {
1456         const struct ovsdb_idl_table_class *class = row->table->class;
1457
1458         if (!row->new) {
1459             if (class->is_root) {
1460                 struct json *op = json_object_create();
1461                 json_object_put_string(op, "op", "delete");
1462                 json_object_put_string(op, "table", class->name);
1463                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
1464                 json_array_add(operations, op);
1465                 any_updates = true;
1466             } else {
1467                 /* Let ovsdb-server decide whether to really delete it. */
1468             }
1469         } else if (row->old != row->new) {
1470             struct json *row_json;
1471             struct json *op;
1472             size_t idx;
1473
1474             op = json_object_create();
1475             json_object_put_string(op, "op", row->old ? "update" : "insert");
1476             json_object_put_string(op, "table", class->name);
1477             if (row->old) {
1478                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
1479             } else {
1480                 struct ovsdb_idl_txn_insert *insert;
1481
1482                 any_updates = true;
1483
1484                 json_object_put(op, "uuid-name",
1485                                 json_string_create_nocopy(
1486                                     uuid_name_from_uuid(&row->uuid)));
1487
1488                 insert = xmalloc(sizeof *insert);
1489                 insert->dummy = row->uuid;
1490                 insert->op_index = operations->u.array.n - 1;
1491                 uuid_zero(&insert->real);
1492                 hmap_insert(&txn->inserted_rows, &insert->hmap_node,
1493                             uuid_hash(&insert->dummy));
1494             }
1495             row_json = json_object_create();
1496             json_object_put(op, "row", row_json);
1497
1498             if (row->written) {
1499                 BITMAP_FOR_EACH_1 (idx, class->n_columns, row->written) {
1500                     const struct ovsdb_idl_column *column =
1501                                                         &class->columns[idx];
1502
1503                     if (row->old
1504                         || !ovsdb_datum_is_default(&row->new[idx],
1505                                                   &column->type)) {
1506                         json_object_put(row_json, column->name,
1507                                         substitute_uuids(
1508                                             ovsdb_datum_to_json(&row->new[idx],
1509                                                                 &column->type),
1510                                             txn));
1511
1512                         /* If anything really changed, consider it an update.
1513                          * We can't suppress not-really-changed values earlier
1514                          * or transactions would become nonatomic (see the big
1515                          * comment inside ovsdb_idl_txn_write()). */
1516                         if (!any_updates && row->old &&
1517                             !ovsdb_datum_equals(&row->old[idx], &row->new[idx],
1518                                                 &column->type)) {
1519                             any_updates = true;
1520                         }
1521                     }
1522                 }
1523             }
1524
1525             if (!row->old || !shash_is_empty(json_object(row_json))) {
1526                 json_array_add(operations, op);
1527             } else {
1528                 json_destroy(op);
1529             }
1530         }
1531     }
1532
1533     /* Add increment. */
1534     if (txn->inc_table && any_updates) {
1535         struct json *op;
1536
1537         txn->inc_index = operations->u.array.n - 1;
1538
1539         op = json_object_create();
1540         json_object_put_string(op, "op", "mutate");
1541         json_object_put_string(op, "table", txn->inc_table);
1542         json_object_put(op, "where",
1543                         substitute_uuids(where_uuid_equals(&txn->inc_row),
1544                                          txn));
1545         json_object_put(op, "mutations",
1546                         json_array_create_1(
1547                             json_array_create_3(
1548                                 json_string_create(txn->inc_column),
1549                                 json_string_create("+="),
1550                                 json_integer_create(1))));
1551         json_array_add(operations, op);
1552
1553         op = json_object_create();
1554         json_object_put_string(op, "op", "select");
1555         json_object_put_string(op, "table", txn->inc_table);
1556         json_object_put(op, "where",
1557                         substitute_uuids(where_uuid_equals(&txn->inc_row),
1558                                          txn));
1559         json_object_put(op, "columns",
1560                         json_array_create_1(json_string_create(
1561                                                 txn->inc_column)));
1562         json_array_add(operations, op);
1563     }
1564
1565     if (txn->comment.length) {
1566         struct json *op = json_object_create();
1567         json_object_put_string(op, "op", "comment");
1568         json_object_put_string(op, "comment", ds_cstr(&txn->comment));
1569         json_array_add(operations, op);
1570     }
1571
1572     if (txn->dry_run) {
1573         struct json *op = json_object_create();
1574         json_object_put_string(op, "op", "abort");
1575         json_array_add(operations, op);
1576     }
1577
1578     if (!any_updates) {
1579         txn->status = TXN_UNCHANGED;
1580         json_destroy(operations);
1581     } else if (!jsonrpc_session_send(
1582                    txn->idl->session,
1583                    jsonrpc_create_request(
1584                        "transact", operations, &txn->request_id))) {
1585         hmap_insert(&txn->idl->outstanding_txns, &txn->hmap_node,
1586                     json_hash(txn->request_id, 0));
1587         txn->status = TXN_INCOMPLETE;
1588     } else {
1589         txn->status = TXN_TRY_AGAIN;
1590     }
1591
1592     ovsdb_idl_txn_disassemble(txn);
1593     return txn->status;
1594 }
1595
1596 /* Attempts to commit 'txn', blocking until the commit either succeeds or
1597  * fails.  Returns the final commit status, which may be any TXN_* value other
1598  * than TXN_INCOMPLETE. */
1599 enum ovsdb_idl_txn_status
1600 ovsdb_idl_txn_commit_block(struct ovsdb_idl_txn *txn)
1601 {
1602     enum ovsdb_idl_txn_status status;
1603
1604     fatal_signal_run();
1605     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
1606         ovsdb_idl_run(txn->idl);
1607         ovsdb_idl_wait(txn->idl);
1608         ovsdb_idl_txn_wait(txn);
1609         poll_block();
1610     }
1611     return status;
1612 }
1613
1614 int64_t
1615 ovsdb_idl_txn_get_increment_new_value(const struct ovsdb_idl_txn *txn)
1616 {
1617     assert(txn->status == TXN_SUCCESS);
1618     return txn->inc_new_value;
1619 }
1620
1621 void
1622 ovsdb_idl_txn_abort(struct ovsdb_idl_txn *txn)
1623 {
1624     ovsdb_idl_txn_disassemble(txn);
1625     if (txn->status == TXN_UNCOMMITTED || txn->status == TXN_INCOMPLETE) {
1626         txn->status = TXN_ABORTED;
1627     }
1628 }
1629
1630 const char *
1631 ovsdb_idl_txn_get_error(const struct ovsdb_idl_txn *txn)
1632 {
1633     if (txn->status != TXN_ERROR) {
1634         return ovsdb_idl_txn_status_to_string(txn->status);
1635     } else if (txn->error) {
1636         return txn->error;
1637     } else {
1638         return "no error details available";
1639     }
1640 }
1641
1642 static void
1643 ovsdb_idl_txn_set_error_json(struct ovsdb_idl_txn *txn,
1644                              const struct json *json)
1645 {
1646     if (txn->error == NULL) {
1647         txn->error = json_to_string(json, JSSF_SORT);
1648     }
1649 }
1650
1651 /* For transaction 'txn' that completed successfully, finds and returns the
1652  * permanent UUID that the database assigned to a newly inserted row, given the
1653  * 'uuid' that ovsdb_idl_txn_insert() assigned locally to that row.
1654  *
1655  * Returns NULL if 'uuid' is not a UUID assigned by ovsdb_idl_txn_insert() or
1656  * if it was assigned by that function and then deleted by
1657  * ovsdb_idl_txn_delete() within the same transaction.  (Rows that are inserted
1658  * and then deleted within a single transaction are never sent to the database
1659  * server, so it never assigns them a permanent UUID.) */
1660 const struct uuid *
1661 ovsdb_idl_txn_get_insert_uuid(const struct ovsdb_idl_txn *txn,
1662                               const struct uuid *uuid)
1663 {
1664     const struct ovsdb_idl_txn_insert *insert;
1665
1666     assert(txn->status == TXN_SUCCESS || txn->status == TXN_UNCHANGED);
1667     HMAP_FOR_EACH_IN_BUCKET (insert, hmap_node,
1668                              uuid_hash(uuid), &txn->inserted_rows) {
1669         if (uuid_equals(uuid, &insert->dummy)) {
1670             return &insert->real;
1671         }
1672     }
1673     return NULL;
1674 }
1675
1676 static void
1677 ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1678                        enum ovsdb_idl_txn_status status)
1679 {
1680     txn->status = status;
1681     hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1682 }
1683
1684 /* Writes 'datum' to the specified 'column' in 'row_'.  Updates both 'row_'
1685  * itself and the structs derived from it (e.g. the "struct ovsrec_*", for
1686  * ovs-vswitchd).
1687  *
1688  * 'datum' must have the correct type for its column.  The IDL does not check
1689  * that it meets schema constraints, but ovsdb-server will do so at commit time
1690  * so it had better be correct.
1691  *
1692  * A transaction must be in progress.  Replication of 'column' must not have
1693  * been disabled (by calling ovsdb_idl_omit()).
1694  *
1695  * Usually this function is used indirectly through one of the "set" functions
1696  * generated by ovsdb-idlc.
1697  *
1698  * Takes ownership of what 'datum' points to (and in some cases destroys that
1699  * data before returning) but makes a copy of 'datum' itself.  (Commonly
1700  * 'datum' is on the caller's stack.) */
1701 void
1702 ovsdb_idl_txn_write(const struct ovsdb_idl_row *row_,
1703                     const struct ovsdb_idl_column *column,
1704                     struct ovsdb_datum *datum)
1705 {
1706     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1707     const struct ovsdb_idl_table_class *class;
1708     size_t column_idx;
1709
1710     if (ovsdb_idl_row_is_synthetic(row)) {
1711         ovsdb_datum_destroy(datum, &column->type);
1712         return;
1713     }
1714
1715     class = row->table->class;
1716     column_idx = column - class->columns;
1717
1718     assert(row->new != NULL);
1719     assert(column_idx < class->n_columns);
1720     assert(row->old == NULL ||
1721            row->table->modes[column_idx] & OVSDB_IDL_MONITOR);
1722
1723     /* If this is a write-only column and the datum being written is the same
1724      * as the one already there, just skip the update entirely.  This is worth
1725      * optimizing because we have a lot of columns that get periodically
1726      * refreshed into the database but don't actually change that often.
1727      *
1728      * We don't do this for read/write columns because that would break
1729      * atomicity of transactions--some other client might have written a
1730      * different value in that column since we read it.  (But if a whole
1731      * transaction only does writes of existing values, without making any real
1732      * changes, we will drop the whole transaction later in
1733      * ovsdb_idl_txn_commit().) */
1734     if (row->table->modes[column_idx] == OVSDB_IDL_MONITOR
1735         && ovsdb_datum_equals(ovsdb_idl_read(row, column),
1736                               datum, &column->type)) {
1737         ovsdb_datum_destroy(datum, &column->type);
1738         return;
1739     }
1740
1741     if (hmap_node_is_null(&row->txn_node)) {
1742         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1743                     uuid_hash(&row->uuid));
1744     }
1745     if (row->old == row->new) {
1746         row->new = xmalloc(class->n_columns * sizeof *row->new);
1747     }
1748     if (!row->written) {
1749         row->written = bitmap_allocate(class->n_columns);
1750     }
1751     if (bitmap_is_set(row->written, column_idx)) {
1752         ovsdb_datum_destroy(&row->new[column_idx], &column->type);
1753     } else {
1754         bitmap_set1(row->written, column_idx);
1755     }
1756     row->new[column_idx] = *datum;
1757     (column->unparse)(row);
1758     (column->parse)(row, &row->new[column_idx]);
1759 }
1760
1761 /* Causes the original contents of 'column' in 'row_' to be verified as a
1762  * prerequisite to completing the transaction.  That is, if 'column' in 'row_'
1763  * changed (or if 'row_' was deleted) between the time that the IDL originally
1764  * read its contents and the time that the transaction commits, then the
1765  * transaction aborts and ovsdb_idl_txn_commit() returns TXN_AGAIN_WAIT or
1766  * TXN_AGAIN_NOW (depending on whether the database change has already been
1767  * received).
1768  *
1769  * The intention is that, to ensure that no transaction commits based on dirty
1770  * reads, an application should call ovsdb_idl_txn_verify() on each data item
1771  * read as part of a read-modify-write operation.
1772  *
1773  * In some cases ovsdb_idl_txn_verify() reduces to a no-op, because the current
1774  * value of 'column' is already known:
1775  *
1776  *   - If 'row_' is a row created by the current transaction (returned by
1777  *     ovsdb_idl_txn_insert()).
1778  *
1779  *   - If 'column' has already been modified (with ovsdb_idl_txn_write())
1780  *     within the current transaction.
1781  *
1782  * Because of the latter property, always call ovsdb_idl_txn_verify() *before*
1783  * ovsdb_idl_txn_write() for a given read-modify-write.
1784  *
1785  * A transaction must be in progress.
1786  *
1787  * Usually this function is used indirectly through one of the "verify"
1788  * functions generated by ovsdb-idlc. */
1789 void
1790 ovsdb_idl_txn_verify(const struct ovsdb_idl_row *row_,
1791                      const struct ovsdb_idl_column *column)
1792 {
1793     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1794     const struct ovsdb_idl_table_class *class;
1795     size_t column_idx;
1796
1797     if (ovsdb_idl_row_is_synthetic(row)) {
1798         return;
1799     }
1800
1801     class = row->table->class;
1802     column_idx = column - class->columns;
1803
1804     assert(row->new != NULL);
1805     assert(row->old == NULL ||
1806            row->table->modes[column_idx] & OVSDB_IDL_MONITOR);
1807     if (!row->old
1808         || (row->written && bitmap_is_set(row->written, column_idx))) {
1809         return;
1810     }
1811
1812     if (hmap_node_is_null(&row->txn_node)) {
1813         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1814                     uuid_hash(&row->uuid));
1815     }
1816     if (!row->prereqs) {
1817         row->prereqs = bitmap_allocate(class->n_columns);
1818     }
1819     bitmap_set1(row->prereqs, column_idx);
1820 }
1821
1822 /* Deletes 'row_' from its table.  May free 'row_', so it must not be
1823  * accessed afterward.
1824  *
1825  * A transaction must be in progress.
1826  *
1827  * Usually this function is used indirectly through one of the "delete"
1828  * functions generated by ovsdb-idlc. */
1829 void
1830 ovsdb_idl_txn_delete(const struct ovsdb_idl_row *row_)
1831 {
1832     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1833
1834     if (ovsdb_idl_row_is_synthetic(row)) {
1835         return;
1836     }
1837
1838     assert(row->new != NULL);
1839     if (!row->old) {
1840         ovsdb_idl_row_unparse(row);
1841         ovsdb_idl_row_clear_new(row);
1842         assert(!row->prereqs);
1843         hmap_remove(&row->table->rows, &row->hmap_node);
1844         hmap_remove(&row->table->idl->txn->txn_rows, &row->txn_node);
1845         free(row);
1846         return;
1847     }
1848     if (hmap_node_is_null(&row->txn_node)) {
1849         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1850                     uuid_hash(&row->uuid));
1851     }
1852     ovsdb_idl_row_clear_new(row);
1853     row->new = NULL;
1854 }
1855
1856 /* Inserts and returns a new row in the table with the specified 'class' in the
1857  * database with open transaction 'txn'.
1858  *
1859  * The new row is assigned a provisional UUID.  If 'uuid' is null then one is
1860  * randomly generated; otherwise 'uuid' should specify a randomly generated
1861  * UUID not otherwise in use.  ovsdb-server will assign a different UUID when
1862  * 'txn' is committed, but the IDL will replace any uses of the provisional
1863  * UUID in the data to be to be committed by the UUID assigned by
1864  * ovsdb-server.
1865  *
1866  * Usually this function is used indirectly through one of the "insert"
1867  * functions generated by ovsdb-idlc. */
1868 const struct ovsdb_idl_row *
1869 ovsdb_idl_txn_insert(struct ovsdb_idl_txn *txn,
1870                      const struct ovsdb_idl_table_class *class,
1871                      const struct uuid *uuid)
1872 {
1873     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(class);
1874
1875     if (uuid) {
1876         assert(!ovsdb_idl_txn_get_row(txn, uuid));
1877         row->uuid = *uuid;
1878     } else {
1879         uuid_generate(&row->uuid);
1880     }
1881
1882     row->table = ovsdb_idl_table_from_class(txn->idl, class);
1883     row->new = xmalloc(class->n_columns * sizeof *row->new);
1884     hmap_insert(&row->table->rows, &row->hmap_node, uuid_hash(&row->uuid));
1885     hmap_insert(&txn->txn_rows, &row->txn_node, uuid_hash(&row->uuid));
1886     return row;
1887 }
1888
1889 static void
1890 ovsdb_idl_txn_abort_all(struct ovsdb_idl *idl)
1891 {
1892     struct ovsdb_idl_txn *txn;
1893
1894     HMAP_FOR_EACH (txn, hmap_node, &idl->outstanding_txns) {
1895         ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
1896     }
1897 }
1898
1899 static struct ovsdb_idl_txn *
1900 ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
1901 {
1902     struct ovsdb_idl_txn *txn;
1903
1904     HMAP_FOR_EACH_WITH_HASH (txn, hmap_node,
1905                              json_hash(id, 0), &idl->outstanding_txns) {
1906         if (json_equal(id, txn->request_id)) {
1907             return txn;
1908         }
1909     }
1910     return NULL;
1911 }
1912
1913 static bool
1914 check_json_type(const struct json *json, enum json_type type, const char *name)
1915 {
1916     if (!json) {
1917         VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
1918         return false;
1919     } else if (json->type != type) {
1920         VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
1921                      name, json_type_to_string(json->type),
1922                      json_type_to_string(type));
1923         return false;
1924     } else {
1925         return true;
1926     }
1927 }
1928
1929 static bool
1930 ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
1931                                 const struct json_array *results)
1932 {
1933     struct json *count, *rows, *row, *column;
1934     struct shash *mutate, *select;
1935
1936     if (txn->inc_index + 2 > results->n) {
1937         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1938                      "for increment (has %zu, needs %u)",
1939                      results->n, txn->inc_index + 2);
1940         return false;
1941     }
1942
1943     /* We know that this is a JSON object because the loop in
1944      * ovsdb_idl_txn_process_reply() checked. */
1945     mutate = json_object(results->elems[txn->inc_index]);
1946     count = shash_find_data(mutate, "count");
1947     if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
1948         return false;
1949     }
1950     if (count->u.integer != 1) {
1951         VLOG_WARN_RL(&syntax_rl,
1952                      "\"mutate\" reply \"count\" is %lld instead of 1",
1953                      count->u.integer);
1954         return false;
1955     }
1956
1957     select = json_object(results->elems[txn->inc_index + 1]);
1958     rows = shash_find_data(select, "rows");
1959     if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
1960         return false;
1961     }
1962     if (rows->u.array.n != 1) {
1963         VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %zu elements "
1964                      "instead of 1",
1965                      rows->u.array.n);
1966         return false;
1967     }
1968     row = rows->u.array.elems[0];
1969     if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
1970         return false;
1971     }
1972     column = shash_find_data(json_object(row), txn->inc_column);
1973     if (!check_json_type(column, JSON_INTEGER,
1974                          "\"select\" reply inc column")) {
1975         return false;
1976     }
1977     txn->inc_new_value = column->u.integer;
1978     return true;
1979 }
1980
1981 static bool
1982 ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
1983                                    const struct json_array *results)
1984 {
1985     static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
1986     struct ovsdb_error *error;
1987     struct json *json_uuid;
1988     union ovsdb_atom uuid;
1989     struct shash *reply;
1990
1991     if (insert->op_index >= results->n) {
1992         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1993                      "for insert (has %zu, needs %u)",
1994                      results->n, insert->op_index);
1995         return false;
1996     }
1997
1998     /* We know that this is a JSON object because the loop in
1999      * ovsdb_idl_txn_process_reply() checked. */
2000     reply = json_object(results->elems[insert->op_index]);
2001     json_uuid = shash_find_data(reply, "uuid");
2002     if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
2003         return false;
2004     }
2005
2006     error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
2007     if (error) {
2008         char *s = ovsdb_error_to_string(error);
2009         VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
2010                      "UUID: %s", s);
2011         free(s);
2012         return false;
2013     }
2014
2015     insert->real = uuid.uuid;
2016
2017     return true;
2018 }
2019
2020 static bool
2021 ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
2022                             const struct jsonrpc_msg *msg)
2023 {
2024     struct ovsdb_idl_txn *txn;
2025     enum ovsdb_idl_txn_status status;
2026
2027     txn = ovsdb_idl_txn_find(idl, msg->id);
2028     if (!txn) {
2029         return false;
2030     }
2031
2032     if (msg->type == JSONRPC_ERROR) {
2033         status = TXN_ERROR;
2034     } else if (msg->result->type != JSON_ARRAY) {
2035         VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
2036         status = TXN_ERROR;
2037     } else {
2038         struct json_array *ops = &msg->result->u.array;
2039         int hard_errors = 0;
2040         int soft_errors = 0;
2041         int lock_errors = 0;
2042         size_t i;
2043
2044         for (i = 0; i < ops->n; i++) {
2045             struct json *op = ops->elems[i];
2046
2047             if (op->type == JSON_NULL) {
2048                 /* This isn't an error in itself but indicates that some prior
2049                  * operation failed, so make sure that we know about it. */
2050                 soft_errors++;
2051             } else if (op->type == JSON_OBJECT) {
2052                 struct json *error;
2053
2054                 error = shash_find_data(json_object(op), "error");
2055                 if (error) {
2056                     if (error->type == JSON_STRING) {
2057                         if (!strcmp(error->u.string, "timed out")) {
2058                             soft_errors++;
2059                         } else if (!strcmp(error->u.string, "not owner")) {
2060                             lock_errors++;
2061                         } else if (strcmp(error->u.string, "aborted")) {
2062                             hard_errors++;
2063                             ovsdb_idl_txn_set_error_json(txn, op);
2064                         }
2065                     } else {
2066                         hard_errors++;
2067                         ovsdb_idl_txn_set_error_json(txn, op);
2068                         VLOG_WARN_RL(&syntax_rl,
2069                                      "\"error\" in reply is not JSON string");
2070                     }
2071                 }
2072             } else {
2073                 hard_errors++;
2074                 ovsdb_idl_txn_set_error_json(txn, op);
2075                 VLOG_WARN_RL(&syntax_rl,
2076                              "operation reply is not JSON null or object");
2077             }
2078         }
2079
2080         if (!soft_errors && !hard_errors && !lock_errors) {
2081             struct ovsdb_idl_txn_insert *insert;
2082
2083             if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
2084                 hard_errors++;
2085             }
2086
2087             HMAP_FOR_EACH (insert, hmap_node, &txn->inserted_rows) {
2088                 if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
2089                     hard_errors++;
2090                 }
2091             }
2092         }
2093
2094         status = (hard_errors ? TXN_ERROR
2095                   : lock_errors ? TXN_NOT_LOCKED
2096                   : soft_errors ? TXN_TRY_AGAIN
2097                   : TXN_SUCCESS);
2098     }
2099
2100     ovsdb_idl_txn_complete(txn, status);
2101     return true;
2102 }
2103
2104 struct ovsdb_idl_txn *
2105 ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
2106 {
2107     struct ovsdb_idl_txn *txn = row->table->idl->txn;
2108     assert(txn != NULL);
2109     return txn;
2110 }
2111
2112 struct ovsdb_idl *
2113 ovsdb_idl_txn_get_idl (struct ovsdb_idl_txn *txn)
2114 {
2115     return txn->idl;
2116 }
2117 \f
2118 /* If 'lock_name' is nonnull, configures 'idl' to obtain the named lock from
2119  * the database server and to avoid modifying the database when the lock cannot
2120  * be acquired (that is, when another client has the same lock).
2121  *
2122  * If 'lock_name' is NULL, drops the locking requirement and releases the
2123  * lock. */
2124 void
2125 ovsdb_idl_set_lock(struct ovsdb_idl *idl, const char *lock_name)
2126 {
2127     assert(!idl->txn);
2128     assert(hmap_is_empty(&idl->outstanding_txns));
2129
2130     if (idl->lock_name && (!lock_name || strcmp(lock_name, idl->lock_name))) {
2131         /* Release previous lock. */
2132         ovsdb_idl_send_unlock_request(idl);
2133         free(idl->lock_name);
2134         idl->lock_name = NULL;
2135         idl->is_lock_contended = false;
2136     }
2137
2138     if (lock_name && !idl->lock_name) {
2139         /* Acquire new lock. */
2140         idl->lock_name = xstrdup(lock_name);
2141         ovsdb_idl_send_lock_request(idl);
2142     }
2143 }
2144
2145 /* Returns true if 'idl' is configured to obtain a lock and owns that lock.
2146  *
2147  * Locking and unlocking happens asynchronously from the database client's
2148  * point of view, so the information is only useful for optimization (e.g. if
2149  * the client doesn't have the lock then there's no point in trying to write to
2150  * the database). */
2151 bool
2152 ovsdb_idl_has_lock(const struct ovsdb_idl *idl)
2153 {
2154     return idl->has_lock;
2155 }
2156
2157 /* Returns true if 'idl' is configured to obtain a lock but the database server
2158  * has indicated that some other client already owns the requested lock. */
2159 bool
2160 ovsdb_idl_is_lock_contended(const struct ovsdb_idl *idl)
2161 {
2162     return idl->is_lock_contended;
2163 }
2164
2165 static void
2166 ovsdb_idl_update_has_lock(struct ovsdb_idl *idl, bool new_has_lock)
2167 {
2168     if (new_has_lock && !idl->has_lock) {
2169         if (!idl->monitor_request_id) {
2170             idl->change_seqno++;
2171         } else {
2172             /* We're waiting for a monitor reply, so don't signal that the
2173              * database changed.  The monitor reply will increment change_seqno
2174              * anyhow. */
2175         }
2176         idl->is_lock_contended = false;
2177     }
2178     idl->has_lock = new_has_lock;
2179 }
2180
2181 static void
2182 ovsdb_idl_send_lock_request__(struct ovsdb_idl *idl, const char *method,
2183                               struct json **idp)
2184 {
2185     ovsdb_idl_update_has_lock(idl, false);
2186
2187     json_destroy(idl->lock_request_id);
2188     idl->lock_request_id = NULL;
2189
2190     if (jsonrpc_session_is_connected(idl->session)) {
2191         struct json *params;
2192
2193         params = json_array_create_1(json_string_create(idl->lock_name));
2194         jsonrpc_session_send(idl->session,
2195                              jsonrpc_create_request(method, params, idp));
2196     }
2197 }
2198
2199 static void
2200 ovsdb_idl_send_lock_request(struct ovsdb_idl *idl)
2201 {
2202     ovsdb_idl_send_lock_request__(idl, "lock", &idl->lock_request_id);
2203 }
2204
2205 static void
2206 ovsdb_idl_send_unlock_request(struct ovsdb_idl *idl)
2207 {
2208     ovsdb_idl_send_lock_request__(idl, "unlock", NULL);
2209 }
2210
2211 static void
2212 ovsdb_idl_parse_lock_reply(struct ovsdb_idl *idl, const struct json *result)
2213 {
2214     bool got_lock;
2215
2216     json_destroy(idl->lock_request_id);
2217     idl->lock_request_id = NULL;
2218
2219     if (result->type == JSON_OBJECT) {
2220         const struct json *locked;
2221
2222         locked = shash_find_data(json_object(result), "locked");
2223         got_lock = locked && locked->type == JSON_TRUE;
2224     } else {
2225         got_lock = false;
2226     }
2227
2228     ovsdb_idl_update_has_lock(idl, got_lock);
2229     if (!got_lock) {
2230         idl->is_lock_contended = true;
2231     }
2232 }
2233
2234 static void
2235 ovsdb_idl_parse_lock_notify(struct ovsdb_idl *idl,
2236                             const struct json *params,
2237                             bool new_has_lock)
2238 {
2239     if (idl->lock_name
2240         && params->type == JSON_ARRAY
2241         && json_array(params)->n > 0
2242         && json_array(params)->elems[0]->type == JSON_STRING) {
2243         const char *lock_name = json_string(json_array(params)->elems[0]);
2244
2245         if (!strcmp(idl->lock_name, lock_name)) {
2246             ovsdb_idl_update_has_lock(idl, new_has_lock);
2247             if (!new_has_lock) {
2248                 idl->is_lock_contended = true;
2249             }
2250         }
2251     }
2252 }