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