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