ovsdb-idl: Check if row->written is valid.
[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
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             if (row->written) {
674                 BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
675                     ovsdb_datum_destroy(&row->new[i], &class->columns[i].type);
676                 }
677             }
678             free(row->new);
679             free(row->written);
680             row->written = NULL;
681         }
682         row->new = row->old;
683     }
684 }
685
686 static void
687 ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
688 {
689     struct ovsdb_idl_arc *arc, *next;
690
691     /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
692      * that this causes to be unreferenced. */
693     LIST_FOR_EACH_SAFE (arc, next, struct ovsdb_idl_arc, src_node,
694                         &row->src_arcs) {
695         list_remove(&arc->dst_node);
696         if (destroy_dsts
697             && ovsdb_idl_row_is_orphan(arc->dst)
698             && list_is_empty(&arc->dst->dst_arcs)) {
699             ovsdb_idl_row_destroy(arc->dst);
700         }
701         free(arc);
702     }
703     list_init(&row->src_arcs);
704 }
705
706 /* Force nodes that reference 'row' to reparse. */
707 static void
708 ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
709 {
710     struct ovsdb_idl_arc *arc, *next;
711
712     /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
713      * 'arc', so we need to use the "safe" variant of list traversal.  However,
714      * calling an ovsdb_idl_column's 'parse' function will add an arc
715      * equivalent to 'arc' to row->arcs.  That could be a problem for
716      * traversal, but it adds it at the beginning of the list to prevent us
717      * from stumbling upon it again.
718      *
719      * (If duplicate arcs were possible then we would need to make sure that
720      * 'next' didn't also point into 'arc''s destination, but we forbid
721      * duplicate arcs.) */
722     LIST_FOR_EACH_SAFE (arc, next, struct ovsdb_idl_arc, dst_node,
723                         &row->dst_arcs) {
724         struct ovsdb_idl_row *ref = arc->src;
725
726         ovsdb_idl_row_unparse(ref);
727         ovsdb_idl_row_clear_arcs(ref, false);
728         ovsdb_idl_row_parse(ref);
729     }
730 }
731
732 static struct ovsdb_idl_row *
733 ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
734 {
735     struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
736     list_init(&row->src_arcs);
737     list_init(&row->dst_arcs);
738     hmap_node_nullify(&row->txn_node);
739     return row;
740 }
741
742 static struct ovsdb_idl_row *
743 ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
744 {
745     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class);
746     hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
747     row->uuid = *uuid;
748     row->table = table;
749     return row;
750 }
751
752 static void
753 ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
754 {
755     if (row) {
756         ovsdb_idl_row_clear_old(row);
757         hmap_remove(&row->table->rows, &row->hmap_node);
758         free(row);
759     }
760 }
761
762 static void
763 ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct json *row_json)
764 {
765     const struct ovsdb_idl_table_class *class = row->table->class;
766     size_t i;
767
768     assert(!row->old && !row->new);
769     row->old = row->new = xmalloc(class->n_columns * sizeof *row->old);
770     for (i = 0; i < class->n_columns; i++) {
771         ovsdb_datum_init_default(&row->old[i], &class->columns[i].type);
772     }
773     ovsdb_idl_row_update(row, row_json);
774     ovsdb_idl_row_parse(row);
775
776     ovsdb_idl_row_reparse_backrefs(row);
777 }
778
779 static void
780 ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
781 {
782     ovsdb_idl_row_unparse(row);
783     ovsdb_idl_row_clear_arcs(row, true);
784     ovsdb_idl_row_clear_old(row);
785     if (list_is_empty(&row->dst_arcs)) {
786         ovsdb_idl_row_destroy(row);
787     } else {
788         ovsdb_idl_row_reparse_backrefs(row);
789     }
790 }
791
792 static void
793 ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct json *row_json)
794 {
795     ovsdb_idl_row_unparse(row);
796     ovsdb_idl_row_clear_arcs(row, true);
797     ovsdb_idl_row_update(row, row_json);
798     ovsdb_idl_row_parse(row);
799 }
800
801 static bool
802 may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
803 {
804     const struct ovsdb_idl_arc *arc;
805
806     /* No self-arcs. */
807     if (src == dst) {
808         return false;
809     }
810
811     /* No duplicate arcs.
812      *
813      * We only need to test whether the first arc in dst->dst_arcs originates
814      * at 'src', since we add all of the arcs from a given source in a clump
815      * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
816      * added at the front of the dst_arcs list. */
817     if (list_is_empty(&dst->dst_arcs)) {
818         return true;
819     }
820     arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
821     return arc->src != src;
822 }
823
824 static struct ovsdb_idl_table *
825 ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
826                            const struct ovsdb_idl_table_class *table_class)
827 {
828     return &idl->tables[table_class - idl->class->tables];
829 }
830
831 struct ovsdb_idl_row *
832 ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
833                       struct ovsdb_idl_table_class *dst_table_class,
834                       const struct uuid *dst_uuid)
835 {
836     struct ovsdb_idl *idl = src->table->idl;
837     struct ovsdb_idl_table *dst_table;
838     struct ovsdb_idl_arc *arc;
839     struct ovsdb_idl_row *dst;
840
841     dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
842     dst = ovsdb_idl_get_row(dst_table, dst_uuid);
843     if (idl->txn) {
844         /* We're being called from ovsdb_idl_txn_write().  We must not update
845          * any arcs, because the transaction will be backed out at commit or
846          * abort time and we don't want our graph screwed up.
847          *
848          * Just return the destination row, if there is one and it has not been
849          * deleted. */
850         if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new)) {
851             return dst;
852         }
853         return NULL;
854     } else {
855         /* We're being called from some other context.  Update the graph. */
856         if (!dst) {
857             dst = ovsdb_idl_row_create(dst_table, dst_uuid);
858         }
859
860         /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
861         if (may_add_arc(src, dst)) {
862             /* The arc *must* be added at the front of the dst_arcs list.  See
863              * ovsdb_idl_row_reparse_backrefs() for details. */
864             arc = xmalloc(sizeof *arc);
865             list_push_front(&src->src_arcs, &arc->src_node);
866             list_push_front(&dst->dst_arcs, &arc->dst_node);
867             arc->src = src;
868             arc->dst = dst;
869         }
870
871         return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
872     }
873 }
874
875 const struct ovsdb_idl_row *
876 ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
877                            const struct ovsdb_idl_table_class *tc,
878                            const struct uuid *uuid)
879 {
880     return ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
881 }
882
883 static struct ovsdb_idl_row *
884 next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
885 {
886     for (; node; node = hmap_next(&table->rows, node)) {
887         struct ovsdb_idl_row *row;
888
889         row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
890         if (ovsdb_idl_row_exists(row)) {
891             return row;
892         }
893     }
894     return NULL;
895 }
896
897 const struct ovsdb_idl_row *
898 ovsdb_idl_first_row(const struct ovsdb_idl *idl,
899                     const struct ovsdb_idl_table_class *table_class)
900 {
901     struct ovsdb_idl_table *table
902         = ovsdb_idl_table_from_class(idl, table_class);
903     return next_real_row(table, hmap_first(&table->rows));
904 }
905
906 const struct ovsdb_idl_row *
907 ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
908 {
909     struct ovsdb_idl_table *table = row->table;
910
911     return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
912 }
913 \f
914 /* Transactions. */
915
916 static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
917                                    enum ovsdb_idl_txn_status);
918
919 const char *
920 ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
921 {
922     switch (status) {
923     case TXN_UNCHANGED:
924         return "unchanged";
925     case TXN_INCOMPLETE:
926         return "incomplete";
927     case TXN_ABORTED:
928         return "aborted";
929     case TXN_SUCCESS:
930         return "success";
931     case TXN_TRY_AGAIN:
932         return "try again";
933     case TXN_ERROR:
934         return "error";
935     }
936     return "<unknown>";
937 }
938
939 struct ovsdb_idl_txn *
940 ovsdb_idl_txn_create(struct ovsdb_idl *idl)
941 {
942     struct ovsdb_idl_txn *txn;
943
944     assert(!idl->txn);
945     idl->txn = txn = xmalloc(sizeof *txn);
946     txn->request_id = NULL;
947     txn->idl = idl;
948     hmap_init(&txn->txn_rows);
949     txn->status = TXN_INCOMPLETE;
950     txn->error = NULL;
951     txn->dry_run = false;
952     ds_init(&txn->comment);
953
954     txn->inc_table = NULL;
955     txn->inc_column = NULL;
956     txn->inc_where = NULL;
957
958     hmap_init(&txn->inserted_rows);
959
960     return txn;
961 }
962
963 /* Appends 's', which is treated as a printf()-type format string, to the
964  * comments that will be passed to the OVSDB server when 'txn' is committed.
965  * (The comment will be committed to the OVSDB log, which "ovsdb-tool
966  * show-log" can print in a relatively human-readable form.) */
967 void
968 ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s, ...)
969 {
970     va_list args;
971
972     if (txn->comment.length) {
973         ds_put_char(&txn->comment, '\n');
974     }
975
976     va_start(args, s);
977     ds_put_format_valist(&txn->comment, s, args);
978     va_end(args);
979 }
980
981 void
982 ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
983 {
984     txn->dry_run = true;
985 }
986
987 void
988 ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn, const char *table,
989                         const char *column, const struct json *where)
990 {
991     assert(!txn->inc_table);
992     txn->inc_table = xstrdup(table);
993     txn->inc_column = xstrdup(column);
994     txn->inc_where = where ? json_clone(where) : json_array_create_empty();
995 }
996
997 void
998 ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
999 {
1000     struct ovsdb_idl_txn_insert *insert, *next;
1001
1002     json_destroy(txn->request_id);
1003     if (txn->status == TXN_INCOMPLETE) {
1004         hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1005     }
1006     ovsdb_idl_txn_abort(txn);
1007     ds_destroy(&txn->comment);
1008     free(txn->error);
1009     free(txn->inc_table);
1010     free(txn->inc_column);
1011     json_destroy(txn->inc_where);
1012     HMAP_FOR_EACH_SAFE (insert, next, struct ovsdb_idl_txn_insert, hmap_node,
1013                         &txn->inserted_rows) {
1014         free(insert);
1015     }
1016     hmap_destroy(&txn->inserted_rows);
1017     free(txn);
1018 }
1019
1020 void
1021 ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
1022 {
1023     if (txn->status != TXN_INCOMPLETE) {
1024         poll_immediate_wake();
1025     }
1026 }
1027
1028 static struct json *
1029 where_uuid_equals(const struct uuid *uuid)
1030 {
1031     return
1032         json_array_create_1(
1033             json_array_create_3(
1034                 json_string_create("_uuid"),
1035                 json_string_create("=="),
1036                 json_array_create_2(
1037                     json_string_create("uuid"),
1038                     json_string_create_nocopy(
1039                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
1040 }
1041
1042 static char *
1043 uuid_name_from_uuid(const struct uuid *uuid)
1044 {
1045     char *name;
1046     char *p;
1047
1048     name = xasprintf("row"UUID_FMT, UUID_ARGS(uuid));
1049     for (p = name; *p != '\0'; p++) {
1050         if (*p == '-') {
1051             *p = '_';
1052         }
1053     }
1054
1055     return name;
1056 }
1057
1058 static const struct ovsdb_idl_row *
1059 ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
1060 {
1061     const struct ovsdb_idl_row *row;
1062
1063     HMAP_FOR_EACH_WITH_HASH (row, struct ovsdb_idl_row, txn_node,
1064                              uuid_hash(uuid), &txn->txn_rows) {
1065         if (uuid_equals(&row->uuid, uuid)) {
1066             return row;
1067         }
1068     }
1069     return NULL;
1070 }
1071
1072 /* XXX there must be a cleaner way to do this */
1073 static struct json *
1074 substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
1075 {
1076     if (json->type == JSON_ARRAY) {
1077         struct uuid uuid;
1078         size_t i;
1079
1080         if (json->u.array.n == 2
1081             && json->u.array.elems[0]->type == JSON_STRING
1082             && json->u.array.elems[1]->type == JSON_STRING
1083             && !strcmp(json->u.array.elems[0]->u.string, "uuid")
1084             && uuid_from_string(&uuid, json->u.array.elems[1]->u.string)) {
1085             const struct ovsdb_idl_row *row;
1086
1087             row = ovsdb_idl_txn_get_row(txn, &uuid);
1088             if (row && !row->old && row->new) {
1089                 json_destroy(json);
1090
1091                 return json_array_create_2(
1092                     json_string_create("named-uuid"),
1093                     json_string_create_nocopy(uuid_name_from_uuid(&uuid)));
1094             }
1095         }
1096
1097         for (i = 0; i < json->u.array.n; i++) {
1098             json->u.array.elems[i] = substitute_uuids(json->u.array.elems[i],
1099                                                       txn);
1100         }
1101     } else if (json->type == JSON_OBJECT) {
1102         struct shash_node *node;
1103
1104         SHASH_FOR_EACH (node, json_object(json)) {
1105             node->data = substitute_uuids(node->data, txn);
1106         }
1107     }
1108     return json;
1109 }
1110
1111 static void
1112 ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
1113 {
1114     struct ovsdb_idl_row *row, *next;
1115
1116     /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
1117      * ovsdb_idl_column's 'parse' function, which will call
1118      * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
1119      * transaction and fail to update the graph.  */
1120     txn->idl->txn = NULL;
1121
1122     HMAP_FOR_EACH_SAFE (row, next, struct ovsdb_idl_row, txn_node,
1123                         &txn->txn_rows) {
1124         if (row->old) {
1125             if (row->written) {
1126                 ovsdb_idl_row_unparse(row);
1127                 ovsdb_idl_row_clear_arcs(row, false);
1128                 ovsdb_idl_row_parse(row);
1129             }
1130         } else {
1131             ovsdb_idl_row_unparse(row);
1132         }
1133         ovsdb_idl_row_clear_new(row);
1134
1135         free(row->prereqs);
1136         row->prereqs = NULL;
1137
1138         free(row->written);
1139         row->written = NULL;
1140
1141         hmap_remove(&txn->txn_rows, &row->txn_node);
1142         hmap_node_nullify(&row->txn_node);
1143         if (!row->old) {
1144             hmap_remove(&row->table->rows, &row->hmap_node);
1145             free(row);
1146         }
1147     }
1148     hmap_destroy(&txn->txn_rows);
1149     hmap_init(&txn->txn_rows);
1150 }
1151
1152 enum ovsdb_idl_txn_status
1153 ovsdb_idl_txn_commit(struct ovsdb_idl_txn *txn)
1154 {
1155     struct ovsdb_idl_row *row;
1156     struct json *operations;
1157     bool any_updates;
1158
1159     if (txn != txn->idl->txn) {
1160         return txn->status;
1161     }
1162
1163     operations = json_array_create_1(
1164         json_string_create(txn->idl->class->database));
1165
1166     /* Add prerequisites and declarations of new rows. */
1167     HMAP_FOR_EACH (row, struct ovsdb_idl_row, txn_node, &txn->txn_rows) {
1168         /* XXX check that deleted rows exist even if no prereqs? */
1169         if (row->prereqs) {
1170             const struct ovsdb_idl_table_class *class = row->table->class;
1171             size_t n_columns = class->n_columns;
1172             struct json *op, *columns, *row_json;
1173             size_t idx;
1174
1175             op = json_object_create();
1176             json_array_add(operations, op);
1177             json_object_put_string(op, "op", "wait");
1178             json_object_put_string(op, "table", class->name);
1179             json_object_put(op, "timeout", json_integer_create(0));
1180             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1181             json_object_put_string(op, "until", "==");
1182             columns = json_array_create_empty();
1183             json_object_put(op, "columns", columns);
1184             row_json = json_object_create();
1185             json_object_put(op, "rows", json_array_create_1(row_json));
1186
1187             BITMAP_FOR_EACH_1 (idx, n_columns, row->prereqs) {
1188                 const struct ovsdb_idl_column *column = &class->columns[idx];
1189                 json_array_add(columns, json_string_create(column->name));
1190                 json_object_put(row_json, column->name,
1191                                 ovsdb_datum_to_json(&row->old[idx],
1192                                                     &column->type));
1193             }
1194         }
1195     }
1196
1197     /* Add updates. */
1198     any_updates = false;
1199     HMAP_FOR_EACH (row, struct ovsdb_idl_row, txn_node, &txn->txn_rows) {
1200         const struct ovsdb_idl_table_class *class = row->table->class;
1201
1202         if (row->old == row->new) {
1203             continue;
1204         } else if (!row->new) {
1205             struct json *op = json_object_create();
1206             json_object_put_string(op, "op", "delete");
1207             json_object_put_string(op, "table", class->name);
1208             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1209             json_array_add(operations, op);
1210             any_updates = true;
1211         } else {
1212             struct json *row_json;
1213             struct json *op;
1214             size_t idx;
1215
1216             op = json_object_create();
1217             json_object_put_string(op, "op", row->old ? "update" : "insert");
1218             json_object_put_string(op, "table", class->name);
1219             if (row->old) {
1220                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
1221             } else {
1222                 struct ovsdb_idl_txn_insert *insert;
1223
1224                 json_object_put(op, "uuid-name",
1225                                 json_string_create_nocopy(
1226                                     uuid_name_from_uuid(&row->uuid)));
1227
1228                 insert = xmalloc(sizeof *insert);
1229                 insert->dummy = row->uuid;
1230                 insert->op_index = operations->u.array.n - 1;
1231                 uuid_zero(&insert->real);
1232                 hmap_insert(&txn->inserted_rows, &insert->hmap_node,
1233                             uuid_hash(&insert->dummy));
1234             }
1235             row_json = json_object_create();
1236             json_object_put(op, "row", row_json);
1237
1238             if (row->written) {
1239                 BITMAP_FOR_EACH_1 (idx, class->n_columns, row->written) {
1240                     const struct ovsdb_idl_column *column =
1241                                                         &class->columns[idx];
1242
1243                     if (row->old
1244                         ? !ovsdb_datum_equals(&row->old[idx], &row->new[idx],
1245                                               &column->type)
1246                         : !ovsdb_datum_is_default(&row->new[idx],
1247                                                   &column->type)) {
1248                         json_object_put(row_json, column->name,
1249                                         substitute_uuids(
1250                                             ovsdb_datum_to_json(&row->new[idx],
1251                                                                 &column->type),
1252                                             txn));
1253                     }
1254                 }
1255             }
1256
1257             if (!row->old || !shash_is_empty(json_object(row_json))) {
1258                 json_array_add(operations, op);
1259                 any_updates = true;
1260             } else {
1261                 json_destroy(op);
1262             }
1263         }
1264     }
1265
1266     /* Add increment. */
1267     if (txn->inc_table && any_updates) {
1268         struct json *op;
1269
1270         txn->inc_index = operations->u.array.n - 1;
1271
1272         op = json_object_create();
1273         json_object_put_string(op, "op", "mutate");
1274         json_object_put_string(op, "table", txn->inc_table);
1275         json_object_put(op, "where",
1276                         substitute_uuids(json_clone(txn->inc_where), txn));
1277         json_object_put(op, "mutations",
1278                         json_array_create_1(
1279                             json_array_create_3(
1280                                 json_string_create(txn->inc_column),
1281                                 json_string_create("+="),
1282                                 json_integer_create(1))));
1283         json_array_add(operations, op);
1284
1285         op = json_object_create();
1286         json_object_put_string(op, "op", "select");
1287         json_object_put_string(op, "table", txn->inc_table);
1288         json_object_put(op, "where",
1289                         substitute_uuids(json_clone(txn->inc_where), txn));
1290         json_object_put(op, "columns",
1291                         json_array_create_1(json_string_create(
1292                                                 txn->inc_column)));
1293         json_array_add(operations, op);
1294     }
1295
1296     if (txn->comment.length) {
1297         struct json *op = json_object_create();
1298         json_object_put_string(op, "op", "comment");
1299         json_object_put_string(op, "comment", ds_cstr(&txn->comment));
1300         json_array_add(operations, op);
1301     }
1302
1303     if (txn->dry_run) {
1304         struct json *op = json_object_create();
1305         json_object_put_string(op, "op", "abort");
1306         json_array_add(operations, op);
1307     }
1308
1309     if (!any_updates) {
1310         txn->status = TXN_UNCHANGED;
1311         json_destroy(operations);
1312     } else if (!jsonrpc_session_send(
1313                    txn->idl->session,
1314                    jsonrpc_create_request(
1315                        "transact", operations, &txn->request_id))) {
1316         hmap_insert(&txn->idl->outstanding_txns, &txn->hmap_node,
1317                     json_hash(txn->request_id, 0));
1318     } else {
1319         txn->status = TXN_TRY_AGAIN;
1320     }
1321
1322     ovsdb_idl_txn_disassemble(txn);
1323     return txn->status;
1324 }
1325
1326 /* Attempts to commit 'txn', blocking until the commit either succeeds or
1327  * fails.  Returns the final commit status, which may be any TXN_* value other
1328  * than TXN_INCOMPLETE. */
1329 enum ovsdb_idl_txn_status
1330 ovsdb_idl_txn_commit_block(struct ovsdb_idl_txn *txn)
1331 {
1332     enum ovsdb_idl_txn_status status;
1333
1334     fatal_signal_run();
1335     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
1336         ovsdb_idl_run(txn->idl);
1337         ovsdb_idl_wait(txn->idl);
1338         ovsdb_idl_txn_wait(txn);
1339         poll_block();
1340     }
1341     return status;
1342 }
1343
1344 int64_t
1345 ovsdb_idl_txn_get_increment_new_value(const struct ovsdb_idl_txn *txn)
1346 {
1347     assert(txn->status == TXN_SUCCESS);
1348     return txn->inc_new_value;
1349 }
1350
1351 void
1352 ovsdb_idl_txn_abort(struct ovsdb_idl_txn *txn)
1353 {
1354     ovsdb_idl_txn_disassemble(txn);
1355     if (txn->status == TXN_INCOMPLETE) {
1356         txn->status = TXN_ABORTED;
1357     }
1358 }
1359
1360 const char *
1361 ovsdb_idl_txn_get_error(const struct ovsdb_idl_txn *txn)
1362 {
1363     if (txn->status != TXN_ERROR) {
1364         return ovsdb_idl_txn_status_to_string(txn->status);
1365     } else if (txn->error) {
1366         return txn->error;
1367     } else {
1368         return "no error details available";
1369     }
1370 }
1371
1372 static void
1373 ovsdb_idl_txn_set_error_json(struct ovsdb_idl_txn *txn,
1374                              const struct json *json)
1375 {
1376     if (txn->error == NULL) {
1377         txn->error = json_to_string(json, JSSF_SORT);
1378     }
1379 }
1380
1381 /* For transaction 'txn' that completed successfully, finds and returns the
1382  * permanent UUID that the database assigned to a newly inserted row, given the
1383  * 'uuid' that ovsdb_idl_txn_insert() assigned locally to that row.
1384  *
1385  * Returns NULL if 'uuid' is not a UUID assigned by ovsdb_idl_txn_insert() or
1386  * if it was assigned by that function and then deleted by
1387  * ovsdb_idl_txn_delete() within the same transaction.  (Rows that are inserted
1388  * and then deleted within a single transaction are never sent to the database
1389  * server, so it never assigns them a permanent UUID.) */
1390 const struct uuid *
1391 ovsdb_idl_txn_get_insert_uuid(const struct ovsdb_idl_txn *txn,
1392                               const struct uuid *uuid)
1393 {
1394     const struct ovsdb_idl_txn_insert *insert;
1395
1396     assert(txn->status == TXN_SUCCESS || txn->status == TXN_UNCHANGED);
1397     HMAP_FOR_EACH_IN_BUCKET (insert, struct ovsdb_idl_txn_insert, hmap_node,
1398                              uuid_hash(uuid), &txn->inserted_rows) {
1399         if (uuid_equals(uuid, &insert->dummy)) {
1400             return &insert->real;
1401         }
1402     }
1403     return NULL;
1404 }
1405
1406 static void
1407 ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1408                        enum ovsdb_idl_txn_status status)
1409 {
1410     txn->status = status;
1411     hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1412 }
1413
1414 void
1415 ovsdb_idl_txn_read(const struct ovsdb_idl_row *row,
1416                    const struct ovsdb_idl_column *column,
1417                    struct ovsdb_datum *datum)
1418 {
1419     const struct ovsdb_idl_table_class *class = row->table->class;
1420     size_t column_idx = column - class->columns;
1421
1422     assert(row->new != NULL);
1423     if (row->written && bitmap_is_set(row->written, column_idx)) {
1424         ovsdb_datum_clone(datum, &row->new[column_idx], &column->type);
1425     } else if (row->old) {
1426         ovsdb_datum_clone(datum, &row->old[column_idx], &column->type);
1427     } else {
1428         ovsdb_datum_init_default(datum, &column->type);
1429     }
1430 }
1431
1432 void
1433 ovsdb_idl_txn_write(const struct ovsdb_idl_row *row_,
1434                     const struct ovsdb_idl_column *column,
1435                     struct ovsdb_datum *datum)
1436 {
1437     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1438     const struct ovsdb_idl_table_class *class = row->table->class;
1439     size_t column_idx = column - class->columns;
1440
1441     assert(row->new != NULL);
1442     assert(column_idx < class->n_columns);
1443     if (hmap_node_is_null(&row->txn_node)) {
1444         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1445                     uuid_hash(&row->uuid));
1446     }
1447     if (row->old == row->new) {
1448         row->new = xmalloc(class->n_columns * sizeof *row->new);
1449     }
1450     if (!row->written) {
1451         row->written = bitmap_allocate(class->n_columns);
1452     }
1453     if (bitmap_is_set(row->written, column_idx)) {
1454         ovsdb_datum_destroy(&row->new[column_idx], &column->type);
1455     } else {
1456         bitmap_set1(row->written, column_idx);
1457     }
1458     row->new[column_idx] = *datum;
1459     (column->unparse)(row);
1460     (column->parse)(row, &row->new[column_idx]);
1461 }
1462
1463 void
1464 ovsdb_idl_txn_verify(const struct ovsdb_idl_row *row_,
1465                      const struct ovsdb_idl_column *column)
1466 {
1467     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1468     const struct ovsdb_idl_table_class *class = row->table->class;
1469     size_t column_idx = column - class->columns;
1470
1471     assert(row->new != NULL);
1472     if (!row->old
1473         || (row->written && bitmap_is_set(row->written, column_idx))) {
1474         return;
1475     }
1476
1477     if (hmap_node_is_null(&row->txn_node)) {
1478         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1479                     uuid_hash(&row->uuid));
1480     }
1481     if (!row->prereqs) {
1482         row->prereqs = bitmap_allocate(class->n_columns);
1483     }
1484     bitmap_set1(row->prereqs, column_idx);
1485 }
1486
1487 void
1488 ovsdb_idl_txn_delete(const struct ovsdb_idl_row *row_)
1489 {
1490     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1491
1492     assert(row->new != NULL);
1493     if (!row->old) {
1494         ovsdb_idl_row_unparse(row);
1495         ovsdb_idl_row_clear_new(row);
1496         assert(!row->prereqs);
1497         hmap_remove(&row->table->rows, &row->hmap_node);
1498         hmap_remove(&row->table->idl->txn->txn_rows, &row->txn_node);
1499         free(row);
1500         return;
1501     }
1502     if (hmap_node_is_null(&row->txn_node)) {
1503         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1504                     uuid_hash(&row->uuid));
1505     }
1506     ovsdb_idl_row_clear_new(row);
1507     row->new = NULL;
1508 }
1509
1510 const struct ovsdb_idl_row *
1511 ovsdb_idl_txn_insert(struct ovsdb_idl_txn *txn,
1512                      const struct ovsdb_idl_table_class *class,
1513                      const struct uuid *uuid)
1514 {
1515     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(class);
1516
1517     if (uuid) {
1518         assert(!ovsdb_idl_txn_get_row(txn, uuid));
1519         row->uuid = *uuid;
1520     } else {
1521         uuid_generate(&row->uuid);
1522     }
1523
1524     row->table = ovsdb_idl_table_from_class(txn->idl, class);
1525     row->new = xmalloc(class->n_columns * sizeof *row->new);
1526     hmap_insert(&row->table->rows, &row->hmap_node, uuid_hash(&row->uuid));
1527     hmap_insert(&txn->txn_rows, &row->txn_node, uuid_hash(&row->uuid));
1528     return row;
1529 }
1530
1531 static void
1532 ovsdb_idl_txn_abort_all(struct ovsdb_idl *idl)
1533 {
1534     struct ovsdb_idl_txn *txn;
1535
1536     HMAP_FOR_EACH (txn, struct ovsdb_idl_txn, hmap_node,
1537                    &idl->outstanding_txns) {
1538         ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
1539     }
1540 }
1541
1542 static struct ovsdb_idl_txn *
1543 ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
1544 {
1545     struct ovsdb_idl_txn *txn;
1546
1547     HMAP_FOR_EACH_WITH_HASH (txn, struct ovsdb_idl_txn, hmap_node,
1548                              json_hash(id, 0), &idl->outstanding_txns) {
1549         if (json_equal(id, txn->request_id)) {
1550             return txn;
1551         }
1552     }
1553     return NULL;
1554 }
1555
1556 static bool
1557 check_json_type(const struct json *json, enum json_type type, const char *name)
1558 {
1559     if (!json) {
1560         VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
1561         return false;
1562     } else if (json->type != type) {
1563         VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
1564                      name, json_type_to_string(json->type),
1565                      json_type_to_string(type));
1566         return false;
1567     } else {
1568         return true;
1569     }
1570 }
1571
1572 static bool
1573 ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
1574                                 const struct json_array *results)
1575 {
1576     struct json *count, *rows, *row, *column;
1577     struct shash *mutate, *select;
1578
1579     if (txn->inc_index + 2 > results->n) {
1580         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1581                      "for increment (has %zu, needs %u)",
1582                      results->n, txn->inc_index + 2);
1583         return false;
1584     }
1585
1586     /* We know that this is a JSON object because the loop in
1587      * ovsdb_idl_txn_process_reply() checked. */
1588     mutate = json_object(results->elems[txn->inc_index]);
1589     count = shash_find_data(mutate, "count");
1590     if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
1591         return false;
1592     }
1593     if (count->u.integer != 1) {
1594         VLOG_WARN_RL(&syntax_rl,
1595                      "\"mutate\" reply \"count\" is %lld instead of 1",
1596                      count->u.integer);
1597         return false;
1598     }
1599
1600     select = json_object(results->elems[txn->inc_index + 1]);
1601     rows = shash_find_data(select, "rows");
1602     if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
1603         return false;
1604     }
1605     if (rows->u.array.n != 1) {
1606         VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %zu elements "
1607                      "instead of 1",
1608                      rows->u.array.n);
1609         return false;
1610     }
1611     row = rows->u.array.elems[0];
1612     if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
1613         return false;
1614     }
1615     column = shash_find_data(json_object(row), txn->inc_column);
1616     if (!check_json_type(column, JSON_INTEGER,
1617                          "\"select\" reply inc column")) {
1618         return false;
1619     }
1620     txn->inc_new_value = column->u.integer;
1621     return true;
1622 }
1623
1624 static bool
1625 ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
1626                                    const struct json_array *results)
1627 {
1628     static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
1629     struct ovsdb_error *error;
1630     struct json *json_uuid;
1631     union ovsdb_atom uuid;
1632     struct shash *reply;
1633
1634     if (insert->op_index >= results->n) {
1635         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1636                      "for insert (has %zu, needs %u)",
1637                      results->n, insert->op_index);
1638         return false;
1639     }
1640
1641     /* We know that this is a JSON object because the loop in
1642      * ovsdb_idl_txn_process_reply() checked. */
1643     reply = json_object(results->elems[insert->op_index]);
1644     json_uuid = shash_find_data(reply, "uuid");
1645     if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
1646         return false;
1647     }
1648
1649     error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
1650     if (error) {
1651         char *s = ovsdb_error_to_string(error);
1652         VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
1653                      "UUID: %s", s);
1654         free(s);
1655         return false;
1656     }
1657
1658     insert->real = uuid.uuid;
1659
1660     return true;
1661 }
1662
1663 static bool
1664 ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
1665                             const struct jsonrpc_msg *msg)
1666 {
1667     struct ovsdb_idl_txn *txn;
1668     enum ovsdb_idl_txn_status status;
1669
1670     txn = ovsdb_idl_txn_find(idl, msg->id);
1671     if (!txn) {
1672         return false;
1673     }
1674
1675     if (msg->type == JSONRPC_ERROR) {
1676         status = TXN_ERROR;
1677     } else if (msg->result->type != JSON_ARRAY) {
1678         VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
1679         status = TXN_ERROR;
1680     } else {
1681         struct json_array *ops = &msg->result->u.array;
1682         int hard_errors = 0;
1683         int soft_errors = 0;
1684         size_t i;
1685
1686         for (i = 0; i < ops->n; i++) {
1687             struct json *op = ops->elems[i];
1688
1689             if (op->type == JSON_NULL) {
1690                 /* This isn't an error in itself but indicates that some prior
1691                  * operation failed, so make sure that we know about it. */
1692                 soft_errors++;
1693             } else if (op->type == JSON_OBJECT) {
1694                 struct json *error;
1695
1696                 error = shash_find_data(json_object(op), "error");
1697                 if (error) {
1698                     if (error->type == JSON_STRING) {
1699                         if (!strcmp(error->u.string, "timed out")) {
1700                             soft_errors++;
1701                         } else if (strcmp(error->u.string, "aborted")) {
1702                             hard_errors++;
1703                             ovsdb_idl_txn_set_error_json(txn, op);
1704                         }
1705                     } else {
1706                         hard_errors++;
1707                         ovsdb_idl_txn_set_error_json(txn, op);
1708                         VLOG_WARN_RL(&syntax_rl,
1709                                      "\"error\" in reply is not JSON string");
1710                     }
1711                 }
1712             } else {
1713                 hard_errors++;
1714                 ovsdb_idl_txn_set_error_json(txn, op);
1715                 VLOG_WARN_RL(&syntax_rl,
1716                              "operation reply is not JSON null or object");
1717             }
1718         }
1719
1720         if (!soft_errors && !hard_errors) {
1721             struct ovsdb_idl_txn_insert *insert;
1722
1723             if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
1724                 hard_errors++;
1725             }
1726
1727             HMAP_FOR_EACH (insert, struct ovsdb_idl_txn_insert, hmap_node,
1728                            &txn->inserted_rows) {
1729                 if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
1730                     hard_errors++;
1731                 }
1732             }
1733         }
1734
1735         status = (hard_errors ? TXN_ERROR
1736                   : soft_errors ? TXN_TRY_AGAIN
1737                   : TXN_SUCCESS);
1738     }
1739
1740     ovsdb_idl_txn_complete(txn, status);
1741     return true;
1742 }
1743
1744 struct ovsdb_idl_txn *
1745 ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
1746 {
1747     struct ovsdb_idl_txn *txn = row->table->idl->txn;
1748     assert(txn != NULL);
1749     return txn;
1750 }
1751
1752 struct ovsdb_idl *
1753 ovsdb_idl_txn_get_idl (struct ovsdb_idl_txn *txn)
1754 {
1755     return txn->idl;
1756 }
1757