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