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