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