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