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