Merge branch 'mainstream'
[sliver-openvswitch.git] / lib / ovsdb-idl.c
1 /* Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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 <errno.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <stdlib.h>
24
25 #include "bitmap.h"
26 #include "dynamic-string.h"
27 #include "fatal-signal.h"
28 #include "json.h"
29 #include "jsonrpc.h"
30 #include "ovsdb-data.h"
31 #include "ovsdb-error.h"
32 #include "ovsdb-idl-provider.h"
33 #include "poll-loop.h"
34 #include "shash.h"
35 #include "util.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(ovsdb_idl);
39
40 /* An arc from one idl_row to another.  When row A contains a UUID that
41  * references row B, this is represented by an arc from A (the source) to B
42  * (the destination).
43  *
44  * Arcs from a row to itself are omitted, that is, src and dst are always
45  * different.
46  *
47  * Arcs are never duplicated, that is, even if there are multiple references
48  * from A to B, there is only a single arc from A to B.
49  *
50  * Arcs are directed: an arc from A to B is the converse of an an arc from B to
51  * A.  Both an arc and its converse may both be present, if each row refers
52  * to the other circularly.
53  *
54  * The source and destination row may be in the same table or in different
55  * tables.
56  */
57 struct ovsdb_idl_arc {
58     struct list src_node;       /* In src->src_arcs list. */
59     struct list dst_node;       /* In dst->dst_arcs list. */
60     struct ovsdb_idl_row *src;  /* Source row. */
61     struct ovsdb_idl_row *dst;  /* Destination row. */
62 };
63
64 struct ovsdb_idl {
65     const struct ovsdb_idl_class *class;
66     struct jsonrpc_session *session;
67     struct shash table_by_name;
68     struct ovsdb_idl_table *tables; /* Contains "struct ovsdb_idl_table *"s.*/
69     struct json *monitor_request_id;
70     unsigned int last_monitor_request_seqno;
71     unsigned int change_seqno;
72     bool verify_write_only;
73
74     /* Database locking. */
75     char *lock_name;            /* Name of lock we need, NULL if none. */
76     bool has_lock;              /* Has db server told us we have the lock? */
77     bool is_lock_contended;     /* Has db server told us we can't get lock? */
78     struct json *lock_request_id; /* JSON-RPC ID of in-flight lock request. */
79
80     /* Transaction support. */
81     struct ovsdb_idl_txn *txn;
82     struct hmap outstanding_txns;
83 };
84
85 struct ovsdb_idl_txn {
86     struct hmap_node hmap_node;
87     struct json *request_id;
88     struct ovsdb_idl *idl;
89     struct hmap txn_rows;
90     enum ovsdb_idl_txn_status status;
91     char *error;
92     bool dry_run;
93     struct ds comment;
94
95     /* Increments. */
96     const char *inc_table;
97     const char *inc_column;
98     struct uuid inc_row;
99     unsigned int inc_index;
100     int64_t inc_new_value;
101
102     /* Inserted rows. */
103     struct hmap inserted_rows;  /* Contains "struct ovsdb_idl_txn_insert"s. */
104 };
105
106 struct ovsdb_idl_txn_insert {
107     struct hmap_node hmap_node; /* In struct ovsdb_idl_txn's inserted_rows. */
108     struct uuid dummy;          /* Dummy UUID used locally. */
109     int op_index;               /* Index into transaction's operation array. */
110     struct uuid real;           /* Real UUID used by database server. */
111 };
112
113 static struct vlog_rate_limit syntax_rl = VLOG_RATE_LIMIT_INIT(1, 5);
114 static struct vlog_rate_limit semantic_rl = VLOG_RATE_LIMIT_INIT(1, 5);
115
116 static void ovsdb_idl_clear(struct ovsdb_idl *);
117 static void ovsdb_idl_send_monitor_request(struct ovsdb_idl *);
118 static void ovsdb_idl_parse_update(struct ovsdb_idl *, const struct json *);
119 static struct ovsdb_error *ovsdb_idl_parse_update__(struct ovsdb_idl *,
120                                                     const struct json *);
121 static bool ovsdb_idl_process_update(struct ovsdb_idl_table *,
122                                      const struct uuid *,
123                                      const struct json *old,
124                                      const struct json *new);
125 static void ovsdb_idl_insert_row(struct ovsdb_idl_row *, const struct json *);
126 static void ovsdb_idl_delete_row(struct ovsdb_idl_row *);
127 static bool ovsdb_idl_modify_row(struct ovsdb_idl_row *, const struct json *);
128
129 static bool ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *);
130 static struct ovsdb_idl_row *ovsdb_idl_row_create__(
131     const struct ovsdb_idl_table_class *);
132 static struct ovsdb_idl_row *ovsdb_idl_row_create(struct ovsdb_idl_table *,
133                                                   const struct uuid *);
134 static void ovsdb_idl_row_destroy(struct ovsdb_idl_row *);
135
136 static void ovsdb_idl_row_parse(struct ovsdb_idl_row *);
137 static void ovsdb_idl_row_unparse(struct ovsdb_idl_row *);
138 static void ovsdb_idl_row_clear_old(struct ovsdb_idl_row *);
139 static void ovsdb_idl_row_clear_new(struct ovsdb_idl_row *);
140
141 static void ovsdb_idl_txn_abort_all(struct ovsdb_idl *);
142 static bool ovsdb_idl_txn_process_reply(struct ovsdb_idl *,
143                                         const struct jsonrpc_msg *msg);
144
145 static void ovsdb_idl_send_lock_request(struct ovsdb_idl *);
146 static void ovsdb_idl_send_unlock_request(struct ovsdb_idl *);
147 static void ovsdb_idl_parse_lock_reply(struct ovsdb_idl *,
148                                        const struct json *);
149 static void ovsdb_idl_parse_lock_notify(struct ovsdb_idl *,
150                                         const struct json *params,
151                                         bool new_has_lock);
152
153 /* Creates and returns a connection to database 'remote', which should be in a
154  * form acceptable to jsonrpc_session_open().  The connection will maintain an
155  * in-memory replica of the remote database whose schema is described by
156  * 'class'.  (Ordinarily 'class' is compiled from an OVSDB schema automatically
157  * by ovsdb-idlc.)
158  *
159  * Passes 'retry' to jsonrpc_session_open().  See that function for
160  * documentation.
161  *
162  * If 'monitor_everything_by_default' is true, then everything in the remote
163  * database will be replicated by default.  ovsdb_idl_omit() and
164  * ovsdb_idl_omit_alert() may be used to selectively drop some columns from
165  * monitoring.
166  *
167  * If 'monitor_everything_by_default' is false, then no columns or tables will
168  * be replicated by default.  ovsdb_idl_add_column() and ovsdb_idl_add_table()
169  * must be used to choose some columns or tables to replicate.
170  */
171 struct ovsdb_idl *
172 ovsdb_idl_create(const char *remote, const struct ovsdb_idl_class *class,
173                  bool monitor_everything_by_default, bool retry)
174 {
175     struct ovsdb_idl *idl;
176     uint8_t default_mode;
177     size_t i;
178
179     default_mode = (monitor_everything_by_default
180                     ? OVSDB_IDL_MONITOR | OVSDB_IDL_ALERT
181                     : 0);
182
183     idl = xzalloc(sizeof *idl);
184     idl->class = class;
185     idl->session = jsonrpc_session_open(remote, retry);
186     shash_init(&idl->table_by_name);
187     idl->tables = xmalloc(class->n_tables * sizeof *idl->tables);
188     for (i = 0; i < class->n_tables; i++) {
189         const struct ovsdb_idl_table_class *tc = &class->tables[i];
190         struct ovsdb_idl_table *table = &idl->tables[i];
191         size_t j;
192
193         shash_add_assert(&idl->table_by_name, tc->name, table);
194         table->class = tc;
195         table->modes = xmalloc(tc->n_columns);
196         memset(table->modes, default_mode, tc->n_columns);
197         table->need_table = false;
198         shash_init(&table->columns);
199         for (j = 0; j < tc->n_columns; j++) {
200             const struct ovsdb_idl_column *column = &tc->columns[j];
201
202             shash_add_assert(&table->columns, column->name, column);
203         }
204         hmap_init(&table->rows);
205         table->idl = idl;
206     }
207     idl->last_monitor_request_seqno = UINT_MAX;
208     hmap_init(&idl->outstanding_txns);
209
210     return idl;
211 }
212
213 /* Destroys 'idl' and all of the data structures that it manages. */
214 void
215 ovsdb_idl_destroy(struct ovsdb_idl *idl)
216 {
217     if (idl) {
218         size_t i;
219
220         ovs_assert(!idl->txn);
221         ovsdb_idl_clear(idl);
222         jsonrpc_session_close(idl->session);
223
224         for (i = 0; i < idl->class->n_tables; i++) {
225             struct ovsdb_idl_table *table = &idl->tables[i];
226             shash_destroy(&table->columns);
227             hmap_destroy(&table->rows);
228             free(table->modes);
229         }
230         shash_destroy(&idl->table_by_name);
231         free(idl->tables);
232         json_destroy(idl->monitor_request_id);
233         free(idl->lock_name);
234         json_destroy(idl->lock_request_id);
235         hmap_destroy(&idl->outstanding_txns);
236         free(idl);
237     }
238 }
239
240 static void
241 ovsdb_idl_clear(struct ovsdb_idl *idl)
242 {
243     bool changed = false;
244     size_t i;
245
246     for (i = 0; i < idl->class->n_tables; i++) {
247         struct ovsdb_idl_table *table = &idl->tables[i];
248         struct ovsdb_idl_row *row, *next_row;
249
250         if (hmap_is_empty(&table->rows)) {
251             continue;
252         }
253
254         changed = true;
255         HMAP_FOR_EACH_SAFE (row, next_row, hmap_node, &table->rows) {
256             struct ovsdb_idl_arc *arc, *next_arc;
257
258             if (!ovsdb_idl_row_is_orphan(row)) {
259                 ovsdb_idl_row_unparse(row);
260             }
261             LIST_FOR_EACH_SAFE (arc, next_arc, src_node, &row->src_arcs) {
262                 free(arc);
263             }
264             /* No need to do anything with dst_arcs: some node has those arcs
265              * as forward arcs and will destroy them itself. */
266
267             ovsdb_idl_row_destroy(row);
268         }
269     }
270
271     if (changed) {
272         idl->change_seqno++;
273     }
274 }
275
276 /* Processes a batch of messages from the database server on 'idl'.  This may
277  * cause the IDL's contents to change.  The client may check for that with
278  * ovsdb_idl_get_seqno(). */
279 void
280 ovsdb_idl_run(struct ovsdb_idl *idl)
281 {
282     int i;
283
284     ovs_assert(!idl->txn);
285     jsonrpc_session_run(idl->session);
286     for (i = 0; jsonrpc_session_is_connected(idl->session) && i < 50; i++) {
287         struct jsonrpc_msg *msg;
288         unsigned int seqno;
289
290         seqno = jsonrpc_session_get_seqno(idl->session);
291         if (idl->last_monitor_request_seqno != seqno) {
292             idl->last_monitor_request_seqno = seqno;
293             ovsdb_idl_txn_abort_all(idl);
294             ovsdb_idl_send_monitor_request(idl);
295             if (idl->lock_name) {
296                 ovsdb_idl_send_lock_request(idl);
297             }
298             break;
299         }
300
301         msg = jsonrpc_session_recv(idl->session);
302         if (!msg) {
303             break;
304         }
305
306         if (msg->type == JSONRPC_NOTIFY
307             && !strcmp(msg->method, "update")
308             && msg->params->type == JSON_ARRAY
309             && msg->params->u.array.n == 2
310             && msg->params->u.array.elems[0]->type == JSON_NULL) {
311             /* Database contents changed. */
312             ovsdb_idl_parse_update(idl, msg->params->u.array.elems[1]);
313         } else if (msg->type == JSONRPC_REPLY
314                    && idl->monitor_request_id
315                    && json_equal(idl->monitor_request_id, msg->id)) {
316             /* Reply to our "monitor" request. */
317             idl->change_seqno++;
318             json_destroy(idl->monitor_request_id);
319             idl->monitor_request_id = NULL;
320             ovsdb_idl_clear(idl);
321             ovsdb_idl_parse_update(idl, msg->result);
322         } else if (msg->type == JSONRPC_REPLY
323                    && idl->lock_request_id
324                    && json_equal(idl->lock_request_id, msg->id)) {
325             /* Reply to our "lock" request. */
326             ovsdb_idl_parse_lock_reply(idl, msg->result);
327         } else if (msg->type == JSONRPC_NOTIFY
328                    && !strcmp(msg->method, "locked")) {
329             /* We got our lock. */
330             ovsdb_idl_parse_lock_notify(idl, msg->params, true);
331         } else if (msg->type == JSONRPC_NOTIFY
332                    && !strcmp(msg->method, "stolen")) {
333             /* Someone else stole our lock. */
334             ovsdb_idl_parse_lock_notify(idl, msg->params, false);
335         } else if (msg->type == JSONRPC_REPLY && msg->id->type == JSON_STRING
336                    && !strcmp(msg->id->u.string, "echo")) {
337             /* Reply to our echo request.  Ignore it. */
338         } else if ((msg->type == JSONRPC_ERROR
339                     || msg->type == JSONRPC_REPLY)
340                    && ovsdb_idl_txn_process_reply(idl, msg)) {
341             /* ovsdb_idl_txn_process_reply() did everything needful. */
342         } else {
343             /* This can happen if ovsdb_idl_txn_destroy() is called to destroy
344              * a transaction before we receive the reply, so keep the log level
345              * low. */
346             VLOG_DBG("%s: received unexpected %s message",
347                      jsonrpc_session_get_name(idl->session),
348                      jsonrpc_msg_type_to_string(msg->type));
349         }
350         jsonrpc_msg_destroy(msg);
351     }
352 }
353
354 /* Arranges for poll_block() to wake up when ovsdb_idl_run() has something to
355  * do or when activity occurs on a transaction on 'idl'. */
356 void
357 ovsdb_idl_wait(struct ovsdb_idl *idl)
358 {
359     jsonrpc_session_wait(idl->session);
360     jsonrpc_session_recv_wait(idl->session);
361 }
362
363 /* Returns a "sequence number" that represents the state of 'idl'.  When
364  * ovsdb_idl_run() changes the database, the sequence number changes.  The
365  * initial fetch of the entire contents of the remote database is considered to
366  * be one kind of change.  Successfully acquiring a lock, if one has been
367  * configured with ovsdb_idl_set_lock(), is also considered to be a change.
368  *
369  * As long as the sequence number does not change, the client may continue to
370  * use any data structures it obtains from 'idl'.  But when it changes, the
371  * client must not access any of these data structures again, because they
372  * could have freed or reused for other purposes.
373  *
374  * The sequence number can occasionally change even if the database does not.
375  * This happens if the connection to the database drops and reconnects, which
376  * causes the database contents to be reloaded even if they didn't change.  (It
377  * could also happen if the database server sends out a "change" that reflects
378  * what the IDL already thought was in the database.  The database server is
379  * not supposed to do that, but bugs could in theory cause it to do so.) */
380 unsigned int
381 ovsdb_idl_get_seqno(const struct ovsdb_idl *idl)
382 {
383     return idl->change_seqno;
384 }
385
386 /* Returns true if 'idl' successfully connected to the remote database and
387  * retrieved its contents (even if the connection subsequently dropped and is
388  * in the process of reconnecting).  If so, then 'idl' contains an atomic
389  * snapshot of the database's contents (but it might be arbitrarily old if the
390  * connection dropped).
391  *
392  * Returns false if 'idl' has never connected or retrieved the database's
393  * contents.  If so, 'idl' is empty. */
394 bool
395 ovsdb_idl_has_ever_connected(const struct ovsdb_idl *idl)
396 {
397     return ovsdb_idl_get_seqno(idl) != 0;
398 }
399
400 /* Forces 'idl' to drop its connection to the database and reconnect.  In the
401  * meantime, the contents of 'idl' will not change. */
402 void
403 ovsdb_idl_force_reconnect(struct ovsdb_idl *idl)
404 {
405     jsonrpc_session_force_reconnect(idl->session);
406 }
407
408 /* Some IDL users should only write to write-only columns.  Furthermore,
409  * writing to a column which is not write-only can cause serious performance
410  * degradations for these users.  This function causes 'idl' to reject writes
411  * to columns which are not marked write only using ovsdb_idl_omit_alert(). */
412 void
413 ovsdb_idl_verify_write_only(struct ovsdb_idl *idl)
414 {
415     idl->verify_write_only = true;
416 }
417
418 bool
419 ovsdb_idl_is_alive(const struct ovsdb_idl *idl)
420 {
421     return jsonrpc_session_is_alive(idl->session);
422 }
423
424 int
425 ovsdb_idl_get_last_error(const struct ovsdb_idl *idl)
426 {
427     return jsonrpc_session_get_last_error(idl->session);
428 }
429 \f
430 static unsigned char *
431 ovsdb_idl_get_mode(struct ovsdb_idl *idl,
432                    const struct ovsdb_idl_column *column)
433 {
434     size_t i;
435
436     ovs_assert(!idl->change_seqno);
437
438     for (i = 0; i < idl->class->n_tables; i++) {
439         const struct ovsdb_idl_table *table = &idl->tables[i];
440         const struct ovsdb_idl_table_class *tc = table->class;
441
442         if (column >= tc->columns && column < &tc->columns[tc->n_columns]) {
443             return &table->modes[column - tc->columns];
444         }
445     }
446
447     NOT_REACHED();
448 }
449
450 static void
451 add_ref_table(struct ovsdb_idl *idl, const struct ovsdb_base_type *base)
452 {
453     if (base->type == OVSDB_TYPE_UUID && base->u.uuid.refTableName) {
454         struct ovsdb_idl_table *table;
455
456         table = shash_find_data(&idl->table_by_name,
457                                 base->u.uuid.refTableName);
458         if (table) {
459             table->need_table = true;
460         } else {
461             VLOG_WARN("%s IDL class missing referenced table %s",
462                       idl->class->database, base->u.uuid.refTableName);
463         }
464     }
465 }
466
467 /* Turns on OVSDB_IDL_MONITOR and OVSDB_IDL_ALERT for 'column' in 'idl'.  Also
468  * ensures that any tables referenced by 'column' will be replicated, even if
469  * no columns in that table are selected for replication (see
470  * ovsdb_idl_add_table() for more information).
471  *
472  * This function is only useful if 'monitor_everything_by_default' was false in
473  * the call to ovsdb_idl_create().  This function should be called between
474  * ovsdb_idl_create() and the first call to ovsdb_idl_run().
475  */
476 void
477 ovsdb_idl_add_column(struct ovsdb_idl *idl,
478                      const struct ovsdb_idl_column *column)
479 {
480     *ovsdb_idl_get_mode(idl, column) = OVSDB_IDL_MONITOR | OVSDB_IDL_ALERT;
481     add_ref_table(idl, &column->type.key);
482     add_ref_table(idl, &column->type.value);
483 }
484
485 /* Ensures that the table with class 'tc' will be replicated on 'idl' even if
486  * no columns are selected for replication.  This can be useful because it
487  * allows 'idl' to keep track of what rows in the table actually exist, which
488  * in turn allows columns that reference the table to have accurate contents.
489  * (The IDL presents the database with references to rows that do not exist
490  * removed.)
491  *
492  * This function is only useful if 'monitor_everything_by_default' was false in
493  * the call to ovsdb_idl_create().  This function should be called between
494  * ovsdb_idl_create() and the first call to ovsdb_idl_run().
495  */
496 void
497 ovsdb_idl_add_table(struct ovsdb_idl *idl,
498                     const struct ovsdb_idl_table_class *tc)
499 {
500     size_t i;
501
502     for (i = 0; i < idl->class->n_tables; i++) {
503         struct ovsdb_idl_table *table = &idl->tables[i];
504
505         if (table->class == tc) {
506             table->need_table = true;
507             return;
508         }
509     }
510
511     NOT_REACHED();
512 }
513
514 /* Turns off OVSDB_IDL_ALERT for 'column' in 'idl'.
515  *
516  * This function should be called between ovsdb_idl_create() and the first call
517  * to ovsdb_idl_run().
518  */
519 void
520 ovsdb_idl_omit_alert(struct ovsdb_idl *idl,
521                      const struct ovsdb_idl_column *column)
522 {
523     *ovsdb_idl_get_mode(idl, column) &= ~OVSDB_IDL_ALERT;
524 }
525
526 /* Sets the mode for 'column' in 'idl' to 0.  See the big comment above
527  * OVSDB_IDL_MONITOR for details.
528  *
529  * This function should be called between ovsdb_idl_create() and the first call
530  * to ovsdb_idl_run().
531  */
532 void
533 ovsdb_idl_omit(struct ovsdb_idl *idl, const struct ovsdb_idl_column *column)
534 {
535     *ovsdb_idl_get_mode(idl, column) = 0;
536 }
537 \f
538 static void
539 ovsdb_idl_send_monitor_request(struct ovsdb_idl *idl)
540 {
541     struct json *monitor_requests;
542     struct jsonrpc_msg *msg;
543     size_t i;
544
545     monitor_requests = json_object_create();
546     for (i = 0; i < idl->class->n_tables; i++) {
547         const struct ovsdb_idl_table *table = &idl->tables[i];
548         const struct ovsdb_idl_table_class *tc = table->class;
549         struct json *monitor_request, *columns;
550         size_t j;
551
552         columns = table->need_table ? json_array_create_empty() : NULL;
553         for (j = 0; j < tc->n_columns; j++) {
554             const struct ovsdb_idl_column *column = &tc->columns[j];
555             if (table->modes[j] & OVSDB_IDL_MONITOR) {
556                 if (!columns) {
557                     columns = json_array_create_empty();
558                 }
559                 json_array_add(columns, json_string_create(column->name));
560             }
561         }
562
563         if (columns) {
564             monitor_request = json_object_create();
565             json_object_put(monitor_request, "columns", columns);
566             json_object_put(monitor_requests, tc->name, monitor_request);
567         }
568     }
569
570     json_destroy(idl->monitor_request_id);
571     msg = jsonrpc_create_request(
572         "monitor",
573         json_array_create_3(json_string_create(idl->class->database),
574                             json_null_create(), monitor_requests),
575         &idl->monitor_request_id);
576     jsonrpc_session_send(idl->session, msg);
577 }
578
579 static void
580 ovsdb_idl_parse_update(struct ovsdb_idl *idl, const struct json *table_updates)
581 {
582     struct ovsdb_error *error = ovsdb_idl_parse_update__(idl, table_updates);
583     if (error) {
584         if (!VLOG_DROP_WARN(&syntax_rl)) {
585             char *s = ovsdb_error_to_string(error);
586             VLOG_WARN_RL(&syntax_rl, "%s", s);
587             free(s);
588         }
589         ovsdb_error_destroy(error);
590     }
591 }
592
593 static struct ovsdb_error *
594 ovsdb_idl_parse_update__(struct ovsdb_idl *idl,
595                          const struct json *table_updates)
596 {
597     const struct shash_node *tables_node;
598
599     if (table_updates->type != JSON_OBJECT) {
600         return ovsdb_syntax_error(table_updates, NULL,
601                                   "<table-updates> is not an object");
602     }
603     SHASH_FOR_EACH (tables_node, json_object(table_updates)) {
604         const struct json *table_update = tables_node->data;
605         const struct shash_node *table_node;
606         struct ovsdb_idl_table *table;
607
608         table = shash_find_data(&idl->table_by_name, tables_node->name);
609         if (!table) {
610             return ovsdb_syntax_error(
611                 table_updates, NULL,
612                 "<table-updates> includes unknown table \"%s\"",
613                 tables_node->name);
614         }
615
616         if (table_update->type != JSON_OBJECT) {
617             return ovsdb_syntax_error(table_update, NULL,
618                                       "<table-update> for table \"%s\" is "
619                                       "not an object", table->class->name);
620         }
621         SHASH_FOR_EACH (table_node, json_object(table_update)) {
622             const struct json *row_update = table_node->data;
623             const struct json *old_json, *new_json;
624             struct uuid uuid;
625
626             if (!uuid_from_string(&uuid, table_node->name)) {
627                 return ovsdb_syntax_error(table_update, NULL,
628                                           "<table-update> for table \"%s\" "
629                                           "contains bad UUID "
630                                           "\"%s\" as member name",
631                                           table->class->name,
632                                           table_node->name);
633             }
634             if (row_update->type != JSON_OBJECT) {
635                 return ovsdb_syntax_error(row_update, NULL,
636                                           "<table-update> for table \"%s\" "
637                                           "contains <row-update> for %s that "
638                                           "is not an object",
639                                           table->class->name,
640                                           table_node->name);
641             }
642
643             old_json = shash_find_data(json_object(row_update), "old");
644             new_json = shash_find_data(json_object(row_update), "new");
645             if (old_json && old_json->type != JSON_OBJECT) {
646                 return ovsdb_syntax_error(old_json, NULL,
647                                           "\"old\" <row> is not object");
648             } else if (new_json && new_json->type != JSON_OBJECT) {
649                 return ovsdb_syntax_error(new_json, NULL,
650                                           "\"new\" <row> is not object");
651             } else if ((old_json != NULL) + (new_json != NULL)
652                        != shash_count(json_object(row_update))) {
653                 return ovsdb_syntax_error(row_update, NULL,
654                                           "<row-update> contains unexpected "
655                                           "member");
656             } else if (!old_json && !new_json) {
657                 return ovsdb_syntax_error(row_update, NULL,
658                                           "<row-update> missing \"old\" "
659                                           "and \"new\" members");
660             }
661
662             if (ovsdb_idl_process_update(table, &uuid, old_json, new_json)) {
663                 idl->change_seqno++;
664             }
665         }
666     }
667
668     return NULL;
669 }
670
671 static struct ovsdb_idl_row *
672 ovsdb_idl_get_row(struct ovsdb_idl_table *table, const struct uuid *uuid)
673 {
674     struct ovsdb_idl_row *row;
675
676     HMAP_FOR_EACH_WITH_HASH (row, hmap_node, uuid_hash(uuid), &table->rows) {
677         if (uuid_equals(&row->uuid, uuid)) {
678             return row;
679         }
680     }
681     return NULL;
682 }
683
684 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
685  * otherwise. */
686 static bool
687 ovsdb_idl_process_update(struct ovsdb_idl_table *table,
688                          const struct uuid *uuid, const struct json *old,
689                          const struct json *new)
690 {
691     struct ovsdb_idl_row *row;
692
693     row = ovsdb_idl_get_row(table, uuid);
694     if (!new) {
695         /* Delete row. */
696         if (row && !ovsdb_idl_row_is_orphan(row)) {
697             /* XXX perhaps we should check the 'old' values? */
698             ovsdb_idl_delete_row(row);
699         } else {
700             VLOG_WARN_RL(&semantic_rl, "cannot delete missing row "UUID_FMT" "
701                          "from table %s",
702                          UUID_ARGS(uuid), table->class->name);
703             return false;
704         }
705     } else if (!old) {
706         /* Insert row. */
707         if (!row) {
708             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
709         } else if (ovsdb_idl_row_is_orphan(row)) {
710             ovsdb_idl_insert_row(row, new);
711         } else {
712             VLOG_WARN_RL(&semantic_rl, "cannot add existing row "UUID_FMT" to "
713                          "table %s", UUID_ARGS(uuid), table->class->name);
714             return ovsdb_idl_modify_row(row, new);
715         }
716     } else {
717         /* Modify row. */
718         if (row) {
719             /* XXX perhaps we should check the 'old' values? */
720             if (!ovsdb_idl_row_is_orphan(row)) {
721                 return ovsdb_idl_modify_row(row, new);
722             } else {
723                 VLOG_WARN_RL(&semantic_rl, "cannot modify missing but "
724                              "referenced row "UUID_FMT" in table %s",
725                              UUID_ARGS(uuid), table->class->name);
726                 ovsdb_idl_insert_row(row, new);
727             }
728         } else {
729             VLOG_WARN_RL(&semantic_rl, "cannot modify missing row "UUID_FMT" "
730                          "in table %s", UUID_ARGS(uuid), table->class->name);
731             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
732         }
733     }
734
735     return true;
736 }
737
738 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
739  * otherwise. */
740 static bool
741 ovsdb_idl_row_update(struct ovsdb_idl_row *row, const struct json *row_json)
742 {
743     struct ovsdb_idl_table *table = row->table;
744     struct shash_node *node;
745     bool changed = false;
746
747     SHASH_FOR_EACH (node, json_object(row_json)) {
748         const char *column_name = node->name;
749         const struct ovsdb_idl_column *column;
750         struct ovsdb_datum datum;
751         struct ovsdb_error *error;
752
753         column = shash_find_data(&table->columns, column_name);
754         if (!column) {
755             VLOG_WARN_RL(&syntax_rl, "unknown column %s updating row "UUID_FMT,
756                          column_name, UUID_ARGS(&row->uuid));
757             continue;
758         }
759
760         error = ovsdb_datum_from_json(&datum, &column->type, node->data, NULL);
761         if (!error) {
762             unsigned int column_idx = column - table->class->columns;
763             struct ovsdb_datum *old = &row->old[column_idx];
764
765             if (!ovsdb_datum_equals(old, &datum, &column->type)) {
766                 ovsdb_datum_swap(old, &datum);
767                 if (table->modes[column_idx] & OVSDB_IDL_ALERT) {
768                     changed = true;
769                 }
770             } else {
771                 /* Didn't really change but the OVSDB monitor protocol always
772                  * includes every value in a row. */
773             }
774
775             ovsdb_datum_destroy(&datum, &column->type);
776         } else {
777             char *s = ovsdb_error_to_string(error);
778             VLOG_WARN_RL(&syntax_rl, "error parsing column %s in row "UUID_FMT
779                          " in table %s: %s", column_name,
780                          UUID_ARGS(&row->uuid), table->class->name, s);
781             free(s);
782             ovsdb_error_destroy(error);
783         }
784     }
785     return changed;
786 }
787
788 /* When a row A refers to row B through a column with a "refTable" constraint,
789  * but row B does not exist, row B is called an "orphan row".  Orphan rows
790  * should not persist, because the database enforces referential integrity, but
791  * they can appear transiently as changes from the database are received (the
792  * database doesn't try to topologically sort them and circular references mean
793  * it isn't always possible anyhow).
794  *
795  * This function returns true if 'row' is an orphan row, otherwise false.
796  */
797 static bool
798 ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *row)
799 {
800     return !row->old && !row->new;
801 }
802
803 /* Returns true if 'row' is conceptually part of the database as modified by
804  * the current transaction (if any), false otherwise.
805  *
806  * This function will return true if 'row' is not an orphan (see the comment on
807  * ovsdb_idl_row_is_orphan()) and:
808  *
809  *   - 'row' exists in the database and has not been deleted within the
810  *     current transaction (if any).
811  *
812  *   - 'row' was inserted within the current transaction and has not been
813  *     deleted.  (In the latter case you should not have passed 'row' in at
814  *     all, because ovsdb_idl_txn_delete() freed it.)
815  *
816  * This function will return false if 'row' is an orphan or if 'row' was
817  * deleted within the current transaction.
818  */
819 static bool
820 ovsdb_idl_row_exists(const struct ovsdb_idl_row *row)
821 {
822     return row->new != NULL;
823 }
824
825 static void
826 ovsdb_idl_row_parse(struct ovsdb_idl_row *row)
827 {
828     const struct ovsdb_idl_table_class *class = row->table->class;
829     size_t i;
830
831     for (i = 0; i < class->n_columns; i++) {
832         const struct ovsdb_idl_column *c = &class->columns[i];
833         (c->parse)(row, &row->old[i]);
834     }
835 }
836
837 static void
838 ovsdb_idl_row_unparse(struct ovsdb_idl_row *row)
839 {
840     const struct ovsdb_idl_table_class *class = row->table->class;
841     size_t i;
842
843     for (i = 0; i < class->n_columns; i++) {
844         const struct ovsdb_idl_column *c = &class->columns[i];
845         (c->unparse)(row);
846     }
847 }
848
849 static void
850 ovsdb_idl_row_clear_old(struct ovsdb_idl_row *row)
851 {
852     ovs_assert(row->old == row->new);
853     if (!ovsdb_idl_row_is_orphan(row)) {
854         const struct ovsdb_idl_table_class *class = row->table->class;
855         size_t i;
856
857         for (i = 0; i < class->n_columns; i++) {
858             ovsdb_datum_destroy(&row->old[i], &class->columns[i].type);
859         }
860         free(row->old);
861         row->old = row->new = NULL;
862     }
863 }
864
865 static void
866 ovsdb_idl_row_clear_new(struct ovsdb_idl_row *row)
867 {
868     if (row->old != row->new) {
869         if (row->new) {
870             const struct ovsdb_idl_table_class *class = row->table->class;
871             size_t i;
872
873             if (row->written) {
874                 BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
875                     ovsdb_datum_destroy(&row->new[i], &class->columns[i].type);
876                 }
877             }
878             free(row->new);
879             free(row->written);
880             row->written = NULL;
881         }
882         row->new = row->old;
883     }
884 }
885
886 static void
887 ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
888 {
889     struct ovsdb_idl_arc *arc, *next;
890
891     /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
892      * that this causes to be unreferenced. */
893     LIST_FOR_EACH_SAFE (arc, next, src_node, &row->src_arcs) {
894         list_remove(&arc->dst_node);
895         if (destroy_dsts
896             && ovsdb_idl_row_is_orphan(arc->dst)
897             && list_is_empty(&arc->dst->dst_arcs)) {
898             ovsdb_idl_row_destroy(arc->dst);
899         }
900         free(arc);
901     }
902     list_init(&row->src_arcs);
903 }
904
905 /* Force nodes that reference 'row' to reparse. */
906 static void
907 ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
908 {
909     struct ovsdb_idl_arc *arc, *next;
910
911     /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
912      * 'arc', so we need to use the "safe" variant of list traversal.  However,
913      * calling an ovsdb_idl_column's 'parse' function will add an arc
914      * equivalent to 'arc' to row->arcs.  That could be a problem for
915      * traversal, but it adds it at the beginning of the list to prevent us
916      * from stumbling upon it again.
917      *
918      * (If duplicate arcs were possible then we would need to make sure that
919      * 'next' didn't also point into 'arc''s destination, but we forbid
920      * duplicate arcs.) */
921     LIST_FOR_EACH_SAFE (arc, next, dst_node, &row->dst_arcs) {
922         struct ovsdb_idl_row *ref = arc->src;
923
924         ovsdb_idl_row_unparse(ref);
925         ovsdb_idl_row_clear_arcs(ref, false);
926         ovsdb_idl_row_parse(ref);
927     }
928 }
929
930 static struct ovsdb_idl_row *
931 ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
932 {
933     struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
934     class->row_init(row);
935     list_init(&row->src_arcs);
936     list_init(&row->dst_arcs);
937     hmap_node_nullify(&row->txn_node);
938     return row;
939 }
940
941 static struct ovsdb_idl_row *
942 ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
943 {
944     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class);
945     hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
946     row->uuid = *uuid;
947     row->table = table;
948     return row;
949 }
950
951 static void
952 ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
953 {
954     if (row) {
955         ovsdb_idl_row_clear_old(row);
956         hmap_remove(&row->table->rows, &row->hmap_node);
957         free(row);
958     }
959 }
960
961 static void
962 ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct json *row_json)
963 {
964     const struct ovsdb_idl_table_class *class = row->table->class;
965     size_t i;
966
967     ovs_assert(!row->old && !row->new);
968     row->old = row->new = xmalloc(class->n_columns * sizeof *row->old);
969     for (i = 0; i < class->n_columns; i++) {
970         ovsdb_datum_init_default(&row->old[i], &class->columns[i].type);
971     }
972     ovsdb_idl_row_update(row, row_json);
973     ovsdb_idl_row_parse(row);
974
975     ovsdb_idl_row_reparse_backrefs(row);
976 }
977
978 static void
979 ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
980 {
981     ovsdb_idl_row_unparse(row);
982     ovsdb_idl_row_clear_arcs(row, true);
983     ovsdb_idl_row_clear_old(row);
984     if (list_is_empty(&row->dst_arcs)) {
985         ovsdb_idl_row_destroy(row);
986     } else {
987         ovsdb_idl_row_reparse_backrefs(row);
988     }
989 }
990
991 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
992  * otherwise. */
993 static bool
994 ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct json *row_json)
995 {
996     bool changed;
997
998     ovsdb_idl_row_unparse(row);
999     ovsdb_idl_row_clear_arcs(row, true);
1000     changed = ovsdb_idl_row_update(row, row_json);
1001     ovsdb_idl_row_parse(row);
1002
1003     return changed;
1004 }
1005
1006 static bool
1007 may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
1008 {
1009     const struct ovsdb_idl_arc *arc;
1010
1011     /* No self-arcs. */
1012     if (src == dst) {
1013         return false;
1014     }
1015
1016     /* No duplicate arcs.
1017      *
1018      * We only need to test whether the first arc in dst->dst_arcs originates
1019      * at 'src', since we add all of the arcs from a given source in a clump
1020      * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
1021      * added at the front of the dst_arcs list. */
1022     if (list_is_empty(&dst->dst_arcs)) {
1023         return true;
1024     }
1025     arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
1026     return arc->src != src;
1027 }
1028
1029 static struct ovsdb_idl_table *
1030 ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
1031                            const struct ovsdb_idl_table_class *table_class)
1032 {
1033     return &idl->tables[table_class - idl->class->tables];
1034 }
1035
1036 /* Called by ovsdb-idlc generated code. */
1037 struct ovsdb_idl_row *
1038 ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
1039                       struct ovsdb_idl_table_class *dst_table_class,
1040                       const struct uuid *dst_uuid)
1041 {
1042     struct ovsdb_idl *idl = src->table->idl;
1043     struct ovsdb_idl_table *dst_table;
1044     struct ovsdb_idl_arc *arc;
1045     struct ovsdb_idl_row *dst;
1046
1047     dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
1048     dst = ovsdb_idl_get_row(dst_table, dst_uuid);
1049     if (idl->txn) {
1050         /* We're being called from ovsdb_idl_txn_write().  We must not update
1051          * any arcs, because the transaction will be backed out at commit or
1052          * abort time and we don't want our graph screwed up.
1053          *
1054          * Just return the destination row, if there is one and it has not been
1055          * deleted. */
1056         if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new)) {
1057             return dst;
1058         }
1059         return NULL;
1060     } else {
1061         /* We're being called from some other context.  Update the graph. */
1062         if (!dst) {
1063             dst = ovsdb_idl_row_create(dst_table, dst_uuid);
1064         }
1065
1066         /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
1067         if (may_add_arc(src, dst)) {
1068             /* The arc *must* be added at the front of the dst_arcs list.  See
1069              * ovsdb_idl_row_reparse_backrefs() for details. */
1070             arc = xmalloc(sizeof *arc);
1071             list_push_front(&src->src_arcs, &arc->src_node);
1072             list_push_front(&dst->dst_arcs, &arc->dst_node);
1073             arc->src = src;
1074             arc->dst = dst;
1075         }
1076
1077         return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
1078     }
1079 }
1080
1081 /* Searches 'tc''s table in 'idl' for a row with UUID 'uuid'.  Returns a
1082  * pointer to the row if there is one, otherwise a null pointer.  */
1083 const struct ovsdb_idl_row *
1084 ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
1085                            const struct ovsdb_idl_table_class *tc,
1086                            const struct uuid *uuid)
1087 {
1088     return ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
1089 }
1090
1091 static struct ovsdb_idl_row *
1092 next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
1093 {
1094     for (; node; node = hmap_next(&table->rows, node)) {
1095         struct ovsdb_idl_row *row;
1096
1097         row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
1098         if (ovsdb_idl_row_exists(row)) {
1099             return row;
1100         }
1101     }
1102     return NULL;
1103 }
1104
1105 /* Returns a row in 'table_class''s table in 'idl', or a null pointer if that
1106  * table is empty.
1107  *
1108  * Database tables are internally maintained as hash tables, so adding or
1109  * removing rows while traversing the same table can cause some rows to be
1110  * visited twice or not at apply. */
1111 const struct ovsdb_idl_row *
1112 ovsdb_idl_first_row(const struct ovsdb_idl *idl,
1113                     const struct ovsdb_idl_table_class *table_class)
1114 {
1115     struct ovsdb_idl_table *table
1116         = ovsdb_idl_table_from_class(idl, table_class);
1117     return next_real_row(table, hmap_first(&table->rows));
1118 }
1119
1120 /* Returns a row following 'row' within its table, or a null pointer if 'row'
1121  * is the last row in its table. */
1122 const struct ovsdb_idl_row *
1123 ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
1124 {
1125     struct ovsdb_idl_table *table = row->table;
1126
1127     return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
1128 }
1129
1130 /* Reads and returns the value of 'column' within 'row'.  If an ongoing
1131  * transaction has changed 'column''s value, the modified value is returned.
1132  *
1133  * The caller must not modify or free the returned value.
1134  *
1135  * Various kinds of changes can invalidate the returned value: writing to the
1136  * same 'column' in 'row' (e.g. with ovsdb_idl_txn_write()), deleting 'row'
1137  * (e.g. with ovsdb_idl_txn_delete()), or completing an ongoing transaction
1138  * (e.g. with ovsdb_idl_txn_commit() or ovsdb_idl_txn_abort()).  If the
1139  * returned value is needed for a long time, it is best to make a copy of it
1140  * with ovsdb_datum_clone(). */
1141 const struct ovsdb_datum *
1142 ovsdb_idl_read(const struct ovsdb_idl_row *row,
1143                const struct ovsdb_idl_column *column)
1144 {
1145     const struct ovsdb_idl_table_class *class;
1146     size_t column_idx;
1147
1148     ovs_assert(!ovsdb_idl_row_is_synthetic(row));
1149
1150     class = row->table->class;
1151     column_idx = column - class->columns;
1152
1153     ovs_assert(row->new != NULL);
1154     ovs_assert(column_idx < class->n_columns);
1155
1156     if (row->written && bitmap_is_set(row->written, column_idx)) {
1157         return &row->new[column_idx];
1158     } else if (row->old) {
1159         return &row->old[column_idx];
1160     } else {
1161         return ovsdb_datum_default(&column->type);
1162     }
1163 }
1164
1165 /* Same as ovsdb_idl_read(), except that it also asserts that 'column' has key
1166  * type 'key_type' and value type 'value_type'.  (Scalar and set types will
1167  * have a value type of OVSDB_TYPE_VOID.)
1168  *
1169  * This is useful in code that "knows" that a particular column has a given
1170  * type, so that it will abort if someone changes the column's type without
1171  * updating the code that uses it. */
1172 const struct ovsdb_datum *
1173 ovsdb_idl_get(const struct ovsdb_idl_row *row,
1174               const struct ovsdb_idl_column *column,
1175               enum ovsdb_atomic_type key_type OVS_UNUSED,
1176               enum ovsdb_atomic_type value_type OVS_UNUSED)
1177 {
1178     ovs_assert(column->type.key.type == key_type);
1179     ovs_assert(column->type.value.type == value_type);
1180
1181     return ovsdb_idl_read(row, column);
1182 }
1183
1184 /* Returns false if 'row' was obtained from the IDL, true if it was initialized
1185  * to all-zero-bits by some other entity.  If 'row' was set up some other way
1186  * then the return value is indeterminate. */
1187 bool
1188 ovsdb_idl_row_is_synthetic(const struct ovsdb_idl_row *row)
1189 {
1190     return row->table == NULL;
1191 }
1192 \f
1193 /* Transactions. */
1194
1195 static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1196                                    enum ovsdb_idl_txn_status);
1197
1198 /* Returns a string representation of 'status'.  The caller must not modify or
1199  * free the returned string.
1200  *
1201  * The return value is probably useful only for debug log messages and unit
1202  * tests. */
1203 const char *
1204 ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
1205 {
1206     switch (status) {
1207     case TXN_UNCOMMITTED:
1208         return "uncommitted";
1209     case TXN_UNCHANGED:
1210         return "unchanged";
1211     case TXN_INCOMPLETE:
1212         return "incomplete";
1213     case TXN_ABORTED:
1214         return "aborted";
1215     case TXN_SUCCESS:
1216         return "success";
1217     case TXN_TRY_AGAIN:
1218         return "try again";
1219     case TXN_NOT_LOCKED:
1220         return "not locked";
1221     case TXN_ERROR:
1222         return "error";
1223     }
1224     return "<unknown>";
1225 }
1226
1227 /* Starts a new transaction on 'idl'.  A given ovsdb_idl may only have a single
1228  * active transaction at a time.  See the large comment in ovsdb-idl.h for
1229  * general information on transactions. */
1230 struct ovsdb_idl_txn *
1231 ovsdb_idl_txn_create(struct ovsdb_idl *idl)
1232 {
1233     struct ovsdb_idl_txn *txn;
1234
1235     ovs_assert(!idl->txn);
1236     idl->txn = txn = xmalloc(sizeof *txn);
1237     txn->request_id = NULL;
1238     txn->idl = idl;
1239     hmap_init(&txn->txn_rows);
1240     txn->status = TXN_UNCOMMITTED;
1241     txn->error = NULL;
1242     txn->dry_run = false;
1243     ds_init(&txn->comment);
1244
1245     txn->inc_table = NULL;
1246     txn->inc_column = NULL;
1247
1248     hmap_init(&txn->inserted_rows);
1249
1250     return txn;
1251 }
1252
1253 /* Appends 's', which is treated as a printf()-type format string, to the
1254  * comments that will be passed to the OVSDB server when 'txn' is committed.
1255  * (The comment will be committed to the OVSDB log, which "ovsdb-tool
1256  * show-log" can print in a relatively human-readable form.) */
1257 void
1258 ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s, ...)
1259 {
1260     va_list args;
1261
1262     if (txn->comment.length) {
1263         ds_put_char(&txn->comment, '\n');
1264     }
1265
1266     va_start(args, s);
1267     ds_put_format_valist(&txn->comment, s, args);
1268     va_end(args);
1269 }
1270
1271 /* Marks 'txn' as a transaction that will not actually modify the database.  In
1272  * almost every way, the transaction is treated like other transactions.  It
1273  * must be committed or aborted like other transactions, it will be sent to the
1274  * database server like other transactions, and so on.  The only difference is
1275  * that the operations sent to the database server will include, as the last
1276  * step, an "abort" operation, so that any changes made by the transaction will
1277  * not actually take effect. */
1278 void
1279 ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
1280 {
1281     txn->dry_run = true;
1282 }
1283
1284 /* Causes 'txn', when committed, to increment the value of 'column' within
1285  * 'row' by 1.  'column' must have an integer type.  After 'txn' commits
1286  * successfully, the client may retrieve the final (incremented) value of
1287  * 'column' with ovsdb_idl_txn_get_increment_new_value().
1288  *
1289  * The client could accomplish something similar with ovsdb_idl_read(),
1290  * ovsdb_idl_txn_verify() and ovsdb_idl_txn_write(), or with ovsdb-idlc
1291  * generated wrappers for these functions.  However, ovsdb_idl_txn_increment()
1292  * will never (by itself) fail because of a verify error.
1293  *
1294  * The intended use is for incrementing the "next_cfg" column in the
1295  * Open_vSwitch table. */
1296 void
1297 ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn,
1298                         const struct ovsdb_idl_row *row,
1299                         const struct ovsdb_idl_column *column)
1300 {
1301     ovs_assert(!txn->inc_table);
1302     ovs_assert(column->type.key.type == OVSDB_TYPE_INTEGER);
1303     ovs_assert(column->type.value.type == OVSDB_TYPE_VOID);
1304
1305     txn->inc_table = row->table->class->name;
1306     txn->inc_column = column->name;
1307     txn->inc_row = row->uuid;
1308 }
1309
1310 /* Destroys 'txn' and frees all associated memory.  If ovsdb_idl_txn_commit()
1311  * has been called for 'txn' but the commit is still incomplete (that is, the
1312  * last call returned TXN_INCOMPLETE) then the transaction may or may not still
1313  * end up committing at the database server, but the client will not be able to
1314  * get any further status information back. */
1315 void
1316 ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
1317 {
1318     struct ovsdb_idl_txn_insert *insert, *next;
1319
1320     json_destroy(txn->request_id);
1321     if (txn->status == TXN_INCOMPLETE) {
1322         hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1323     }
1324     ovsdb_idl_txn_abort(txn);
1325     ds_destroy(&txn->comment);
1326     free(txn->error);
1327     HMAP_FOR_EACH_SAFE (insert, next, hmap_node, &txn->inserted_rows) {
1328         free(insert);
1329     }
1330     hmap_destroy(&txn->inserted_rows);
1331     free(txn);
1332 }
1333
1334 /* Causes poll_block() to wake up if 'txn' has completed committing. */
1335 void
1336 ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
1337 {
1338     if (txn->status != TXN_UNCOMMITTED && txn->status != TXN_INCOMPLETE) {
1339         poll_immediate_wake();
1340     }
1341 }
1342
1343 static struct json *
1344 where_uuid_equals(const struct uuid *uuid)
1345 {
1346     return
1347         json_array_create_1(
1348             json_array_create_3(
1349                 json_string_create("_uuid"),
1350                 json_string_create("=="),
1351                 json_array_create_2(
1352                     json_string_create("uuid"),
1353                     json_string_create_nocopy(
1354                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
1355 }
1356
1357 static char *
1358 uuid_name_from_uuid(const struct uuid *uuid)
1359 {
1360     char *name;
1361     char *p;
1362
1363     name = xasprintf("row"UUID_FMT, UUID_ARGS(uuid));
1364     for (p = name; *p != '\0'; p++) {
1365         if (*p == '-') {
1366             *p = '_';
1367         }
1368     }
1369
1370     return name;
1371 }
1372
1373 static const struct ovsdb_idl_row *
1374 ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
1375 {
1376     const struct ovsdb_idl_row *row;
1377
1378     HMAP_FOR_EACH_WITH_HASH (row, txn_node, uuid_hash(uuid), &txn->txn_rows) {
1379         if (uuid_equals(&row->uuid, uuid)) {
1380             return row;
1381         }
1382     }
1383     return NULL;
1384 }
1385
1386 /* XXX there must be a cleaner way to do this */
1387 static struct json *
1388 substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
1389 {
1390     if (json->type == JSON_ARRAY) {
1391         struct uuid uuid;
1392         size_t i;
1393
1394         if (json->u.array.n == 2
1395             && json->u.array.elems[0]->type == JSON_STRING
1396             && json->u.array.elems[1]->type == JSON_STRING
1397             && !strcmp(json->u.array.elems[0]->u.string, "uuid")
1398             && uuid_from_string(&uuid, json->u.array.elems[1]->u.string)) {
1399             const struct ovsdb_idl_row *row;
1400
1401             row = ovsdb_idl_txn_get_row(txn, &uuid);
1402             if (row && !row->old && row->new) {
1403                 json_destroy(json);
1404
1405                 return json_array_create_2(
1406                     json_string_create("named-uuid"),
1407                     json_string_create_nocopy(uuid_name_from_uuid(&uuid)));
1408             }
1409         }
1410
1411         for (i = 0; i < json->u.array.n; i++) {
1412             json->u.array.elems[i] = substitute_uuids(json->u.array.elems[i],
1413                                                       txn);
1414         }
1415     } else if (json->type == JSON_OBJECT) {
1416         struct shash_node *node;
1417
1418         SHASH_FOR_EACH (node, json_object(json)) {
1419             node->data = substitute_uuids(node->data, txn);
1420         }
1421     }
1422     return json;
1423 }
1424
1425 static void
1426 ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
1427 {
1428     struct ovsdb_idl_row *row, *next;
1429
1430     /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
1431      * ovsdb_idl_column's 'parse' function, which will call
1432      * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
1433      * transaction and fail to update the graph.  */
1434     txn->idl->txn = NULL;
1435
1436     HMAP_FOR_EACH_SAFE (row, next, txn_node, &txn->txn_rows) {
1437         if (row->old) {
1438             if (row->written) {
1439                 ovsdb_idl_row_unparse(row);
1440                 ovsdb_idl_row_clear_arcs(row, false);
1441                 ovsdb_idl_row_parse(row);
1442             }
1443         } else {
1444             ovsdb_idl_row_unparse(row);
1445         }
1446         ovsdb_idl_row_clear_new(row);
1447
1448         free(row->prereqs);
1449         row->prereqs = NULL;
1450
1451         free(row->written);
1452         row->written = NULL;
1453
1454         hmap_remove(&txn->txn_rows, &row->txn_node);
1455         hmap_node_nullify(&row->txn_node);
1456         if (!row->old) {
1457             hmap_remove(&row->table->rows, &row->hmap_node);
1458             free(row);
1459         }
1460     }
1461     hmap_destroy(&txn->txn_rows);
1462     hmap_init(&txn->txn_rows);
1463 }
1464
1465 /* Attempts to commit 'txn'.  Returns the status of the commit operation, one
1466  * of the following TXN_* constants:
1467  *
1468  *   TXN_INCOMPLETE:
1469  *
1470  *       The transaction is in progress, but not yet complete.  The caller
1471  *       should call again later, after calling ovsdb_idl_run() to let the IDL
1472  *       do OVSDB protocol processing.
1473  *
1474  *   TXN_UNCHANGED:
1475  *
1476  *       The transaction is complete.  (It didn't actually change the database,
1477  *       so the IDL didn't send any request to the database server.)
1478  *
1479  *   TXN_ABORTED:
1480  *
1481  *       The caller previously called ovsdb_idl_txn_abort().
1482  *
1483  *   TXN_SUCCESS:
1484  *
1485  *       The transaction was successful.  The update made by the transaction
1486  *       (and possibly other changes made by other database clients) should
1487  *       already be visible in the IDL.
1488  *
1489  *   TXN_TRY_AGAIN:
1490  *
1491  *       The transaction failed for some transient reason, e.g. because a
1492  *       "verify" operation reported an inconsistency or due to a network
1493  *       problem.  The caller should wait for a change to the database, then
1494  *       compose a new transaction, and commit the new transaction.
1495  *
1496  *       Use the return value of ovsdb_idl_get_seqno() to wait for a change in
1497  *       the database.  It is important to use its return value *before* the
1498  *       initial call to ovsdb_idl_txn_commit() as the baseline for this
1499  *       purpose, because the change that one should wait for can happen after
1500  *       the initial call but before the call that returns TXN_TRY_AGAIN, and
1501  *       using some other baseline value in that situation could cause an
1502  *       indefinite wait if the database rarely changes.
1503  *
1504  *   TXN_NOT_LOCKED:
1505  *
1506  *       The transaction failed because the IDL has been configured to require
1507  *       a database lock (with ovsdb_idl_set_lock()) but didn't get it yet or
1508  *       has already lost it.
1509  *
1510  * Committing a transaction rolls back all of the changes that it made to the
1511  * IDL's copy of the database.  If the transaction commits successfully, then
1512  * the database server will send an update and, thus, the IDL will be updated
1513  * with the committed changes. */
1514 enum ovsdb_idl_txn_status
1515 ovsdb_idl_txn_commit(struct ovsdb_idl_txn *txn)
1516 {
1517     struct ovsdb_idl_row *row;
1518     struct json *operations;
1519     bool any_updates;
1520
1521     if (txn != txn->idl->txn) {
1522         return txn->status;
1523     }
1524
1525     /* If we need a lock but don't have it, give up quickly. */
1526     if (txn->idl->lock_name && !ovsdb_idl_has_lock(txn->idl)) {
1527         txn->status = TXN_NOT_LOCKED;
1528         ovsdb_idl_txn_disassemble(txn);
1529         return txn->status;
1530     }
1531
1532     operations = json_array_create_1(
1533         json_string_create(txn->idl->class->database));
1534
1535     /* Assert that we have the required lock (avoiding a race). */
1536     if (txn->idl->lock_name) {
1537         struct json *op = json_object_create();
1538         json_array_add(operations, op);
1539         json_object_put_string(op, "op", "assert");
1540         json_object_put_string(op, "lock", txn->idl->lock_name);
1541     }
1542
1543     /* Add prerequisites and declarations of new rows. */
1544     HMAP_FOR_EACH (row, txn_node, &txn->txn_rows) {
1545         /* XXX check that deleted rows exist even if no prereqs? */
1546         if (row->prereqs) {
1547             const struct ovsdb_idl_table_class *class = row->table->class;
1548             size_t n_columns = class->n_columns;
1549             struct json *op, *columns, *row_json;
1550             size_t idx;
1551
1552             op = json_object_create();
1553             json_array_add(operations, op);
1554             json_object_put_string(op, "op", "wait");
1555             json_object_put_string(op, "table", class->name);
1556             json_object_put(op, "timeout", json_integer_create(0));
1557             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1558             json_object_put_string(op, "until", "==");
1559             columns = json_array_create_empty();
1560             json_object_put(op, "columns", columns);
1561             row_json = json_object_create();
1562             json_object_put(op, "rows", json_array_create_1(row_json));
1563
1564             BITMAP_FOR_EACH_1 (idx, n_columns, row->prereqs) {
1565                 const struct ovsdb_idl_column *column = &class->columns[idx];
1566                 json_array_add(columns, json_string_create(column->name));
1567                 json_object_put(row_json, column->name,
1568                                 ovsdb_datum_to_json(&row->old[idx],
1569                                                     &column->type));
1570             }
1571         }
1572     }
1573
1574     /* Add updates. */
1575     any_updates = false;
1576     HMAP_FOR_EACH (row, txn_node, &txn->txn_rows) {
1577         const struct ovsdb_idl_table_class *class = row->table->class;
1578
1579         if (!row->new) {
1580             if (class->is_root) {
1581                 struct json *op = json_object_create();
1582                 json_object_put_string(op, "op", "delete");
1583                 json_object_put_string(op, "table", class->name);
1584                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
1585                 json_array_add(operations, op);
1586                 any_updates = true;
1587             } else {
1588                 /* Let ovsdb-server decide whether to really delete it. */
1589             }
1590         } else if (row->old != row->new) {
1591             struct json *row_json;
1592             struct json *op;
1593             size_t idx;
1594
1595             op = json_object_create();
1596             json_object_put_string(op, "op", row->old ? "update" : "insert");
1597             json_object_put_string(op, "table", class->name);
1598             if (row->old) {
1599                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
1600             } else {
1601                 struct ovsdb_idl_txn_insert *insert;
1602
1603                 any_updates = true;
1604
1605                 json_object_put(op, "uuid-name",
1606                                 json_string_create_nocopy(
1607                                     uuid_name_from_uuid(&row->uuid)));
1608
1609                 insert = xmalloc(sizeof *insert);
1610                 insert->dummy = row->uuid;
1611                 insert->op_index = operations->u.array.n - 1;
1612                 uuid_zero(&insert->real);
1613                 hmap_insert(&txn->inserted_rows, &insert->hmap_node,
1614                             uuid_hash(&insert->dummy));
1615             }
1616             row_json = json_object_create();
1617             json_object_put(op, "row", row_json);
1618
1619             if (row->written) {
1620                 BITMAP_FOR_EACH_1 (idx, class->n_columns, row->written) {
1621                     const struct ovsdb_idl_column *column =
1622                                                         &class->columns[idx];
1623
1624                     if (row->old
1625                         || !ovsdb_datum_is_default(&row->new[idx],
1626                                                   &column->type)) {
1627                         json_object_put(row_json, column->name,
1628                                         substitute_uuids(
1629                                             ovsdb_datum_to_json(&row->new[idx],
1630                                                                 &column->type),
1631                                             txn));
1632
1633                         /* If anything really changed, consider it an update.
1634                          * We can't suppress not-really-changed values earlier
1635                          * or transactions would become nonatomic (see the big
1636                          * comment inside ovsdb_idl_txn_write()). */
1637                         if (!any_updates && row->old &&
1638                             !ovsdb_datum_equals(&row->old[idx], &row->new[idx],
1639                                                 &column->type)) {
1640                             any_updates = true;
1641                         }
1642                     }
1643                 }
1644             }
1645
1646             if (!row->old || !shash_is_empty(json_object(row_json))) {
1647                 json_array_add(operations, op);
1648             } else {
1649                 json_destroy(op);
1650             }
1651         }
1652     }
1653
1654     /* Add increment. */
1655     if (txn->inc_table && any_updates) {
1656         struct json *op;
1657
1658         txn->inc_index = operations->u.array.n - 1;
1659
1660         op = json_object_create();
1661         json_object_put_string(op, "op", "mutate");
1662         json_object_put_string(op, "table", txn->inc_table);
1663         json_object_put(op, "where",
1664                         substitute_uuids(where_uuid_equals(&txn->inc_row),
1665                                          txn));
1666         json_object_put(op, "mutations",
1667                         json_array_create_1(
1668                             json_array_create_3(
1669                                 json_string_create(txn->inc_column),
1670                                 json_string_create("+="),
1671                                 json_integer_create(1))));
1672         json_array_add(operations, op);
1673
1674         op = json_object_create();
1675         json_object_put_string(op, "op", "select");
1676         json_object_put_string(op, "table", txn->inc_table);
1677         json_object_put(op, "where",
1678                         substitute_uuids(where_uuid_equals(&txn->inc_row),
1679                                          txn));
1680         json_object_put(op, "columns",
1681                         json_array_create_1(json_string_create(
1682                                                 txn->inc_column)));
1683         json_array_add(operations, op);
1684     }
1685
1686     if (txn->comment.length) {
1687         struct json *op = json_object_create();
1688         json_object_put_string(op, "op", "comment");
1689         json_object_put_string(op, "comment", ds_cstr(&txn->comment));
1690         json_array_add(operations, op);
1691     }
1692
1693     if (txn->dry_run) {
1694         struct json *op = json_object_create();
1695         json_object_put_string(op, "op", "abort");
1696         json_array_add(operations, op);
1697     }
1698
1699     if (!any_updates) {
1700         txn->status = TXN_UNCHANGED;
1701         json_destroy(operations);
1702     } else if (!jsonrpc_session_send(
1703                    txn->idl->session,
1704                    jsonrpc_create_request(
1705                        "transact", operations, &txn->request_id))) {
1706         hmap_insert(&txn->idl->outstanding_txns, &txn->hmap_node,
1707                     json_hash(txn->request_id, 0));
1708         txn->status = TXN_INCOMPLETE;
1709     } else {
1710         txn->status = TXN_TRY_AGAIN;
1711     }
1712
1713     ovsdb_idl_txn_disassemble(txn);
1714     return txn->status;
1715 }
1716
1717 /* Attempts to commit 'txn', blocking until the commit either succeeds or
1718  * fails.  Returns the final commit status, which may be any TXN_* value other
1719  * than TXN_INCOMPLETE.
1720  *
1721  * This function calls ovsdb_idl_run() on 'txn''s IDL, so it may cause the
1722  * return value of ovsdb_idl_get_seqno() to change. */
1723 enum ovsdb_idl_txn_status
1724 ovsdb_idl_txn_commit_block(struct ovsdb_idl_txn *txn)
1725 {
1726     enum ovsdb_idl_txn_status status;
1727
1728     fatal_signal_run();
1729     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
1730         ovsdb_idl_run(txn->idl);
1731         ovsdb_idl_wait(txn->idl);
1732         ovsdb_idl_txn_wait(txn);
1733         poll_block();
1734     }
1735     return status;
1736 }
1737
1738 /* Returns the final (incremented) value of the column in 'txn' that was set to
1739  * be incremented by ovsdb_idl_txn_increment().  'txn' must have committed
1740  * successfully. */
1741 int64_t
1742 ovsdb_idl_txn_get_increment_new_value(const struct ovsdb_idl_txn *txn)
1743 {
1744     ovs_assert(txn->status == TXN_SUCCESS);
1745     return txn->inc_new_value;
1746 }
1747
1748 /* Aborts 'txn' without sending it to the database server.  This is effective
1749  * only if ovsdb_idl_txn_commit() has not yet been called for 'txn'.
1750  * Otherwise, it has no effect.
1751  *
1752  * Aborting a transaction doesn't free its memory.  Use
1753  * ovsdb_idl_txn_destroy() to do that. */
1754 void
1755 ovsdb_idl_txn_abort(struct ovsdb_idl_txn *txn)
1756 {
1757     ovsdb_idl_txn_disassemble(txn);
1758     if (txn->status == TXN_UNCOMMITTED || txn->status == TXN_INCOMPLETE) {
1759         txn->status = TXN_ABORTED;
1760     }
1761 }
1762
1763 /* Returns a string that reports the error status for 'txn'.  The caller must
1764  * not modify or free the returned string.  A call to ovsdb_idl_txn_destroy()
1765  * for 'txn' may free the returned string.
1766  *
1767  * The return value is ordinarily one of the strings that
1768  * ovsdb_idl_txn_status_to_string() would return, but if the transaction failed
1769  * due to an error reported by the database server, the return value is that
1770  * error. */
1771 const char *
1772 ovsdb_idl_txn_get_error(const struct ovsdb_idl_txn *txn)
1773 {
1774     if (txn->status != TXN_ERROR) {
1775         return ovsdb_idl_txn_status_to_string(txn->status);
1776     } else if (txn->error) {
1777         return txn->error;
1778     } else {
1779         return "no error details available";
1780     }
1781 }
1782
1783 static void
1784 ovsdb_idl_txn_set_error_json(struct ovsdb_idl_txn *txn,
1785                              const struct json *json)
1786 {
1787     if (txn->error == NULL) {
1788         txn->error = json_to_string(json, JSSF_SORT);
1789     }
1790 }
1791
1792 /* For transaction 'txn' that completed successfully, finds and returns the
1793  * permanent UUID that the database assigned to a newly inserted row, given the
1794  * 'uuid' that ovsdb_idl_txn_insert() assigned locally to that row.
1795  *
1796  * Returns NULL if 'uuid' is not a UUID assigned by ovsdb_idl_txn_insert() or
1797  * if it was assigned by that function and then deleted by
1798  * ovsdb_idl_txn_delete() within the same transaction.  (Rows that are inserted
1799  * and then deleted within a single transaction are never sent to the database
1800  * server, so it never assigns them a permanent UUID.) */
1801 const struct uuid *
1802 ovsdb_idl_txn_get_insert_uuid(const struct ovsdb_idl_txn *txn,
1803                               const struct uuid *uuid)
1804 {
1805     const struct ovsdb_idl_txn_insert *insert;
1806
1807     ovs_assert(txn->status == TXN_SUCCESS || txn->status == TXN_UNCHANGED);
1808     HMAP_FOR_EACH_IN_BUCKET (insert, hmap_node,
1809                              uuid_hash(uuid), &txn->inserted_rows) {
1810         if (uuid_equals(uuid, &insert->dummy)) {
1811             return &insert->real;
1812         }
1813     }
1814     return NULL;
1815 }
1816
1817 static void
1818 ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1819                        enum ovsdb_idl_txn_status status)
1820 {
1821     txn->status = status;
1822     hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1823 }
1824
1825 /* Writes 'datum' to the specified 'column' in 'row_'.  Updates both 'row_'
1826  * itself and the structs derived from it (e.g. the "struct ovsrec_*", for
1827  * ovs-vswitchd).
1828  *
1829  * 'datum' must have the correct type for its column.  The IDL does not check
1830  * that it meets schema constraints, but ovsdb-server will do so at commit time
1831  * so it had better be correct.
1832  *
1833  * A transaction must be in progress.  Replication of 'column' must not have
1834  * been disabled (by calling ovsdb_idl_omit()).
1835  *
1836  * Usually this function is used indirectly through one of the "set" functions
1837  * generated by ovsdb-idlc.
1838  *
1839  * Takes ownership of what 'datum' points to (and in some cases destroys that
1840  * data before returning) but makes a copy of 'datum' itself.  (Commonly
1841  * 'datum' is on the caller's stack.) */
1842 static void
1843 ovsdb_idl_txn_write__(const struct ovsdb_idl_row *row_,
1844                       const struct ovsdb_idl_column *column,
1845                       struct ovsdb_datum *datum, bool owns_datum)
1846 {
1847     struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
1848     const struct ovsdb_idl_table_class *class;
1849     size_t column_idx;
1850     bool write_only;
1851
1852     if (ovsdb_idl_row_is_synthetic(row)) {
1853         goto discard_datum;
1854     }
1855
1856     class = row->table->class;
1857     column_idx = column - class->columns;
1858     write_only = row->table->modes[column_idx] == OVSDB_IDL_MONITOR;
1859
1860     ovs_assert(row->new != NULL);
1861     ovs_assert(column_idx < class->n_columns);
1862     ovs_assert(row->old == NULL ||
1863                row->table->modes[column_idx] & OVSDB_IDL_MONITOR);
1864
1865     if (row->table->idl->verify_write_only && !write_only) {
1866         VLOG_ERR("Bug: Attempt to write to a read/write column (%s:%s) when"
1867                  " explicitly configured not to.", class->name, column->name);
1868         goto discard_datum;
1869     }
1870
1871     /* If this is a write-only column and the datum being written is the same
1872      * as the one already there, just skip the update entirely.  This is worth
1873      * optimizing because we have a lot of columns that get periodically
1874      * refreshed into the database but don't actually change that often.
1875      *
1876      * We don't do this for read/write columns because that would break
1877      * atomicity of transactions--some other client might have written a
1878      * different value in that column since we read it.  (But if a whole
1879      * transaction only does writes of existing values, without making any real
1880      * changes, we will drop the whole transaction later in
1881      * ovsdb_idl_txn_commit().) */
1882     if (write_only && ovsdb_datum_equals(ovsdb_idl_read(row, column),
1883                                          datum, &column->type)) {
1884         goto discard_datum;
1885     }
1886
1887     if (hmap_node_is_null(&row->txn_node)) {
1888         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1889                     uuid_hash(&row->uuid));
1890     }
1891     if (row->old == row->new) {
1892         row->new = xmalloc(class->n_columns * sizeof *row->new);
1893     }
1894     if (!row->written) {
1895         row->written = bitmap_allocate(class->n_columns);
1896     }
1897     if (bitmap_is_set(row->written, column_idx)) {
1898         ovsdb_datum_destroy(&row->new[column_idx], &column->type);
1899     } else {
1900         bitmap_set1(row->written, column_idx);
1901     }
1902     if (owns_datum) {
1903         row->new[column_idx] = *datum;
1904     } else {
1905         ovsdb_datum_clone(&row->new[column_idx], datum, &column->type);
1906     }
1907     (column->unparse)(row);
1908     (column->parse)(row, &row->new[column_idx]);
1909     return;
1910
1911 discard_datum:
1912     if (owns_datum) {
1913         ovsdb_datum_destroy(datum, &column->type);
1914     }
1915 }
1916
1917 void
1918 ovsdb_idl_txn_write(const struct ovsdb_idl_row *row,
1919                     const struct ovsdb_idl_column *column,
1920                     struct ovsdb_datum *datum)
1921 {
1922     ovsdb_idl_txn_write__(row, column, datum, true);
1923 }
1924
1925 void
1926 ovsdb_idl_txn_write_clone(const struct ovsdb_idl_row *row,
1927                           const struct ovsdb_idl_column *column,
1928                           const struct ovsdb_datum *datum)
1929 {
1930     ovsdb_idl_txn_write__(row, column,
1931                           CONST_CAST(struct ovsdb_datum *, datum), false);
1932 }
1933
1934 /* Causes the original contents of 'column' in 'row_' to be verified as a
1935  * prerequisite to completing the transaction.  That is, if 'column' in 'row_'
1936  * changed (or if 'row_' was deleted) between the time that the IDL originally
1937  * read its contents and the time that the transaction commits, then the
1938  * transaction aborts and ovsdb_idl_txn_commit() returns TXN_AGAIN_WAIT or
1939  * TXN_AGAIN_NOW (depending on whether the database change has already been
1940  * received).
1941  *
1942  * The intention is that, to ensure that no transaction commits based on dirty
1943  * reads, an application should call ovsdb_idl_txn_verify() on each data item
1944  * read as part of a read-modify-write operation.
1945  *
1946  * In some cases ovsdb_idl_txn_verify() reduces to a no-op, because the current
1947  * value of 'column' is already known:
1948  *
1949  *   - If 'row_' is a row created by the current transaction (returned by
1950  *     ovsdb_idl_txn_insert()).
1951  *
1952  *   - If 'column' has already been modified (with ovsdb_idl_txn_write())
1953  *     within the current transaction.
1954  *
1955  * Because of the latter property, always call ovsdb_idl_txn_verify() *before*
1956  * ovsdb_idl_txn_write() for a given read-modify-write.
1957  *
1958  * A transaction must be in progress.
1959  *
1960  * Usually this function is used indirectly through one of the "verify"
1961  * functions generated by ovsdb-idlc. */
1962 void
1963 ovsdb_idl_txn_verify(const struct ovsdb_idl_row *row_,
1964                      const struct ovsdb_idl_column *column)
1965 {
1966     struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
1967     const struct ovsdb_idl_table_class *class;
1968     size_t column_idx;
1969
1970     if (ovsdb_idl_row_is_synthetic(row)) {
1971         return;
1972     }
1973
1974     class = row->table->class;
1975     column_idx = column - class->columns;
1976
1977     ovs_assert(row->new != NULL);
1978     ovs_assert(row->old == NULL ||
1979                row->table->modes[column_idx] & OVSDB_IDL_MONITOR);
1980     if (!row->old
1981         || (row->written && bitmap_is_set(row->written, column_idx))) {
1982         return;
1983     }
1984
1985     if (hmap_node_is_null(&row->txn_node)) {
1986         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1987                     uuid_hash(&row->uuid));
1988     }
1989     if (!row->prereqs) {
1990         row->prereqs = bitmap_allocate(class->n_columns);
1991     }
1992     bitmap_set1(row->prereqs, column_idx);
1993 }
1994
1995 /* Deletes 'row_' from its table.  May free 'row_', so it must not be
1996  * accessed afterward.
1997  *
1998  * A transaction must be in progress.
1999  *
2000  * Usually this function is used indirectly through one of the "delete"
2001  * functions generated by ovsdb-idlc. */
2002 void
2003 ovsdb_idl_txn_delete(const struct ovsdb_idl_row *row_)
2004 {
2005     struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
2006
2007     if (ovsdb_idl_row_is_synthetic(row)) {
2008         return;
2009     }
2010
2011     ovs_assert(row->new != NULL);
2012     if (!row->old) {
2013         ovsdb_idl_row_unparse(row);
2014         ovsdb_idl_row_clear_new(row);
2015         ovs_assert(!row->prereqs);
2016         hmap_remove(&row->table->rows, &row->hmap_node);
2017         hmap_remove(&row->table->idl->txn->txn_rows, &row->txn_node);
2018         free(row);
2019         return;
2020     }
2021     if (hmap_node_is_null(&row->txn_node)) {
2022         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
2023                     uuid_hash(&row->uuid));
2024     }
2025     ovsdb_idl_row_clear_new(row);
2026     row->new = NULL;
2027 }
2028
2029 /* Inserts and returns a new row in the table with the specified 'class' in the
2030  * database with open transaction 'txn'.
2031  *
2032  * The new row is assigned a provisional UUID.  If 'uuid' is null then one is
2033  * randomly generated; otherwise 'uuid' should specify a randomly generated
2034  * UUID not otherwise in use.  ovsdb-server will assign a different UUID when
2035  * 'txn' is committed, but the IDL will replace any uses of the provisional
2036  * UUID in the data to be to be committed by the UUID assigned by
2037  * ovsdb-server.
2038  *
2039  * Usually this function is used indirectly through one of the "insert"
2040  * functions generated by ovsdb-idlc. */
2041 const struct ovsdb_idl_row *
2042 ovsdb_idl_txn_insert(struct ovsdb_idl_txn *txn,
2043                      const struct ovsdb_idl_table_class *class,
2044                      const struct uuid *uuid)
2045 {
2046     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(class);
2047
2048     if (uuid) {
2049         ovs_assert(!ovsdb_idl_txn_get_row(txn, uuid));
2050         row->uuid = *uuid;
2051     } else {
2052         uuid_generate(&row->uuid);
2053     }
2054
2055     row->table = ovsdb_idl_table_from_class(txn->idl, class);
2056     row->new = xmalloc(class->n_columns * sizeof *row->new);
2057     hmap_insert(&row->table->rows, &row->hmap_node, uuid_hash(&row->uuid));
2058     hmap_insert(&txn->txn_rows, &row->txn_node, uuid_hash(&row->uuid));
2059     return row;
2060 }
2061
2062 static void
2063 ovsdb_idl_txn_abort_all(struct ovsdb_idl *idl)
2064 {
2065     struct ovsdb_idl_txn *txn;
2066
2067     HMAP_FOR_EACH (txn, hmap_node, &idl->outstanding_txns) {
2068         ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
2069     }
2070 }
2071
2072 static struct ovsdb_idl_txn *
2073 ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
2074 {
2075     struct ovsdb_idl_txn *txn;
2076
2077     HMAP_FOR_EACH_WITH_HASH (txn, hmap_node,
2078                              json_hash(id, 0), &idl->outstanding_txns) {
2079         if (json_equal(id, txn->request_id)) {
2080             return txn;
2081         }
2082     }
2083     return NULL;
2084 }
2085
2086 static bool
2087 check_json_type(const struct json *json, enum json_type type, const char *name)
2088 {
2089     if (!json) {
2090         VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
2091         return false;
2092     } else if (json->type != type) {
2093         VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
2094                      name, json_type_to_string(json->type),
2095                      json_type_to_string(type));
2096         return false;
2097     } else {
2098         return true;
2099     }
2100 }
2101
2102 static bool
2103 ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
2104                                 const struct json_array *results)
2105 {
2106     struct json *count, *rows, *row, *column;
2107     struct shash *mutate, *select;
2108
2109     if (txn->inc_index + 2 > results->n) {
2110         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
2111                      "for increment (has %zu, needs %u)",
2112                      results->n, txn->inc_index + 2);
2113         return false;
2114     }
2115
2116     /* We know that this is a JSON object because the loop in
2117      * ovsdb_idl_txn_process_reply() checked. */
2118     mutate = json_object(results->elems[txn->inc_index]);
2119     count = shash_find_data(mutate, "count");
2120     if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
2121         return false;
2122     }
2123     if (count->u.integer != 1) {
2124         VLOG_WARN_RL(&syntax_rl,
2125                      "\"mutate\" reply \"count\" is %lld instead of 1",
2126                      count->u.integer);
2127         return false;
2128     }
2129
2130     select = json_object(results->elems[txn->inc_index + 1]);
2131     rows = shash_find_data(select, "rows");
2132     if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
2133         return false;
2134     }
2135     if (rows->u.array.n != 1) {
2136         VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %zu elements "
2137                      "instead of 1",
2138                      rows->u.array.n);
2139         return false;
2140     }
2141     row = rows->u.array.elems[0];
2142     if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
2143         return false;
2144     }
2145     column = shash_find_data(json_object(row), txn->inc_column);
2146     if (!check_json_type(column, JSON_INTEGER,
2147                          "\"select\" reply inc column")) {
2148         return false;
2149     }
2150     txn->inc_new_value = column->u.integer;
2151     return true;
2152 }
2153
2154 static bool
2155 ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
2156                                    const struct json_array *results)
2157 {
2158     static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
2159     struct ovsdb_error *error;
2160     struct json *json_uuid;
2161     union ovsdb_atom uuid;
2162     struct shash *reply;
2163
2164     if (insert->op_index >= results->n) {
2165         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
2166                      "for insert (has %zu, needs %u)",
2167                      results->n, insert->op_index);
2168         return false;
2169     }
2170
2171     /* We know that this is a JSON object because the loop in
2172      * ovsdb_idl_txn_process_reply() checked. */
2173     reply = json_object(results->elems[insert->op_index]);
2174     json_uuid = shash_find_data(reply, "uuid");
2175     if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
2176         return false;
2177     }
2178
2179     error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
2180     if (error) {
2181         char *s = ovsdb_error_to_string(error);
2182         VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
2183                      "UUID: %s", s);
2184         free(s);
2185         ovsdb_error_destroy(error);
2186         return false;
2187     }
2188
2189     insert->real = uuid.uuid;
2190
2191     return true;
2192 }
2193
2194 static bool
2195 ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
2196                             const struct jsonrpc_msg *msg)
2197 {
2198     struct ovsdb_idl_txn *txn;
2199     enum ovsdb_idl_txn_status status;
2200
2201     txn = ovsdb_idl_txn_find(idl, msg->id);
2202     if (!txn) {
2203         return false;
2204     }
2205
2206     if (msg->type == JSONRPC_ERROR) {
2207         status = TXN_ERROR;
2208     } else if (msg->result->type != JSON_ARRAY) {
2209         VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
2210         status = TXN_ERROR;
2211     } else {
2212         struct json_array *ops = &msg->result->u.array;
2213         int hard_errors = 0;
2214         int soft_errors = 0;
2215         int lock_errors = 0;
2216         size_t i;
2217
2218         for (i = 0; i < ops->n; i++) {
2219             struct json *op = ops->elems[i];
2220
2221             if (op->type == JSON_NULL) {
2222                 /* This isn't an error in itself but indicates that some prior
2223                  * operation failed, so make sure that we know about it. */
2224                 soft_errors++;
2225             } else if (op->type == JSON_OBJECT) {
2226                 struct json *error;
2227
2228                 error = shash_find_data(json_object(op), "error");
2229                 if (error) {
2230                     if (error->type == JSON_STRING) {
2231                         if (!strcmp(error->u.string, "timed out")) {
2232                             soft_errors++;
2233                         } else if (!strcmp(error->u.string, "not owner")) {
2234                             lock_errors++;
2235                         } else if (strcmp(error->u.string, "aborted")) {
2236                             hard_errors++;
2237                             ovsdb_idl_txn_set_error_json(txn, op);
2238                         }
2239                     } else {
2240                         hard_errors++;
2241                         ovsdb_idl_txn_set_error_json(txn, op);
2242                         VLOG_WARN_RL(&syntax_rl,
2243                                      "\"error\" in reply is not JSON string");
2244                     }
2245                 }
2246             } else {
2247                 hard_errors++;
2248                 ovsdb_idl_txn_set_error_json(txn, op);
2249                 VLOG_WARN_RL(&syntax_rl,
2250                              "operation reply is not JSON null or object");
2251             }
2252         }
2253
2254         if (!soft_errors && !hard_errors && !lock_errors) {
2255             struct ovsdb_idl_txn_insert *insert;
2256
2257             if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
2258                 hard_errors++;
2259             }
2260
2261             HMAP_FOR_EACH (insert, hmap_node, &txn->inserted_rows) {
2262                 if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
2263                     hard_errors++;
2264                 }
2265             }
2266         }
2267
2268         status = (hard_errors ? TXN_ERROR
2269                   : lock_errors ? TXN_NOT_LOCKED
2270                   : soft_errors ? TXN_TRY_AGAIN
2271                   : TXN_SUCCESS);
2272     }
2273
2274     ovsdb_idl_txn_complete(txn, status);
2275     return true;
2276 }
2277
2278 /* Returns the transaction currently active for 'row''s IDL.  A transaction
2279  * must currently be active. */
2280 struct ovsdb_idl_txn *
2281 ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
2282 {
2283     struct ovsdb_idl_txn *txn = row->table->idl->txn;
2284     ovs_assert(txn != NULL);
2285     return txn;
2286 }
2287
2288 /* Returns the IDL on which 'txn' acts. */
2289 struct ovsdb_idl *
2290 ovsdb_idl_txn_get_idl (struct ovsdb_idl_txn *txn)
2291 {
2292     return txn->idl;
2293 }
2294 \f
2295 /* If 'lock_name' is nonnull, configures 'idl' to obtain the named lock from
2296  * the database server and to avoid modifying the database when the lock cannot
2297  * be acquired (that is, when another client has the same lock).
2298  *
2299  * If 'lock_name' is NULL, drops the locking requirement and releases the
2300  * lock. */
2301 void
2302 ovsdb_idl_set_lock(struct ovsdb_idl *idl, const char *lock_name)
2303 {
2304     ovs_assert(!idl->txn);
2305     ovs_assert(hmap_is_empty(&idl->outstanding_txns));
2306
2307     if (idl->lock_name && (!lock_name || strcmp(lock_name, idl->lock_name))) {
2308         /* Release previous lock. */
2309         ovsdb_idl_send_unlock_request(idl);
2310         free(idl->lock_name);
2311         idl->lock_name = NULL;
2312         idl->is_lock_contended = false;
2313     }
2314
2315     if (lock_name && !idl->lock_name) {
2316         /* Acquire new lock. */
2317         idl->lock_name = xstrdup(lock_name);
2318         ovsdb_idl_send_lock_request(idl);
2319     }
2320 }
2321
2322 /* Returns true if 'idl' is configured to obtain a lock and owns that lock.
2323  *
2324  * Locking and unlocking happens asynchronously from the database client's
2325  * point of view, so the information is only useful for optimization (e.g. if
2326  * the client doesn't have the lock then there's no point in trying to write to
2327  * the database). */
2328 bool
2329 ovsdb_idl_has_lock(const struct ovsdb_idl *idl)
2330 {
2331     return idl->has_lock;
2332 }
2333
2334 /* Returns true if 'idl' is configured to obtain a lock but the database server
2335  * has indicated that some other client already owns the requested lock. */
2336 bool
2337 ovsdb_idl_is_lock_contended(const struct ovsdb_idl *idl)
2338 {
2339     return idl->is_lock_contended;
2340 }
2341
2342 static void
2343 ovsdb_idl_update_has_lock(struct ovsdb_idl *idl, bool new_has_lock)
2344 {
2345     if (new_has_lock && !idl->has_lock) {
2346         if (!idl->monitor_request_id) {
2347             idl->change_seqno++;
2348         } else {
2349             /* We're waiting for a monitor reply, so don't signal that the
2350              * database changed.  The monitor reply will increment change_seqno
2351              * anyhow. */
2352         }
2353         idl->is_lock_contended = false;
2354     }
2355     idl->has_lock = new_has_lock;
2356 }
2357
2358 static void
2359 ovsdb_idl_send_lock_request__(struct ovsdb_idl *idl, const char *method,
2360                               struct json **idp)
2361 {
2362     ovsdb_idl_update_has_lock(idl, false);
2363
2364     json_destroy(idl->lock_request_id);
2365     idl->lock_request_id = NULL;
2366
2367     if (jsonrpc_session_is_connected(idl->session)) {
2368         struct json *params;
2369
2370         params = json_array_create_1(json_string_create(idl->lock_name));
2371         jsonrpc_session_send(idl->session,
2372                              jsonrpc_create_request(method, params, idp));
2373     }
2374 }
2375
2376 static void
2377 ovsdb_idl_send_lock_request(struct ovsdb_idl *idl)
2378 {
2379     ovsdb_idl_send_lock_request__(idl, "lock", &idl->lock_request_id);
2380 }
2381
2382 static void
2383 ovsdb_idl_send_unlock_request(struct ovsdb_idl *idl)
2384 {
2385     ovsdb_idl_send_lock_request__(idl, "unlock", NULL);
2386 }
2387
2388 static void
2389 ovsdb_idl_parse_lock_reply(struct ovsdb_idl *idl, const struct json *result)
2390 {
2391     bool got_lock;
2392
2393     json_destroy(idl->lock_request_id);
2394     idl->lock_request_id = NULL;
2395
2396     if (result->type == JSON_OBJECT) {
2397         const struct json *locked;
2398
2399         locked = shash_find_data(json_object(result), "locked");
2400         got_lock = locked && locked->type == JSON_TRUE;
2401     } else {
2402         got_lock = false;
2403     }
2404
2405     ovsdb_idl_update_has_lock(idl, got_lock);
2406     if (!got_lock) {
2407         idl->is_lock_contended = true;
2408     }
2409 }
2410
2411 static void
2412 ovsdb_idl_parse_lock_notify(struct ovsdb_idl *idl,
2413                             const struct json *params,
2414                             bool new_has_lock)
2415 {
2416     if (idl->lock_name
2417         && params->type == JSON_ARRAY
2418         && json_array(params)->n > 0
2419         && json_array(params)->elems[0]->type == JSON_STRING) {
2420         const char *lock_name = json_string(json_array(params)->elems[0]);
2421
2422         if (!strcmp(idl->lock_name, lock_name)) {
2423             ovsdb_idl_update_has_lock(idl, new_has_lock);
2424             if (!new_has_lock) {
2425                 idl->is_lock_contended = true;
2426             }
2427         }
2428     }
2429 }