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