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