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