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