Switch many macros from using CONTAINER_OF to using OBJECT_CONTAINING.
[cascardo/ovs.git] / lib / ovsdb-idl.c
1 /* Copyright (c) 2009, 2010 Nicira Networks.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "ovsdb-idl.h"
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <stdlib.h>
25
26 #include "bitmap.h"
27 #include "dynamic-string.h"
28 #include "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, hmap_node, &table->rows) {
219             struct ovsdb_idl_arc *arc, *next_arc;
220
221             if (!ovsdb_idl_row_is_orphan(row)) {
222                 ovsdb_idl_row_unparse(row);
223             }
224             LIST_FOR_EACH_SAFE (arc, next_arc, src_node, &row->src_arcs) {
225                 free(arc);
226             }
227             /* No need to do anything with dst_arcs: some node has those arcs
228              * as forward arcs and will destroy them itself. */
229
230             ovsdb_idl_row_destroy(row);
231         }
232     }
233
234     if (changed) {
235         idl->change_seqno++;
236     }
237 }
238
239 /* Processes a batch of messages from the database server on 'idl'.  Returns
240  * true if the database as seen through 'idl' changed, false if it did not
241  * change.  The initial fetch of the entire contents of the remote database is
242  * considered to be one kind of change.
243  *
244  * When this function returns false, the client may continue to use any data
245  * structures it obtained from 'idl' in the past.  But when it returns true,
246  * the client must not access any of these data structures again, because they
247  * could have freed or reused for other purposes.
248  *
249  * This function can return occasional false positives, that is, report that
250  * the database changed even though it didn't.  This happens if the connection
251  * to the database drops and reconnects, which causes the database contents to
252  * be reloaded even if they didn't change.  (It could also happen if the
253  * database server sends out a "change" that reflects what we already thought
254  * was in the database, but the database server is not supposed to do that.)
255  *
256  * As an alternative to checking the return value, the client may check for
257  * changes in the value returned by ovsdb_idl_get_seqno().
258  */
259 bool
260 ovsdb_idl_run(struct ovsdb_idl *idl)
261 {
262     unsigned int initial_change_seqno = idl->change_seqno;
263     int i;
264
265     assert(!idl->txn);
266     jsonrpc_session_run(idl->session);
267     for (i = 0; jsonrpc_session_is_connected(idl->session) && i < 50; i++) {
268         struct jsonrpc_msg *msg, *reply;
269         unsigned int seqno;
270
271         seqno = jsonrpc_session_get_seqno(idl->session);
272         if (idl->last_monitor_request_seqno != seqno) {
273             idl->last_monitor_request_seqno = seqno;
274             ovsdb_idl_txn_abort_all(idl);
275             ovsdb_idl_send_monitor_request(idl);
276             break;
277         }
278
279         msg = jsonrpc_session_recv(idl->session);
280         if (!msg) {
281             break;
282         }
283
284         reply = NULL;
285         if (msg->type == JSONRPC_NOTIFY
286                    && !strcmp(msg->method, "update")
287                    && msg->params->type == JSON_ARRAY
288                    && msg->params->u.array.n == 2
289                    && msg->params->u.array.elems[0]->type == JSON_NULL) {
290             ovsdb_idl_parse_update(idl, msg->params->u.array.elems[1]);
291         } else if (msg->type == JSONRPC_REPLY
292                    && idl->monitor_request_id
293                    && json_equal(idl->monitor_request_id, msg->id)) {
294             idl->change_seqno++;
295             json_destroy(idl->monitor_request_id);
296             idl->monitor_request_id = NULL;
297             ovsdb_idl_clear(idl);
298             ovsdb_idl_parse_update(idl, msg->result);
299         } else if (msg->type == JSONRPC_REPLY
300                    && msg->id && msg->id->type == JSON_STRING
301                    && !strcmp(msg->id->u.string, "echo")) {
302             /* It's a reply to our echo request.  Ignore it. */
303         } else if ((msg->type == JSONRPC_ERROR
304                     || msg->type == JSONRPC_REPLY)
305                    && ovsdb_idl_txn_process_reply(idl, msg)) {
306             /* ovsdb_idl_txn_process_reply() did everything needful. */
307         } else {
308             /* This can happen if ovsdb_idl_txn_destroy() is called to destroy
309              * a transaction before we receive the reply, so keep the log level
310              * low. */
311             VLOG_DBG("%s: received unexpected %s message",
312                      jsonrpc_session_get_name(idl->session),
313                      jsonrpc_msg_type_to_string(msg->type));
314         }
315         if (reply) {
316             jsonrpc_session_send(idl->session, reply);
317         }
318         jsonrpc_msg_destroy(msg);
319     }
320
321     return initial_change_seqno != idl->change_seqno;
322 }
323
324 /* Arranges for poll_block() to wake up when ovsdb_idl_run() has something to
325  * do or when activity occurs on a transaction on 'idl'. */
326 void
327 ovsdb_idl_wait(struct ovsdb_idl *idl)
328 {
329     jsonrpc_session_wait(idl->session);
330     jsonrpc_session_recv_wait(idl->session);
331 }
332
333 /* Returns a number that represents the state of 'idl'.  When 'idl' is updated
334  * (by ovsdb_idl_run()), the return value changes. */
335 unsigned int
336 ovsdb_idl_get_seqno(const struct ovsdb_idl *idl)
337 {
338     return idl->change_seqno;
339 }
340
341 /* Returns true if 'idl' successfully connected to the remote database and
342  * retrieved its contents (even if the connection subsequently dropped and is
343  * in the process of reconnecting).  If so, then 'idl' contains an atomic
344  * snapshot of the database's contents (but it might be arbitrarily old if the
345  * connection dropped).
346  *
347  * Returns false if 'idl' has never connected or retrieved the database's
348  * contents.  If so, 'idl' is empty. */
349 bool
350 ovsdb_idl_has_ever_connected(const struct ovsdb_idl *idl)
351 {
352     return ovsdb_idl_get_seqno(idl) != 0;
353 }
354
355 /* Forces 'idl' to drop its connection to the database and reconnect.  In the
356  * meantime, the contents of 'idl' will not change. */
357 void
358 ovsdb_idl_force_reconnect(struct ovsdb_idl *idl)
359 {
360     jsonrpc_session_force_reconnect(idl->session);
361 }
362
363 static void
364 ovsdb_idl_set_mode(struct ovsdb_idl *idl,
365                    const struct ovsdb_idl_column *column,
366                    enum ovsdb_idl_mode mode)
367 {
368     size_t i;
369
370     for (i = 0; i < idl->class->n_tables; i++) {
371         const struct ovsdb_idl_table *table = &idl->tables[i];
372         const struct ovsdb_idl_table_class *tc = table->class;
373
374         if (column >= tc->columns && column < &tc->columns[tc->n_columns]) {
375             unsigned char *modep = &table->modes[column - tc->columns];
376             assert(*modep == OVSDB_IDL_MODE_RW || *modep == mode);
377             *modep = mode;
378             return;
379         }
380     }
381
382     NOT_REACHED();
383 }
384
385 /* By default, 'idl' replicates all of the columns in the remote database, and
386  * ovsdb_idl_run() returns true upon a change to any column in the database.
387  * Call this function to avoid alerting ovsdb_idl_run()'s caller upon changes
388  * to 'column'.
389  *
390  * This is useful for columns that a client treats as "write-only", that is, it
391  * updates them but doesn't want to get alerted about its own updates.  It also
392  * won't be alerted about other clients' updates, so this is suitable only for
393  * use by a client that "owns" a particular column.
394  *
395  * The client must be careful not to retain pointers to data in 'column' across
396  * calls to ovsdb_idl_run(), even when that function returns false, because
397  * the client is not alerted to changes.
398  *
399  * This function should be called after ovsdb_idl_create(), but before the
400  * first call to ovsdb_idl_run().  For any given column, this function may be
401  * called or ovsdb_idl_omit() may be called, but not both. */
402 void
403 ovsdb_idl_set_write_only(struct ovsdb_idl *idl,
404                          const struct ovsdb_idl_column *column)
405 {
406     ovsdb_idl_set_mode(idl, column, OVSDB_IDL_MODE_WO);
407 }
408
409 /* By default, 'idl' replicates all of the columns in the remote database.
410  * Call this function to omit replicating 'column'.  This saves CPU time and
411  * bandwidth to the database.
412  *
413  * This function should be called after ovsdb_idl_create(), but before the
414  * first call to ovsdb_idl_run().  For any given column, this function may be
415  * called or ovsdb_idl_set_write_only() may be called, but not both. */
416 void
417 ovsdb_idl_omit(struct ovsdb_idl *idl, const struct ovsdb_idl_column *column)
418 {
419     ovsdb_idl_set_mode(idl, column, OVSDB_IDL_MODE_NONE);
420 }
421 \f
422 static void
423 ovsdb_idl_send_monitor_request(struct ovsdb_idl *idl)
424 {
425     struct json *monitor_requests;
426     struct jsonrpc_msg *msg;
427     size_t i;
428
429     monitor_requests = json_object_create();
430     for (i = 0; i < idl->class->n_tables; i++) {
431         const struct ovsdb_idl_table *table = &idl->tables[i];
432         const struct ovsdb_idl_table_class *tc = table->class;
433         struct json *monitor_request, *columns;
434         size_t j;
435
436         monitor_request = json_object_create();
437         columns = json_array_create_empty();
438         for (j = 0; j < tc->n_columns; j++) {
439             const struct ovsdb_idl_column *column = &tc->columns[j];
440             if (table->modes[j] != OVSDB_IDL_MODE_NONE) {
441                 json_array_add(columns, json_string_create(column->name));
442             }
443         }
444         json_object_put(monitor_request, "columns", columns);
445         json_object_put(monitor_requests, tc->name, monitor_request);
446     }
447
448     json_destroy(idl->monitor_request_id);
449     msg = jsonrpc_create_request(
450         "monitor",
451         json_array_create_3(json_string_create(idl->class->database),
452                             json_null_create(), monitor_requests),
453         &idl->monitor_request_id);
454     jsonrpc_session_send(idl->session, msg);
455 }
456
457 static void
458 ovsdb_idl_parse_update(struct ovsdb_idl *idl, const struct json *table_updates)
459 {
460     struct ovsdb_error *error = ovsdb_idl_parse_update__(idl, table_updates);
461     if (error) {
462         if (!VLOG_DROP_WARN(&syntax_rl)) {
463             char *s = ovsdb_error_to_string(error);
464             VLOG_WARN_RL(&syntax_rl, "%s", s);
465             free(s);
466         }
467         ovsdb_error_destroy(error);
468     }
469 }
470
471 static struct ovsdb_error *
472 ovsdb_idl_parse_update__(struct ovsdb_idl *idl,
473                          const struct json *table_updates)
474 {
475     const struct shash_node *tables_node;
476
477     if (table_updates->type != JSON_OBJECT) {
478         return ovsdb_syntax_error(table_updates, NULL,
479                                   "<table-updates> is not an object");
480     }
481     SHASH_FOR_EACH (tables_node, json_object(table_updates)) {
482         const struct json *table_update = tables_node->data;
483         const struct shash_node *table_node;
484         struct ovsdb_idl_table *table;
485
486         table = shash_find_data(&idl->table_by_name, tables_node->name);
487         if (!table) {
488             return ovsdb_syntax_error(
489                 table_updates, NULL,
490                 "<table-updates> includes unknown table \"%s\"",
491                 tables_node->name);
492         }
493
494         if (table_update->type != JSON_OBJECT) {
495             return ovsdb_syntax_error(table_update, NULL,
496                                       "<table-update> for table \"%s\" is "
497                                       "not an object", table->class->name);
498         }
499         SHASH_FOR_EACH (table_node, json_object(table_update)) {
500             const struct json *row_update = table_node->data;
501             const struct json *old_json, *new_json;
502             struct uuid uuid;
503
504             if (!uuid_from_string(&uuid, table_node->name)) {
505                 return ovsdb_syntax_error(table_update, NULL,
506                                           "<table-update> for table \"%s\" "
507                                           "contains bad UUID "
508                                           "\"%s\" as member name",
509                                           table->class->name,
510                                           table_node->name);
511             }
512             if (row_update->type != JSON_OBJECT) {
513                 return ovsdb_syntax_error(row_update, NULL,
514                                           "<table-update> for table \"%s\" "
515                                           "contains <row-update> for %s that "
516                                           "is not an object",
517                                           table->class->name,
518                                           table_node->name);
519             }
520
521             old_json = shash_find_data(json_object(row_update), "old");
522             new_json = shash_find_data(json_object(row_update), "new");
523             if (old_json && old_json->type != JSON_OBJECT) {
524                 return ovsdb_syntax_error(old_json, NULL,
525                                           "\"old\" <row> is not object");
526             } else if (new_json && new_json->type != JSON_OBJECT) {
527                 return ovsdb_syntax_error(new_json, NULL,
528                                           "\"new\" <row> is not object");
529             } else if ((old_json != NULL) + (new_json != NULL)
530                        != shash_count(json_object(row_update))) {
531                 return ovsdb_syntax_error(row_update, NULL,
532                                           "<row-update> contains unexpected "
533                                           "member");
534             } else if (!old_json && !new_json) {
535                 return ovsdb_syntax_error(row_update, NULL,
536                                           "<row-update> missing \"old\" "
537                                           "and \"new\" members");
538             }
539
540             if (ovsdb_idl_process_update(table, &uuid, old_json, new_json)) {
541                 idl->change_seqno++;
542             }
543         }
544     }
545
546     return NULL;
547 }
548
549 static struct ovsdb_idl_row *
550 ovsdb_idl_get_row(struct ovsdb_idl_table *table, const struct uuid *uuid)
551 {
552     struct ovsdb_idl_row *row;
553
554     HMAP_FOR_EACH_WITH_HASH (row, hmap_node, uuid_hash(uuid), &table->rows) {
555         if (uuid_equals(&row->uuid, uuid)) {
556             return row;
557         }
558     }
559     return NULL;
560 }
561
562 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
563  * otherwise. */
564 static bool
565 ovsdb_idl_process_update(struct ovsdb_idl_table *table,
566                          const struct uuid *uuid, const struct json *old,
567                          const struct json *new)
568 {
569     struct ovsdb_idl_row *row;
570
571     row = ovsdb_idl_get_row(table, uuid);
572     if (!new) {
573         /* Delete row. */
574         if (row && !ovsdb_idl_row_is_orphan(row)) {
575             /* XXX perhaps we should check the 'old' values? */
576             ovsdb_idl_delete_row(row);
577         } else {
578             VLOG_WARN_RL(&semantic_rl, "cannot delete missing row "UUID_FMT" "
579                          "from table %s",
580                          UUID_ARGS(uuid), table->class->name);
581             return false;
582         }
583     } else if (!old) {
584         /* Insert row. */
585         if (!row) {
586             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
587         } else if (ovsdb_idl_row_is_orphan(row)) {
588             ovsdb_idl_insert_row(row, new);
589         } else {
590             VLOG_WARN_RL(&semantic_rl, "cannot add existing row "UUID_FMT" to "
591                          "table %s", UUID_ARGS(uuid), table->class->name);
592             return ovsdb_idl_modify_row(row, new);
593         }
594     } else {
595         /* Modify row. */
596         if (row) {
597             /* XXX perhaps we should check the 'old' values? */
598             if (!ovsdb_idl_row_is_orphan(row)) {
599                 return ovsdb_idl_modify_row(row, new);
600             } else {
601                 VLOG_WARN_RL(&semantic_rl, "cannot modify missing but "
602                              "referenced row "UUID_FMT" in table %s",
603                              UUID_ARGS(uuid), table->class->name);
604                 ovsdb_idl_insert_row(row, new);
605             }
606         } else {
607             VLOG_WARN_RL(&semantic_rl, "cannot modify missing row "UUID_FMT" "
608                          "in table %s", UUID_ARGS(uuid), table->class->name);
609             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
610         }
611     }
612
613     return true;
614 }
615
616 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
617  * otherwise. */
618 static bool
619 ovsdb_idl_row_update(struct ovsdb_idl_row *row, const struct json *row_json)
620 {
621     struct ovsdb_idl_table *table = row->table;
622     struct shash_node *node;
623     bool changed = false;
624
625     SHASH_FOR_EACH (node, json_object(row_json)) {
626         const char *column_name = node->name;
627         const struct ovsdb_idl_column *column;
628         struct ovsdb_datum datum;
629         struct ovsdb_error *error;
630
631         column = shash_find_data(&table->columns, column_name);
632         if (!column) {
633             VLOG_WARN_RL(&syntax_rl, "unknown column %s updating row "UUID_FMT,
634                          column_name, UUID_ARGS(&row->uuid));
635             continue;
636         }
637
638         error = ovsdb_datum_from_json(&datum, &column->type, node->data, NULL);
639         if (!error) {
640             unsigned int column_idx = column - table->class->columns;
641             struct ovsdb_datum *old = &row->old[column_idx];
642
643             if (!ovsdb_datum_equals(old, &datum, &column->type)) {
644                 ovsdb_datum_swap(old, &datum);
645                 if (table->modes[column_idx] == OVSDB_IDL_MODE_RW) {
646                     changed = true;
647                 }
648             } else {
649                 /* Didn't really change but the OVSDB monitor protocol always
650                  * includes every value in a row. */
651             }
652
653             ovsdb_datum_destroy(&datum, &column->type);
654         } else {
655             char *s = ovsdb_error_to_string(error);
656             VLOG_WARN_RL(&syntax_rl, "error parsing column %s in row "UUID_FMT
657                          " in table %s: %s", column_name,
658                          UUID_ARGS(&row->uuid), table->class->name, s);
659             free(s);
660             ovsdb_error_destroy(error);
661         }
662     }
663     return changed;
664 }
665
666 /* When a row A refers to row B through a column with a "refTable" constraint,
667  * but row B does not exist, row B is called an "orphan row".  Orphan rows
668  * should not persist, because the database enforces referential integrity, but
669  * they can appear transiently as changes from the database are received (the
670  * database doesn't try to topologically sort them and circular references mean
671  * it isn't always possible anyhow).
672  *
673  * This function returns true if 'row' is an orphan row, otherwise false.
674  */
675 static bool
676 ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *row)
677 {
678     return !row->old && !row->new;
679 }
680
681 /* Returns true if 'row' is conceptually part of the database as modified by
682  * the current transaction (if any), false otherwise.
683  *
684  * This function will return true if 'row' is not an orphan (see the comment on
685  * ovsdb_idl_row_is_orphan()) and:
686  *
687  *   - 'row' exists in the database and has not been deleted within the
688  *     current transaction (if any).
689  *
690  *   - 'row' was inserted within the current transaction and has not been
691  *     deleted.  (In the latter case you should not have passed 'row' in at
692  *     all, because ovsdb_idl_txn_delete() freed it.)
693  *
694  * This function will return false if 'row' is an orphan or if 'row' was
695  * deleted within the current transaction.
696  */
697 static bool
698 ovsdb_idl_row_exists(const struct ovsdb_idl_row *row)
699 {
700     return row->new != NULL;
701 }
702
703 static void
704 ovsdb_idl_row_parse(struct ovsdb_idl_row *row)
705 {
706     const struct ovsdb_idl_table_class *class = row->table->class;
707     size_t i;
708
709     for (i = 0; i < class->n_columns; i++) {
710         const struct ovsdb_idl_column *c = &class->columns[i];
711         (c->parse)(row, &row->old[i]);
712     }
713 }
714
715 static void
716 ovsdb_idl_row_unparse(struct ovsdb_idl_row *row)
717 {
718     const struct ovsdb_idl_table_class *class = row->table->class;
719     size_t i;
720
721     for (i = 0; i < class->n_columns; i++) {
722         const struct ovsdb_idl_column *c = &class->columns[i];
723         (c->unparse)(row);
724     }
725 }
726
727 static void
728 ovsdb_idl_row_clear_old(struct ovsdb_idl_row *row)
729 {
730     assert(row->old == row->new);
731     if (!ovsdb_idl_row_is_orphan(row)) {
732         const struct ovsdb_idl_table_class *class = row->table->class;
733         size_t i;
734
735         for (i = 0; i < class->n_columns; i++) {
736             ovsdb_datum_destroy(&row->old[i], &class->columns[i].type);
737         }
738         free(row->old);
739         row->old = row->new = NULL;
740     }
741 }
742
743 static void
744 ovsdb_idl_row_clear_new(struct ovsdb_idl_row *row)
745 {
746     if (row->old != row->new) {
747         if (row->new) {
748             const struct ovsdb_idl_table_class *class = row->table->class;
749             size_t i;
750
751             if (row->written) {
752                 BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
753                     ovsdb_datum_destroy(&row->new[i], &class->columns[i].type);
754                 }
755             }
756             free(row->new);
757             free(row->written);
758             row->written = NULL;
759         }
760         row->new = row->old;
761     }
762 }
763
764 static void
765 ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
766 {
767     struct ovsdb_idl_arc *arc, *next;
768
769     /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
770      * that this causes to be unreferenced. */
771     LIST_FOR_EACH_SAFE (arc, next, src_node, &row->src_arcs) {
772         list_remove(&arc->dst_node);
773         if (destroy_dsts
774             && ovsdb_idl_row_is_orphan(arc->dst)
775             && list_is_empty(&arc->dst->dst_arcs)) {
776             ovsdb_idl_row_destroy(arc->dst);
777         }
778         free(arc);
779     }
780     list_init(&row->src_arcs);
781 }
782
783 /* Force nodes that reference 'row' to reparse. */
784 static void
785 ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
786 {
787     struct ovsdb_idl_arc *arc, *next;
788
789     /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
790      * 'arc', so we need to use the "safe" variant of list traversal.  However,
791      * calling an ovsdb_idl_column's 'parse' function will add an arc
792      * equivalent to 'arc' to row->arcs.  That could be a problem for
793      * traversal, but it adds it at the beginning of the list to prevent us
794      * from stumbling upon it again.
795      *
796      * (If duplicate arcs were possible then we would need to make sure that
797      * 'next' didn't also point into 'arc''s destination, but we forbid
798      * duplicate arcs.) */
799     LIST_FOR_EACH_SAFE (arc, next, dst_node, &row->dst_arcs) {
800         struct ovsdb_idl_row *ref = arc->src;
801
802         ovsdb_idl_row_unparse(ref);
803         ovsdb_idl_row_clear_arcs(ref, false);
804         ovsdb_idl_row_parse(ref);
805     }
806 }
807
808 static struct ovsdb_idl_row *
809 ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
810 {
811     struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
812     list_init(&row->src_arcs);
813     list_init(&row->dst_arcs);
814     hmap_node_nullify(&row->txn_node);
815     return row;
816 }
817
818 static struct ovsdb_idl_row *
819 ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
820 {
821     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class);
822     hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
823     row->uuid = *uuid;
824     row->table = table;
825     return row;
826 }
827
828 static void
829 ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
830 {
831     if (row) {
832         ovsdb_idl_row_clear_old(row);
833         hmap_remove(&row->table->rows, &row->hmap_node);
834         free(row);
835     }
836 }
837
838 static void
839 ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct json *row_json)
840 {
841     const struct ovsdb_idl_table_class *class = row->table->class;
842     size_t i;
843
844     assert(!row->old && !row->new);
845     row->old = row->new = xmalloc(class->n_columns * sizeof *row->old);
846     for (i = 0; i < class->n_columns; i++) {
847         ovsdb_datum_init_default(&row->old[i], &class->columns[i].type);
848     }
849     ovsdb_idl_row_update(row, row_json);
850     ovsdb_idl_row_parse(row);
851
852     ovsdb_idl_row_reparse_backrefs(row);
853 }
854
855 static void
856 ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
857 {
858     ovsdb_idl_row_unparse(row);
859     ovsdb_idl_row_clear_arcs(row, true);
860     ovsdb_idl_row_clear_old(row);
861     if (list_is_empty(&row->dst_arcs)) {
862         ovsdb_idl_row_destroy(row);
863     } else {
864         ovsdb_idl_row_reparse_backrefs(row);
865     }
866 }
867
868 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
869  * otherwise. */
870 static bool
871 ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct json *row_json)
872 {
873     bool changed;
874
875     ovsdb_idl_row_unparse(row);
876     ovsdb_idl_row_clear_arcs(row, true);
877     changed = ovsdb_idl_row_update(row, row_json);
878     ovsdb_idl_row_parse(row);
879
880     return changed;
881 }
882
883 static bool
884 may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
885 {
886     const struct ovsdb_idl_arc *arc;
887
888     /* No self-arcs. */
889     if (src == dst) {
890         return false;
891     }
892
893     /* No duplicate arcs.
894      *
895      * We only need to test whether the first arc in dst->dst_arcs originates
896      * at 'src', since we add all of the arcs from a given source in a clump
897      * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
898      * added at the front of the dst_arcs list. */
899     if (list_is_empty(&dst->dst_arcs)) {
900         return true;
901     }
902     arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
903     return arc->src != src;
904 }
905
906 static struct ovsdb_idl_table *
907 ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
908                            const struct ovsdb_idl_table_class *table_class)
909 {
910     return &idl->tables[table_class - idl->class->tables];
911 }
912
913 struct ovsdb_idl_row *
914 ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
915                       struct ovsdb_idl_table_class *dst_table_class,
916                       const struct uuid *dst_uuid)
917 {
918     struct ovsdb_idl *idl = src->table->idl;
919     struct ovsdb_idl_table *dst_table;
920     struct ovsdb_idl_arc *arc;
921     struct ovsdb_idl_row *dst;
922
923     dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
924     dst = ovsdb_idl_get_row(dst_table, dst_uuid);
925     if (idl->txn) {
926         /* We're being called from ovsdb_idl_txn_write().  We must not update
927          * any arcs, because the transaction will be backed out at commit or
928          * abort time and we don't want our graph screwed up.
929          *
930          * Just return the destination row, if there is one and it has not been
931          * deleted. */
932         if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new)) {
933             return dst;
934         }
935         return NULL;
936     } else {
937         /* We're being called from some other context.  Update the graph. */
938         if (!dst) {
939             dst = ovsdb_idl_row_create(dst_table, dst_uuid);
940         }
941
942         /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
943         if (may_add_arc(src, dst)) {
944             /* The arc *must* be added at the front of the dst_arcs list.  See
945              * ovsdb_idl_row_reparse_backrefs() for details. */
946             arc = xmalloc(sizeof *arc);
947             list_push_front(&src->src_arcs, &arc->src_node);
948             list_push_front(&dst->dst_arcs, &arc->dst_node);
949             arc->src = src;
950             arc->dst = dst;
951         }
952
953         return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
954     }
955 }
956
957 const struct ovsdb_idl_row *
958 ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
959                            const struct ovsdb_idl_table_class *tc,
960                            const struct uuid *uuid)
961 {
962     return ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
963 }
964
965 static struct ovsdb_idl_row *
966 next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
967 {
968     for (; node; node = hmap_next(&table->rows, node)) {
969         struct ovsdb_idl_row *row;
970
971         row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
972         if (ovsdb_idl_row_exists(row)) {
973             return row;
974         }
975     }
976     return NULL;
977 }
978
979 const struct ovsdb_idl_row *
980 ovsdb_idl_first_row(const struct ovsdb_idl *idl,
981                     const struct ovsdb_idl_table_class *table_class)
982 {
983     struct ovsdb_idl_table *table
984         = ovsdb_idl_table_from_class(idl, table_class);
985     return next_real_row(table, hmap_first(&table->rows));
986 }
987
988 const struct ovsdb_idl_row *
989 ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
990 {
991     struct ovsdb_idl_table *table = row->table;
992
993     return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
994 }
995
996 /* Reads and returns the value of 'column' within 'row'.  If an ongoing
997  * transaction has changed 'column''s value, the modified value is returned.
998  *
999  * The caller must not modify or free the returned value.
1000  *
1001  * Various kinds of changes can invalidate the returned value: writing to the
1002  * same 'column' in 'row' (e.g. with ovsdb_idl_txn_write()), deleting 'row'
1003  * (e.g. with ovsdb_idl_txn_delete()), or completing an ongoing transaction
1004  * (e.g. with ovsdb_idl_txn_commit() or ovsdb_idl_txn_abort()).  If the
1005  * returned value is needed for a long time, it is best to make a copy of it
1006  * with ovsdb_datum_clone(). */
1007 const struct ovsdb_datum *
1008 ovsdb_idl_read(const struct ovsdb_idl_row *row,
1009                const struct ovsdb_idl_column *column)
1010 {
1011     const struct ovsdb_idl_table_class *class = row->table->class;
1012     size_t column_idx = column - class->columns;
1013
1014     assert(row->new != NULL);
1015     assert(column_idx < class->n_columns);
1016
1017     if (row->written && bitmap_is_set(row->written, column_idx)) {
1018         return &row->new[column_idx];
1019     } else if (row->old) {
1020         return &row->old[column_idx];
1021     } else {
1022         return ovsdb_datum_default(&column->type);
1023     }
1024 }
1025
1026 /* Same as ovsdb_idl_read(), except that it also asserts that 'column' has key
1027  * type 'key_type' and value type 'value_type'.  (Scalar and set types will
1028  * have a value type of OVSDB_TYPE_VOID.)
1029  *
1030  * This is useful in code that "knows" that a particular column has a given
1031  * type, so that it will abort if someone changes the column's type without
1032  * updating the code that uses it. */
1033 const struct ovsdb_datum *
1034 ovsdb_idl_get(const struct ovsdb_idl_row *row,
1035               const struct ovsdb_idl_column *column,
1036               enum ovsdb_atomic_type key_type OVS_UNUSED,
1037               enum ovsdb_atomic_type value_type OVS_UNUSED)
1038 {
1039     assert(column->type.key.type == key_type);
1040     assert(column->type.value.type == value_type);
1041
1042     return ovsdb_idl_read(row, column);
1043 }
1044 \f
1045 /* Transactions. */
1046
1047 static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1048                                    enum ovsdb_idl_txn_status);
1049
1050 const char *
1051 ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
1052 {
1053     switch (status) {
1054     case TXN_UNCHANGED:
1055         return "unchanged";
1056     case TXN_INCOMPLETE:
1057         return "incomplete";
1058     case TXN_ABORTED:
1059         return "aborted";
1060     case TXN_SUCCESS:
1061         return "success";
1062     case TXN_TRY_AGAIN:
1063         return "try again";
1064     case TXN_ERROR:
1065         return "error";
1066     }
1067     return "<unknown>";
1068 }
1069
1070 struct ovsdb_idl_txn *
1071 ovsdb_idl_txn_create(struct ovsdb_idl *idl)
1072 {
1073     struct ovsdb_idl_txn *txn;
1074
1075     assert(!idl->txn);
1076     idl->txn = txn = xmalloc(sizeof *txn);
1077     txn->request_id = NULL;
1078     txn->idl = idl;
1079     hmap_init(&txn->txn_rows);
1080     txn->status = TXN_INCOMPLETE;
1081     txn->error = NULL;
1082     txn->dry_run = false;
1083     ds_init(&txn->comment);
1084
1085     txn->inc_table = NULL;
1086     txn->inc_column = NULL;
1087     txn->inc_where = NULL;
1088
1089     hmap_init(&txn->inserted_rows);
1090
1091     return txn;
1092 }
1093
1094 /* Appends 's', which is treated as a printf()-type format string, to the
1095  * comments that will be passed to the OVSDB server when 'txn' is committed.
1096  * (The comment will be committed to the OVSDB log, which "ovsdb-tool
1097  * show-log" can print in a relatively human-readable form.) */
1098 void
1099 ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s, ...)
1100 {
1101     va_list args;
1102
1103     if (txn->comment.length) {
1104         ds_put_char(&txn->comment, '\n');
1105     }
1106
1107     va_start(args, s);
1108     ds_put_format_valist(&txn->comment, s, args);
1109     va_end(args);
1110 }
1111
1112 void
1113 ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
1114 {
1115     txn->dry_run = true;
1116 }
1117
1118 void
1119 ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn, const char *table,
1120                         const char *column, const struct json *where)
1121 {
1122     assert(!txn->inc_table);
1123     txn->inc_table = xstrdup(table);
1124     txn->inc_column = xstrdup(column);
1125     txn->inc_where = where ? json_clone(where) : json_array_create_empty();
1126 }
1127
1128 void
1129 ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
1130 {
1131     struct ovsdb_idl_txn_insert *insert, *next;
1132
1133     json_destroy(txn->request_id);
1134     if (txn->status == TXN_INCOMPLETE) {
1135         hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1136     }
1137     ovsdb_idl_txn_abort(txn);
1138     ds_destroy(&txn->comment);
1139     free(txn->error);
1140     free(txn->inc_table);
1141     free(txn->inc_column);
1142     json_destroy(txn->inc_where);
1143     HMAP_FOR_EACH_SAFE (insert, next, hmap_node, &txn->inserted_rows) {
1144         free(insert);
1145     }
1146     hmap_destroy(&txn->inserted_rows);
1147     free(txn);
1148 }
1149
1150 void
1151 ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
1152 {
1153     if (txn->status != TXN_INCOMPLETE) {
1154         poll_immediate_wake();
1155     }
1156 }
1157
1158 static struct json *
1159 where_uuid_equals(const struct uuid *uuid)
1160 {
1161     return
1162         json_array_create_1(
1163             json_array_create_3(
1164                 json_string_create("_uuid"),
1165                 json_string_create("=="),
1166                 json_array_create_2(
1167                     json_string_create("uuid"),
1168                     json_string_create_nocopy(
1169                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
1170 }
1171
1172 static char *
1173 uuid_name_from_uuid(const struct uuid *uuid)
1174 {
1175     char *name;
1176     char *p;
1177
1178     name = xasprintf("row"UUID_FMT, UUID_ARGS(uuid));
1179     for (p = name; *p != '\0'; p++) {
1180         if (*p == '-') {
1181             *p = '_';
1182         }
1183     }
1184
1185     return name;
1186 }
1187
1188 static const struct ovsdb_idl_row *
1189 ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
1190 {
1191     const struct ovsdb_idl_row *row;
1192
1193     HMAP_FOR_EACH_WITH_HASH (row, txn_node, uuid_hash(uuid), &txn->txn_rows) {
1194         if (uuid_equals(&row->uuid, uuid)) {
1195             return row;
1196         }
1197     }
1198     return NULL;
1199 }
1200
1201 /* XXX there must be a cleaner way to do this */
1202 static struct json *
1203 substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
1204 {
1205     if (json->type == JSON_ARRAY) {
1206         struct uuid uuid;
1207         size_t i;
1208
1209         if (json->u.array.n == 2
1210             && json->u.array.elems[0]->type == JSON_STRING
1211             && json->u.array.elems[1]->type == JSON_STRING
1212             && !strcmp(json->u.array.elems[0]->u.string, "uuid")
1213             && uuid_from_string(&uuid, json->u.array.elems[1]->u.string)) {
1214             const struct ovsdb_idl_row *row;
1215
1216             row = ovsdb_idl_txn_get_row(txn, &uuid);
1217             if (row && !row->old && row->new) {
1218                 json_destroy(json);
1219
1220                 return json_array_create_2(
1221                     json_string_create("named-uuid"),
1222                     json_string_create_nocopy(uuid_name_from_uuid(&uuid)));
1223             }
1224         }
1225
1226         for (i = 0; i < json->u.array.n; i++) {
1227             json->u.array.elems[i] = substitute_uuids(json->u.array.elems[i],
1228                                                       txn);
1229         }
1230     } else if (json->type == JSON_OBJECT) {
1231         struct shash_node *node;
1232
1233         SHASH_FOR_EACH (node, json_object(json)) {
1234             node->data = substitute_uuids(node->data, txn);
1235         }
1236     }
1237     return json;
1238 }
1239
1240 static void
1241 ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
1242 {
1243     struct ovsdb_idl_row *row, *next;
1244
1245     /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
1246      * ovsdb_idl_column's 'parse' function, which will call
1247      * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
1248      * transaction and fail to update the graph.  */
1249     txn->idl->txn = NULL;
1250
1251     HMAP_FOR_EACH_SAFE (row, next, txn_node, &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, 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, 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, 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, hmap_node, &idl->outstanding_txns) {
1649         ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
1650     }
1651 }
1652
1653 static struct ovsdb_idl_txn *
1654 ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
1655 {
1656     struct ovsdb_idl_txn *txn;
1657
1658     HMAP_FOR_EACH_WITH_HASH (txn, hmap_node,
1659                              json_hash(id, 0), &idl->outstanding_txns) {
1660         if (json_equal(id, txn->request_id)) {
1661             return txn;
1662         }
1663     }
1664     return NULL;
1665 }
1666
1667 static bool
1668 check_json_type(const struct json *json, enum json_type type, const char *name)
1669 {
1670     if (!json) {
1671         VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
1672         return false;
1673     } else if (json->type != type) {
1674         VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
1675                      name, json_type_to_string(json->type),
1676                      json_type_to_string(type));
1677         return false;
1678     } else {
1679         return true;
1680     }
1681 }
1682
1683 static bool
1684 ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
1685                                 const struct json_array *results)
1686 {
1687     struct json *count, *rows, *row, *column;
1688     struct shash *mutate, *select;
1689
1690     if (txn->inc_index + 2 > results->n) {
1691         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1692                      "for increment (has %zu, needs %u)",
1693                      results->n, txn->inc_index + 2);
1694         return false;
1695     }
1696
1697     /* We know that this is a JSON object because the loop in
1698      * ovsdb_idl_txn_process_reply() checked. */
1699     mutate = json_object(results->elems[txn->inc_index]);
1700     count = shash_find_data(mutate, "count");
1701     if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
1702         return false;
1703     }
1704     if (count->u.integer != 1) {
1705         VLOG_WARN_RL(&syntax_rl,
1706                      "\"mutate\" reply \"count\" is %lld instead of 1",
1707                      count->u.integer);
1708         return false;
1709     }
1710
1711     select = json_object(results->elems[txn->inc_index + 1]);
1712     rows = shash_find_data(select, "rows");
1713     if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
1714         return false;
1715     }
1716     if (rows->u.array.n != 1) {
1717         VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %zu elements "
1718                      "instead of 1",
1719                      rows->u.array.n);
1720         return false;
1721     }
1722     row = rows->u.array.elems[0];
1723     if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
1724         return false;
1725     }
1726     column = shash_find_data(json_object(row), txn->inc_column);
1727     if (!check_json_type(column, JSON_INTEGER,
1728                          "\"select\" reply inc column")) {
1729         return false;
1730     }
1731     txn->inc_new_value = column->u.integer;
1732     return true;
1733 }
1734
1735 static bool
1736 ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
1737                                    const struct json_array *results)
1738 {
1739     static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
1740     struct ovsdb_error *error;
1741     struct json *json_uuid;
1742     union ovsdb_atom uuid;
1743     struct shash *reply;
1744
1745     if (insert->op_index >= results->n) {
1746         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1747                      "for insert (has %zu, needs %u)",
1748                      results->n, insert->op_index);
1749         return false;
1750     }
1751
1752     /* We know that this is a JSON object because the loop in
1753      * ovsdb_idl_txn_process_reply() checked. */
1754     reply = json_object(results->elems[insert->op_index]);
1755     json_uuid = shash_find_data(reply, "uuid");
1756     if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
1757         return false;
1758     }
1759
1760     error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
1761     if (error) {
1762         char *s = ovsdb_error_to_string(error);
1763         VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
1764                      "UUID: %s", s);
1765         free(s);
1766         return false;
1767     }
1768
1769     insert->real = uuid.uuid;
1770
1771     return true;
1772 }
1773
1774 static bool
1775 ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
1776                             const struct jsonrpc_msg *msg)
1777 {
1778     struct ovsdb_idl_txn *txn;
1779     enum ovsdb_idl_txn_status status;
1780
1781     txn = ovsdb_idl_txn_find(idl, msg->id);
1782     if (!txn) {
1783         return false;
1784     }
1785
1786     if (msg->type == JSONRPC_ERROR) {
1787         status = TXN_ERROR;
1788     } else if (msg->result->type != JSON_ARRAY) {
1789         VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
1790         status = TXN_ERROR;
1791     } else {
1792         struct json_array *ops = &msg->result->u.array;
1793         int hard_errors = 0;
1794         int soft_errors = 0;
1795         size_t i;
1796
1797         for (i = 0; i < ops->n; i++) {
1798             struct json *op = ops->elems[i];
1799
1800             if (op->type == JSON_NULL) {
1801                 /* This isn't an error in itself but indicates that some prior
1802                  * operation failed, so make sure that we know about it. */
1803                 soft_errors++;
1804             } else if (op->type == JSON_OBJECT) {
1805                 struct json *error;
1806
1807                 error = shash_find_data(json_object(op), "error");
1808                 if (error) {
1809                     if (error->type == JSON_STRING) {
1810                         if (!strcmp(error->u.string, "timed out")) {
1811                             soft_errors++;
1812                         } else if (strcmp(error->u.string, "aborted")) {
1813                             hard_errors++;
1814                             ovsdb_idl_txn_set_error_json(txn, op);
1815                         }
1816                     } else {
1817                         hard_errors++;
1818                         ovsdb_idl_txn_set_error_json(txn, op);
1819                         VLOG_WARN_RL(&syntax_rl,
1820                                      "\"error\" in reply is not JSON string");
1821                     }
1822                 }
1823             } else {
1824                 hard_errors++;
1825                 ovsdb_idl_txn_set_error_json(txn, op);
1826                 VLOG_WARN_RL(&syntax_rl,
1827                              "operation reply is not JSON null or object");
1828             }
1829         }
1830
1831         if (!soft_errors && !hard_errors) {
1832             struct ovsdb_idl_txn_insert *insert;
1833
1834             if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
1835                 hard_errors++;
1836             }
1837
1838             HMAP_FOR_EACH (insert, hmap_node, &txn->inserted_rows) {
1839                 if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
1840                     hard_errors++;
1841                 }
1842             }
1843         }
1844
1845         status = (hard_errors ? TXN_ERROR
1846                   : soft_errors ? TXN_TRY_AGAIN
1847                   : TXN_SUCCESS);
1848     }
1849
1850     ovsdb_idl_txn_complete(txn, status);
1851     return true;
1852 }
1853
1854 struct ovsdb_idl_txn *
1855 ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
1856 {
1857     struct ovsdb_idl_txn *txn = row->table->idl->txn;
1858     assert(txn != NULL);
1859     return txn;
1860 }
1861
1862 struct ovsdb_idl *
1863 ovsdb_idl_txn_get_idl (struct ovsdb_idl_txn *txn)
1864 {
1865     return txn->idl;
1866 }
1867