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