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