ovsdb-idl: Make it possible to omit or pay less attention to columns.
[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             ovsdb_datum_swap(&row->old[column_idx], &datum);
645             ovsdb_datum_destroy(&datum, &column->type);
646             if (table->modes[column_idx] == OVSDB_IDL_MODE_RW) {
647                 changed = true;
648             }
649         } else {
650             char *s = ovsdb_error_to_string(error);
651             VLOG_WARN_RL(&syntax_rl, "error parsing column %s in row "UUID_FMT
652                          " in table %s: %s", column_name,
653                          UUID_ARGS(&row->uuid), table->class->name, s);
654             free(s);
655             ovsdb_error_destroy(error);
656         }
657     }
658     return changed;
659 }
660
661 /* When a row A refers to row B through a column with a "refTable" constraint,
662  * but row B does not exist, row B is called an "orphan row".  Orphan rows
663  * should not persist, because the database enforces referential integrity, but
664  * they can appear transiently as changes from the database are received (the
665  * database doesn't try to topologically sort them and circular references mean
666  * it isn't always possible anyhow).
667  *
668  * This function returns true if 'row' is an orphan row, otherwise false.
669  */
670 static bool
671 ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *row)
672 {
673     return !row->old && !row->new;
674 }
675
676 /* Returns true if 'row' is conceptually part of the database as modified by
677  * the current transaction (if any), false otherwise.
678  *
679  * This function will return true if 'row' is not an orphan (see the comment on
680  * ovsdb_idl_row_is_orphan()) and:
681  *
682  *   - 'row' exists in the database and has not been deleted within the
683  *     current transaction (if any).
684  *
685  *   - 'row' was inserted within the current transaction and has not been
686  *     deleted.  (In the latter case you should not have passed 'row' in at
687  *     all, because ovsdb_idl_txn_delete() freed it.)
688  *
689  * This function will return false if 'row' is an orphan or if 'row' was
690  * deleted within the current transaction.
691  */
692 static bool
693 ovsdb_idl_row_exists(const struct ovsdb_idl_row *row)
694 {
695     return row->new != NULL;
696 }
697
698 static void
699 ovsdb_idl_row_parse(struct ovsdb_idl_row *row)
700 {
701     const struct ovsdb_idl_table_class *class = row->table->class;
702     size_t i;
703
704     for (i = 0; i < class->n_columns; i++) {
705         const struct ovsdb_idl_column *c = &class->columns[i];
706         (c->parse)(row, &row->old[i]);
707     }
708 }
709
710 static void
711 ovsdb_idl_row_unparse(struct ovsdb_idl_row *row)
712 {
713     const struct ovsdb_idl_table_class *class = row->table->class;
714     size_t i;
715
716     for (i = 0; i < class->n_columns; i++) {
717         const struct ovsdb_idl_column *c = &class->columns[i];
718         (c->unparse)(row);
719     }
720 }
721
722 static void
723 ovsdb_idl_row_clear_old(struct ovsdb_idl_row *row)
724 {
725     assert(row->old == row->new);
726     if (!ovsdb_idl_row_is_orphan(row)) {
727         const struct ovsdb_idl_table_class *class = row->table->class;
728         size_t i;
729
730         for (i = 0; i < class->n_columns; i++) {
731             ovsdb_datum_destroy(&row->old[i], &class->columns[i].type);
732         }
733         free(row->old);
734         row->old = row->new = NULL;
735     }
736 }
737
738 static void
739 ovsdb_idl_row_clear_new(struct ovsdb_idl_row *row)
740 {
741     if (row->old != row->new) {
742         if (row->new) {
743             const struct ovsdb_idl_table_class *class = row->table->class;
744             size_t i;
745
746             if (row->written) {
747                 BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
748                     ovsdb_datum_destroy(&row->new[i], &class->columns[i].type);
749                 }
750             }
751             free(row->new);
752             free(row->written);
753             row->written = NULL;
754         }
755         row->new = row->old;
756     }
757 }
758
759 static void
760 ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
761 {
762     struct ovsdb_idl_arc *arc, *next;
763
764     /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
765      * that this causes to be unreferenced. */
766     LIST_FOR_EACH_SAFE (arc, next, struct ovsdb_idl_arc, src_node,
767                         &row->src_arcs) {
768         list_remove(&arc->dst_node);
769         if (destroy_dsts
770             && ovsdb_idl_row_is_orphan(arc->dst)
771             && list_is_empty(&arc->dst->dst_arcs)) {
772             ovsdb_idl_row_destroy(arc->dst);
773         }
774         free(arc);
775     }
776     list_init(&row->src_arcs);
777 }
778
779 /* Force nodes that reference 'row' to reparse. */
780 static void
781 ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
782 {
783     struct ovsdb_idl_arc *arc, *next;
784
785     /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
786      * 'arc', so we need to use the "safe" variant of list traversal.  However,
787      * calling an ovsdb_idl_column's 'parse' function will add an arc
788      * equivalent to 'arc' to row->arcs.  That could be a problem for
789      * traversal, but it adds it at the beginning of the list to prevent us
790      * from stumbling upon it again.
791      *
792      * (If duplicate arcs were possible then we would need to make sure that
793      * 'next' didn't also point into 'arc''s destination, but we forbid
794      * duplicate arcs.) */
795     LIST_FOR_EACH_SAFE (arc, next, struct ovsdb_idl_arc, dst_node,
796                         &row->dst_arcs) {
797         struct ovsdb_idl_row *ref = arc->src;
798
799         ovsdb_idl_row_unparse(ref);
800         ovsdb_idl_row_clear_arcs(ref, false);
801         ovsdb_idl_row_parse(ref);
802     }
803 }
804
805 static struct ovsdb_idl_row *
806 ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
807 {
808     struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
809     list_init(&row->src_arcs);
810     list_init(&row->dst_arcs);
811     hmap_node_nullify(&row->txn_node);
812     return row;
813 }
814
815 static struct ovsdb_idl_row *
816 ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
817 {
818     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class);
819     hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
820     row->uuid = *uuid;
821     row->table = table;
822     return row;
823 }
824
825 static void
826 ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
827 {
828     if (row) {
829         ovsdb_idl_row_clear_old(row);
830         hmap_remove(&row->table->rows, &row->hmap_node);
831         free(row);
832     }
833 }
834
835 static void
836 ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct json *row_json)
837 {
838     const struct ovsdb_idl_table_class *class = row->table->class;
839     size_t i;
840
841     assert(!row->old && !row->new);
842     row->old = row->new = xmalloc(class->n_columns * sizeof *row->old);
843     for (i = 0; i < class->n_columns; i++) {
844         ovsdb_datum_init_default(&row->old[i], &class->columns[i].type);
845     }
846     ovsdb_idl_row_update(row, row_json);
847     ovsdb_idl_row_parse(row);
848
849     ovsdb_idl_row_reparse_backrefs(row);
850 }
851
852 static void
853 ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
854 {
855     ovsdb_idl_row_unparse(row);
856     ovsdb_idl_row_clear_arcs(row, true);
857     ovsdb_idl_row_clear_old(row);
858     if (list_is_empty(&row->dst_arcs)) {
859         ovsdb_idl_row_destroy(row);
860     } else {
861         ovsdb_idl_row_reparse_backrefs(row);
862     }
863 }
864
865 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
866  * otherwise. */
867 static bool
868 ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct json *row_json)
869 {
870     bool changed;
871
872     ovsdb_idl_row_unparse(row);
873     ovsdb_idl_row_clear_arcs(row, true);
874     changed = ovsdb_idl_row_update(row, row_json);
875     ovsdb_idl_row_parse(row);
876
877     return changed;
878 }
879
880 static bool
881 may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
882 {
883     const struct ovsdb_idl_arc *arc;
884
885     /* No self-arcs. */
886     if (src == dst) {
887         return false;
888     }
889
890     /* No duplicate arcs.
891      *
892      * We only need to test whether the first arc in dst->dst_arcs originates
893      * at 'src', since we add all of the arcs from a given source in a clump
894      * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
895      * added at the front of the dst_arcs list. */
896     if (list_is_empty(&dst->dst_arcs)) {
897         return true;
898     }
899     arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
900     return arc->src != src;
901 }
902
903 static struct ovsdb_idl_table *
904 ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
905                            const struct ovsdb_idl_table_class *table_class)
906 {
907     return &idl->tables[table_class - idl->class->tables];
908 }
909
910 struct ovsdb_idl_row *
911 ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
912                       struct ovsdb_idl_table_class *dst_table_class,
913                       const struct uuid *dst_uuid)
914 {
915     struct ovsdb_idl *idl = src->table->idl;
916     struct ovsdb_idl_table *dst_table;
917     struct ovsdb_idl_arc *arc;
918     struct ovsdb_idl_row *dst;
919
920     dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
921     dst = ovsdb_idl_get_row(dst_table, dst_uuid);
922     if (idl->txn) {
923         /* We're being called from ovsdb_idl_txn_write().  We must not update
924          * any arcs, because the transaction will be backed out at commit or
925          * abort time and we don't want our graph screwed up.
926          *
927          * Just return the destination row, if there is one and it has not been
928          * deleted. */
929         if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new)) {
930             return dst;
931         }
932         return NULL;
933     } else {
934         /* We're being called from some other context.  Update the graph. */
935         if (!dst) {
936             dst = ovsdb_idl_row_create(dst_table, dst_uuid);
937         }
938
939         /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
940         if (may_add_arc(src, dst)) {
941             /* The arc *must* be added at the front of the dst_arcs list.  See
942              * ovsdb_idl_row_reparse_backrefs() for details. */
943             arc = xmalloc(sizeof *arc);
944             list_push_front(&src->src_arcs, &arc->src_node);
945             list_push_front(&dst->dst_arcs, &arc->dst_node);
946             arc->src = src;
947             arc->dst = dst;
948         }
949
950         return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
951     }
952 }
953
954 const struct ovsdb_idl_row *
955 ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
956                            const struct ovsdb_idl_table_class *tc,
957                            const struct uuid *uuid)
958 {
959     return ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
960 }
961
962 static struct ovsdb_idl_row *
963 next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
964 {
965     for (; node; node = hmap_next(&table->rows, node)) {
966         struct ovsdb_idl_row *row;
967
968         row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
969         if (ovsdb_idl_row_exists(row)) {
970             return row;
971         }
972     }
973     return NULL;
974 }
975
976 const struct ovsdb_idl_row *
977 ovsdb_idl_first_row(const struct ovsdb_idl *idl,
978                     const struct ovsdb_idl_table_class *table_class)
979 {
980     struct ovsdb_idl_table *table
981         = ovsdb_idl_table_from_class(idl, table_class);
982     return next_real_row(table, hmap_first(&table->rows));
983 }
984
985 const struct ovsdb_idl_row *
986 ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
987 {
988     struct ovsdb_idl_table *table = row->table;
989
990     return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
991 }
992
993 /* Reads and returns the value of 'column' within 'row'.  If an ongoing
994  * transaction has changed 'column''s value, the modified value is returned.
995  *
996  * The caller must not modify or free the returned value.
997  *
998  * Various kinds of changes can invalidate the returned value: writing to the
999  * same 'column' in 'row' (e.g. with ovsdb_idl_txn_write()), deleting 'row'
1000  * (e.g. with ovsdb_idl_txn_delete()), or completing an ongoing transaction
1001  * (e.g. with ovsdb_idl_txn_commit() or ovsdb_idl_txn_abort()).  If the
1002  * returned value is needed for a long time, it is best to make a copy of it
1003  * with ovsdb_datum_clone(). */
1004 const struct ovsdb_datum *
1005 ovsdb_idl_read(const struct ovsdb_idl_row *row,
1006                const struct ovsdb_idl_column *column)
1007 {
1008     const struct ovsdb_idl_table_class *class = row->table->class;
1009     size_t column_idx = column - class->columns;
1010
1011     assert(row->new != NULL);
1012     assert(column_idx < class->n_columns);
1013
1014     if (row->written && bitmap_is_set(row->written, column_idx)) {
1015         return &row->new[column_idx];
1016     } else if (row->old) {
1017         return &row->old[column_idx];
1018     } else {
1019         return ovsdb_datum_default(&column->type);
1020     }
1021 }
1022
1023 /* Same as ovsdb_idl_read(), except that it also asserts that 'column' has key
1024  * type 'key_type' and value type 'value_type'.  (Scalar and set types will
1025  * have a value type of OVSDB_TYPE_VOID.)
1026  *
1027  * This is useful in code that "knows" that a particular column has a given
1028  * type, so that it will abort if someone changes the column's type without
1029  * updating the code that uses it. */
1030 const struct ovsdb_datum *
1031 ovsdb_idl_get(const struct ovsdb_idl_row *row,
1032               const struct ovsdb_idl_column *column,
1033               enum ovsdb_atomic_type key_type OVS_UNUSED,
1034               enum ovsdb_atomic_type value_type OVS_UNUSED)
1035 {
1036     assert(column->type.key.type == key_type);
1037     assert(column->type.value.type == value_type);
1038
1039     return ovsdb_idl_read(row, column);
1040 }
1041 \f
1042 /* Transactions. */
1043
1044 static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1045                                    enum ovsdb_idl_txn_status);
1046
1047 const char *
1048 ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
1049 {
1050     switch (status) {
1051     case TXN_UNCHANGED:
1052         return "unchanged";
1053     case TXN_INCOMPLETE:
1054         return "incomplete";
1055     case TXN_ABORTED:
1056         return "aborted";
1057     case TXN_SUCCESS:
1058         return "success";
1059     case TXN_TRY_AGAIN:
1060         return "try again";
1061     case TXN_ERROR:
1062         return "error";
1063     }
1064     return "<unknown>";
1065 }
1066
1067 struct ovsdb_idl_txn *
1068 ovsdb_idl_txn_create(struct ovsdb_idl *idl)
1069 {
1070     struct ovsdb_idl_txn *txn;
1071
1072     assert(!idl->txn);
1073     idl->txn = txn = xmalloc(sizeof *txn);
1074     txn->request_id = NULL;
1075     txn->idl = idl;
1076     hmap_init(&txn->txn_rows);
1077     txn->status = TXN_INCOMPLETE;
1078     txn->error = NULL;
1079     txn->dry_run = false;
1080     ds_init(&txn->comment);
1081
1082     txn->inc_table = NULL;
1083     txn->inc_column = NULL;
1084     txn->inc_where = NULL;
1085
1086     hmap_init(&txn->inserted_rows);
1087
1088     return txn;
1089 }
1090
1091 /* Appends 's', which is treated as a printf()-type format string, to the
1092  * comments that will be passed to the OVSDB server when 'txn' is committed.
1093  * (The comment will be committed to the OVSDB log, which "ovsdb-tool
1094  * show-log" can print in a relatively human-readable form.) */
1095 void
1096 ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s, ...)
1097 {
1098     va_list args;
1099
1100     if (txn->comment.length) {
1101         ds_put_char(&txn->comment, '\n');
1102     }
1103
1104     va_start(args, s);
1105     ds_put_format_valist(&txn->comment, s, args);
1106     va_end(args);
1107 }
1108
1109 void
1110 ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
1111 {
1112     txn->dry_run = true;
1113 }
1114
1115 void
1116 ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn, const char *table,
1117                         const char *column, const struct json *where)
1118 {
1119     assert(!txn->inc_table);
1120     txn->inc_table = xstrdup(table);
1121     txn->inc_column = xstrdup(column);
1122     txn->inc_where = where ? json_clone(where) : json_array_create_empty();
1123 }
1124
1125 void
1126 ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
1127 {
1128     struct ovsdb_idl_txn_insert *insert, *next;
1129
1130     json_destroy(txn->request_id);
1131     if (txn->status == TXN_INCOMPLETE) {
1132         hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1133     }
1134     ovsdb_idl_txn_abort(txn);
1135     ds_destroy(&txn->comment);
1136     free(txn->error);
1137     free(txn->inc_table);
1138     free(txn->inc_column);
1139     json_destroy(txn->inc_where);
1140     HMAP_FOR_EACH_SAFE (insert, next, struct ovsdb_idl_txn_insert, hmap_node,
1141                         &txn->inserted_rows) {
1142         free(insert);
1143     }
1144     hmap_destroy(&txn->inserted_rows);
1145     free(txn);
1146 }
1147
1148 void
1149 ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
1150 {
1151     if (txn->status != TXN_INCOMPLETE) {
1152         poll_immediate_wake();
1153     }
1154 }
1155
1156 static struct json *
1157 where_uuid_equals(const struct uuid *uuid)
1158 {
1159     return
1160         json_array_create_1(
1161             json_array_create_3(
1162                 json_string_create("_uuid"),
1163                 json_string_create("=="),
1164                 json_array_create_2(
1165                     json_string_create("uuid"),
1166                     json_string_create_nocopy(
1167                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
1168 }
1169
1170 static char *
1171 uuid_name_from_uuid(const struct uuid *uuid)
1172 {
1173     char *name;
1174     char *p;
1175
1176     name = xasprintf("row"UUID_FMT, UUID_ARGS(uuid));
1177     for (p = name; *p != '\0'; p++) {
1178         if (*p == '-') {
1179             *p = '_';
1180         }
1181     }
1182
1183     return name;
1184 }
1185
1186 static const struct ovsdb_idl_row *
1187 ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
1188 {
1189     const struct ovsdb_idl_row *row;
1190
1191     HMAP_FOR_EACH_WITH_HASH (row, struct ovsdb_idl_row, txn_node,
1192                              uuid_hash(uuid), &txn->txn_rows) {
1193         if (uuid_equals(&row->uuid, uuid)) {
1194             return row;
1195         }
1196     }
1197     return NULL;
1198 }
1199
1200 /* XXX there must be a cleaner way to do this */
1201 static struct json *
1202 substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
1203 {
1204     if (json->type == JSON_ARRAY) {
1205         struct uuid uuid;
1206         size_t i;
1207
1208         if (json->u.array.n == 2
1209             && json->u.array.elems[0]->type == JSON_STRING
1210             && json->u.array.elems[1]->type == JSON_STRING
1211             && !strcmp(json->u.array.elems[0]->u.string, "uuid")
1212             && uuid_from_string(&uuid, json->u.array.elems[1]->u.string)) {
1213             const struct ovsdb_idl_row *row;
1214
1215             row = ovsdb_idl_txn_get_row(txn, &uuid);
1216             if (row && !row->old && row->new) {
1217                 json_destroy(json);
1218
1219                 return json_array_create_2(
1220                     json_string_create("named-uuid"),
1221                     json_string_create_nocopy(uuid_name_from_uuid(&uuid)));
1222             }
1223         }
1224
1225         for (i = 0; i < json->u.array.n; i++) {
1226             json->u.array.elems[i] = substitute_uuids(json->u.array.elems[i],
1227                                                       txn);
1228         }
1229     } else if (json->type == JSON_OBJECT) {
1230         struct shash_node *node;
1231
1232         SHASH_FOR_EACH (node, json_object(json)) {
1233             node->data = substitute_uuids(node->data, txn);
1234         }
1235     }
1236     return json;
1237 }
1238
1239 static void
1240 ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
1241 {
1242     struct ovsdb_idl_row *row, *next;
1243
1244     /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
1245      * ovsdb_idl_column's 'parse' function, which will call
1246      * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
1247      * transaction and fail to update the graph.  */
1248     txn->idl->txn = NULL;
1249
1250     HMAP_FOR_EACH_SAFE (row, next, struct ovsdb_idl_row, txn_node,
1251                         &txn->txn_rows) {
1252         if (row->old) {
1253             if (row->written) {
1254                 ovsdb_idl_row_unparse(row);
1255                 ovsdb_idl_row_clear_arcs(row, false);
1256                 ovsdb_idl_row_parse(row);
1257             }
1258         } else {
1259             ovsdb_idl_row_unparse(row);
1260         }
1261         ovsdb_idl_row_clear_new(row);
1262
1263         free(row->prereqs);
1264         row->prereqs = NULL;
1265
1266         free(row->written);
1267         row->written = NULL;
1268
1269         hmap_remove(&txn->txn_rows, &row->txn_node);
1270         hmap_node_nullify(&row->txn_node);
1271         if (!row->old) {
1272             hmap_remove(&row->table->rows, &row->hmap_node);
1273             free(row);
1274         }
1275     }
1276     hmap_destroy(&txn->txn_rows);
1277     hmap_init(&txn->txn_rows);
1278 }
1279
1280 enum ovsdb_idl_txn_status
1281 ovsdb_idl_txn_commit(struct ovsdb_idl_txn *txn)
1282 {
1283     struct ovsdb_idl_row *row;
1284     struct json *operations;
1285     bool any_updates;
1286
1287     if (txn != txn->idl->txn) {
1288         return txn->status;
1289     }
1290
1291     operations = json_array_create_1(
1292         json_string_create(txn->idl->class->database));
1293
1294     /* Add prerequisites and declarations of new rows. */
1295     HMAP_FOR_EACH (row, struct ovsdb_idl_row, txn_node, &txn->txn_rows) {
1296         /* XXX check that deleted rows exist even if no prereqs? */
1297         if (row->prereqs) {
1298             const struct ovsdb_idl_table_class *class = row->table->class;
1299             size_t n_columns = class->n_columns;
1300             struct json *op, *columns, *row_json;
1301             size_t idx;
1302
1303             op = json_object_create();
1304             json_array_add(operations, op);
1305             json_object_put_string(op, "op", "wait");
1306             json_object_put_string(op, "table", class->name);
1307             json_object_put(op, "timeout", json_integer_create(0));
1308             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1309             json_object_put_string(op, "until", "==");
1310             columns = json_array_create_empty();
1311             json_object_put(op, "columns", columns);
1312             row_json = json_object_create();
1313             json_object_put(op, "rows", json_array_create_1(row_json));
1314
1315             BITMAP_FOR_EACH_1 (idx, n_columns, row->prereqs) {
1316                 const struct ovsdb_idl_column *column = &class->columns[idx];
1317                 json_array_add(columns, json_string_create(column->name));
1318                 json_object_put(row_json, column->name,
1319                                 ovsdb_datum_to_json(&row->old[idx],
1320                                                     &column->type));
1321             }
1322         }
1323     }
1324
1325     /* Add updates. */
1326     any_updates = false;
1327     HMAP_FOR_EACH (row, struct ovsdb_idl_row, txn_node, &txn->txn_rows) {
1328         const struct ovsdb_idl_table_class *class = row->table->class;
1329
1330         if (row->old == row->new) {
1331             continue;
1332         } else if (!row->new) {
1333             struct json *op = json_object_create();
1334             json_object_put_string(op, "op", "delete");
1335             json_object_put_string(op, "table", class->name);
1336             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1337             json_array_add(operations, op);
1338             any_updates = true;
1339         } else {
1340             struct json *row_json;
1341             struct json *op;
1342             size_t idx;
1343
1344             op = json_object_create();
1345             json_object_put_string(op, "op", row->old ? "update" : "insert");
1346             json_object_put_string(op, "table", class->name);
1347             if (row->old) {
1348                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
1349             } else {
1350                 struct ovsdb_idl_txn_insert *insert;
1351
1352                 json_object_put(op, "uuid-name",
1353                                 json_string_create_nocopy(
1354                                     uuid_name_from_uuid(&row->uuid)));
1355
1356                 insert = xmalloc(sizeof *insert);
1357                 insert->dummy = row->uuid;
1358                 insert->op_index = operations->u.array.n - 1;
1359                 uuid_zero(&insert->real);
1360                 hmap_insert(&txn->inserted_rows, &insert->hmap_node,
1361                             uuid_hash(&insert->dummy));
1362             }
1363             row_json = json_object_create();
1364             json_object_put(op, "row", row_json);
1365
1366             if (row->written) {
1367                 BITMAP_FOR_EACH_1 (idx, class->n_columns, row->written) {
1368                     const struct ovsdb_idl_column *column =
1369                                                         &class->columns[idx];
1370
1371                     if (row->old
1372                         ? !ovsdb_datum_equals(&row->old[idx], &row->new[idx],
1373                                               &column->type)
1374                         : !ovsdb_datum_is_default(&row->new[idx],
1375                                                   &column->type)) {
1376                         json_object_put(row_json, column->name,
1377                                         substitute_uuids(
1378                                             ovsdb_datum_to_json(&row->new[idx],
1379                                                                 &column->type),
1380                                             txn));
1381                     }
1382                 }
1383             }
1384
1385             if (!row->old || !shash_is_empty(json_object(row_json))) {
1386                 json_array_add(operations, op);
1387                 any_updates = true;
1388             } else {
1389                 json_destroy(op);
1390             }
1391         }
1392     }
1393
1394     /* Add increment. */
1395     if (txn->inc_table && any_updates) {
1396         struct json *op;
1397
1398         txn->inc_index = operations->u.array.n - 1;
1399
1400         op = json_object_create();
1401         json_object_put_string(op, "op", "mutate");
1402         json_object_put_string(op, "table", txn->inc_table);
1403         json_object_put(op, "where",
1404                         substitute_uuids(json_clone(txn->inc_where), txn));
1405         json_object_put(op, "mutations",
1406                         json_array_create_1(
1407                             json_array_create_3(
1408                                 json_string_create(txn->inc_column),
1409                                 json_string_create("+="),
1410                                 json_integer_create(1))));
1411         json_array_add(operations, op);
1412
1413         op = json_object_create();
1414         json_object_put_string(op, "op", "select");
1415         json_object_put_string(op, "table", txn->inc_table);
1416         json_object_put(op, "where",
1417                         substitute_uuids(json_clone(txn->inc_where), txn));
1418         json_object_put(op, "columns",
1419                         json_array_create_1(json_string_create(
1420                                                 txn->inc_column)));
1421         json_array_add(operations, op);
1422     }
1423
1424     if (txn->comment.length) {
1425         struct json *op = json_object_create();
1426         json_object_put_string(op, "op", "comment");
1427         json_object_put_string(op, "comment", ds_cstr(&txn->comment));
1428         json_array_add(operations, op);
1429     }
1430
1431     if (txn->dry_run) {
1432         struct json *op = json_object_create();
1433         json_object_put_string(op, "op", "abort");
1434         json_array_add(operations, op);
1435     }
1436
1437     if (!any_updates) {
1438         txn->status = TXN_UNCHANGED;
1439         json_destroy(operations);
1440     } else if (!jsonrpc_session_send(
1441                    txn->idl->session,
1442                    jsonrpc_create_request(
1443                        "transact", operations, &txn->request_id))) {
1444         hmap_insert(&txn->idl->outstanding_txns, &txn->hmap_node,
1445                     json_hash(txn->request_id, 0));
1446     } else {
1447         txn->status = TXN_TRY_AGAIN;
1448     }
1449
1450     ovsdb_idl_txn_disassemble(txn);
1451     return txn->status;
1452 }
1453
1454 /* Attempts to commit 'txn', blocking until the commit either succeeds or
1455  * fails.  Returns the final commit status, which may be any TXN_* value other
1456  * than TXN_INCOMPLETE. */
1457 enum ovsdb_idl_txn_status
1458 ovsdb_idl_txn_commit_block(struct ovsdb_idl_txn *txn)
1459 {
1460     enum ovsdb_idl_txn_status status;
1461
1462     fatal_signal_run();
1463     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
1464         ovsdb_idl_run(txn->idl);
1465         ovsdb_idl_wait(txn->idl);
1466         ovsdb_idl_txn_wait(txn);
1467         poll_block();
1468     }
1469     return status;
1470 }
1471
1472 int64_t
1473 ovsdb_idl_txn_get_increment_new_value(const struct ovsdb_idl_txn *txn)
1474 {
1475     assert(txn->status == TXN_SUCCESS);
1476     return txn->inc_new_value;
1477 }
1478
1479 void
1480 ovsdb_idl_txn_abort(struct ovsdb_idl_txn *txn)
1481 {
1482     ovsdb_idl_txn_disassemble(txn);
1483     if (txn->status == TXN_INCOMPLETE) {
1484         txn->status = TXN_ABORTED;
1485     }
1486 }
1487
1488 const char *
1489 ovsdb_idl_txn_get_error(const struct ovsdb_idl_txn *txn)
1490 {
1491     if (txn->status != TXN_ERROR) {
1492         return ovsdb_idl_txn_status_to_string(txn->status);
1493     } else if (txn->error) {
1494         return txn->error;
1495     } else {
1496         return "no error details available";
1497     }
1498 }
1499
1500 static void
1501 ovsdb_idl_txn_set_error_json(struct ovsdb_idl_txn *txn,
1502                              const struct json *json)
1503 {
1504     if (txn->error == NULL) {
1505         txn->error = json_to_string(json, JSSF_SORT);
1506     }
1507 }
1508
1509 /* For transaction 'txn' that completed successfully, finds and returns the
1510  * permanent UUID that the database assigned to a newly inserted row, given the
1511  * 'uuid' that ovsdb_idl_txn_insert() assigned locally to that row.
1512  *
1513  * Returns NULL if 'uuid' is not a UUID assigned by ovsdb_idl_txn_insert() or
1514  * if it was assigned by that function and then deleted by
1515  * ovsdb_idl_txn_delete() within the same transaction.  (Rows that are inserted
1516  * and then deleted within a single transaction are never sent to the database
1517  * server, so it never assigns them a permanent UUID.) */
1518 const struct uuid *
1519 ovsdb_idl_txn_get_insert_uuid(const struct ovsdb_idl_txn *txn,
1520                               const struct uuid *uuid)
1521 {
1522     const struct ovsdb_idl_txn_insert *insert;
1523
1524     assert(txn->status == TXN_SUCCESS || txn->status == TXN_UNCHANGED);
1525     HMAP_FOR_EACH_IN_BUCKET (insert, struct ovsdb_idl_txn_insert, hmap_node,
1526                              uuid_hash(uuid), &txn->inserted_rows) {
1527         if (uuid_equals(uuid, &insert->dummy)) {
1528             return &insert->real;
1529         }
1530     }
1531     return NULL;
1532 }
1533
1534 static void
1535 ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1536                        enum ovsdb_idl_txn_status status)
1537 {
1538     txn->status = status;
1539     hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1540 }
1541
1542 void
1543 ovsdb_idl_txn_write(const struct ovsdb_idl_row *row_,
1544                     const struct ovsdb_idl_column *column,
1545                     struct ovsdb_datum *datum)
1546 {
1547     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1548     const struct ovsdb_idl_table_class *class = row->table->class;
1549     size_t column_idx = column - class->columns;
1550
1551     assert(row->new != NULL);
1552     assert(column_idx < class->n_columns);
1553     assert(row->table->modes[column_idx] != OVSDB_IDL_MODE_NONE);
1554
1555     if (hmap_node_is_null(&row->txn_node)) {
1556         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1557                     uuid_hash(&row->uuid));
1558     }
1559     if (row->old == row->new) {
1560         row->new = xmalloc(class->n_columns * sizeof *row->new);
1561     }
1562     if (!row->written) {
1563         row->written = bitmap_allocate(class->n_columns);
1564     }
1565     if (bitmap_is_set(row->written, column_idx)) {
1566         ovsdb_datum_destroy(&row->new[column_idx], &column->type);
1567     } else {
1568         bitmap_set1(row->written, column_idx);
1569     }
1570     row->new[column_idx] = *datum;
1571     (column->unparse)(row);
1572     (column->parse)(row, &row->new[column_idx]);
1573 }
1574
1575 void
1576 ovsdb_idl_txn_verify(const struct ovsdb_idl_row *row_,
1577                      const struct ovsdb_idl_column *column)
1578 {
1579     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1580     const struct ovsdb_idl_table_class *class = row->table->class;
1581     size_t column_idx = column - class->columns;
1582
1583     assert(row->new != NULL);
1584     if (!row->old
1585         || (row->written && bitmap_is_set(row->written, column_idx))) {
1586         return;
1587     }
1588
1589     if (hmap_node_is_null(&row->txn_node)) {
1590         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1591                     uuid_hash(&row->uuid));
1592     }
1593     if (!row->prereqs) {
1594         row->prereqs = bitmap_allocate(class->n_columns);
1595     }
1596     bitmap_set1(row->prereqs, column_idx);
1597 }
1598
1599 void
1600 ovsdb_idl_txn_delete(const struct ovsdb_idl_row *row_)
1601 {
1602     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1603
1604     assert(row->new != NULL);
1605     if (!row->old) {
1606         ovsdb_idl_row_unparse(row);
1607         ovsdb_idl_row_clear_new(row);
1608         assert(!row->prereqs);
1609         hmap_remove(&row->table->rows, &row->hmap_node);
1610         hmap_remove(&row->table->idl->txn->txn_rows, &row->txn_node);
1611         free(row);
1612         return;
1613     }
1614     if (hmap_node_is_null(&row->txn_node)) {
1615         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1616                     uuid_hash(&row->uuid));
1617     }
1618     ovsdb_idl_row_clear_new(row);
1619     row->new = NULL;
1620 }
1621
1622 const struct ovsdb_idl_row *
1623 ovsdb_idl_txn_insert(struct ovsdb_idl_txn *txn,
1624                      const struct ovsdb_idl_table_class *class,
1625                      const struct uuid *uuid)
1626 {
1627     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(class);
1628
1629     if (uuid) {
1630         assert(!ovsdb_idl_txn_get_row(txn, uuid));
1631         row->uuid = *uuid;
1632     } else {
1633         uuid_generate(&row->uuid);
1634     }
1635
1636     row->table = ovsdb_idl_table_from_class(txn->idl, class);
1637     row->new = xmalloc(class->n_columns * sizeof *row->new);
1638     hmap_insert(&row->table->rows, &row->hmap_node, uuid_hash(&row->uuid));
1639     hmap_insert(&txn->txn_rows, &row->txn_node, uuid_hash(&row->uuid));
1640     return row;
1641 }
1642
1643 static void
1644 ovsdb_idl_txn_abort_all(struct ovsdb_idl *idl)
1645 {
1646     struct ovsdb_idl_txn *txn;
1647
1648     HMAP_FOR_EACH (txn, struct ovsdb_idl_txn, hmap_node,
1649                    &idl->outstanding_txns) {
1650         ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
1651     }
1652 }
1653
1654 static struct ovsdb_idl_txn *
1655 ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
1656 {
1657     struct ovsdb_idl_txn *txn;
1658
1659     HMAP_FOR_EACH_WITH_HASH (txn, struct ovsdb_idl_txn, hmap_node,
1660                              json_hash(id, 0), &idl->outstanding_txns) {
1661         if (json_equal(id, txn->request_id)) {
1662             return txn;
1663         }
1664     }
1665     return NULL;
1666 }
1667
1668 static bool
1669 check_json_type(const struct json *json, enum json_type type, const char *name)
1670 {
1671     if (!json) {
1672         VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
1673         return false;
1674     } else if (json->type != type) {
1675         VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
1676                      name, json_type_to_string(json->type),
1677                      json_type_to_string(type));
1678         return false;
1679     } else {
1680         return true;
1681     }
1682 }
1683
1684 static bool
1685 ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
1686                                 const struct json_array *results)
1687 {
1688     struct json *count, *rows, *row, *column;
1689     struct shash *mutate, *select;
1690
1691     if (txn->inc_index + 2 > results->n) {
1692         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1693                      "for increment (has %zu, needs %u)",
1694                      results->n, txn->inc_index + 2);
1695         return false;
1696     }
1697
1698     /* We know that this is a JSON object because the loop in
1699      * ovsdb_idl_txn_process_reply() checked. */
1700     mutate = json_object(results->elems[txn->inc_index]);
1701     count = shash_find_data(mutate, "count");
1702     if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
1703         return false;
1704     }
1705     if (count->u.integer != 1) {
1706         VLOG_WARN_RL(&syntax_rl,
1707                      "\"mutate\" reply \"count\" is %lld instead of 1",
1708                      count->u.integer);
1709         return false;
1710     }
1711
1712     select = json_object(results->elems[txn->inc_index + 1]);
1713     rows = shash_find_data(select, "rows");
1714     if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
1715         return false;
1716     }
1717     if (rows->u.array.n != 1) {
1718         VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %zu elements "
1719                      "instead of 1",
1720                      rows->u.array.n);
1721         return false;
1722     }
1723     row = rows->u.array.elems[0];
1724     if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
1725         return false;
1726     }
1727     column = shash_find_data(json_object(row), txn->inc_column);
1728     if (!check_json_type(column, JSON_INTEGER,
1729                          "\"select\" reply inc column")) {
1730         return false;
1731     }
1732     txn->inc_new_value = column->u.integer;
1733     return true;
1734 }
1735
1736 static bool
1737 ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
1738                                    const struct json_array *results)
1739 {
1740     static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
1741     struct ovsdb_error *error;
1742     struct json *json_uuid;
1743     union ovsdb_atom uuid;
1744     struct shash *reply;
1745
1746     if (insert->op_index >= results->n) {
1747         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1748                      "for insert (has %zu, needs %u)",
1749                      results->n, insert->op_index);
1750         return false;
1751     }
1752
1753     /* We know that this is a JSON object because the loop in
1754      * ovsdb_idl_txn_process_reply() checked. */
1755     reply = json_object(results->elems[insert->op_index]);
1756     json_uuid = shash_find_data(reply, "uuid");
1757     if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
1758         return false;
1759     }
1760
1761     error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
1762     if (error) {
1763         char *s = ovsdb_error_to_string(error);
1764         VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
1765                      "UUID: %s", s);
1766         free(s);
1767         return false;
1768     }
1769
1770     insert->real = uuid.uuid;
1771
1772     return true;
1773 }
1774
1775 static bool
1776 ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
1777                             const struct jsonrpc_msg *msg)
1778 {
1779     struct ovsdb_idl_txn *txn;
1780     enum ovsdb_idl_txn_status status;
1781
1782     txn = ovsdb_idl_txn_find(idl, msg->id);
1783     if (!txn) {
1784         return false;
1785     }
1786
1787     if (msg->type == JSONRPC_ERROR) {
1788         status = TXN_ERROR;
1789     } else if (msg->result->type != JSON_ARRAY) {
1790         VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
1791         status = TXN_ERROR;
1792     } else {
1793         struct json_array *ops = &msg->result->u.array;
1794         int hard_errors = 0;
1795         int soft_errors = 0;
1796         size_t i;
1797
1798         for (i = 0; i < ops->n; i++) {
1799             struct json *op = ops->elems[i];
1800
1801             if (op->type == JSON_NULL) {
1802                 /* This isn't an error in itself but indicates that some prior
1803                  * operation failed, so make sure that we know about it. */
1804                 soft_errors++;
1805             } else if (op->type == JSON_OBJECT) {
1806                 struct json *error;
1807
1808                 error = shash_find_data(json_object(op), "error");
1809                 if (error) {
1810                     if (error->type == JSON_STRING) {
1811                         if (!strcmp(error->u.string, "timed out")) {
1812                             soft_errors++;
1813                         } else if (strcmp(error->u.string, "aborted")) {
1814                             hard_errors++;
1815                             ovsdb_idl_txn_set_error_json(txn, op);
1816                         }
1817                     } else {
1818                         hard_errors++;
1819                         ovsdb_idl_txn_set_error_json(txn, op);
1820                         VLOG_WARN_RL(&syntax_rl,
1821                                      "\"error\" in reply is not JSON string");
1822                     }
1823                 }
1824             } else {
1825                 hard_errors++;
1826                 ovsdb_idl_txn_set_error_json(txn, op);
1827                 VLOG_WARN_RL(&syntax_rl,
1828                              "operation reply is not JSON null or object");
1829             }
1830         }
1831
1832         if (!soft_errors && !hard_errors) {
1833             struct ovsdb_idl_txn_insert *insert;
1834
1835             if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
1836                 hard_errors++;
1837             }
1838
1839             HMAP_FOR_EACH (insert, struct ovsdb_idl_txn_insert, hmap_node,
1840                            &txn->inserted_rows) {
1841                 if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
1842                     hard_errors++;
1843                 }
1844             }
1845         }
1846
1847         status = (hard_errors ? TXN_ERROR
1848                   : soft_errors ? TXN_TRY_AGAIN
1849                   : TXN_SUCCESS);
1850     }
1851
1852     ovsdb_idl_txn_complete(txn, status);
1853     return true;
1854 }
1855
1856 struct ovsdb_idl_txn *
1857 ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
1858 {
1859     struct ovsdb_idl_txn *txn = row->table->idl->txn;
1860     assert(txn != NULL);
1861     return txn;
1862 }
1863
1864 struct ovsdb_idl *
1865 ovsdb_idl_txn_get_idl (struct ovsdb_idl_txn *txn)
1866 {
1867     return txn->idl;
1868 }
1869