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