ovsdb-idl: Fix iteration over rows in IDL tables.
[sliver-openvswitch.git] / lib / ovsdb-idl.c
1 /* Copyright (c) 2009, 2010 Nicira Networks.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "ovsdb-idl.h"
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <stdlib.h>
25
26 #include "bitmap.h"
27 #include "dynamic-string.h"
28 #include "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",
346         json_array_create_3(json_string_create(idl->class->database),
347                             json_null_create(), monitor_requests),
348         &idl->monitor_request_id);
349     jsonrpc_session_send(idl->session, msg);
350 }
351
352 static void
353 ovsdb_idl_parse_update(struct ovsdb_idl *idl, const struct json *table_updates)
354 {
355     struct ovsdb_error *error;
356
357     idl->change_seqno++;
358
359     error = ovsdb_idl_parse_update__(idl, table_updates);
360     if (error) {
361         if (!VLOG_DROP_WARN(&syntax_rl)) {
362             char *s = ovsdb_error_to_string(error);
363             VLOG_WARN_RL(&syntax_rl, "%s", s);
364             free(s);
365         }
366         ovsdb_error_destroy(error);
367     }
368 }
369
370 static struct ovsdb_error *
371 ovsdb_idl_parse_update__(struct ovsdb_idl *idl,
372                          const struct json *table_updates)
373 {
374     const struct shash_node *tables_node;
375
376     if (table_updates->type != JSON_OBJECT) {
377         return ovsdb_syntax_error(table_updates, NULL,
378                                   "<table-updates> is not an object");
379     }
380     SHASH_FOR_EACH (tables_node, json_object(table_updates)) {
381         const struct json *table_update = tables_node->data;
382         const struct shash_node *table_node;
383         struct ovsdb_idl_table *table;
384
385         table = shash_find_data(&idl->table_by_name, tables_node->name);
386         if (!table) {
387             return ovsdb_syntax_error(
388                 table_updates, NULL,
389                 "<table-updates> includes unknown table \"%s\"",
390                 tables_node->name);
391         }
392
393         if (table_update->type != JSON_OBJECT) {
394             return ovsdb_syntax_error(table_update, NULL,
395                                       "<table-update> for table \"%s\" is "
396                                       "not an object", table->class->name);
397         }
398         SHASH_FOR_EACH (table_node, json_object(table_update)) {
399             const struct json *row_update = table_node->data;
400             const struct json *old_json, *new_json;
401             struct uuid uuid;
402
403             if (!uuid_from_string(&uuid, table_node->name)) {
404                 return ovsdb_syntax_error(table_update, NULL,
405                                           "<table-update> for table \"%s\" "
406                                           "contains bad UUID "
407                                           "\"%s\" as member name",
408                                           table->class->name,
409                                           table_node->name);
410             }
411             if (row_update->type != JSON_OBJECT) {
412                 return ovsdb_syntax_error(row_update, NULL,
413                                           "<table-update> for table \"%s\" "
414                                           "contains <row-update> for %s that "
415                                           "is not an object",
416                                           table->class->name,
417                                           table_node->name);
418             }
419
420             old_json = shash_find_data(json_object(row_update), "old");
421             new_json = shash_find_data(json_object(row_update), "new");
422             if (old_json && old_json->type != JSON_OBJECT) {
423                 return ovsdb_syntax_error(old_json, NULL,
424                                           "\"old\" <row> is not object");
425             } else if (new_json && new_json->type != JSON_OBJECT) {
426                 return ovsdb_syntax_error(new_json, NULL,
427                                           "\"new\" <row> is not object");
428             } else if ((old_json != NULL) + (new_json != NULL)
429                        != shash_count(json_object(row_update))) {
430                 return ovsdb_syntax_error(row_update, NULL,
431                                           "<row-update> contains unexpected "
432                                           "member");
433             } else if (!old_json && !new_json) {
434                 return ovsdb_syntax_error(row_update, NULL,
435                                           "<row-update> missing \"old\" "
436                                           "and \"new\" members");
437             }
438
439             ovsdb_idl_process_update(table, &uuid, old_json, new_json);
440         }
441     }
442
443     return NULL;
444 }
445
446 static struct ovsdb_idl_row *
447 ovsdb_idl_get_row(struct ovsdb_idl_table *table, const struct uuid *uuid)
448 {
449     struct ovsdb_idl_row *row;
450
451     HMAP_FOR_EACH_WITH_HASH (row, struct ovsdb_idl_row, hmap_node,
452                              uuid_hash(uuid), &table->rows) {
453         if (uuid_equals(&row->uuid, uuid)) {
454             return row;
455         }
456     }
457     return NULL;
458 }
459
460 static void
461 ovsdb_idl_process_update(struct ovsdb_idl_table *table,
462                          const struct uuid *uuid, const struct json *old,
463                          const struct json *new)
464 {
465     struct ovsdb_idl_row *row;
466
467     row = ovsdb_idl_get_row(table, uuid);
468     if (!new) {
469         /* Delete row. */
470         if (row && !ovsdb_idl_row_is_orphan(row)) {
471             /* XXX perhaps we should check the 'old' values? */
472             ovsdb_idl_delete_row(row);
473         } else {
474             VLOG_WARN_RL(&semantic_rl, "cannot delete missing row "UUID_FMT" "
475                          "from table %s",
476                          UUID_ARGS(uuid), table->class->name);
477         }
478     } else if (!old) {
479         /* Insert row. */
480         if (!row) {
481             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
482         } else if (ovsdb_idl_row_is_orphan(row)) {
483             ovsdb_idl_insert_row(row, new);
484         } else {
485             VLOG_WARN_RL(&semantic_rl, "cannot add existing row "UUID_FMT" to "
486                          "table %s", UUID_ARGS(uuid), table->class->name);
487             ovsdb_idl_modify_row(row, new);
488         }
489     } else {
490         /* Modify row. */
491         if (row) {
492             /* XXX perhaps we should check the 'old' values? */
493             if (!ovsdb_idl_row_is_orphan(row)) {
494                 ovsdb_idl_modify_row(row, new);
495             } else {
496                 VLOG_WARN_RL(&semantic_rl, "cannot modify missing but "
497                              "referenced row "UUID_FMT" in table %s",
498                              UUID_ARGS(uuid), table->class->name);
499                 ovsdb_idl_insert_row(row, new);
500             }
501         } else {
502             VLOG_WARN_RL(&semantic_rl, "cannot modify missing row "UUID_FMT" "
503                          "in table %s", UUID_ARGS(uuid), table->class->name);
504             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
505         }
506     }
507 }
508
509 static void
510 ovsdb_idl_row_update(struct ovsdb_idl_row *row, const struct json *row_json)
511 {
512     struct ovsdb_idl_table *table = row->table;
513     struct shash_node *node;
514
515     SHASH_FOR_EACH (node, json_object(row_json)) {
516         const char *column_name = node->name;
517         const struct ovsdb_idl_column *column;
518         struct ovsdb_datum datum;
519         struct ovsdb_error *error;
520
521         column = shash_find_data(&table->columns, column_name);
522         if (!column) {
523             VLOG_WARN_RL(&syntax_rl, "unknown column %s updating row "UUID_FMT,
524                          column_name, UUID_ARGS(&row->uuid));
525             continue;
526         }
527
528         error = ovsdb_datum_from_json(&datum, &column->type, node->data, NULL);
529         if (!error) {
530             ovsdb_datum_swap(&row->old[column - table->class->columns],
531                              &datum);
532             ovsdb_datum_destroy(&datum, &column->type);
533         } else {
534             char *s = ovsdb_error_to_string(error);
535             VLOG_WARN_RL(&syntax_rl, "error parsing column %s in row "UUID_FMT
536                          " in table %s: %s", column_name,
537                          UUID_ARGS(&row->uuid), table->class->name, s);
538             free(s);
539             ovsdb_error_destroy(error);
540         }
541     }
542 }
543
544 static bool
545 ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *row)
546 {
547     return !row->old;
548 /* Returns true if 'row' is conceptually part of the database as modified by
549  * the current transaction (if any), false otherwise.
550  *
551  * This function will return true if 'row' is not an orphan (see the comment on
552  * ovsdb_idl_row_is_orphan()) and:
553  *
554  *   - 'row' exists in the database and has not been deleted within the
555  *     current transaction (if any).
556  *
557  *   - 'row' was inserted within the current transaction and has not been
558  *     deleted.  (In the latter case you should not have passed 'row' in at
559  *     all, because ovsdb_idl_txn_delete() freed it.)
560  *
561  * This function will return false if 'row' is an orphan or if 'row' was
562  * deleted within the current transaction.
563  */
564 static bool
565 ovsdb_idl_row_exists(const struct ovsdb_idl_row *row)
566 {
567     return row->new != NULL;
568 }
569
570 static void
571 ovsdb_idl_row_parse(struct ovsdb_idl_row *row)
572 {
573     const struct ovsdb_idl_table_class *class = row->table->class;
574     size_t i;
575
576     for (i = 0; i < class->n_columns; i++) {
577         const struct ovsdb_idl_column *c = &class->columns[i];
578         (c->parse)(row, &row->old[i]);
579     }
580 }
581
582 static void
583 ovsdb_idl_row_unparse(struct ovsdb_idl_row *row)
584 {
585     const struct ovsdb_idl_table_class *class = row->table->class;
586     size_t i;
587
588     for (i = 0; i < class->n_columns; i++) {
589         const struct ovsdb_idl_column *c = &class->columns[i];
590         (c->unparse)(row);
591     }
592 }
593
594 static void
595 ovsdb_idl_row_clear_old(struct ovsdb_idl_row *row)
596 {
597     assert(row->old == row->new);
598     if (!ovsdb_idl_row_is_orphan(row)) {
599         const struct ovsdb_idl_table_class *class = row->table->class;
600         size_t i;
601
602         for (i = 0; i < class->n_columns; i++) {
603             ovsdb_datum_destroy(&row->old[i], &class->columns[i].type);
604         }
605         free(row->old);
606         row->old = row->new = NULL;
607     }
608 }
609
610 static void
611 ovsdb_idl_row_clear_new(struct ovsdb_idl_row *row)
612 {
613     if (row->old != row->new) {
614         if (row->new) {
615             const struct ovsdb_idl_table_class *class = row->table->class;
616             size_t i;
617
618             BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
619                 ovsdb_datum_destroy(&row->new[i], &class->columns[i].type);
620             }
621             free(row->new);
622             free(row->written);
623             row->written = NULL;
624         }
625         row->new = row->old;
626     }
627 }
628
629 static void
630 ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
631 {
632     struct ovsdb_idl_arc *arc, *next;
633
634     /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
635      * that this causes to be unreferenced. */
636     LIST_FOR_EACH_SAFE (arc, next, struct ovsdb_idl_arc, src_node,
637                         &row->src_arcs) {
638         list_remove(&arc->dst_node);
639         if (destroy_dsts
640             && ovsdb_idl_row_is_orphan(arc->dst)
641             && list_is_empty(&arc->dst->dst_arcs)) {
642             ovsdb_idl_row_destroy(arc->dst);
643         }
644         free(arc);
645     }
646     list_init(&row->src_arcs);
647 }
648
649 /* Force nodes that reference 'row' to reparse. */
650 static void
651 ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
652 {
653     struct ovsdb_idl_arc *arc, *next;
654
655     /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
656      * 'arc', so we need to use the "safe" variant of list traversal.  However,
657      * calling an ovsdb_idl_column's 'parse' function will add an arc
658      * equivalent to 'arc' to row->arcs.  That could be a problem for
659      * traversal, but it adds it at the beginning of the list to prevent us
660      * from stumbling upon it again.
661      *
662      * (If duplicate arcs were possible then we would need to make sure that
663      * 'next' didn't also point into 'arc''s destination, but we forbid
664      * duplicate arcs.) */
665     LIST_FOR_EACH_SAFE (arc, next, struct ovsdb_idl_arc, dst_node,
666                         &row->dst_arcs) {
667         struct ovsdb_idl_row *ref = arc->src;
668
669         ovsdb_idl_row_unparse(ref);
670         ovsdb_idl_row_clear_arcs(ref, false);
671         ovsdb_idl_row_parse(ref);
672     }
673 }
674
675 static struct ovsdb_idl_row *
676 ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
677 {
678     struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
679     list_init(&row->src_arcs);
680     list_init(&row->dst_arcs);
681     hmap_node_nullify(&row->txn_node);
682     return row;
683 }
684
685 static struct ovsdb_idl_row *
686 ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
687 {
688     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class);
689     hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
690     row->uuid = *uuid;
691     row->table = table;
692     return row;
693 }
694
695 static void
696 ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
697 {
698     if (row) {
699         ovsdb_idl_row_clear_old(row);
700         hmap_remove(&row->table->rows, &row->hmap_node);
701         free(row);
702     }
703 }
704
705 static void
706 ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct json *row_json)
707 {
708     const struct ovsdb_idl_table_class *class = row->table->class;
709     size_t i;
710
711     assert(!row->old && !row->new);
712     row->old = row->new = xmalloc(class->n_columns * sizeof *row->old);
713     for (i = 0; i < class->n_columns; i++) {
714         ovsdb_datum_init_default(&row->old[i], &class->columns[i].type);
715     }
716     ovsdb_idl_row_update(row, row_json);
717     ovsdb_idl_row_parse(row);
718
719     ovsdb_idl_row_reparse_backrefs(row);
720 }
721
722 static void
723 ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
724 {
725     ovsdb_idl_row_unparse(row);
726     ovsdb_idl_row_clear_arcs(row, true);
727     ovsdb_idl_row_clear_old(row);
728     if (list_is_empty(&row->dst_arcs)) {
729         ovsdb_idl_row_destroy(row);
730     } else {
731         ovsdb_idl_row_reparse_backrefs(row);
732     }
733 }
734
735 static void
736 ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct json *row_json)
737 {
738     ovsdb_idl_row_unparse(row);
739     ovsdb_idl_row_clear_arcs(row, true);
740     ovsdb_idl_row_update(row, row_json);
741     ovsdb_idl_row_parse(row);
742 }
743
744 static bool
745 may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
746 {
747     const struct ovsdb_idl_arc *arc;
748
749     /* No self-arcs. */
750     if (src == dst) {
751         return false;
752     }
753
754     /* No duplicate arcs.
755      *
756      * We only need to test whether the first arc in dst->dst_arcs originates
757      * at 'src', since we add all of the arcs from a given source in a clump
758      * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
759      * added at the front of the dst_arcs list. */
760     if (list_is_empty(&dst->dst_arcs)) {
761         return true;
762     }
763     arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
764     return arc->src != src;
765 }
766
767 static struct ovsdb_idl_table *
768 ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
769                            const struct ovsdb_idl_table_class *table_class)
770 {
771     return &idl->tables[table_class - idl->class->tables];
772 }
773
774 struct ovsdb_idl_row *
775 ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
776                       struct ovsdb_idl_table_class *dst_table_class,
777                       const struct uuid *dst_uuid)
778 {
779     struct ovsdb_idl *idl = src->table->idl;
780     struct ovsdb_idl_table *dst_table;
781     struct ovsdb_idl_arc *arc;
782     struct ovsdb_idl_row *dst;
783
784     dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
785     dst = ovsdb_idl_get_row(dst_table, dst_uuid);
786     if (idl->txn) {
787         /* We're being called from ovsdb_idl_txn_write().  We must not update
788          * any arcs, because the transaction will be backed out at commit or
789          * abort time and we don't want our graph screwed up.
790          *
791          * Just return the destination row, if there is one and it has not been
792          * deleted. */
793         if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new)) {
794             return dst;
795         }
796         return NULL;
797     } else {
798         /* We're being called from some other context.  Update the graph. */
799         if (!dst) {
800             dst = ovsdb_idl_row_create(dst_table, dst_uuid);
801         }
802
803         /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
804         if (may_add_arc(src, dst)) {
805             /* The arc *must* be added at the front of the dst_arcs list.  See
806              * ovsdb_idl_row_reparse_backrefs() for details. */
807             arc = xmalloc(sizeof *arc);
808             list_push_front(&src->src_arcs, &arc->src_node);
809             list_push_front(&dst->dst_arcs, &arc->dst_node);
810             arc->src = src;
811             arc->dst = dst;
812         }
813
814         return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
815     }
816 }
817
818 const struct ovsdb_idl_row *
819 ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
820                            const struct ovsdb_idl_table_class *tc,
821                            const struct uuid *uuid)
822 {
823     return ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
824 }
825
826 static struct ovsdb_idl_row *
827 next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
828 {
829     for (; node; node = hmap_next(&table->rows, node)) {
830         struct ovsdb_idl_row *row;
831
832         row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
833         if (ovsdb_idl_row_exists(row)) {
834             return row;
835         }
836     }
837     return NULL;
838 }
839
840 const struct ovsdb_idl_row *
841 ovsdb_idl_first_row(const struct ovsdb_idl *idl,
842                     const struct ovsdb_idl_table_class *table_class)
843 {
844     struct ovsdb_idl_table *table
845         = ovsdb_idl_table_from_class(idl, table_class);
846     return next_real_row(table, hmap_first(&table->rows));
847 }
848
849 const struct ovsdb_idl_row *
850 ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
851 {
852     struct ovsdb_idl_table *table = row->table;
853
854     return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
855 }
856 \f
857 /* Transactions. */
858
859 static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
860                                    enum ovsdb_idl_txn_status);
861
862 const char *
863 ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
864 {
865     switch (status) {
866     case TXN_UNCHANGED:
867         return "unchanged";
868     case TXN_INCOMPLETE:
869         return "incomplete";
870     case TXN_ABORTED:
871         return "aborted";
872     case TXN_SUCCESS:
873         return "success";
874     case TXN_TRY_AGAIN:
875         return "try again";
876     case TXN_ERROR:
877         return "error";
878     }
879     return "<unknown>";
880 }
881
882 struct ovsdb_idl_txn *
883 ovsdb_idl_txn_create(struct ovsdb_idl *idl)
884 {
885     struct ovsdb_idl_txn *txn;
886
887     assert(!idl->txn);
888     idl->txn = txn = xmalloc(sizeof *txn);
889     txn->request_id = NULL;
890     txn->idl = idl;
891     hmap_init(&txn->txn_rows);
892     txn->status = TXN_INCOMPLETE;
893     txn->error = NULL;
894     txn->dry_run = false;
895     ds_init(&txn->comment);
896
897     txn->inc_table = NULL;
898     txn->inc_column = NULL;
899     txn->inc_where = NULL;
900
901     hmap_init(&txn->inserted_rows);
902
903     return txn;
904 }
905
906 void
907 ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s)
908 {
909     if (txn->comment.length) {
910         ds_put_char(&txn->comment, '\n');
911     }
912     ds_put_cstr(&txn->comment, s);
913 }
914
915 void
916 ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
917 {
918     txn->dry_run = true;
919 }
920
921 void
922 ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn, const char *table,
923                         const char *column, const struct json *where)
924 {
925     assert(!txn->inc_table);
926     txn->inc_table = xstrdup(table);
927     txn->inc_column = xstrdup(column);
928     txn->inc_where = where ? json_clone(where) : json_array_create_empty();
929 }
930
931 void
932 ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
933 {
934     struct ovsdb_idl_txn_insert *insert, *next;
935
936     json_destroy(txn->request_id);
937     if (txn->status == TXN_INCOMPLETE) {
938         hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
939     }
940     ovsdb_idl_txn_abort(txn);
941     ds_destroy(&txn->comment);
942     free(txn->error);
943     free(txn->inc_table);
944     free(txn->inc_column);
945     json_destroy(txn->inc_where);
946     HMAP_FOR_EACH_SAFE (insert, next, struct ovsdb_idl_txn_insert, hmap_node,
947                         &txn->inserted_rows) {
948         free(insert);
949     }
950     hmap_destroy(&txn->inserted_rows);
951     free(txn);
952 }
953
954 void
955 ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
956 {
957     if (txn->status != TXN_INCOMPLETE) {
958         poll_immediate_wake();
959     }
960 }
961
962 static struct json *
963 where_uuid_equals(const struct uuid *uuid)
964 {
965     return
966         json_array_create_1(
967             json_array_create_3(
968                 json_string_create("_uuid"),
969                 json_string_create("=="),
970                 json_array_create_2(
971                     json_string_create("uuid"),
972                     json_string_create_nocopy(
973                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
974 }
975
976 static char *
977 uuid_name_from_uuid(const struct uuid *uuid)
978 {
979     char *name;
980     char *p;
981
982     name = xasprintf("row"UUID_FMT, UUID_ARGS(uuid));
983     for (p = name; *p != '\0'; p++) {
984         if (*p == '-') {
985             *p = '_';
986         }
987     }
988
989     return name;
990 }
991
992 static const struct ovsdb_idl_row *
993 ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
994 {
995     const struct ovsdb_idl_row *row;
996
997     HMAP_FOR_EACH_WITH_HASH (row, struct ovsdb_idl_row, txn_node,
998                              uuid_hash(uuid), &txn->txn_rows) {
999         if (uuid_equals(&row->uuid, uuid)) {
1000             return row;
1001         }
1002     }
1003     return NULL;
1004 }
1005
1006 /* XXX there must be a cleaner way to do this */
1007 static struct json *
1008 substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
1009 {
1010     if (json->type == JSON_ARRAY) {
1011         struct uuid uuid;
1012         size_t i;
1013
1014         if (json->u.array.n == 2
1015             && json->u.array.elems[0]->type == JSON_STRING
1016             && json->u.array.elems[1]->type == JSON_STRING
1017             && !strcmp(json->u.array.elems[0]->u.string, "uuid")
1018             && uuid_from_string(&uuid, json->u.array.elems[1]->u.string)) {
1019             const struct ovsdb_idl_row *row;
1020
1021             row = ovsdb_idl_txn_get_row(txn, &uuid);
1022             if (row && !row->old && row->new) {
1023                 json_destroy(json);
1024
1025                 return json_array_create_2(
1026                     json_string_create("named-uuid"),
1027                     json_string_create_nocopy(uuid_name_from_uuid(&uuid)));
1028             }
1029         }
1030
1031         for (i = 0; i < json->u.array.n; i++) {
1032             json->u.array.elems[i] = substitute_uuids(json->u.array.elems[i],
1033                                                       txn);
1034         }
1035     } else if (json->type == JSON_OBJECT) {
1036         struct shash_node *node;
1037
1038         SHASH_FOR_EACH (node, json_object(json)) {
1039             node->data = substitute_uuids(node->data, txn);
1040         }
1041     }
1042     return json;
1043 }
1044
1045 static void
1046 ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
1047 {
1048     struct ovsdb_idl_row *row, *next;
1049
1050     /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
1051      * ovsdb_idl_column's 'parse' function, which will call
1052      * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
1053      * transaction and fail to update the graph.  */
1054     txn->idl->txn = NULL;
1055
1056     HMAP_FOR_EACH_SAFE (row, next, struct ovsdb_idl_row, txn_node,
1057                         &txn->txn_rows) {
1058         if (row->old) {
1059             if (row->written) {
1060                 ovsdb_idl_row_unparse(row);
1061                 ovsdb_idl_row_clear_arcs(row, false);
1062                 ovsdb_idl_row_parse(row);
1063             }
1064         } else {
1065             ovsdb_idl_row_unparse(row);
1066         }
1067         ovsdb_idl_row_clear_new(row);
1068
1069         free(row->prereqs);
1070         row->prereqs = NULL;
1071
1072         free(row->written);
1073         row->written = NULL;
1074
1075         hmap_remove(&txn->txn_rows, &row->txn_node);
1076         hmap_node_nullify(&row->txn_node);
1077         if (!row->old) {
1078             hmap_remove(&row->table->rows, &row->hmap_node);
1079             free(row);
1080         }
1081     }
1082     hmap_destroy(&txn->txn_rows);
1083     hmap_init(&txn->txn_rows);
1084 }
1085
1086 enum ovsdb_idl_txn_status
1087 ovsdb_idl_txn_commit(struct ovsdb_idl_txn *txn)
1088 {
1089     struct ovsdb_idl_row *row;
1090     struct json *operations;
1091     bool any_updates;
1092
1093     if (txn != txn->idl->txn) {
1094         return txn->status;
1095     }
1096
1097     operations = json_array_create_1(
1098         json_string_create(txn->idl->class->database));
1099
1100     /* Add prerequisites and declarations of new rows. */
1101     HMAP_FOR_EACH (row, struct ovsdb_idl_row, txn_node, &txn->txn_rows) {
1102         /* XXX check that deleted rows exist even if no prereqs? */
1103         if (row->prereqs) {
1104             const struct ovsdb_idl_table_class *class = row->table->class;
1105             size_t n_columns = class->n_columns;
1106             struct json *op, *columns, *row_json;
1107             size_t idx;
1108
1109             op = json_object_create();
1110             json_array_add(operations, op);
1111             json_object_put_string(op, "op", "wait");
1112             json_object_put_string(op, "table", class->name);
1113             json_object_put(op, "timeout", json_integer_create(0));
1114             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1115             json_object_put_string(op, "until", "==");
1116             columns = json_array_create_empty();
1117             json_object_put(op, "columns", columns);
1118             row_json = json_object_create();
1119             json_object_put(op, "rows", json_array_create_1(row_json));
1120
1121             BITMAP_FOR_EACH_1 (idx, n_columns, row->prereqs) {
1122                 const struct ovsdb_idl_column *column = &class->columns[idx];
1123                 json_array_add(columns, json_string_create(column->name));
1124                 json_object_put(row_json, column->name,
1125                                 ovsdb_datum_to_json(&row->old[idx],
1126                                                     &column->type));
1127             }
1128         }
1129     }
1130
1131     /* Add updates. */
1132     any_updates = false;
1133     HMAP_FOR_EACH (row, struct ovsdb_idl_row, txn_node, &txn->txn_rows) {
1134         const struct ovsdb_idl_table_class *class = row->table->class;
1135
1136         if (row->old == row->new) {
1137             continue;
1138         } else if (!row->new) {
1139             struct json *op = json_object_create();
1140             json_object_put_string(op, "op", "delete");
1141             json_object_put_string(op, "table", class->name);
1142             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1143             json_array_add(operations, op);
1144             any_updates = true;
1145         } else {
1146             struct json *row_json;
1147             struct json *op;
1148             size_t idx;
1149
1150             op = json_object_create();
1151             json_object_put_string(op, "op", row->old ? "update" : "insert");
1152             json_object_put_string(op, "table", class->name);
1153             if (row->old) {
1154                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
1155             } else {
1156                 struct ovsdb_idl_txn_insert *insert;
1157
1158                 json_object_put(op, "uuid-name",
1159                                 json_string_create_nocopy(
1160                                     uuid_name_from_uuid(&row->uuid)));
1161
1162                 insert = xmalloc(sizeof *insert);
1163                 insert->dummy = row->uuid;
1164                 insert->op_index = operations->u.array.n - 1;
1165                 uuid_zero(&insert->real);
1166                 hmap_insert(&txn->inserted_rows, &insert->hmap_node,
1167                             uuid_hash(&insert->dummy));
1168             }
1169             row_json = json_object_create();
1170             json_object_put(op, "row", row_json);
1171
1172             BITMAP_FOR_EACH_1 (idx, class->n_columns, row->written) {
1173                 const struct ovsdb_idl_column *column = &class->columns[idx];
1174
1175                 if (row->old
1176                     ? !ovsdb_datum_equals(&row->old[idx], &row->new[idx],
1177                                           &column->type)
1178                     : !ovsdb_datum_is_default(&row->new[idx], &column->type)) {
1179                     json_object_put(row_json, column->name,
1180                                     substitute_uuids(
1181                                         ovsdb_datum_to_json(&row->new[idx],
1182                                                             &column->type),
1183                                         txn));
1184                 }
1185             }
1186
1187             if (!row->old || !shash_is_empty(json_object(row_json))) {
1188                 json_array_add(operations, op);
1189                 any_updates = true;
1190             } else {
1191                 json_destroy(op);
1192             }
1193         }
1194     }
1195
1196     /* Add increment. */
1197     if (txn->inc_table && any_updates) {
1198         struct json *op;
1199
1200         txn->inc_index = operations->u.array.n - 1;
1201
1202         op = json_object_create();
1203         json_object_put_string(op, "op", "mutate");
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, "mutations",
1208                         json_array_create_1(
1209                             json_array_create_3(
1210                                 json_string_create(txn->inc_column),
1211                                 json_string_create("+="),
1212                                 json_integer_create(1))));
1213         json_array_add(operations, op);
1214
1215         op = json_object_create();
1216         json_object_put_string(op, "op", "select");
1217         json_object_put_string(op, "table", txn->inc_table);
1218         json_object_put(op, "where",
1219                         substitute_uuids(json_clone(txn->inc_where), txn));
1220         json_object_put(op, "columns",
1221                         json_array_create_1(json_string_create(
1222                                                 txn->inc_column)));
1223         json_array_add(operations, op);
1224     }
1225
1226     if (txn->comment.length) {
1227         struct json *op = json_object_create();
1228         json_object_put_string(op, "op", "comment");
1229         json_object_put_string(op, "comment", ds_cstr(&txn->comment));
1230         json_array_add(operations, op);
1231     }
1232
1233     if (txn->dry_run) {
1234         struct json *op = json_object_create();
1235         json_object_put_string(op, "op", "abort");
1236         json_array_add(operations, op);
1237     }
1238
1239     if (!any_updates) {
1240         txn->status = TXN_UNCHANGED;
1241         json_destroy(operations);
1242     } else if (!jsonrpc_session_send(
1243                    txn->idl->session,
1244                    jsonrpc_create_request(
1245                        "transact", operations, &txn->request_id))) {
1246         hmap_insert(&txn->idl->outstanding_txns, &txn->hmap_node,
1247                     json_hash(txn->request_id, 0));
1248     } else {
1249         txn->status = TXN_TRY_AGAIN;
1250     }
1251
1252     ovsdb_idl_txn_disassemble(txn);
1253     return txn->status;
1254 }
1255
1256 int64_t
1257 ovsdb_idl_txn_get_increment_new_value(const struct ovsdb_idl_txn *txn)
1258 {
1259     assert(txn->status == TXN_SUCCESS);
1260     return txn->inc_new_value;
1261 }
1262
1263 void
1264 ovsdb_idl_txn_abort(struct ovsdb_idl_txn *txn)
1265 {
1266     ovsdb_idl_txn_disassemble(txn);
1267     if (txn->status == TXN_INCOMPLETE) {
1268         txn->status = TXN_ABORTED;
1269     }
1270 }
1271
1272 const char *
1273 ovsdb_idl_txn_get_error(const struct ovsdb_idl_txn *txn)
1274 {
1275     if (txn->status != TXN_ERROR) {
1276         return ovsdb_idl_txn_status_to_string(txn->status);
1277     } else if (txn->error) {
1278         return txn->error;
1279     } else {
1280         return "no error details available";
1281     }
1282 }
1283
1284 static void
1285 ovsdb_idl_txn_set_error_json(struct ovsdb_idl_txn *txn,
1286                              const struct json *json)
1287 {
1288     if (txn->error == NULL) {
1289         txn->error = json_to_string(json, JSSF_SORT);
1290     }
1291 }
1292
1293 /* For transaction 'txn' that completed successfully, finds and returns the
1294  * permanent UUID that the database assigned to a newly inserted row, given the
1295  * 'uuid' that ovsdb_idl_txn_insert() assigned locally to that row.
1296  *
1297  * Returns NULL if 'uuid' is not a UUID assigned by ovsdb_idl_txn_insert() or
1298  * if it was assigned by that function and then deleted by
1299  * ovsdb_idl_txn_delete() within the same transaction.  (Rows that are inserted
1300  * and then deleted within a single transaction are never sent to the database
1301  * server, so it never assigns them a permanent UUID.) */
1302 const struct uuid *
1303 ovsdb_idl_txn_get_insert_uuid(const struct ovsdb_idl_txn *txn,
1304                               const struct uuid *uuid)
1305 {
1306     const struct ovsdb_idl_txn_insert *insert;
1307
1308     assert(txn->status == TXN_SUCCESS || txn->status == TXN_UNCHANGED);
1309     HMAP_FOR_EACH_IN_BUCKET (insert, struct ovsdb_idl_txn_insert, hmap_node,
1310                              uuid_hash(uuid), &txn->inserted_rows) {
1311         if (uuid_equals(uuid, &insert->dummy)) {
1312             return &insert->real;
1313         }
1314     }
1315     return NULL;
1316 }
1317
1318 static void
1319 ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1320                        enum ovsdb_idl_txn_status status)
1321 {
1322     txn->status = status;
1323     hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1324 }
1325
1326 void
1327 ovsdb_idl_txn_read(const struct ovsdb_idl_row *row,
1328                    const struct ovsdb_idl_column *column,
1329                    struct ovsdb_datum *datum)
1330 {
1331     const struct ovsdb_idl_table_class *class = row->table->class;
1332     size_t column_idx = column - class->columns;
1333
1334     assert(row->new != NULL);
1335     if (row->written && bitmap_is_set(row->written, column_idx)) {
1336         ovsdb_datum_clone(datum, &row->new[column_idx], &column->type);
1337     } else if (row->old) {
1338         ovsdb_datum_clone(datum, &row->old[column_idx], &column->type);
1339     } else {
1340         ovsdb_datum_init_default(datum, &column->type);
1341     }
1342 }
1343
1344 void
1345 ovsdb_idl_txn_write(const struct ovsdb_idl_row *row_,
1346                     const struct ovsdb_idl_column *column,
1347                     struct ovsdb_datum *datum)
1348 {
1349     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1350     const struct ovsdb_idl_table_class *class = row->table->class;
1351     size_t column_idx = column - class->columns;
1352
1353     assert(row->new != NULL);
1354     assert(column_idx < class->n_columns);
1355     if (hmap_node_is_null(&row->txn_node)) {
1356         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1357                     uuid_hash(&row->uuid));
1358     }
1359     if (row->old == row->new) {
1360         row->new = xmalloc(class->n_columns * sizeof *row->new);
1361     }
1362     if (!row->written) {
1363         row->written = bitmap_allocate(class->n_columns);
1364     }
1365     if (bitmap_is_set(row->written, column_idx)) {
1366         ovsdb_datum_destroy(&row->new[column_idx], &column->type);
1367     } else {
1368         bitmap_set1(row->written, column_idx);
1369     }
1370     row->new[column_idx] = *datum;
1371     (column->unparse)(row);
1372     (column->parse)(row, &row->new[column_idx]);
1373 }
1374
1375 void
1376 ovsdb_idl_txn_verify(const struct ovsdb_idl_row *row_,
1377                      const struct ovsdb_idl_column *column)
1378 {
1379     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1380     const struct ovsdb_idl_table_class *class = row->table->class;
1381     size_t column_idx = column - class->columns;
1382
1383     assert(row->new != NULL);
1384     if (!row->old
1385         || (row->written && bitmap_is_set(row->written, column_idx))) {
1386         return;
1387     }
1388
1389     if (hmap_node_is_null(&row->txn_node)) {
1390         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1391                     uuid_hash(&row->uuid));
1392     }
1393     if (!row->prereqs) {
1394         row->prereqs = bitmap_allocate(class->n_columns);
1395     }
1396     bitmap_set1(row->prereqs, column_idx);
1397 }
1398
1399 void
1400 ovsdb_idl_txn_delete(const struct ovsdb_idl_row *row_)
1401 {
1402     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1403
1404     assert(row->new != NULL);
1405     if (!row->old) {
1406         ovsdb_idl_row_unparse(row);
1407         ovsdb_idl_row_clear_new(row);
1408         assert(!row->prereqs);
1409         hmap_remove(&row->table->rows, &row->hmap_node);
1410         hmap_remove(&row->table->idl->txn->txn_rows, &row->txn_node);
1411         free(row);
1412         return;
1413     }
1414     if (hmap_node_is_null(&row->txn_node)) {
1415         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1416                     uuid_hash(&row->uuid));
1417     }
1418     ovsdb_idl_row_clear_new(row);
1419     row->new = NULL;
1420 }
1421
1422 const struct ovsdb_idl_row *
1423 ovsdb_idl_txn_insert(struct ovsdb_idl_txn *txn,
1424                      const struct ovsdb_idl_table_class *class)
1425 {
1426     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(class);
1427     uuid_generate(&row->uuid);
1428     row->table = ovsdb_idl_table_from_class(txn->idl, class);
1429     row->new = xmalloc(class->n_columns * sizeof *row->new);
1430     row->written = bitmap_allocate(class->n_columns);
1431     hmap_insert(&row->table->rows, &row->hmap_node, uuid_hash(&row->uuid));
1432     hmap_insert(&txn->txn_rows, &row->txn_node, uuid_hash(&row->uuid));
1433     return row;
1434 }
1435
1436 static void
1437 ovsdb_idl_txn_abort_all(struct ovsdb_idl *idl)
1438 {
1439     struct ovsdb_idl_txn *txn;
1440
1441     HMAP_FOR_EACH (txn, struct ovsdb_idl_txn, hmap_node,
1442                    &idl->outstanding_txns) {
1443         ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
1444     }
1445 }
1446
1447 static struct ovsdb_idl_txn *
1448 ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
1449 {
1450     struct ovsdb_idl_txn *txn;
1451
1452     HMAP_FOR_EACH_WITH_HASH (txn, struct ovsdb_idl_txn, hmap_node,
1453                              json_hash(id, 0), &idl->outstanding_txns) {
1454         if (json_equal(id, txn->request_id)) {
1455             return txn;
1456         }
1457     }
1458     return NULL;
1459 }
1460
1461 static bool
1462 check_json_type(const struct json *json, enum json_type type, const char *name)
1463 {
1464     if (!json) {
1465         VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
1466         return false;
1467     } else if (json->type != type) {
1468         VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
1469                      name, json_type_to_string(json->type),
1470                      json_type_to_string(type));
1471         return false;
1472     } else {
1473         return true;
1474     }
1475 }
1476
1477 static bool
1478 ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
1479                                 const struct json_array *results)
1480 {
1481     struct json *count, *rows, *row, *column;
1482     struct shash *mutate, *select;
1483
1484     if (txn->inc_index + 2 > results->n) {
1485         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1486                      "for increment (has %u, needs %u)",
1487                      results->n, txn->inc_index + 2);
1488         return false;
1489     }
1490
1491     /* We know that this is a JSON object because the loop in
1492      * ovsdb_idl_txn_process_reply() checked. */
1493     mutate = json_object(results->elems[txn->inc_index]);
1494     count = shash_find_data(mutate, "count");
1495     if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
1496         return false;
1497     }
1498     if (count->u.integer != 1) {
1499         VLOG_WARN_RL(&syntax_rl,
1500                      "\"mutate\" reply \"count\" is %"PRId64" instead of 1",
1501                      count->u.integer);
1502         return false;
1503     }
1504
1505     select = json_object(results->elems[txn->inc_index + 1]);
1506     rows = shash_find_data(select, "rows");
1507     if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
1508         return false;
1509     }
1510     if (rows->u.array.n != 1) {
1511         VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %u elements "
1512                      "instead of 1",
1513                      rows->u.array.n);
1514         return false;
1515     }
1516     row = rows->u.array.elems[0];
1517     if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
1518         return false;
1519     }
1520     column = shash_find_data(json_object(row), txn->inc_column);
1521     if (!check_json_type(column, JSON_INTEGER,
1522                          "\"select\" reply inc column")) {
1523         return false;
1524     }
1525     txn->inc_new_value = column->u.integer;
1526     return true;
1527 }
1528
1529 static bool
1530 ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
1531                                    const struct json_array *results)
1532 {
1533     static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
1534     struct ovsdb_error *error;
1535     struct json *json_uuid;
1536     union ovsdb_atom uuid;
1537     struct shash *reply;
1538
1539     if (insert->op_index >= results->n) {
1540         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1541                      "for insert (has %u, needs %u)",
1542                      results->n, insert->op_index);
1543         return false;
1544     }
1545
1546     /* We know that this is a JSON object because the loop in
1547      * ovsdb_idl_txn_process_reply() checked. */
1548     reply = json_object(results->elems[insert->op_index]);
1549     json_uuid = shash_find_data(reply, "uuid");
1550     if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
1551         return false;
1552     }
1553
1554     error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
1555     if (error) {
1556         char *s = ovsdb_error_to_string(error);
1557         VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
1558                      "UUID: %s", s);
1559         free(s);
1560         return false;
1561     }
1562
1563     insert->real = uuid.uuid;
1564
1565     return true;
1566 }
1567
1568 static bool
1569 ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
1570                             const struct jsonrpc_msg *msg)
1571 {
1572     struct ovsdb_idl_txn *txn;
1573     enum ovsdb_idl_txn_status status;
1574
1575     txn = ovsdb_idl_txn_find(idl, msg->id);
1576     if (!txn) {
1577         return false;
1578     }
1579
1580     if (msg->type == JSONRPC_ERROR) {
1581         status = TXN_ERROR;
1582     } else if (msg->result->type != JSON_ARRAY) {
1583         VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
1584         status = TXN_ERROR;
1585     } else {
1586         struct json_array *ops = &msg->result->u.array;
1587         int hard_errors = 0;
1588         int soft_errors = 0;
1589         size_t i;
1590
1591         for (i = 0; i < ops->n; i++) {
1592             struct json *op = ops->elems[i];
1593
1594             if (op->type == JSON_NULL) {
1595                 /* This isn't an error in itself but indicates that some prior
1596                  * operation failed, so make sure that we know about it. */
1597                 soft_errors++;
1598             } else if (op->type == JSON_OBJECT) {
1599                 struct json *error;
1600
1601                 error = shash_find_data(json_object(op), "error");
1602                 if (error) {
1603                     if (error->type == JSON_STRING) {
1604                         if (!strcmp(error->u.string, "timed out")) {
1605                             soft_errors++;
1606                         } else if (strcmp(error->u.string, "aborted")) {
1607                             hard_errors++;
1608                             ovsdb_idl_txn_set_error_json(txn, op);
1609                         }
1610                     } else {
1611                         hard_errors++;
1612                         ovsdb_idl_txn_set_error_json(txn, op);
1613                         VLOG_WARN_RL(&syntax_rl,
1614                                      "\"error\" in reply is not JSON string");
1615                     }
1616                 }
1617             } else {
1618                 hard_errors++;
1619                 ovsdb_idl_txn_set_error_json(txn, op);
1620                 VLOG_WARN_RL(&syntax_rl,
1621                              "operation reply is not JSON null or object");
1622             }
1623         }
1624
1625         if (!soft_errors && !hard_errors) {
1626             struct ovsdb_idl_txn_insert *insert;
1627
1628             if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
1629                 hard_errors++;
1630             }
1631
1632             HMAP_FOR_EACH (insert, struct ovsdb_idl_txn_insert, hmap_node,
1633                            &txn->inserted_rows) {
1634                 if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
1635                     hard_errors++;
1636                 }
1637             }
1638         }
1639
1640         status = (hard_errors ? TXN_ERROR
1641                   : soft_errors ? TXN_TRY_AGAIN
1642                   : TXN_SUCCESS);
1643     }
1644
1645     ovsdb_idl_txn_complete(txn, status);
1646     return true;
1647 }
1648
1649 struct ovsdb_idl_txn *
1650 ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
1651 {
1652     struct ovsdb_idl_txn *txn = row->table->idl->txn;
1653     assert(txn != NULL);
1654     return txn;
1655 }