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