ovn-controller: Fix memory leak reported by valgrind.
[cascardo/ovs.git] / lib / ovsdb-idl.c
1 /* Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "ovsdb-idl.h"
19
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <stdlib.h>
24
25 #include "bitmap.h"
26 #include "coverage.h"
27 #include "openvswitch/dynamic-string.h"
28 #include "fatal-signal.h"
29 #include "json.h"
30 #include "jsonrpc.h"
31 #include "ovsdb/ovsdb.h"
32 #include "ovsdb/table.h"
33 #include "ovsdb-data.h"
34 #include "ovsdb-error.h"
35 #include "ovsdb-idl-provider.h"
36 #include "ovsdb-parser.h"
37 #include "poll-loop.h"
38 #include "shash.h"
39 #include "sset.h"
40 #include "util.h"
41 #include "openvswitch/vlog.h"
42
43 VLOG_DEFINE_THIS_MODULE(ovsdb_idl);
44
45 COVERAGE_DEFINE(txn_uncommitted);
46 COVERAGE_DEFINE(txn_unchanged);
47 COVERAGE_DEFINE(txn_incomplete);
48 COVERAGE_DEFINE(txn_aborted);
49 COVERAGE_DEFINE(txn_success);
50 COVERAGE_DEFINE(txn_try_again);
51 COVERAGE_DEFINE(txn_not_locked);
52 COVERAGE_DEFINE(txn_error);
53
54 /* An arc from one idl_row to another.  When row A contains a UUID that
55  * references row B, this is represented by an arc from A (the source) to B
56  * (the destination).
57  *
58  * Arcs from a row to itself are omitted, that is, src and dst are always
59  * different.
60  *
61  * Arcs are never duplicated, that is, even if there are multiple references
62  * from A to B, there is only a single arc from A to B.
63  *
64  * Arcs are directed: an arc from A to B is the converse of an an arc from B to
65  * A.  Both an arc and its converse may both be present, if each row refers
66  * to the other circularly.
67  *
68  * The source and destination row may be in the same table or in different
69  * tables.
70  */
71 struct ovsdb_idl_arc {
72     struct ovs_list src_node;   /* In src->src_arcs list. */
73     struct ovs_list dst_node;   /* In dst->dst_arcs list. */
74     struct ovsdb_idl_row *src;  /* Source row. */
75     struct ovsdb_idl_row *dst;  /* Destination row. */
76 };
77
78 enum ovsdb_idl_state {
79     IDL_S_SCHEMA_REQUESTED,
80     IDL_S_MONITOR_REQUESTED,
81     IDL_S_MONITORING,
82     IDL_S_MONITOR2_REQUESTED,
83     IDL_S_MONITORING2,
84     IDL_S_NO_SCHEMA
85 };
86
87 struct ovsdb_idl {
88     const struct ovsdb_idl_class *class;
89     struct jsonrpc_session *session;
90     struct shash table_by_name;
91     struct ovsdb_idl_table *tables; /* Contains "struct ovsdb_idl_table *"s.*/
92     unsigned int change_seqno;
93     bool verify_write_only;
94
95     /* Session state. */
96     unsigned int state_seqno;
97     enum ovsdb_idl_state state;
98     struct json *request_id;
99     struct json *schema;
100
101     /* Database locking. */
102     char *lock_name;            /* Name of lock we need, NULL if none. */
103     bool has_lock;              /* Has db server told us we have the lock? */
104     bool is_lock_contended;     /* Has db server told us we can't get lock? */
105     struct json *lock_request_id; /* JSON-RPC ID of in-flight lock request. */
106
107     /* Transaction support. */
108     struct ovsdb_idl_txn *txn;
109     struct hmap outstanding_txns;
110 };
111
112 struct ovsdb_idl_txn {
113     struct hmap_node hmap_node;
114     struct json *request_id;
115     struct ovsdb_idl *idl;
116     struct hmap txn_rows;
117     enum ovsdb_idl_txn_status status;
118     char *error;
119     bool dry_run;
120     struct ds comment;
121
122     /* Increments. */
123     const char *inc_table;
124     const char *inc_column;
125     struct uuid inc_row;
126     unsigned int inc_index;
127     int64_t inc_new_value;
128
129     /* Inserted rows. */
130     struct hmap inserted_rows;  /* Contains "struct ovsdb_idl_txn_insert"s. */
131 };
132
133 struct ovsdb_idl_txn_insert {
134     struct hmap_node hmap_node; /* In struct ovsdb_idl_txn's inserted_rows. */
135     struct uuid dummy;          /* Dummy UUID used locally. */
136     int op_index;               /* Index into transaction's operation array. */
137     struct uuid real;           /* Real UUID used by database server. */
138 };
139
140 enum ovsdb_update_version {
141     OVSDB_UPDATE,               /* RFC 7047 "update" method. */
142     OVSDB_UPDATE2               /* "update2" Extension to RFC 7047.
143                                    See ovsdb-server(1) for more information. */
144 };
145
146 /* Name arrays indexed by 'enum ovsdb_update_version'. */
147 static const char *table_updates_names[] = {"table_updates", "table_updates2"};
148 static const char *table_update_names[] = {"table_update", "table_update2"};
149 static const char *row_update_names[] = {"row_update", "row_update2"};
150
151 static struct vlog_rate_limit syntax_rl = VLOG_RATE_LIMIT_INIT(1, 5);
152 static struct vlog_rate_limit semantic_rl = VLOG_RATE_LIMIT_INIT(1, 5);
153
154 static void ovsdb_idl_clear(struct ovsdb_idl *);
155 static void ovsdb_idl_send_schema_request(struct ovsdb_idl *);
156 static void ovsdb_idl_send_monitor_request(struct ovsdb_idl *);
157 static void ovsdb_idl_send_monitor2_request(struct ovsdb_idl *);
158 static void ovsdb_idl_parse_update(struct ovsdb_idl *, const struct json *,
159                                    enum ovsdb_update_version);
160 static struct ovsdb_error *ovsdb_idl_parse_update__(struct ovsdb_idl *,
161                                                     const struct json *,
162                                                     enum ovsdb_update_version);
163 static bool ovsdb_idl_process_update(struct ovsdb_idl_table *,
164                                      const struct uuid *,
165                                      const struct json *old,
166                                      const struct json *new);
167 static bool ovsdb_idl_process_update2(struct ovsdb_idl_table *,
168                                       const struct uuid *,
169                                       const char *operation,
170                                       const struct json *row);
171 static void ovsdb_idl_insert_row(struct ovsdb_idl_row *, const struct json *);
172 static void ovsdb_idl_delete_row(struct ovsdb_idl_row *);
173 static bool ovsdb_idl_modify_row(struct ovsdb_idl_row *, const struct json *);
174 static bool ovsdb_idl_modify_row_by_diff(struct ovsdb_idl_row *,
175                                          const struct json *);
176
177 static bool ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *);
178 static struct ovsdb_idl_row *ovsdb_idl_row_create__(
179     const struct ovsdb_idl_table_class *);
180 static struct ovsdb_idl_row *ovsdb_idl_row_create(struct ovsdb_idl_table *,
181                                                   const struct uuid *);
182 static void ovsdb_idl_row_destroy(struct ovsdb_idl_row *);
183 static void ovsdb_idl_row_destroy_postprocess(struct ovsdb_idl *);
184 static void ovsdb_idl_destroy_all_map_op_lists(struct ovsdb_idl_row *);
185
186 static void ovsdb_idl_row_parse(struct ovsdb_idl_row *);
187 static void ovsdb_idl_row_unparse(struct ovsdb_idl_row *);
188 static void ovsdb_idl_row_clear_old(struct ovsdb_idl_row *);
189 static void ovsdb_idl_row_clear_new(struct ovsdb_idl_row *);
190 static void ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *, bool destroy_dsts);
191
192 static void ovsdb_idl_txn_abort_all(struct ovsdb_idl *);
193 static bool ovsdb_idl_txn_process_reply(struct ovsdb_idl *,
194                                         const struct jsonrpc_msg *msg);
195 static bool ovsdb_idl_txn_extract_mutations(struct ovsdb_idl_row *,
196                                             struct json *);
197 static void ovsdb_idl_txn_add_map_op(struct ovsdb_idl_row *,
198                                      const struct ovsdb_idl_column *,
199                                      struct ovsdb_datum *,
200                                      enum map_op_type);
201
202 static void ovsdb_idl_send_lock_request(struct ovsdb_idl *);
203 static void ovsdb_idl_send_unlock_request(struct ovsdb_idl *);
204 static void ovsdb_idl_parse_lock_reply(struct ovsdb_idl *,
205                                        const struct json *);
206 static void ovsdb_idl_parse_lock_notify(struct ovsdb_idl *,
207                                         const struct json *params,
208                                         bool new_has_lock);
209 static struct ovsdb_idl_table *
210 ovsdb_idl_table_from_class(const struct ovsdb_idl *,
211                            const struct ovsdb_idl_table_class *);
212 static bool ovsdb_idl_track_is_set(struct ovsdb_idl_table *table);
213
214 /* Creates and returns a connection to database 'remote', which should be in a
215  * form acceptable to jsonrpc_session_open().  The connection will maintain an
216  * in-memory replica of the remote database whose schema is described by
217  * 'class'.  (Ordinarily 'class' is compiled from an OVSDB schema automatically
218  * by ovsdb-idlc.)
219  *
220  * Passes 'retry' to jsonrpc_session_open().  See that function for
221  * documentation.
222  *
223  * If 'monitor_everything_by_default' is true, then everything in the remote
224  * database will be replicated by default.  ovsdb_idl_omit() and
225  * ovsdb_idl_omit_alert() may be used to selectively drop some columns from
226  * monitoring.
227  *
228  * If 'monitor_everything_by_default' is false, then no columns or tables will
229  * be replicated by default.  ovsdb_idl_add_column() and ovsdb_idl_add_table()
230  * must be used to choose some columns or tables to replicate.
231  */
232 struct ovsdb_idl *
233 ovsdb_idl_create(const char *remote, const struct ovsdb_idl_class *class,
234                  bool monitor_everything_by_default, bool retry)
235 {
236     struct ovsdb_idl *idl;
237     uint8_t default_mode;
238     size_t i;
239
240     default_mode = (monitor_everything_by_default
241                     ? OVSDB_IDL_MONITOR | OVSDB_IDL_ALERT
242                     : 0);
243
244     idl = xzalloc(sizeof *idl);
245     idl->class = class;
246     idl->session = jsonrpc_session_open(remote, retry);
247     shash_init(&idl->table_by_name);
248     idl->tables = xmalloc(class->n_tables * sizeof *idl->tables);
249     for (i = 0; i < class->n_tables; i++) {
250         const struct ovsdb_idl_table_class *tc = &class->tables[i];
251         struct ovsdb_idl_table *table = &idl->tables[i];
252         size_t j;
253
254         shash_add_assert(&idl->table_by_name, tc->name, table);
255         table->class = tc;
256         table->modes = xmalloc(tc->n_columns);
257         memset(table->modes, default_mode, tc->n_columns);
258         table->need_table = false;
259         shash_init(&table->columns);
260         for (j = 0; j < tc->n_columns; j++) {
261             const struct ovsdb_idl_column *column = &tc->columns[j];
262
263             shash_add_assert(&table->columns, column->name, column);
264         }
265         hmap_init(&table->rows);
266         ovs_list_init(&table->track_list);
267         table->change_seqno[OVSDB_IDL_CHANGE_INSERT]
268             = table->change_seqno[OVSDB_IDL_CHANGE_MODIFY]
269             = table->change_seqno[OVSDB_IDL_CHANGE_DELETE] = 0;
270         table->idl = idl;
271     }
272
273     idl->state_seqno = UINT_MAX;
274     idl->request_id = NULL;
275     idl->schema = NULL;
276
277     hmap_init(&idl->outstanding_txns);
278
279     return idl;
280 }
281
282 /* Changes the remote and creates a new session. */
283 void
284 ovsdb_idl_set_remote(struct ovsdb_idl *idl, const char *remote,
285                      bool retry)
286 {
287     if (idl) {
288         ovs_assert(!idl->txn);
289         jsonrpc_session_close(idl->session);
290         idl->session = jsonrpc_session_open(remote, retry);
291         idl->state_seqno = UINT_MAX;
292     }
293 }
294
295 /* Destroys 'idl' and all of the data structures that it manages. */
296 void
297 ovsdb_idl_destroy(struct ovsdb_idl *idl)
298 {
299     if (idl) {
300         size_t i;
301
302         ovs_assert(!idl->txn);
303         ovsdb_idl_clear(idl);
304         jsonrpc_session_close(idl->session);
305
306         for (i = 0; i < idl->class->n_tables; i++) {
307             struct ovsdb_idl_table *table = &idl->tables[i];
308             shash_destroy(&table->columns);
309             hmap_destroy(&table->rows);
310             free(table->modes);
311         }
312         shash_destroy(&idl->table_by_name);
313         free(idl->tables);
314         json_destroy(idl->request_id);
315         free(idl->lock_name);
316         json_destroy(idl->lock_request_id);
317         json_destroy(idl->schema);
318         hmap_destroy(&idl->outstanding_txns);
319         free(idl);
320     }
321 }
322
323 static void
324 ovsdb_idl_clear(struct ovsdb_idl *idl)
325 {
326     bool changed = false;
327     size_t i;
328
329     for (i = 0; i < idl->class->n_tables; i++) {
330         struct ovsdb_idl_table *table = &idl->tables[i];
331         struct ovsdb_idl_row *row, *next_row;
332
333         if (hmap_is_empty(&table->rows)) {
334             continue;
335         }
336
337         changed = true;
338         HMAP_FOR_EACH_SAFE (row, next_row, hmap_node, &table->rows) {
339             struct ovsdb_idl_arc *arc, *next_arc;
340
341             if (!ovsdb_idl_row_is_orphan(row)) {
342                 ovsdb_idl_row_unparse(row);
343             }
344             LIST_FOR_EACH_SAFE (arc, next_arc, src_node, &row->src_arcs) {
345                 free(arc);
346             }
347             /* No need to do anything with dst_arcs: some node has those arcs
348              * as forward arcs and will destroy them itself. */
349
350             if (!ovs_list_is_empty(&row->track_node)) {
351                 ovs_list_remove(&row->track_node);
352             }
353
354             ovsdb_idl_row_destroy(row);
355         }
356     }
357
358     ovsdb_idl_track_clear(idl);
359
360     if (changed) {
361         idl->change_seqno++;
362     }
363 }
364
365 /* Processes a batch of messages from the database server on 'idl'.  This may
366  * cause the IDL's contents to change.  The client may check for that with
367  * ovsdb_idl_get_seqno(). */
368 void
369 ovsdb_idl_run(struct ovsdb_idl *idl)
370 {
371     int i;
372
373     ovs_assert(!idl->txn);
374     jsonrpc_session_run(idl->session);
375     for (i = 0; jsonrpc_session_is_connected(idl->session) && i < 50; i++) {
376         struct jsonrpc_msg *msg;
377         unsigned int seqno;
378
379         seqno = jsonrpc_session_get_seqno(idl->session);
380         if (idl->state_seqno != seqno) {
381             idl->state_seqno = seqno;
382             json_destroy(idl->request_id);
383             idl->request_id = NULL;
384             ovsdb_idl_txn_abort_all(idl);
385
386             ovsdb_idl_send_schema_request(idl);
387             idl->state = IDL_S_SCHEMA_REQUESTED;
388             if (idl->lock_name) {
389                 ovsdb_idl_send_lock_request(idl);
390             }
391         }
392
393         msg = jsonrpc_session_recv(idl->session);
394         if (!msg) {
395             break;
396         }
397
398         if (msg->type == JSONRPC_NOTIFY
399             && !strcmp(msg->method, "update2")
400             && msg->params->type == JSON_ARRAY
401             && msg->params->u.array.n == 2
402             && msg->params->u.array.elems[0]->type == JSON_NULL) {
403             /* Database contents changed. */
404             ovsdb_idl_parse_update(idl, msg->params->u.array.elems[1],
405                                    OVSDB_UPDATE2);
406         } else if (msg->type == JSONRPC_REPLY
407                    && idl->request_id
408                    && json_equal(idl->request_id, msg->id)) {
409             json_destroy(idl->request_id);
410             idl->request_id = NULL;
411
412             switch (idl->state) {
413             case IDL_S_SCHEMA_REQUESTED:
414                 /* Reply to our "get_schema" request. */
415                 idl->schema = json_clone(msg->result);
416                 ovsdb_idl_send_monitor2_request(idl);
417                 idl->state = IDL_S_MONITOR2_REQUESTED;
418                 break;
419
420             case IDL_S_MONITOR_REQUESTED:
421             case IDL_S_MONITOR2_REQUESTED:
422                 /* Reply to our "monitor" or "monitor2" request. */
423                 idl->change_seqno++;
424                 ovsdb_idl_clear(idl);
425                 if (idl->state == IDL_S_MONITOR_REQUESTED) {
426                     idl->state = IDL_S_MONITORING;
427                     ovsdb_idl_parse_update(idl, msg->result, OVSDB_UPDATE);
428                 } else { /* IDL_S_MONITOR2_REQUESTED. */
429                     idl->state = IDL_S_MONITORING2;
430                     ovsdb_idl_parse_update(idl, msg->result, OVSDB_UPDATE2);
431                 }
432
433                 /* Schema is not useful after monitor request is accepted
434                  * by the server.  */
435                 json_destroy(idl->schema);
436                 idl->schema = NULL;
437                 break;
438
439             case IDL_S_MONITORING:
440             case IDL_S_MONITORING2:
441             case IDL_S_NO_SCHEMA:
442             default:
443                 OVS_NOT_REACHED();
444             }
445         } else if (msg->type == JSONRPC_NOTIFY
446             && !strcmp(msg->method, "update")
447             && msg->params->type == JSON_ARRAY
448             && msg->params->u.array.n == 2
449             && msg->params->u.array.elems[0]->type == JSON_NULL) {
450             /* Database contents changed. */
451             ovsdb_idl_parse_update(idl, msg->params->u.array.elems[1],
452                                    OVSDB_UPDATE);
453         } else if (msg->type == JSONRPC_REPLY
454                    && idl->lock_request_id
455                    && json_equal(idl->lock_request_id, msg->id)) {
456             /* Reply to our "lock" request. */
457             ovsdb_idl_parse_lock_reply(idl, msg->result);
458         } else if (msg->type == JSONRPC_NOTIFY
459                    && !strcmp(msg->method, "locked")) {
460             /* We got our lock. */
461             ovsdb_idl_parse_lock_notify(idl, msg->params, true);
462         } else if (msg->type == JSONRPC_NOTIFY
463                    && !strcmp(msg->method, "stolen")) {
464             /* Someone else stole our lock. */
465             ovsdb_idl_parse_lock_notify(idl, msg->params, false);
466         } else if (msg->type == JSONRPC_ERROR
467                    && idl->state == IDL_S_MONITOR2_REQUESTED
468                    && idl->request_id
469                    && json_equal(idl->request_id, msg->id)) {
470             if (msg->error && !strcmp(json_string(msg->error),
471                                       "unknown method")) {
472                 /* Fall back to using "monitor" method.  */
473                 json_destroy(idl->request_id);
474                 idl->request_id = NULL;
475                 ovsdb_idl_send_monitor_request(idl);
476                 idl->state = IDL_S_MONITOR_REQUESTED;
477             }
478         } else if (msg->type == JSONRPC_ERROR
479                    && idl->state == IDL_S_SCHEMA_REQUESTED
480                    && idl->request_id
481                    && json_equal(idl->request_id, msg->id)) {
482                 json_destroy(idl->request_id);
483                 idl->request_id = NULL;
484                 VLOG_ERR("%s: requested schema not found",
485                          jsonrpc_session_get_name(idl->session));
486                 idl->state = IDL_S_NO_SCHEMA;
487         } else if ((msg->type == JSONRPC_ERROR
488                     || msg->type == JSONRPC_REPLY)
489                    && ovsdb_idl_txn_process_reply(idl, msg)) {
490             /* ovsdb_idl_txn_process_reply() did everything needful. */
491         } else {
492             /* This can happen if ovsdb_idl_txn_destroy() is called to destroy
493              * a transaction before we receive the reply, so keep the log level
494              * low. */
495             VLOG_DBG("%s: received unexpected %s message",
496                      jsonrpc_session_get_name(idl->session),
497                      jsonrpc_msg_type_to_string(msg->type));
498         }
499         jsonrpc_msg_destroy(msg);
500     }
501     ovsdb_idl_row_destroy_postprocess(idl);
502 }
503
504 /* Arranges for poll_block() to wake up when ovsdb_idl_run() has something to
505  * do or when activity occurs on a transaction on 'idl'. */
506 void
507 ovsdb_idl_wait(struct ovsdb_idl *idl)
508 {
509     jsonrpc_session_wait(idl->session);
510     jsonrpc_session_recv_wait(idl->session);
511 }
512
513 /* Returns a "sequence number" that represents the state of 'idl'.  When
514  * ovsdb_idl_run() changes the database, the sequence number changes.  The
515  * initial fetch of the entire contents of the remote database is considered to
516  * be one kind of change.  Successfully acquiring a lock, if one has been
517  * configured with ovsdb_idl_set_lock(), is also considered to be a change.
518  *
519  * As long as the sequence number does not change, the client may continue to
520  * use any data structures it obtains from 'idl'.  But when it changes, the
521  * client must not access any of these data structures again, because they
522  * could have freed or reused for other purposes.
523  *
524  * The sequence number can occasionally change even if the database does not.
525  * This happens if the connection to the database drops and reconnects, which
526  * causes the database contents to be reloaded even if they didn't change.  (It
527  * could also happen if the database server sends out a "change" that reflects
528  * what the IDL already thought was in the database.  The database server is
529  * not supposed to do that, but bugs could in theory cause it to do so.) */
530 unsigned int
531 ovsdb_idl_get_seqno(const struct ovsdb_idl *idl)
532 {
533     return idl->change_seqno;
534 }
535
536 /* Returns true if 'idl' successfully connected to the remote database and
537  * retrieved its contents (even if the connection subsequently dropped and is
538  * in the process of reconnecting).  If so, then 'idl' contains an atomic
539  * snapshot of the database's contents (but it might be arbitrarily old if the
540  * connection dropped).
541  *
542  * Returns false if 'idl' has never connected or retrieved the database's
543  * contents.  If so, 'idl' is empty. */
544 bool
545 ovsdb_idl_has_ever_connected(const struct ovsdb_idl *idl)
546 {
547     return ovsdb_idl_get_seqno(idl) != 0;
548 }
549
550 /* Reconfigures 'idl' so that it would reconnect to the database, if
551  * connection was dropped. */
552 void
553 ovsdb_idl_enable_reconnect(struct ovsdb_idl *idl)
554 {
555     jsonrpc_session_enable_reconnect(idl->session);
556 }
557
558 /* Forces 'idl' to drop its connection to the database and reconnect.  In the
559  * meantime, the contents of 'idl' will not change. */
560 void
561 ovsdb_idl_force_reconnect(struct ovsdb_idl *idl)
562 {
563     jsonrpc_session_force_reconnect(idl->session);
564 }
565
566 /* Some IDL users should only write to write-only columns.  Furthermore,
567  * writing to a column which is not write-only can cause serious performance
568  * degradations for these users.  This function causes 'idl' to reject writes
569  * to columns which are not marked write only using ovsdb_idl_omit_alert(). */
570 void
571 ovsdb_idl_verify_write_only(struct ovsdb_idl *idl)
572 {
573     idl->verify_write_only = true;
574 }
575
576 /* Returns true if 'idl' is currently connected or trying to connect
577  * and a negative response to a schema request has not been received */
578 bool
579 ovsdb_idl_is_alive(const struct ovsdb_idl *idl)
580 {
581     return jsonrpc_session_is_alive(idl->session) &&
582            idl->state != IDL_S_NO_SCHEMA;
583 }
584
585 /* Returns the last error reported on a connection by 'idl'.  The return value
586  * is 0 only if no connection made by 'idl' has ever encountered an error and
587  * a negative response to a schema request has never been received. See
588  * jsonrpc_get_status() for jsonrpc_session_get_last_error() return value
589  * interpretation. */
590 int
591 ovsdb_idl_get_last_error(const struct ovsdb_idl *idl)
592 {
593     int err;
594
595     err = jsonrpc_session_get_last_error(idl->session);
596
597     if (err) {
598         return err;
599     } else if (idl->state == IDL_S_NO_SCHEMA) {
600         return ENOENT;
601     } else {
602         return 0;
603     }
604 }
605
606 /* Sets the "probe interval" for 'idl->session' to 'probe_interval', in
607  * milliseconds.
608  */
609 void
610 ovsdb_idl_set_probe_interval(const struct ovsdb_idl *idl, int probe_interval)
611 {
612     jsonrpc_session_set_probe_interval(idl->session, probe_interval);
613 }
614 \f
615 static unsigned char *
616 ovsdb_idl_get_mode(struct ovsdb_idl *idl,
617                    const struct ovsdb_idl_column *column)
618 {
619     size_t i;
620
621     ovs_assert(!idl->change_seqno);
622
623     for (i = 0; i < idl->class->n_tables; i++) {
624         const struct ovsdb_idl_table *table = &idl->tables[i];
625         const struct ovsdb_idl_table_class *tc = table->class;
626
627         if (column >= tc->columns && column < &tc->columns[tc->n_columns]) {
628             return &table->modes[column - tc->columns];
629         }
630     }
631
632     OVS_NOT_REACHED();
633 }
634
635 static void
636 add_ref_table(struct ovsdb_idl *idl, const struct ovsdb_base_type *base)
637 {
638     if (base->type == OVSDB_TYPE_UUID && base->u.uuid.refTableName) {
639         struct ovsdb_idl_table *table;
640
641         table = shash_find_data(&idl->table_by_name,
642                                 base->u.uuid.refTableName);
643         if (table) {
644             table->need_table = true;
645         } else {
646             VLOG_WARN("%s IDL class missing referenced table %s",
647                       idl->class->database, base->u.uuid.refTableName);
648         }
649     }
650 }
651
652 /* Turns on OVSDB_IDL_MONITOR and OVSDB_IDL_ALERT for 'column' in 'idl'.  Also
653  * ensures that any tables referenced by 'column' will be replicated, even if
654  * no columns in that table are selected for replication (see
655  * ovsdb_idl_add_table() for more information).
656  *
657  * This function is only useful if 'monitor_everything_by_default' was false in
658  * the call to ovsdb_idl_create().  This function should be called between
659  * ovsdb_idl_create() and the first call to ovsdb_idl_run().
660  */
661 void
662 ovsdb_idl_add_column(struct ovsdb_idl *idl,
663                      const struct ovsdb_idl_column *column)
664 {
665     *ovsdb_idl_get_mode(idl, column) = OVSDB_IDL_MONITOR | OVSDB_IDL_ALERT;
666     add_ref_table(idl, &column->type.key);
667     add_ref_table(idl, &column->type.value);
668 }
669
670 /* Ensures that the table with class 'tc' will be replicated on 'idl' even if
671  * no columns are selected for replication. Just the necessary data for table
672  * references will be replicated (the UUID of the rows, for instance), any
673  * columns not selected for replication will remain unreplicated.
674  * This can be useful because it allows 'idl' to keep track of what rows in the
675  * table actually exist, which in turn allows columns that reference the table
676  * to have accurate contents. (The IDL presents the database with references to
677  * rows that do not exist removed.)
678  *
679  * This function is only useful if 'monitor_everything_by_default' was false in
680  * the call to ovsdb_idl_create().  This function should be called between
681  * ovsdb_idl_create() and the first call to ovsdb_idl_run().
682  */
683 void
684 ovsdb_idl_add_table(struct ovsdb_idl *idl,
685                     const struct ovsdb_idl_table_class *tc)
686 {
687     size_t i;
688
689     for (i = 0; i < idl->class->n_tables; i++) {
690         struct ovsdb_idl_table *table = &idl->tables[i];
691
692         if (table->class == tc) {
693             table->need_table = true;
694             return;
695         }
696     }
697
698     OVS_NOT_REACHED();
699 }
700
701 /* Turns off OVSDB_IDL_ALERT for 'column' in 'idl'.
702  *
703  * This function should be called between ovsdb_idl_create() and the first call
704  * to ovsdb_idl_run().
705  */
706 void
707 ovsdb_idl_omit_alert(struct ovsdb_idl *idl,
708                      const struct ovsdb_idl_column *column)
709 {
710     *ovsdb_idl_get_mode(idl, column) &= ~OVSDB_IDL_ALERT;
711 }
712
713 /* Sets the mode for 'column' in 'idl' to 0.  See the big comment above
714  * OVSDB_IDL_MONITOR for details.
715  *
716  * This function should be called between ovsdb_idl_create() and the first call
717  * to ovsdb_idl_run().
718  */
719 void
720 ovsdb_idl_omit(struct ovsdb_idl *idl, const struct ovsdb_idl_column *column)
721 {
722     *ovsdb_idl_get_mode(idl, column) = 0;
723 }
724
725 /* Returns the most recent IDL change sequence number that caused a
726  * insert, modify or delete update to the table with class 'table_class'.
727  */
728 unsigned int
729 ovsdb_idl_table_get_seqno(const struct ovsdb_idl *idl,
730                           const struct ovsdb_idl_table_class *table_class)
731 {
732     struct ovsdb_idl_table *table
733         = ovsdb_idl_table_from_class(idl, table_class);
734     unsigned int max_seqno = table->change_seqno[OVSDB_IDL_CHANGE_INSERT];
735
736     if (max_seqno < table->change_seqno[OVSDB_IDL_CHANGE_MODIFY]) {
737         max_seqno = table->change_seqno[OVSDB_IDL_CHANGE_MODIFY];
738     }
739     if (max_seqno < table->change_seqno[OVSDB_IDL_CHANGE_DELETE]) {
740         max_seqno = table->change_seqno[OVSDB_IDL_CHANGE_DELETE];
741     }
742     return max_seqno;
743 }
744
745 /* For each row that contains tracked columns, IDL stores the most
746  * recent IDL change sequence numbers associateed with insert, modify
747  * and delete updates to the table.
748  */
749 unsigned int
750 ovsdb_idl_row_get_seqno(const struct ovsdb_idl_row *row,
751                         enum ovsdb_idl_change change)
752 {
753     return row->change_seqno[change];
754 }
755
756 /* Turns on OVSDB_IDL_TRACK for 'column' in 'idl', ensuring that
757  * all rows whose 'column' is modified are traced. Similarly, insert
758  * or delete of rows having 'column' are tracked. Clients are able
759  * to retrive the tracked rows with the ovsdb_idl_track_get_*()
760  * functions.
761  *
762  * This function should be called between ovsdb_idl_create() and
763  * the first call to ovsdb_idl_run(). The column to be tracked
764  * should have OVSDB_IDL_ALERT turned on.
765  */
766 void
767 ovsdb_idl_track_add_column(struct ovsdb_idl *idl,
768                            const struct ovsdb_idl_column *column)
769 {
770     if (!(*ovsdb_idl_get_mode(idl, column) & OVSDB_IDL_ALERT)) {
771         ovsdb_idl_add_column(idl, column);
772     }
773     *ovsdb_idl_get_mode(idl, column) |= OVSDB_IDL_TRACK;
774 }
775
776 void
777 ovsdb_idl_track_add_all(struct ovsdb_idl *idl)
778 {
779     size_t i, j;
780
781     for (i = 0; i < idl->class->n_tables; i++) {
782         const struct ovsdb_idl_table_class *tc = &idl->class->tables[i];
783
784         for (j = 0; j < tc->n_columns; j++) {
785             const struct ovsdb_idl_column *column = &tc->columns[j];
786             ovsdb_idl_track_add_column(idl, column);
787         }
788     }
789 }
790
791 /* Returns true if 'table' has any tracked column. */
792 static bool
793 ovsdb_idl_track_is_set(struct ovsdb_idl_table *table)
794 {
795     size_t i;
796
797     for (i = 0; i < table->class->n_columns; i++) {
798         if (table->modes[i] & OVSDB_IDL_TRACK) {
799             return true;
800         }
801     }
802    return false;
803 }
804
805 /* Returns the first tracked row in table with class 'table_class'
806  * for the specified 'idl'. Returns NULL if there are no tracked rows */
807 const struct ovsdb_idl_row *
808 ovsdb_idl_track_get_first(const struct ovsdb_idl *idl,
809                           const struct ovsdb_idl_table_class *table_class)
810 {
811     struct ovsdb_idl_table *table
812         = ovsdb_idl_table_from_class(idl, table_class);
813
814     if (!ovs_list_is_empty(&table->track_list)) {
815         return CONTAINER_OF(ovs_list_front(&table->track_list), struct ovsdb_idl_row, track_node);
816     }
817     return NULL;
818 }
819
820 /* Returns the next tracked row in table after the specified 'row'
821  * (in no particular order). Returns NULL if there are no tracked rows */
822 const struct ovsdb_idl_row *
823 ovsdb_idl_track_get_next(const struct ovsdb_idl_row *row)
824 {
825     if (row->track_node.next != &row->table->track_list) {
826         return CONTAINER_OF(row->track_node.next, struct ovsdb_idl_row, track_node);
827     }
828
829     return NULL;
830 }
831
832 /* Returns true if a tracked 'column' in 'row' was updated by IDL, false
833  * otherwise. The tracking data is cleared by ovsdb_idl_track_clear()
834  *
835  * Function returns false if 'column' is not tracked (see
836  * ovsdb_idl_track_add_column()).
837  */
838 bool
839 ovsdb_idl_track_is_updated(const struct ovsdb_idl_row *row,
840                            const struct ovsdb_idl_column *column)
841 {
842     const struct ovsdb_idl_table_class *class;
843     size_t column_idx;
844
845     class = row->table->class;
846     column_idx = column - class->columns;
847
848     if (row->updated && bitmap_is_set(row->updated, column_idx)) {
849         return true;
850     } else {
851         return false;
852     }
853 }
854
855 /* Flushes the tracked rows. Client calls this function after calling
856  * ovsdb_idl_run() and read all tracked rows with the ovsdb_idl_track_get_*()
857  * functions. This is usually done at the end of the client's processing
858  * loop when it is ready to do ovsdb_idl_run() again.
859  */
860 void
861 ovsdb_idl_track_clear(const struct ovsdb_idl *idl)
862 {
863     size_t i;
864
865     for (i = 0; i < idl->class->n_tables; i++) {
866         struct ovsdb_idl_table *table = &idl->tables[i];
867
868         if (!ovs_list_is_empty(&table->track_list)) {
869             struct ovsdb_idl_row *row, *next;
870
871             LIST_FOR_EACH_SAFE(row, next, track_node, &table->track_list) {
872                 if (row->updated) {
873                     free(row->updated);
874                     row->updated = NULL;
875                 }
876                 ovs_list_remove(&row->track_node);
877                 ovs_list_init(&row->track_node);
878                 if (ovsdb_idl_row_is_orphan(row)) {
879                     ovsdb_idl_row_clear_old(row);
880                     free(row);
881                 }
882             }
883         }
884     }
885 }
886
887 \f
888 static void
889 ovsdb_idl_send_schema_request(struct ovsdb_idl *idl)
890 {
891     struct jsonrpc_msg *msg;
892
893     json_destroy(idl->request_id);
894     msg = jsonrpc_create_request(
895         "get_schema",
896         json_array_create_1(json_string_create(idl->class->database)),
897         &idl->request_id);
898     jsonrpc_session_send(idl->session, msg);
899 }
900
901 static void
902 log_error(struct ovsdb_error *error)
903 {
904     char *s = ovsdb_error_to_string(error);
905     VLOG_WARN("error parsing database schema: %s", s);
906     free(s);
907     ovsdb_error_destroy(error);
908 }
909
910 /* Frees 'schema', which is in the format returned by parse_schema(). */
911 static void
912 free_schema(struct shash *schema)
913 {
914     if (schema) {
915         struct shash_node *node, *next;
916
917         SHASH_FOR_EACH_SAFE (node, next, schema) {
918             struct sset *sset = node->data;
919             sset_destroy(sset);
920             free(sset);
921             shash_delete(schema, node);
922         }
923         shash_destroy(schema);
924         free(schema);
925     }
926 }
927
928 /* Parses 'schema_json', an OVSDB schema in JSON format as described in RFC
929  * 7047, to obtain the names of its rows and columns.  If successful, returns
930  * an shash whose keys are table names and whose values are ssets, where each
931  * sset contains the names of its table's columns.  On failure (due to a parse
932  * error), returns NULL.
933  *
934  * It would also be possible to use the general-purpose OVSDB schema parser in
935  * ovsdb-server, but that's overkill, possibly too strict for the current use
936  * case, and would require restructuring ovsdb-server to separate the schema
937  * code from the rest. */
938 static struct shash *
939 parse_schema(const struct json *schema_json)
940 {
941     struct ovsdb_parser parser;
942     const struct json *tables_json;
943     struct ovsdb_error *error;
944     struct shash_node *node;
945     struct shash *schema;
946
947     ovsdb_parser_init(&parser, schema_json, "database schema");
948     tables_json = ovsdb_parser_member(&parser, "tables", OP_OBJECT);
949     error = ovsdb_parser_destroy(&parser);
950     if (error) {
951         log_error(error);
952         return NULL;
953     }
954
955     schema = xmalloc(sizeof *schema);
956     shash_init(schema);
957     SHASH_FOR_EACH (node, json_object(tables_json)) {
958         const char *table_name = node->name;
959         const struct json *json = node->data;
960         const struct json *columns_json;
961
962         ovsdb_parser_init(&parser, json, "table schema for table %s",
963                           table_name);
964         columns_json = ovsdb_parser_member(&parser, "columns", OP_OBJECT);
965         error = ovsdb_parser_destroy(&parser);
966         if (error) {
967             log_error(error);
968             free_schema(schema);
969             return NULL;
970         }
971
972         struct sset *columns = xmalloc(sizeof *columns);
973         sset_init(columns);
974
975         struct shash_node *node2;
976         SHASH_FOR_EACH (node2, json_object(columns_json)) {
977             const char *column_name = node2->name;
978             sset_add(columns, column_name);
979         }
980         shash_add(schema, table_name, columns);
981     }
982     return schema;
983 }
984
985 static void
986 ovsdb_idl_send_monitor_request__(struct ovsdb_idl *idl,
987                                  const char *method)
988 {
989     struct shash *schema;
990     struct json *monitor_requests;
991     struct jsonrpc_msg *msg;
992     size_t i;
993
994     schema = parse_schema(idl->schema);
995     monitor_requests = json_object_create();
996     for (i = 0; i < idl->class->n_tables; i++) {
997         const struct ovsdb_idl_table *table = &idl->tables[i];
998         const struct ovsdb_idl_table_class *tc = table->class;
999         struct json *monitor_request, *columns;
1000         const struct sset *table_schema;
1001         size_t j;
1002
1003         table_schema = (schema
1004                         ? shash_find_data(schema, table->class->name)
1005                         : NULL);
1006
1007         columns = table->need_table ? json_array_create_empty() : NULL;
1008         for (j = 0; j < tc->n_columns; j++) {
1009             const struct ovsdb_idl_column *column = &tc->columns[j];
1010             if (table->modes[j] & OVSDB_IDL_MONITOR) {
1011                 if (table_schema
1012                     && !sset_contains(table_schema, column->name)) {
1013                     VLOG_WARN("%s table in %s database lacks %s column "
1014                               "(database needs upgrade?)",
1015                               table->class->name, idl->class->database,
1016                               column->name);
1017                     continue;
1018                 }
1019                 if (!columns) {
1020                     columns = json_array_create_empty();
1021                 }
1022                 json_array_add(columns, json_string_create(column->name));
1023             }
1024         }
1025
1026         if (columns) {
1027             if (schema && !table_schema) {
1028                 VLOG_WARN("%s database lacks %s table "
1029                           "(database needs upgrade?)",
1030                           idl->class->database, table->class->name);
1031                 json_destroy(columns);
1032                 continue;
1033             }
1034
1035             monitor_request = json_object_create();
1036             json_object_put(monitor_request, "columns", columns);
1037             json_object_put(monitor_requests, tc->name, monitor_request);
1038         }
1039     }
1040     free_schema(schema);
1041
1042     json_destroy(idl->request_id);
1043     msg = jsonrpc_create_request(
1044         method,
1045         json_array_create_3(json_string_create(idl->class->database),
1046                             json_null_create(), monitor_requests),
1047         &idl->request_id);
1048     jsonrpc_session_send(idl->session, msg);
1049 }
1050
1051 static void
1052 ovsdb_idl_send_monitor_request(struct ovsdb_idl *idl)
1053 {
1054     ovsdb_idl_send_monitor_request__(idl, "monitor");
1055 }
1056
1057 static void
1058 log_parse_update_error(struct ovsdb_error *error)
1059 {
1060         if (!VLOG_DROP_WARN(&syntax_rl)) {
1061             char *s = ovsdb_error_to_string(error);
1062             VLOG_WARN_RL(&syntax_rl, "%s", s);
1063             free(s);
1064         }
1065         ovsdb_error_destroy(error);
1066 }
1067
1068 static void
1069 ovsdb_idl_send_monitor2_request(struct ovsdb_idl *idl)
1070 {
1071     ovsdb_idl_send_monitor_request__(idl, "monitor2");
1072 }
1073
1074 static void
1075 ovsdb_idl_parse_update(struct ovsdb_idl *idl, const struct json *table_updates,
1076                        enum ovsdb_update_version version)
1077 {
1078     struct ovsdb_error *error = ovsdb_idl_parse_update__(idl, table_updates,
1079                                                          version);
1080     if (error) {
1081         log_parse_update_error(error);
1082     }
1083 }
1084
1085 static struct ovsdb_error *
1086 ovsdb_idl_parse_update__(struct ovsdb_idl *idl,
1087                          const struct json *table_updates,
1088                          enum ovsdb_update_version version)
1089 {
1090     const struct shash_node *tables_node;
1091     const char *table_updates_name = table_updates_names[version];
1092     const char *table_update_name = table_update_names[version];
1093     const char *row_update_name = row_update_names[version];
1094
1095     if (table_updates->type != JSON_OBJECT) {
1096         return ovsdb_syntax_error(table_updates, NULL,
1097                                   "<%s> is not an object",
1098                                   table_updates_name);
1099     }
1100
1101     SHASH_FOR_EACH (tables_node, json_object(table_updates)) {
1102         const struct json *table_update = tables_node->data;
1103         const struct shash_node *table_node;
1104         struct ovsdb_idl_table *table;
1105
1106         table = shash_find_data(&idl->table_by_name, tables_node->name);
1107         if (!table) {
1108             return ovsdb_syntax_error(
1109                 table_updates, NULL,
1110                 "<%s> includes unknown table \"%s\"",
1111                 table_updates_name,
1112                 tables_node->name);
1113         }
1114
1115         if (table_update->type != JSON_OBJECT) {
1116             return ovsdb_syntax_error(table_update, NULL,
1117                                       "<%s> for table \"%s\" is "
1118                                       "not an object",
1119                                       table_update_name,
1120                                       table->class->name);
1121         }
1122         SHASH_FOR_EACH (table_node, json_object(table_update)) {
1123             const struct json *row_update = table_node->data;
1124             const struct json *old_json, *new_json;
1125             struct uuid uuid;
1126
1127             if (!uuid_from_string(&uuid, table_node->name)) {
1128                 return ovsdb_syntax_error(table_update, NULL,
1129                                           "<%s> for table \"%s\" "
1130                                           "contains bad UUID "
1131                                           "\"%s\" as member name",
1132                                           table_update_name,
1133                                           table->class->name,
1134                                           table_node->name);
1135             }
1136             if (row_update->type != JSON_OBJECT) {
1137                 return ovsdb_syntax_error(row_update, NULL,
1138                                           "<%s> for table \"%s\" "
1139                                           "contains <%s> for %s that "
1140                                           "is not an object",
1141                                           table_update_name,
1142                                           table->class->name,
1143                                           row_update_name,
1144                                           table_node->name);
1145             }
1146
1147             switch(version) {
1148             case OVSDB_UPDATE:
1149                 old_json = shash_find_data(json_object(row_update), "old");
1150                 new_json = shash_find_data(json_object(row_update), "new");
1151                 if (old_json && old_json->type != JSON_OBJECT) {
1152                     return ovsdb_syntax_error(old_json, NULL,
1153                                               "\"old\" <row> is not object");
1154                 } else if (new_json && new_json->type != JSON_OBJECT) {
1155                     return ovsdb_syntax_error(new_json, NULL,
1156                                               "\"new\" <row> is not object");
1157                 } else if ((old_json != NULL) + (new_json != NULL)
1158                            != shash_count(json_object(row_update))) {
1159                     return ovsdb_syntax_error(row_update, NULL,
1160                                               "<row-update> contains "
1161                                               "unexpected member");
1162                 } else if (!old_json && !new_json) {
1163                     return ovsdb_syntax_error(row_update, NULL,
1164                                               "<row-update> missing \"old\" "
1165                                               "and \"new\" members");
1166                 }
1167
1168                 if (ovsdb_idl_process_update(table, &uuid, old_json,
1169                                              new_json)) {
1170                     idl->change_seqno++;
1171                 }
1172                 break;
1173
1174             case OVSDB_UPDATE2: {
1175                 const char *ops[] = {"modify", "insert", "delete", "initial"};
1176                 const char *operation;
1177                 const struct json *row;
1178                 int i;
1179
1180                 for (i = 0; i < ARRAY_SIZE(ops); i++) {
1181                     operation = ops[i];
1182                     row = shash_find_data(json_object(row_update), operation);
1183
1184                     if (row)  {
1185                         if (ovsdb_idl_process_update2(table, &uuid, operation,
1186                                                       row)) {
1187                             idl->change_seqno++;
1188                         }
1189                         break;
1190                     }
1191                 }
1192
1193                 /* row_update2 should contain one of the objects */
1194                 if (i == ARRAY_SIZE(ops)) {
1195                     return ovsdb_syntax_error(row_update, NULL,
1196                                               "<row_update2> includes unknown "
1197                                               "object");
1198                 }
1199                 break;
1200             }
1201
1202             default:
1203                 OVS_NOT_REACHED();
1204             }
1205         }
1206     }
1207
1208     return NULL;
1209 }
1210
1211 static struct ovsdb_idl_row *
1212 ovsdb_idl_get_row(struct ovsdb_idl_table *table, const struct uuid *uuid)
1213 {
1214     struct ovsdb_idl_row *row;
1215
1216     HMAP_FOR_EACH_WITH_HASH (row, hmap_node, uuid_hash(uuid), &table->rows) {
1217         if (uuid_equals(&row->uuid, uuid)) {
1218             return row;
1219         }
1220     }
1221     return NULL;
1222 }
1223
1224 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
1225  * otherwise. */
1226 static bool
1227 ovsdb_idl_process_update(struct ovsdb_idl_table *table,
1228                          const struct uuid *uuid, const struct json *old,
1229                          const struct json *new)
1230 {
1231     struct ovsdb_idl_row *row;
1232
1233     row = ovsdb_idl_get_row(table, uuid);
1234     if (!new) {
1235         /* Delete row. */
1236         if (row && !ovsdb_idl_row_is_orphan(row)) {
1237             /* XXX perhaps we should check the 'old' values? */
1238             ovsdb_idl_delete_row(row);
1239         } else {
1240             VLOG_WARN_RL(&semantic_rl, "cannot delete missing row "UUID_FMT" "
1241                          "from table %s",
1242                          UUID_ARGS(uuid), table->class->name);
1243             return false;
1244         }
1245     } else if (!old) {
1246         /* Insert row. */
1247         if (!row) {
1248             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
1249         } else if (ovsdb_idl_row_is_orphan(row)) {
1250             ovsdb_idl_insert_row(row, new);
1251         } else {
1252             VLOG_WARN_RL(&semantic_rl, "cannot add existing row "UUID_FMT" to "
1253                          "table %s", UUID_ARGS(uuid), table->class->name);
1254             return ovsdb_idl_modify_row(row, new);
1255         }
1256     } else {
1257         /* Modify row. */
1258         if (row) {
1259             /* XXX perhaps we should check the 'old' values? */
1260             if (!ovsdb_idl_row_is_orphan(row)) {
1261                 return ovsdb_idl_modify_row(row, new);
1262             } else {
1263                 VLOG_WARN_RL(&semantic_rl, "cannot modify missing but "
1264                              "referenced row "UUID_FMT" in table %s",
1265                              UUID_ARGS(uuid), table->class->name);
1266                 ovsdb_idl_insert_row(row, new);
1267             }
1268         } else {
1269             VLOG_WARN_RL(&semantic_rl, "cannot modify missing row "UUID_FMT" "
1270                          "in table %s", UUID_ARGS(uuid), table->class->name);
1271             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
1272         }
1273     }
1274
1275     return true;
1276 }
1277
1278 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
1279  * otherwise. */
1280 static bool
1281 ovsdb_idl_process_update2(struct ovsdb_idl_table *table,
1282                           const struct uuid *uuid,
1283                           const char *operation,
1284                           const struct json *json_row)
1285 {
1286     struct ovsdb_idl_row *row;
1287
1288     row = ovsdb_idl_get_row(table, uuid);
1289     if (!strcmp(operation, "delete")) {
1290         /* Delete row. */
1291         if (row && !ovsdb_idl_row_is_orphan(row)) {
1292             ovsdb_idl_delete_row(row);
1293         } else {
1294             VLOG_WARN_RL(&semantic_rl, "cannot delete missing row "UUID_FMT" "
1295                          "from table %s",
1296                          UUID_ARGS(uuid), table->class->name);
1297             return false;
1298         }
1299     } else if (!strcmp(operation, "insert") || !strcmp(operation, "initial")) {
1300         /* Insert row. */
1301         if (!row) {
1302             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), json_row);
1303         } else if (ovsdb_idl_row_is_orphan(row)) {
1304             ovsdb_idl_insert_row(row, json_row);
1305         } else {
1306             VLOG_WARN_RL(&semantic_rl, "cannot add existing row "UUID_FMT" to "
1307                          "table %s", UUID_ARGS(uuid), table->class->name);
1308             ovsdb_idl_delete_row(row);
1309             ovsdb_idl_insert_row(row, json_row);
1310         }
1311     } else if (!strcmp(operation, "modify")) {
1312         /* Modify row. */
1313         if (row) {
1314             if (!ovsdb_idl_row_is_orphan(row)) {
1315                 return ovsdb_idl_modify_row_by_diff(row, json_row);
1316             } else {
1317                 VLOG_WARN_RL(&semantic_rl, "cannot modify missing but "
1318                              "referenced row "UUID_FMT" in table %s",
1319                              UUID_ARGS(uuid), table->class->name);
1320                 return false;
1321             }
1322         } else {
1323             VLOG_WARN_RL(&semantic_rl, "cannot modify missing row "UUID_FMT" "
1324                          "in table %s", UUID_ARGS(uuid), table->class->name);
1325             return false;
1326         }
1327     } else {
1328             VLOG_WARN_RL(&semantic_rl, "unknown operation %s to "
1329                          "table %s", operation, table->class->name);
1330             return false;
1331     }
1332
1333     return true;
1334 }
1335
1336 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
1337  * otherwise.
1338  *
1339  * Change 'row' either with the content of 'row_json' or by apply 'diff'.
1340  * Caller needs to provide either valid 'row_json' or 'diff', but not
1341  * both.  */
1342 static bool
1343 ovsdb_idl_row_change__(struct ovsdb_idl_row *row, const struct json *row_json,
1344                        const struct json *diff_json,
1345                        enum ovsdb_idl_change change)
1346 {
1347     struct ovsdb_idl_table *table = row->table;
1348     const struct ovsdb_idl_table_class *class = table->class;
1349     struct shash_node *node;
1350     bool changed = false;
1351     bool apply_diff = diff_json != NULL;
1352     const struct json *json = apply_diff ? diff_json : row_json;
1353
1354     SHASH_FOR_EACH (node, json_object(json)) {
1355         const char *column_name = node->name;
1356         const struct ovsdb_idl_column *column;
1357         struct ovsdb_datum datum;
1358         struct ovsdb_error *error;
1359         unsigned int column_idx;
1360         struct ovsdb_datum *old;
1361
1362         column = shash_find_data(&table->columns, column_name);
1363         if (!column) {
1364             VLOG_WARN_RL(&syntax_rl, "unknown column %s updating row "UUID_FMT,
1365                          column_name, UUID_ARGS(&row->uuid));
1366             continue;
1367         }
1368
1369         column_idx = column - table->class->columns;
1370         old = &row->old[column_idx];
1371
1372         error = NULL;
1373         if (apply_diff) {
1374             struct ovsdb_datum diff;
1375
1376             ovs_assert(!row_json);
1377             error = ovsdb_transient_datum_from_json(&diff, &column->type,
1378                                                     node->data);
1379             if (!error) {
1380                 error = ovsdb_datum_apply_diff(&datum, old, &diff,
1381                                                &column->type);
1382                 ovsdb_datum_destroy(&diff, &column->type);
1383             }
1384         } else {
1385             ovs_assert(!diff_json);
1386             error = ovsdb_datum_from_json(&datum, &column->type, node->data,
1387                                           NULL);
1388         }
1389
1390         if (!error) {
1391             if (!ovsdb_datum_equals(old, &datum, &column->type)) {
1392                 ovsdb_datum_swap(old, &datum);
1393                 if (table->modes[column_idx] & OVSDB_IDL_ALERT) {
1394                     changed = true;
1395                     row->change_seqno[change]
1396                         = row->table->change_seqno[change]
1397                         = row->table->idl->change_seqno + 1;
1398                     if (table->modes[column_idx] & OVSDB_IDL_TRACK) {
1399                         if (!ovs_list_is_empty(&row->track_node)) {
1400                             ovs_list_remove(&row->track_node);
1401                         }
1402                         ovs_list_push_back(&row->table->track_list,
1403                                        &row->track_node);
1404                         if (!row->updated) {
1405                             row->updated = bitmap_allocate(class->n_columns);
1406                         }
1407                         bitmap_set1(row->updated, column_idx);
1408                     }
1409                 }
1410             } else {
1411                 /* Didn't really change but the OVSDB monitor protocol always
1412                  * includes every value in a row. */
1413             }
1414
1415             ovsdb_datum_destroy(&datum, &column->type);
1416         } else {
1417             char *s = ovsdb_error_to_string(error);
1418             VLOG_WARN_RL(&syntax_rl, "error parsing column %s in row "UUID_FMT
1419                          " in table %s: %s", column_name,
1420                          UUID_ARGS(&row->uuid), table->class->name, s);
1421             free(s);
1422             ovsdb_error_destroy(error);
1423         }
1424     }
1425     return changed;
1426 }
1427
1428 static bool
1429 ovsdb_idl_row_update(struct ovsdb_idl_row *row, const struct json *row_json,
1430                      enum ovsdb_idl_change change)
1431 {
1432     return ovsdb_idl_row_change__(row, row_json, NULL, change);
1433 }
1434
1435 static bool
1436 ovsdb_idl_row_apply_diff(struct ovsdb_idl_row *row,
1437                          const struct json *diff_json,
1438                          enum ovsdb_idl_change change)
1439 {
1440     return ovsdb_idl_row_change__(row, NULL, diff_json, change);
1441 }
1442
1443 /* When a row A refers to row B through a column with a "refTable" constraint,
1444  * but row B does not exist, row B is called an "orphan row".  Orphan rows
1445  * should not persist, because the database enforces referential integrity, but
1446  * they can appear transiently as changes from the database are received (the
1447  * database doesn't try to topologically sort them and circular references mean
1448  * it isn't always possible anyhow).
1449  *
1450  * This function returns true if 'row' is an orphan row, otherwise false.
1451  */
1452 static bool
1453 ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *row)
1454 {
1455     return !row->old && !row->new;
1456 }
1457
1458 /* Returns true if 'row' is conceptually part of the database as modified by
1459  * the current transaction (if any), false otherwise.
1460  *
1461  * This function will return true if 'row' is not an orphan (see the comment on
1462  * ovsdb_idl_row_is_orphan()) and:
1463  *
1464  *   - 'row' exists in the database and has not been deleted within the
1465  *     current transaction (if any).
1466  *
1467  *   - 'row' was inserted within the current transaction and has not been
1468  *     deleted.  (In the latter case you should not have passed 'row' in at
1469  *     all, because ovsdb_idl_txn_delete() freed it.)
1470  *
1471  * This function will return false if 'row' is an orphan or if 'row' was
1472  * deleted within the current transaction.
1473  */
1474 static bool
1475 ovsdb_idl_row_exists(const struct ovsdb_idl_row *row)
1476 {
1477     return row->new != NULL;
1478 }
1479
1480 static void
1481 ovsdb_idl_row_parse(struct ovsdb_idl_row *row)
1482 {
1483     const struct ovsdb_idl_table_class *class = row->table->class;
1484     size_t i;
1485
1486     for (i = 0; i < class->n_columns; i++) {
1487         const struct ovsdb_idl_column *c = &class->columns[i];
1488         (c->parse)(row, &row->old[i]);
1489     }
1490 }
1491
1492 static void
1493 ovsdb_idl_row_unparse(struct ovsdb_idl_row *row)
1494 {
1495     const struct ovsdb_idl_table_class *class = row->table->class;
1496     size_t i;
1497
1498     for (i = 0; i < class->n_columns; i++) {
1499         const struct ovsdb_idl_column *c = &class->columns[i];
1500         (c->unparse)(row);
1501     }
1502 }
1503
1504 static void
1505 ovsdb_idl_row_clear_old(struct ovsdb_idl_row *row)
1506 {
1507     ovs_assert(row->old == row->new);
1508     if (!ovsdb_idl_row_is_orphan(row)) {
1509         const struct ovsdb_idl_table_class *class = row->table->class;
1510         size_t i;
1511
1512         for (i = 0; i < class->n_columns; i++) {
1513             ovsdb_datum_destroy(&row->old[i], &class->columns[i].type);
1514         }
1515         free(row->old);
1516         row->old = row->new = NULL;
1517     }
1518 }
1519
1520 static void
1521 ovsdb_idl_row_clear_new(struct ovsdb_idl_row *row)
1522 {
1523     if (row->old != row->new) {
1524         if (row->new) {
1525             const struct ovsdb_idl_table_class *class = row->table->class;
1526             size_t i;
1527
1528             if (row->written) {
1529                 BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
1530                     ovsdb_datum_destroy(&row->new[i], &class->columns[i].type);
1531                 }
1532             }
1533             free(row->new);
1534             free(row->written);
1535             row->written = NULL;
1536         }
1537         row->new = row->old;
1538     }
1539 }
1540
1541 static void
1542 ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
1543 {
1544     struct ovsdb_idl_arc *arc, *next;
1545
1546     /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
1547      * that this causes to be unreferenced, if tracking is not enabled.
1548      * If tracking is enabled, orphaned nodes are removed from hmap but not
1549      * freed.
1550      */
1551     LIST_FOR_EACH_SAFE (arc, next, src_node, &row->src_arcs) {
1552         ovs_list_remove(&arc->dst_node);
1553         if (destroy_dsts
1554             && ovsdb_idl_row_is_orphan(arc->dst)
1555             && ovs_list_is_empty(&arc->dst->dst_arcs)) {
1556             ovsdb_idl_row_destroy(arc->dst);
1557         }
1558         free(arc);
1559     }
1560     ovs_list_init(&row->src_arcs);
1561 }
1562
1563 /* Force nodes that reference 'row' to reparse. */
1564 static void
1565 ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
1566 {
1567     struct ovsdb_idl_arc *arc, *next;
1568
1569     /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
1570      * 'arc', so we need to use the "safe" variant of list traversal.  However,
1571      * calling an ovsdb_idl_column's 'parse' function will add an arc
1572      * equivalent to 'arc' to row->arcs.  That could be a problem for
1573      * traversal, but it adds it at the beginning of the list to prevent us
1574      * from stumbling upon it again.
1575      *
1576      * (If duplicate arcs were possible then we would need to make sure that
1577      * 'next' didn't also point into 'arc''s destination, but we forbid
1578      * duplicate arcs.) */
1579     LIST_FOR_EACH_SAFE (arc, next, dst_node, &row->dst_arcs) {
1580         struct ovsdb_idl_row *ref = arc->src;
1581
1582         ovsdb_idl_row_unparse(ref);
1583         ovsdb_idl_row_clear_arcs(ref, false);
1584         ovsdb_idl_row_parse(ref);
1585     }
1586 }
1587
1588 static struct ovsdb_idl_row *
1589 ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
1590 {
1591     struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
1592     class->row_init(row);
1593     ovs_list_init(&row->src_arcs);
1594     ovs_list_init(&row->dst_arcs);
1595     hmap_node_nullify(&row->txn_node);
1596     ovs_list_init(&row->track_node);
1597     return row;
1598 }
1599
1600 static struct ovsdb_idl_row *
1601 ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
1602 {
1603     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class);
1604     hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
1605     row->uuid = *uuid;
1606     row->table = table;
1607     row->map_op_written = NULL;
1608     row->map_op_lists = NULL;
1609     return row;
1610 }
1611
1612 static void
1613 ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
1614 {
1615     if (row) {
1616         ovsdb_idl_row_clear_old(row);
1617         hmap_remove(&row->table->rows, &row->hmap_node);
1618         ovsdb_idl_destroy_all_map_op_lists(row);
1619         if (ovsdb_idl_track_is_set(row->table)) {
1620             row->change_seqno[OVSDB_IDL_CHANGE_DELETE]
1621                 = row->table->change_seqno[OVSDB_IDL_CHANGE_DELETE]
1622                 = row->table->idl->change_seqno + 1;
1623         }
1624         if (!ovs_list_is_empty(&row->track_node)) {
1625             ovs_list_remove(&row->track_node);
1626         }
1627         ovs_list_push_back(&row->table->track_list, &row->track_node);
1628     }
1629 }
1630
1631 static void
1632 ovsdb_idl_destroy_all_map_op_lists(struct ovsdb_idl_row *row)
1633 {
1634     if (row->map_op_written) {
1635         /* Clear Map Operation Lists */
1636         size_t idx, n_columns;
1637         const struct ovsdb_idl_column *columns;
1638         const struct ovsdb_type *type;
1639         n_columns = row->table->class->n_columns;
1640         columns = row->table->class->columns;
1641         BITMAP_FOR_EACH_1 (idx, n_columns, row->map_op_written) {
1642             type = &columns[idx].type;
1643             map_op_list_destroy(row->map_op_lists[idx], type);
1644         }
1645         free(row->map_op_lists);
1646         bitmap_free(row->map_op_written);
1647         row->map_op_lists = NULL;
1648         row->map_op_written = NULL;
1649     }
1650 }
1651
1652 static void
1653 ovsdb_idl_row_destroy_postprocess(struct ovsdb_idl *idl)
1654 {
1655     size_t i;
1656
1657     for (i = 0; i < idl->class->n_tables; i++) {
1658         struct ovsdb_idl_table *table = &idl->tables[i];
1659
1660         if (!ovs_list_is_empty(&table->track_list)) {
1661             struct ovsdb_idl_row *row, *next;
1662
1663             LIST_FOR_EACH_SAFE(row, next, track_node, &table->track_list) {
1664                 if (!ovsdb_idl_track_is_set(row->table)) {
1665                     ovs_list_remove(&row->track_node);
1666                     free(row);
1667                 }
1668             }
1669         }
1670     }
1671 }
1672
1673 static void
1674 ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct json *row_json)
1675 {
1676     const struct ovsdb_idl_table_class *class = row->table->class;
1677     size_t i;
1678
1679     ovs_assert(!row->old && !row->new);
1680     row->old = row->new = xmalloc(class->n_columns * sizeof *row->old);
1681     for (i = 0; i < class->n_columns; i++) {
1682         ovsdb_datum_init_default(&row->old[i], &class->columns[i].type);
1683     }
1684     ovsdb_idl_row_update(row, row_json, OVSDB_IDL_CHANGE_INSERT);
1685     ovsdb_idl_row_parse(row);
1686
1687     ovsdb_idl_row_reparse_backrefs(row);
1688 }
1689
1690 static void
1691 ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
1692 {
1693     ovsdb_idl_row_unparse(row);
1694     ovsdb_idl_row_clear_arcs(row, true);
1695     ovsdb_idl_row_clear_old(row);
1696     if (ovs_list_is_empty(&row->dst_arcs)) {
1697         ovsdb_idl_row_destroy(row);
1698     } else {
1699         ovsdb_idl_row_reparse_backrefs(row);
1700     }
1701 }
1702
1703 /* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
1704  * otherwise. */
1705 static bool
1706 ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct json *row_json)
1707 {
1708     bool changed;
1709
1710     ovsdb_idl_row_unparse(row);
1711     ovsdb_idl_row_clear_arcs(row, true);
1712     changed = ovsdb_idl_row_update(row, row_json, OVSDB_IDL_CHANGE_MODIFY);
1713     ovsdb_idl_row_parse(row);
1714
1715     return changed;
1716 }
1717
1718 static bool
1719 ovsdb_idl_modify_row_by_diff(struct ovsdb_idl_row *row,
1720                              const struct json *diff_json)
1721 {
1722     bool changed;
1723
1724     ovsdb_idl_row_unparse(row);
1725     ovsdb_idl_row_clear_arcs(row, true);
1726     changed = ovsdb_idl_row_apply_diff(row, diff_json,
1727                                        OVSDB_IDL_CHANGE_MODIFY);
1728     ovsdb_idl_row_parse(row);
1729
1730     return changed;
1731 }
1732
1733 static bool
1734 may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
1735 {
1736     const struct ovsdb_idl_arc *arc;
1737
1738     /* No self-arcs. */
1739     if (src == dst) {
1740         return false;
1741     }
1742
1743     /* No duplicate arcs.
1744      *
1745      * We only need to test whether the first arc in dst->dst_arcs originates
1746      * at 'src', since we add all of the arcs from a given source in a clump
1747      * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
1748      * added at the front of the dst_arcs list. */
1749     if (ovs_list_is_empty(&dst->dst_arcs)) {
1750         return true;
1751     }
1752     arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
1753     return arc->src != src;
1754 }
1755
1756 static struct ovsdb_idl_table *
1757 ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
1758                            const struct ovsdb_idl_table_class *table_class)
1759 {
1760     return &idl->tables[table_class - idl->class->tables];
1761 }
1762
1763 /* Called by ovsdb-idlc generated code. */
1764 struct ovsdb_idl_row *
1765 ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
1766                       struct ovsdb_idl_table_class *dst_table_class,
1767                       const struct uuid *dst_uuid)
1768 {
1769     struct ovsdb_idl *idl = src->table->idl;
1770     struct ovsdb_idl_table *dst_table;
1771     struct ovsdb_idl_arc *arc;
1772     struct ovsdb_idl_row *dst;
1773
1774     dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
1775     dst = ovsdb_idl_get_row(dst_table, dst_uuid);
1776     if (idl->txn) {
1777         /* We're being called from ovsdb_idl_txn_write().  We must not update
1778          * any arcs, because the transaction will be backed out at commit or
1779          * abort time and we don't want our graph screwed up.
1780          *
1781          * Just return the destination row, if there is one and it has not been
1782          * deleted. */
1783         if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new)) {
1784             return dst;
1785         }
1786         return NULL;
1787     } else {
1788         /* We're being called from some other context.  Update the graph. */
1789         if (!dst) {
1790             dst = ovsdb_idl_row_create(dst_table, dst_uuid);
1791         }
1792
1793         /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
1794         if (may_add_arc(src, dst)) {
1795             /* The arc *must* be added at the front of the dst_arcs list.  See
1796              * ovsdb_idl_row_reparse_backrefs() for details. */
1797             arc = xmalloc(sizeof *arc);
1798             ovs_list_push_front(&src->src_arcs, &arc->src_node);
1799             ovs_list_push_front(&dst->dst_arcs, &arc->dst_node);
1800             arc->src = src;
1801             arc->dst = dst;
1802         }
1803
1804         return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
1805     }
1806 }
1807
1808 /* Searches 'tc''s table in 'idl' for a row with UUID 'uuid'.  Returns a
1809  * pointer to the row if there is one, otherwise a null pointer.  */
1810 const struct ovsdb_idl_row *
1811 ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
1812                            const struct ovsdb_idl_table_class *tc,
1813                            const struct uuid *uuid)
1814 {
1815     return ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
1816 }
1817
1818 static struct ovsdb_idl_row *
1819 next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
1820 {
1821     for (; node; node = hmap_next(&table->rows, node)) {
1822         struct ovsdb_idl_row *row;
1823
1824         row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
1825         if (ovsdb_idl_row_exists(row)) {
1826             return row;
1827         }
1828     }
1829     return NULL;
1830 }
1831
1832 /* Returns a row in 'table_class''s table in 'idl', or a null pointer if that
1833  * table is empty.
1834  *
1835  * Database tables are internally maintained as hash tables, so adding or
1836  * removing rows while traversing the same table can cause some rows to be
1837  * visited twice or not at apply. */
1838 const struct ovsdb_idl_row *
1839 ovsdb_idl_first_row(const struct ovsdb_idl *idl,
1840                     const struct ovsdb_idl_table_class *table_class)
1841 {
1842     struct ovsdb_idl_table *table
1843         = ovsdb_idl_table_from_class(idl, table_class);
1844     return next_real_row(table, hmap_first(&table->rows));
1845 }
1846
1847 /* Returns a row following 'row' within its table, or a null pointer if 'row'
1848  * is the last row in its table. */
1849 const struct ovsdb_idl_row *
1850 ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
1851 {
1852     struct ovsdb_idl_table *table = row->table;
1853
1854     return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
1855 }
1856
1857 /* Reads and returns the value of 'column' within 'row'.  If an ongoing
1858  * transaction has changed 'column''s value, the modified value is returned.
1859  *
1860  * The caller must not modify or free the returned value.
1861  *
1862  * Various kinds of changes can invalidate the returned value: writing to the
1863  * same 'column' in 'row' (e.g. with ovsdb_idl_txn_write()), deleting 'row'
1864  * (e.g. with ovsdb_idl_txn_delete()), or completing an ongoing transaction
1865  * (e.g. with ovsdb_idl_txn_commit() or ovsdb_idl_txn_abort()).  If the
1866  * returned value is needed for a long time, it is best to make a copy of it
1867  * with ovsdb_datum_clone(). */
1868 const struct ovsdb_datum *
1869 ovsdb_idl_read(const struct ovsdb_idl_row *row,
1870                const struct ovsdb_idl_column *column)
1871 {
1872     const struct ovsdb_idl_table_class *class;
1873     size_t column_idx;
1874
1875     ovs_assert(!ovsdb_idl_row_is_synthetic(row));
1876
1877     class = row->table->class;
1878     column_idx = column - class->columns;
1879
1880     ovs_assert(row->new != NULL);
1881     ovs_assert(column_idx < class->n_columns);
1882
1883     if (row->written && bitmap_is_set(row->written, column_idx)) {
1884         return &row->new[column_idx];
1885     } else if (row->old) {
1886         return &row->old[column_idx];
1887     } else {
1888         return ovsdb_datum_default(&column->type);
1889     }
1890 }
1891
1892 /* Same as ovsdb_idl_read(), except that it also asserts that 'column' has key
1893  * type 'key_type' and value type 'value_type'.  (Scalar and set types will
1894  * have a value type of OVSDB_TYPE_VOID.)
1895  *
1896  * This is useful in code that "knows" that a particular column has a given
1897  * type, so that it will abort if someone changes the column's type without
1898  * updating the code that uses it. */
1899 const struct ovsdb_datum *
1900 ovsdb_idl_get(const struct ovsdb_idl_row *row,
1901               const struct ovsdb_idl_column *column,
1902               enum ovsdb_atomic_type key_type OVS_UNUSED,
1903               enum ovsdb_atomic_type value_type OVS_UNUSED)
1904 {
1905     ovs_assert(column->type.key.type == key_type);
1906     ovs_assert(column->type.value.type == value_type);
1907
1908     return ovsdb_idl_read(row, column);
1909 }
1910
1911 /* Returns true if the field represented by 'column' in 'row' may be modified,
1912  * false if it is immutable.
1913  *
1914  * Normally, whether a field is mutable is controlled by its column's schema.
1915  * However, an immutable column can be set to any initial value at the time of
1916  * insertion, so if 'row' is a new row (one that is being added as part of the
1917  * current transaction, supposing that a transaction is in progress) then even
1918  * its "immutable" fields are actually mutable. */
1919 bool
1920 ovsdb_idl_is_mutable(const struct ovsdb_idl_row *row,
1921                      const struct ovsdb_idl_column *column)
1922 {
1923     return column->mutable || (row->new && !row->old);
1924 }
1925
1926 /* Returns false if 'row' was obtained from the IDL, true if it was initialized
1927  * to all-zero-bits by some other entity.  If 'row' was set up some other way
1928  * then the return value is indeterminate. */
1929 bool
1930 ovsdb_idl_row_is_synthetic(const struct ovsdb_idl_row *row)
1931 {
1932     return row->table == NULL;
1933 }
1934 \f
1935 /* Transactions. */
1936
1937 static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1938                                    enum ovsdb_idl_txn_status);
1939
1940 /* Returns a string representation of 'status'.  The caller must not modify or
1941  * free the returned string.
1942  *
1943  * The return value is probably useful only for debug log messages and unit
1944  * tests. */
1945 const char *
1946 ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
1947 {
1948     switch (status) {
1949     case TXN_UNCOMMITTED:
1950         return "uncommitted";
1951     case TXN_UNCHANGED:
1952         return "unchanged";
1953     case TXN_INCOMPLETE:
1954         return "incomplete";
1955     case TXN_ABORTED:
1956         return "aborted";
1957     case TXN_SUCCESS:
1958         return "success";
1959     case TXN_TRY_AGAIN:
1960         return "try again";
1961     case TXN_NOT_LOCKED:
1962         return "not locked";
1963     case TXN_ERROR:
1964         return "error";
1965     }
1966     return "<unknown>";
1967 }
1968
1969 /* Starts a new transaction on 'idl'.  A given ovsdb_idl may only have a single
1970  * active transaction at a time.  See the large comment in ovsdb-idl.h for
1971  * general information on transactions. */
1972 struct ovsdb_idl_txn *
1973 ovsdb_idl_txn_create(struct ovsdb_idl *idl)
1974 {
1975     struct ovsdb_idl_txn *txn;
1976
1977     ovs_assert(!idl->txn);
1978     idl->txn = txn = xmalloc(sizeof *txn);
1979     txn->request_id = NULL;
1980     txn->idl = idl;
1981     hmap_init(&txn->txn_rows);
1982     txn->status = TXN_UNCOMMITTED;
1983     txn->error = NULL;
1984     txn->dry_run = false;
1985     ds_init(&txn->comment);
1986
1987     txn->inc_table = NULL;
1988     txn->inc_column = NULL;
1989
1990     hmap_init(&txn->inserted_rows);
1991
1992     return txn;
1993 }
1994
1995 /* Appends 's', which is treated as a printf()-type format string, to the
1996  * comments that will be passed to the OVSDB server when 'txn' is committed.
1997  * (The comment will be committed to the OVSDB log, which "ovsdb-tool
1998  * show-log" can print in a relatively human-readable form.) */
1999 void
2000 ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s, ...)
2001 {
2002     va_list args;
2003
2004     if (txn->comment.length) {
2005         ds_put_char(&txn->comment, '\n');
2006     }
2007
2008     va_start(args, s);
2009     ds_put_format_valist(&txn->comment, s, args);
2010     va_end(args);
2011 }
2012
2013 /* Marks 'txn' as a transaction that will not actually modify the database.  In
2014  * almost every way, the transaction is treated like other transactions.  It
2015  * must be committed or aborted like other transactions, it will be sent to the
2016  * database server like other transactions, and so on.  The only difference is
2017  * that the operations sent to the database server will include, as the last
2018  * step, an "abort" operation, so that any changes made by the transaction will
2019  * not actually take effect. */
2020 void
2021 ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
2022 {
2023     txn->dry_run = true;
2024 }
2025
2026 /* Causes 'txn', when committed, to increment the value of 'column' within
2027  * 'row' by 1.  'column' must have an integer type.  After 'txn' commits
2028  * successfully, the client may retrieve the final (incremented) value of
2029  * 'column' with ovsdb_idl_txn_get_increment_new_value().
2030  *
2031  * The client could accomplish something similar with ovsdb_idl_read(),
2032  * ovsdb_idl_txn_verify() and ovsdb_idl_txn_write(), or with ovsdb-idlc
2033  * generated wrappers for these functions.  However, ovsdb_idl_txn_increment()
2034  * will never (by itself) fail because of a verify error.
2035  *
2036  * The intended use is for incrementing the "next_cfg" column in the
2037  * Open_vSwitch table. */
2038 void
2039 ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn,
2040                         const struct ovsdb_idl_row *row,
2041                         const struct ovsdb_idl_column *column)
2042 {
2043     ovs_assert(!txn->inc_table);
2044     ovs_assert(column->type.key.type == OVSDB_TYPE_INTEGER);
2045     ovs_assert(column->type.value.type == OVSDB_TYPE_VOID);
2046
2047     txn->inc_table = row->table->class->name;
2048     txn->inc_column = column->name;
2049     txn->inc_row = row->uuid;
2050 }
2051
2052 /* Destroys 'txn' and frees all associated memory.  If ovsdb_idl_txn_commit()
2053  * has been called for 'txn' but the commit is still incomplete (that is, the
2054  * last call returned TXN_INCOMPLETE) then the transaction may or may not still
2055  * end up committing at the database server, but the client will not be able to
2056  * get any further status information back. */
2057 void
2058 ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
2059 {
2060     struct ovsdb_idl_txn_insert *insert, *next;
2061
2062     json_destroy(txn->request_id);
2063     if (txn->status == TXN_INCOMPLETE) {
2064         hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
2065     }
2066     ovsdb_idl_txn_abort(txn);
2067     ds_destroy(&txn->comment);
2068     free(txn->error);
2069     HMAP_FOR_EACH_SAFE (insert, next, hmap_node, &txn->inserted_rows) {
2070         free(insert);
2071     }
2072     hmap_destroy(&txn->inserted_rows);
2073     free(txn);
2074 }
2075
2076 /* Causes poll_block() to wake up if 'txn' has completed committing. */
2077 void
2078 ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
2079 {
2080     if (txn->status != TXN_UNCOMMITTED && txn->status != TXN_INCOMPLETE) {
2081         poll_immediate_wake();
2082     }
2083 }
2084
2085 static struct json *
2086 where_uuid_equals(const struct uuid *uuid)
2087 {
2088     return
2089         json_array_create_1(
2090             json_array_create_3(
2091                 json_string_create("_uuid"),
2092                 json_string_create("=="),
2093                 json_array_create_2(
2094                     json_string_create("uuid"),
2095                     json_string_create_nocopy(
2096                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
2097 }
2098
2099 static char *
2100 uuid_name_from_uuid(const struct uuid *uuid)
2101 {
2102     char *name;
2103     char *p;
2104
2105     name = xasprintf("row"UUID_FMT, UUID_ARGS(uuid));
2106     for (p = name; *p != '\0'; p++) {
2107         if (*p == '-') {
2108             *p = '_';
2109         }
2110     }
2111
2112     return name;
2113 }
2114
2115 static const struct ovsdb_idl_row *
2116 ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
2117 {
2118     const struct ovsdb_idl_row *row;
2119
2120     HMAP_FOR_EACH_WITH_HASH (row, txn_node, uuid_hash(uuid), &txn->txn_rows) {
2121         if (uuid_equals(&row->uuid, uuid)) {
2122             return row;
2123         }
2124     }
2125     return NULL;
2126 }
2127
2128 /* XXX there must be a cleaner way to do this */
2129 static struct json *
2130 substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
2131 {
2132     if (json->type == JSON_ARRAY) {
2133         struct uuid uuid;
2134         size_t i;
2135
2136         if (json->u.array.n == 2
2137             && json->u.array.elems[0]->type == JSON_STRING
2138             && json->u.array.elems[1]->type == JSON_STRING
2139             && !strcmp(json->u.array.elems[0]->u.string, "uuid")
2140             && uuid_from_string(&uuid, json->u.array.elems[1]->u.string)) {
2141             const struct ovsdb_idl_row *row;
2142
2143             row = ovsdb_idl_txn_get_row(txn, &uuid);
2144             if (row && !row->old && row->new) {
2145                 json_destroy(json);
2146
2147                 return json_array_create_2(
2148                     json_string_create("named-uuid"),
2149                     json_string_create_nocopy(uuid_name_from_uuid(&uuid)));
2150             }
2151         }
2152
2153         for (i = 0; i < json->u.array.n; i++) {
2154             json->u.array.elems[i] = substitute_uuids(json->u.array.elems[i],
2155                                                       txn);
2156         }
2157     } else if (json->type == JSON_OBJECT) {
2158         struct shash_node *node;
2159
2160         SHASH_FOR_EACH (node, json_object(json)) {
2161             node->data = substitute_uuids(node->data, txn);
2162         }
2163     }
2164     return json;
2165 }
2166
2167 static void
2168 ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
2169 {
2170     struct ovsdb_idl_row *row, *next;
2171
2172     /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
2173      * ovsdb_idl_column's 'parse' function, which will call
2174      * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
2175      * transaction and fail to update the graph.  */
2176     txn->idl->txn = NULL;
2177
2178     HMAP_FOR_EACH_SAFE (row, next, txn_node, &txn->txn_rows) {
2179         ovsdb_idl_destroy_all_map_op_lists(row);
2180         if (row->old) {
2181             if (row->written) {
2182                 ovsdb_idl_row_unparse(row);
2183                 ovsdb_idl_row_clear_arcs(row, false);
2184                 ovsdb_idl_row_parse(row);
2185             }
2186         } else {
2187             ovsdb_idl_row_unparse(row);
2188         }
2189         ovsdb_idl_row_clear_new(row);
2190
2191         free(row->prereqs);
2192         row->prereqs = NULL;
2193
2194         free(row->written);
2195         row->written = NULL;
2196
2197         hmap_remove(&txn->txn_rows, &row->txn_node);
2198         hmap_node_nullify(&row->txn_node);
2199         if (!row->old) {
2200             hmap_remove(&row->table->rows, &row->hmap_node);
2201             free(row);
2202         }
2203     }
2204     hmap_destroy(&txn->txn_rows);
2205     hmap_init(&txn->txn_rows);
2206 }
2207
2208 static bool
2209 ovsdb_idl_txn_extract_mutations(struct ovsdb_idl_row *row,
2210                                 struct json *mutations)
2211 {
2212     const struct ovsdb_idl_table_class *class = row->table->class;
2213     size_t idx;
2214     bool any_mutations = false;
2215
2216     BITMAP_FOR_EACH_1(idx, class->n_columns, row->map_op_written) {
2217         struct map_op_list *map_op_list;
2218         const struct ovsdb_idl_column *column;
2219         const struct ovsdb_datum *old_datum;
2220         enum ovsdb_atomic_type key_type, value_type;
2221         struct json *mutation, *map, *col_name, *mutator;
2222         struct json *del_set, *ins_map;
2223         bool any_del, any_ins;
2224
2225         map_op_list = row->map_op_lists[idx];
2226         column = &class->columns[idx];
2227         key_type = column->type.key.type;
2228         value_type = column->type.value.type;
2229         old_datum = ovsdb_idl_read(row, column);
2230
2231         del_set = json_array_create_empty();
2232         ins_map = json_array_create_empty();
2233         any_del = false;
2234         any_ins = false;
2235
2236         for (struct map_op *map_op = map_op_list_first(map_op_list); map_op;
2237              map_op = map_op_list_next(map_op_list, map_op)) {
2238
2239             if (map_op_type(map_op) == MAP_OP_UPDATE) {
2240                 /* Find out if value really changed. */
2241                 struct ovsdb_datum *new_datum;
2242                 unsigned int pos;
2243                 new_datum = map_op_datum(map_op);
2244                 pos = ovsdb_datum_find_key(old_datum,
2245                                            &new_datum->keys[0],
2246                                            key_type);
2247                 if (ovsdb_atom_equals(&new_datum->values[0],
2248                                       &old_datum->values[pos],
2249                                       value_type)) {
2250                     /* No change in value. Move on to next update. */
2251                     continue;
2252                 }
2253             } else if (map_op_type(map_op) == MAP_OP_DELETE){
2254                 /* Verify that there is a key to delete. */
2255                 unsigned int pos;
2256                 pos = ovsdb_datum_find_key(old_datum,
2257                                            &map_op_datum(map_op)->keys[0],
2258                                            key_type);
2259                 if (pos == UINT_MAX) {
2260                     /* No key to delete.  Move on to next update. */
2261                     VLOG_WARN("Trying to delete a key that doesn't "
2262                               "exist in the map.");
2263                     continue;
2264                 }
2265             }
2266
2267             if (map_op_type(map_op) == MAP_OP_INSERT) {
2268                 map = json_array_create_2(
2269                     ovsdb_atom_to_json(&map_op_datum(map_op)->keys[0],
2270                                        key_type),
2271                     ovsdb_atom_to_json(&map_op_datum(map_op)->values[0],
2272                                        value_type));
2273                 json_array_add(ins_map, map);
2274                 any_ins = true;
2275             } else { /* MAP_OP_UPDATE or MAP_OP_DELETE */
2276                 map = ovsdb_atom_to_json(&map_op_datum(map_op)->keys[0],
2277                                          key_type);
2278                 json_array_add(del_set, map);
2279                 any_del = true;
2280             }
2281
2282             /* Generate an additional insert mutate for updates. */
2283             if (map_op_type(map_op) == MAP_OP_UPDATE) {
2284                 map = json_array_create_2(
2285                     ovsdb_atom_to_json(&map_op_datum(map_op)->keys[0],
2286                                        key_type),
2287                     ovsdb_atom_to_json(&map_op_datum(map_op)->values[0],
2288                                        value_type));
2289                 json_array_add(ins_map, map);
2290                 any_ins = true;
2291             }
2292         }
2293
2294         if (any_del) {
2295             col_name = json_string_create(column->name);
2296             mutator = json_string_create("delete");
2297             map = json_array_create_2(json_string_create("set"), del_set);
2298             mutation = json_array_create_3(col_name, mutator, map);
2299             json_array_add(mutations, mutation);
2300             any_mutations = true;
2301         } else {
2302             json_destroy(del_set);
2303         }
2304         if (any_ins) {
2305             col_name = json_string_create(column->name);
2306             mutator = json_string_create("insert");
2307             map = json_array_create_2(json_string_create("map"), ins_map);
2308             mutation = json_array_create_3(col_name, mutator, map);
2309             json_array_add(mutations, mutation);
2310             any_mutations = true;
2311         } else {
2312             json_destroy(ins_map);
2313         }
2314     }
2315     return any_mutations;
2316 }
2317
2318 /* Attempts to commit 'txn'.  Returns the status of the commit operation, one
2319  * of the following TXN_* constants:
2320  *
2321  *   TXN_INCOMPLETE:
2322  *
2323  *       The transaction is in progress, but not yet complete.  The caller
2324  *       should call again later, after calling ovsdb_idl_run() to let the IDL
2325  *       do OVSDB protocol processing.
2326  *
2327  *   TXN_UNCHANGED:
2328  *
2329  *       The transaction is complete.  (It didn't actually change the database,
2330  *       so the IDL didn't send any request to the database server.)
2331  *
2332  *   TXN_ABORTED:
2333  *
2334  *       The caller previously called ovsdb_idl_txn_abort().
2335  *
2336  *   TXN_SUCCESS:
2337  *
2338  *       The transaction was successful.  The update made by the transaction
2339  *       (and possibly other changes made by other database clients) should
2340  *       already be visible in the IDL.
2341  *
2342  *   TXN_TRY_AGAIN:
2343  *
2344  *       The transaction failed for some transient reason, e.g. because a
2345  *       "verify" operation reported an inconsistency or due to a network
2346  *       problem.  The caller should wait for a change to the database, then
2347  *       compose a new transaction, and commit the new transaction.
2348  *
2349  *       Use the return value of ovsdb_idl_get_seqno() to wait for a change in
2350  *       the database.  It is important to use its return value *before* the
2351  *       initial call to ovsdb_idl_txn_commit() as the baseline for this
2352  *       purpose, because the change that one should wait for can happen after
2353  *       the initial call but before the call that returns TXN_TRY_AGAIN, and
2354  *       using some other baseline value in that situation could cause an
2355  *       indefinite wait if the database rarely changes.
2356  *
2357  *   TXN_NOT_LOCKED:
2358  *
2359  *       The transaction failed because the IDL has been configured to require
2360  *       a database lock (with ovsdb_idl_set_lock()) but didn't get it yet or
2361  *       has already lost it.
2362  *
2363  * Committing a transaction rolls back all of the changes that it made to the
2364  * IDL's copy of the database.  If the transaction commits successfully, then
2365  * the database server will send an update and, thus, the IDL will be updated
2366  * with the committed changes. */
2367 enum ovsdb_idl_txn_status
2368 ovsdb_idl_txn_commit(struct ovsdb_idl_txn *txn)
2369 {
2370     struct ovsdb_idl_row *row;
2371     struct json *operations;
2372     bool any_updates;
2373
2374     if (txn != txn->idl->txn) {
2375         goto coverage_out;
2376     }
2377
2378     /* If we need a lock but don't have it, give up quickly. */
2379     if (txn->idl->lock_name && !ovsdb_idl_has_lock(txn->idl)) {
2380         txn->status = TXN_NOT_LOCKED;
2381         goto disassemble_out;
2382     }
2383
2384     operations = json_array_create_1(
2385         json_string_create(txn->idl->class->database));
2386
2387     /* Assert that we have the required lock (avoiding a race). */
2388     if (txn->idl->lock_name) {
2389         struct json *op = json_object_create();
2390         json_array_add(operations, op);
2391         json_object_put_string(op, "op", "assert");
2392         json_object_put_string(op, "lock", txn->idl->lock_name);
2393     }
2394
2395     /* Add prerequisites and declarations of new rows. */
2396     HMAP_FOR_EACH (row, txn_node, &txn->txn_rows) {
2397         /* XXX check that deleted rows exist even if no prereqs? */
2398         if (row->prereqs) {
2399             const struct ovsdb_idl_table_class *class = row->table->class;
2400             size_t n_columns = class->n_columns;
2401             struct json *op, *columns, *row_json;
2402             size_t idx;
2403
2404             op = json_object_create();
2405             json_array_add(operations, op);
2406             json_object_put_string(op, "op", "wait");
2407             json_object_put_string(op, "table", class->name);
2408             json_object_put(op, "timeout", json_integer_create(0));
2409             json_object_put(op, "where", where_uuid_equals(&row->uuid));
2410             json_object_put_string(op, "until", "==");
2411             columns = json_array_create_empty();
2412             json_object_put(op, "columns", columns);
2413             row_json = json_object_create();
2414             json_object_put(op, "rows", json_array_create_1(row_json));
2415
2416             BITMAP_FOR_EACH_1 (idx, n_columns, row->prereqs) {
2417                 const struct ovsdb_idl_column *column = &class->columns[idx];
2418                 json_array_add(columns, json_string_create(column->name));
2419                 json_object_put(row_json, column->name,
2420                                 ovsdb_datum_to_json(&row->old[idx],
2421                                                     &column->type));
2422             }
2423         }
2424     }
2425
2426     /* Add updates. */
2427     any_updates = false;
2428     HMAP_FOR_EACH (row, txn_node, &txn->txn_rows) {
2429         const struct ovsdb_idl_table_class *class = row->table->class;
2430
2431         if (!row->new) {
2432             if (class->is_root) {
2433                 struct json *op = json_object_create();
2434                 json_object_put_string(op, "op", "delete");
2435                 json_object_put_string(op, "table", class->name);
2436                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
2437                 json_array_add(operations, op);
2438                 any_updates = true;
2439             } else {
2440                 /* Let ovsdb-server decide whether to really delete it. */
2441             }
2442         } else if (row->old != row->new) {
2443             struct json *row_json;
2444             struct json *op;
2445             size_t idx;
2446
2447             op = json_object_create();
2448             json_object_put_string(op, "op", row->old ? "update" : "insert");
2449             json_object_put_string(op, "table", class->name);
2450             if (row->old) {
2451                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
2452             } else {
2453                 struct ovsdb_idl_txn_insert *insert;
2454
2455                 any_updates = true;
2456
2457                 json_object_put(op, "uuid-name",
2458                                 json_string_create_nocopy(
2459                                     uuid_name_from_uuid(&row->uuid)));
2460
2461                 insert = xmalloc(sizeof *insert);
2462                 insert->dummy = row->uuid;
2463                 insert->op_index = operations->u.array.n - 1;
2464                 uuid_zero(&insert->real);
2465                 hmap_insert(&txn->inserted_rows, &insert->hmap_node,
2466                             uuid_hash(&insert->dummy));
2467             }
2468             row_json = json_object_create();
2469             json_object_put(op, "row", row_json);
2470
2471             if (row->written) {
2472                 BITMAP_FOR_EACH_1 (idx, class->n_columns, row->written) {
2473                     const struct ovsdb_idl_column *column =
2474                                                         &class->columns[idx];
2475
2476                     if (row->old
2477                         || !ovsdb_datum_is_default(&row->new[idx],
2478                                                   &column->type)) {
2479                         json_object_put(row_json, column->name,
2480                                         substitute_uuids(
2481                                             ovsdb_datum_to_json(&row->new[idx],
2482                                                                 &column->type),
2483                                             txn));
2484
2485                         /* If anything really changed, consider it an update.
2486                          * We can't suppress not-really-changed values earlier
2487                          * or transactions would become nonatomic (see the big
2488                          * comment inside ovsdb_idl_txn_write()). */
2489                         if (!any_updates && row->old &&
2490                             !ovsdb_datum_equals(&row->old[idx], &row->new[idx],
2491                                                 &column->type)) {
2492                             any_updates = true;
2493                         }
2494                     }
2495                 }
2496             }
2497
2498             if (!row->old || !shash_is_empty(json_object(row_json))) {
2499                 json_array_add(operations, op);
2500             } else {
2501                 json_destroy(op);
2502             }
2503         }
2504
2505         /* Add mutate operation, for partial map updates. */
2506         if (row->map_op_written) {
2507             struct json *op, *mutations;
2508             bool any_mutations;
2509
2510             op = json_object_create();
2511             json_object_put_string(op, "op", "mutate");
2512             json_object_put_string(op, "table", class->name);
2513             json_object_put(op, "where", where_uuid_equals(&row->uuid));
2514             mutations = json_array_create_empty();
2515             any_mutations = ovsdb_idl_txn_extract_mutations(row, mutations);
2516             json_object_put(op, "mutations", mutations);
2517
2518             if (any_mutations) {
2519                 op = substitute_uuids(op, txn);
2520                 json_array_add(operations, op);
2521                 any_updates = true;
2522             } else {
2523                 json_destroy(op);
2524             }
2525         }
2526     }
2527
2528     /* Add increment. */
2529     if (txn->inc_table && any_updates) {
2530         struct json *op;
2531
2532         txn->inc_index = operations->u.array.n - 1;
2533
2534         op = json_object_create();
2535         json_object_put_string(op, "op", "mutate");
2536         json_object_put_string(op, "table", txn->inc_table);
2537         json_object_put(op, "where",
2538                         substitute_uuids(where_uuid_equals(&txn->inc_row),
2539                                          txn));
2540         json_object_put(op, "mutations",
2541                         json_array_create_1(
2542                             json_array_create_3(
2543                                 json_string_create(txn->inc_column),
2544                                 json_string_create("+="),
2545                                 json_integer_create(1))));
2546         json_array_add(operations, op);
2547
2548         op = json_object_create();
2549         json_object_put_string(op, "op", "select");
2550         json_object_put_string(op, "table", txn->inc_table);
2551         json_object_put(op, "where",
2552                         substitute_uuids(where_uuid_equals(&txn->inc_row),
2553                                          txn));
2554         json_object_put(op, "columns",
2555                         json_array_create_1(json_string_create(
2556                                                 txn->inc_column)));
2557         json_array_add(operations, op);
2558     }
2559
2560     if (txn->comment.length) {
2561         struct json *op = json_object_create();
2562         json_object_put_string(op, "op", "comment");
2563         json_object_put_string(op, "comment", ds_cstr(&txn->comment));
2564         json_array_add(operations, op);
2565     }
2566
2567     if (txn->dry_run) {
2568         struct json *op = json_object_create();
2569         json_object_put_string(op, "op", "abort");
2570         json_array_add(operations, op);
2571     }
2572
2573     if (!any_updates) {
2574         txn->status = TXN_UNCHANGED;
2575         json_destroy(operations);
2576     } else if (!jsonrpc_session_send(
2577                    txn->idl->session,
2578                    jsonrpc_create_request(
2579                        "transact", operations, &txn->request_id))) {
2580         hmap_insert(&txn->idl->outstanding_txns, &txn->hmap_node,
2581                     json_hash(txn->request_id, 0));
2582         txn->status = TXN_INCOMPLETE;
2583     } else {
2584         txn->status = TXN_TRY_AGAIN;
2585     }
2586
2587 disassemble_out:
2588     ovsdb_idl_txn_disassemble(txn);
2589 coverage_out:
2590     switch (txn->status) {
2591     case TXN_UNCOMMITTED:   COVERAGE_INC(txn_uncommitted);    break;
2592     case TXN_UNCHANGED:     COVERAGE_INC(txn_unchanged);      break;
2593     case TXN_INCOMPLETE:    COVERAGE_INC(txn_incomplete);     break;
2594     case TXN_ABORTED:       COVERAGE_INC(txn_aborted);        break;
2595     case TXN_SUCCESS:       COVERAGE_INC(txn_success);        break;
2596     case TXN_TRY_AGAIN:     COVERAGE_INC(txn_try_again);      break;
2597     case TXN_NOT_LOCKED:    COVERAGE_INC(txn_not_locked);     break;
2598     case TXN_ERROR:         COVERAGE_INC(txn_error);          break;
2599     }
2600
2601     return txn->status;
2602 }
2603
2604 /* Attempts to commit 'txn', blocking until the commit either succeeds or
2605  * fails.  Returns the final commit status, which may be any TXN_* value other
2606  * than TXN_INCOMPLETE.
2607  *
2608  * This function calls ovsdb_idl_run() on 'txn''s IDL, so it may cause the
2609  * return value of ovsdb_idl_get_seqno() to change. */
2610 enum ovsdb_idl_txn_status
2611 ovsdb_idl_txn_commit_block(struct ovsdb_idl_txn *txn)
2612 {
2613     enum ovsdb_idl_txn_status status;
2614
2615     fatal_signal_run();
2616     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
2617         ovsdb_idl_run(txn->idl);
2618         ovsdb_idl_wait(txn->idl);
2619         ovsdb_idl_txn_wait(txn);
2620         poll_block();
2621     }
2622     return status;
2623 }
2624
2625 /* Returns the final (incremented) value of the column in 'txn' that was set to
2626  * be incremented by ovsdb_idl_txn_increment().  'txn' must have committed
2627  * successfully. */
2628 int64_t
2629 ovsdb_idl_txn_get_increment_new_value(const struct ovsdb_idl_txn *txn)
2630 {
2631     ovs_assert(txn->status == TXN_SUCCESS);
2632     return txn->inc_new_value;
2633 }
2634
2635 /* Aborts 'txn' without sending it to the database server.  This is effective
2636  * only if ovsdb_idl_txn_commit() has not yet been called for 'txn'.
2637  * Otherwise, it has no effect.
2638  *
2639  * Aborting a transaction doesn't free its memory.  Use
2640  * ovsdb_idl_txn_destroy() to do that. */
2641 void
2642 ovsdb_idl_txn_abort(struct ovsdb_idl_txn *txn)
2643 {
2644     ovsdb_idl_txn_disassemble(txn);
2645     if (txn->status == TXN_UNCOMMITTED || txn->status == TXN_INCOMPLETE) {
2646         txn->status = TXN_ABORTED;
2647     }
2648 }
2649
2650 /* Returns a string that reports the error status for 'txn'.  The caller must
2651  * not modify or free the returned string.  A call to ovsdb_idl_txn_destroy()
2652  * for 'txn' may free the returned string.
2653  *
2654  * The return value is ordinarily one of the strings that
2655  * ovsdb_idl_txn_status_to_string() would return, but if the transaction failed
2656  * due to an error reported by the database server, the return value is that
2657  * error. */
2658 const char *
2659 ovsdb_idl_txn_get_error(const struct ovsdb_idl_txn *txn)
2660 {
2661     if (txn->status != TXN_ERROR) {
2662         return ovsdb_idl_txn_status_to_string(txn->status);
2663     } else if (txn->error) {
2664         return txn->error;
2665     } else {
2666         return "no error details available";
2667     }
2668 }
2669
2670 static void
2671 ovsdb_idl_txn_set_error_json(struct ovsdb_idl_txn *txn,
2672                              const struct json *json)
2673 {
2674     if (txn->error == NULL) {
2675         txn->error = json_to_string(json, JSSF_SORT);
2676     }
2677 }
2678
2679 /* For transaction 'txn' that completed successfully, finds and returns the
2680  * permanent UUID that the database assigned to a newly inserted row, given the
2681  * 'uuid' that ovsdb_idl_txn_insert() assigned locally to that row.
2682  *
2683  * Returns NULL if 'uuid' is not a UUID assigned by ovsdb_idl_txn_insert() or
2684  * if it was assigned by that function and then deleted by
2685  * ovsdb_idl_txn_delete() within the same transaction.  (Rows that are inserted
2686  * and then deleted within a single transaction are never sent to the database
2687  * server, so it never assigns them a permanent UUID.) */
2688 const struct uuid *
2689 ovsdb_idl_txn_get_insert_uuid(const struct ovsdb_idl_txn *txn,
2690                               const struct uuid *uuid)
2691 {
2692     const struct ovsdb_idl_txn_insert *insert;
2693
2694     ovs_assert(txn->status == TXN_SUCCESS || txn->status == TXN_UNCHANGED);
2695     HMAP_FOR_EACH_IN_BUCKET (insert, hmap_node,
2696                              uuid_hash(uuid), &txn->inserted_rows) {
2697         if (uuid_equals(uuid, &insert->dummy)) {
2698             return &insert->real;
2699         }
2700     }
2701     return NULL;
2702 }
2703
2704 static void
2705 ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
2706                        enum ovsdb_idl_txn_status status)
2707 {
2708     txn->status = status;
2709     hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
2710 }
2711
2712 /* Writes 'datum' to the specified 'column' in 'row_'.  Updates both 'row_'
2713  * itself and the structs derived from it (e.g. the "struct ovsrec_*", for
2714  * ovs-vswitchd).
2715  *
2716  * 'datum' must have the correct type for its column.  The IDL does not check
2717  * that it meets schema constraints, but ovsdb-server will do so at commit time
2718  * so it had better be correct.
2719  *
2720  * A transaction must be in progress.  Replication of 'column' must not have
2721  * been disabled (by calling ovsdb_idl_omit()).
2722  *
2723  * Usually this function is used indirectly through one of the "set" functions
2724  * generated by ovsdb-idlc.
2725  *
2726  * Takes ownership of what 'datum' points to (and in some cases destroys that
2727  * data before returning) but makes a copy of 'datum' itself.  (Commonly
2728  * 'datum' is on the caller's stack.) */
2729 static void
2730 ovsdb_idl_txn_write__(const struct ovsdb_idl_row *row_,
2731                       const struct ovsdb_idl_column *column,
2732                       struct ovsdb_datum *datum, bool owns_datum)
2733 {
2734     struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
2735     const struct ovsdb_idl_table_class *class;
2736     size_t column_idx;
2737     bool write_only;
2738
2739     if (ovsdb_idl_row_is_synthetic(row)) {
2740         goto discard_datum;
2741     }
2742
2743     class = row->table->class;
2744     column_idx = column - class->columns;
2745     write_only = row->table->modes[column_idx] == OVSDB_IDL_MONITOR;
2746
2747     ovs_assert(row->new != NULL);
2748     ovs_assert(column_idx < class->n_columns);
2749     ovs_assert(row->old == NULL ||
2750                row->table->modes[column_idx] & OVSDB_IDL_MONITOR);
2751
2752     if (row->table->idl->verify_write_only && !write_only) {
2753         VLOG_ERR("Bug: Attempt to write to a read/write column (%s:%s) when"
2754                  " explicitly configured not to.", class->name, column->name);
2755         goto discard_datum;
2756     }
2757
2758     /* If this is a write-only column and the datum being written is the same
2759      * as the one already there, just skip the update entirely.  This is worth
2760      * optimizing because we have a lot of columns that get periodically
2761      * refreshed into the database but don't actually change that often.
2762      *
2763      * We don't do this for read/write columns because that would break
2764      * atomicity of transactions--some other client might have written a
2765      * different value in that column since we read it.  (But if a whole
2766      * transaction only does writes of existing values, without making any real
2767      * changes, we will drop the whole transaction later in
2768      * ovsdb_idl_txn_commit().) */
2769     if (write_only && ovsdb_datum_equals(ovsdb_idl_read(row, column),
2770                                          datum, &column->type)) {
2771         goto discard_datum;
2772     }
2773
2774     if (hmap_node_is_null(&row->txn_node)) {
2775         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
2776                     uuid_hash(&row->uuid));
2777     }
2778     if (row->old == row->new) {
2779         row->new = xmalloc(class->n_columns * sizeof *row->new);
2780     }
2781     if (!row->written) {
2782         row->written = bitmap_allocate(class->n_columns);
2783     }
2784     if (bitmap_is_set(row->written, column_idx)) {
2785         ovsdb_datum_destroy(&row->new[column_idx], &column->type);
2786     } else {
2787         bitmap_set1(row->written, column_idx);
2788     }
2789     if (owns_datum) {
2790         row->new[column_idx] = *datum;
2791     } else {
2792         ovsdb_datum_clone(&row->new[column_idx], datum, &column->type);
2793     }
2794     (column->unparse)(row);
2795     (column->parse)(row, &row->new[column_idx]);
2796     return;
2797
2798 discard_datum:
2799     if (owns_datum) {
2800         ovsdb_datum_destroy(datum, &column->type);
2801     }
2802 }
2803
2804 void
2805 ovsdb_idl_txn_write(const struct ovsdb_idl_row *row,
2806                     const struct ovsdb_idl_column *column,
2807                     struct ovsdb_datum *datum)
2808 {
2809     ovsdb_idl_txn_write__(row, column, datum, true);
2810 }
2811
2812 void
2813 ovsdb_idl_txn_write_clone(const struct ovsdb_idl_row *row,
2814                           const struct ovsdb_idl_column *column,
2815                           const struct ovsdb_datum *datum)
2816 {
2817     ovsdb_idl_txn_write__(row, column,
2818                           CONST_CAST(struct ovsdb_datum *, datum), false);
2819 }
2820
2821 /* Causes the original contents of 'column' in 'row_' to be verified as a
2822  * prerequisite to completing the transaction.  That is, if 'column' in 'row_'
2823  * changed (or if 'row_' was deleted) between the time that the IDL originally
2824  * read its contents and the time that the transaction commits, then the
2825  * transaction aborts and ovsdb_idl_txn_commit() returns TXN_AGAIN_WAIT or
2826  * TXN_AGAIN_NOW (depending on whether the database change has already been
2827  * received).
2828  *
2829  * The intention is that, to ensure that no transaction commits based on dirty
2830  * reads, an application should call ovsdb_idl_txn_verify() on each data item
2831  * read as part of a read-modify-write operation.
2832  *
2833  * In some cases ovsdb_idl_txn_verify() reduces to a no-op, because the current
2834  * value of 'column' is already known:
2835  *
2836  *   - If 'row_' is a row created by the current transaction (returned by
2837  *     ovsdb_idl_txn_insert()).
2838  *
2839  *   - If 'column' has already been modified (with ovsdb_idl_txn_write())
2840  *     within the current transaction.
2841  *
2842  * Because of the latter property, always call ovsdb_idl_txn_verify() *before*
2843  * ovsdb_idl_txn_write() for a given read-modify-write.
2844  *
2845  * A transaction must be in progress.
2846  *
2847  * Usually this function is used indirectly through one of the "verify"
2848  * functions generated by ovsdb-idlc. */
2849 void
2850 ovsdb_idl_txn_verify(const struct ovsdb_idl_row *row_,
2851                      const struct ovsdb_idl_column *column)
2852 {
2853     struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
2854     const struct ovsdb_idl_table_class *class;
2855     size_t column_idx;
2856
2857     if (ovsdb_idl_row_is_synthetic(row)) {
2858         return;
2859     }
2860
2861     class = row->table->class;
2862     column_idx = column - class->columns;
2863
2864     ovs_assert(row->new != NULL);
2865     ovs_assert(row->old == NULL ||
2866                row->table->modes[column_idx] & OVSDB_IDL_MONITOR);
2867     if (!row->old
2868         || (row->written && bitmap_is_set(row->written, column_idx))) {
2869         return;
2870     }
2871
2872     if (hmap_node_is_null(&row->txn_node)) {
2873         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
2874                     uuid_hash(&row->uuid));
2875     }
2876     if (!row->prereqs) {
2877         row->prereqs = bitmap_allocate(class->n_columns);
2878     }
2879     bitmap_set1(row->prereqs, column_idx);
2880 }
2881
2882 /* Deletes 'row_' from its table.  May free 'row_', so it must not be
2883  * accessed afterward.
2884  *
2885  * A transaction must be in progress.
2886  *
2887  * Usually this function is used indirectly through one of the "delete"
2888  * functions generated by ovsdb-idlc. */
2889 void
2890 ovsdb_idl_txn_delete(const struct ovsdb_idl_row *row_)
2891 {
2892     struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
2893
2894     if (ovsdb_idl_row_is_synthetic(row)) {
2895         return;
2896     }
2897
2898     ovs_assert(row->new != NULL);
2899     if (!row->old) {
2900         ovsdb_idl_row_unparse(row);
2901         ovsdb_idl_row_clear_new(row);
2902         ovs_assert(!row->prereqs);
2903         hmap_remove(&row->table->rows, &row->hmap_node);
2904         hmap_remove(&row->table->idl->txn->txn_rows, &row->txn_node);
2905         free(row);
2906         return;
2907     }
2908     if (hmap_node_is_null(&row->txn_node)) {
2909         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
2910                     uuid_hash(&row->uuid));
2911     }
2912     ovsdb_idl_row_clear_new(row);
2913     row->new = NULL;
2914 }
2915
2916 /* Inserts and returns a new row in the table with the specified 'class' in the
2917  * database with open transaction 'txn'.
2918  *
2919  * The new row is assigned a provisional UUID.  If 'uuid' is null then one is
2920  * randomly generated; otherwise 'uuid' should specify a randomly generated
2921  * UUID not otherwise in use.  ovsdb-server will assign a different UUID when
2922  * 'txn' is committed, but the IDL will replace any uses of the provisional
2923  * UUID in the data to be to be committed by the UUID assigned by
2924  * ovsdb-server.
2925  *
2926  * Usually this function is used indirectly through one of the "insert"
2927  * functions generated by ovsdb-idlc. */
2928 const struct ovsdb_idl_row *
2929 ovsdb_idl_txn_insert(struct ovsdb_idl_txn *txn,
2930                      const struct ovsdb_idl_table_class *class,
2931                      const struct uuid *uuid)
2932 {
2933     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(class);
2934
2935     if (uuid) {
2936         ovs_assert(!ovsdb_idl_txn_get_row(txn, uuid));
2937         row->uuid = *uuid;
2938     } else {
2939         uuid_generate(&row->uuid);
2940     }
2941
2942     row->table = ovsdb_idl_table_from_class(txn->idl, class);
2943     row->new = xmalloc(class->n_columns * sizeof *row->new);
2944     hmap_insert(&row->table->rows, &row->hmap_node, uuid_hash(&row->uuid));
2945     hmap_insert(&txn->txn_rows, &row->txn_node, uuid_hash(&row->uuid));
2946     return row;
2947 }
2948
2949 static void
2950 ovsdb_idl_txn_abort_all(struct ovsdb_idl *idl)
2951 {
2952     struct ovsdb_idl_txn *txn;
2953
2954     HMAP_FOR_EACH (txn, hmap_node, &idl->outstanding_txns) {
2955         ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
2956     }
2957 }
2958
2959 static struct ovsdb_idl_txn *
2960 ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
2961 {
2962     struct ovsdb_idl_txn *txn;
2963
2964     HMAP_FOR_EACH_WITH_HASH (txn, hmap_node,
2965                              json_hash(id, 0), &idl->outstanding_txns) {
2966         if (json_equal(id, txn->request_id)) {
2967             return txn;
2968         }
2969     }
2970     return NULL;
2971 }
2972
2973 static bool
2974 check_json_type(const struct json *json, enum json_type type, const char *name)
2975 {
2976     if (!json) {
2977         VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
2978         return false;
2979     } else if (json->type != type) {
2980         VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
2981                      name, json_type_to_string(json->type),
2982                      json_type_to_string(type));
2983         return false;
2984     } else {
2985         return true;
2986     }
2987 }
2988
2989 static bool
2990 ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
2991                                 const struct json_array *results)
2992 {
2993     struct json *count, *rows, *row, *column;
2994     struct shash *mutate, *select;
2995
2996     if (txn->inc_index + 2 > results->n) {
2997         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
2998                      "for increment (has %"PRIuSIZE", needs %u)",
2999                      results->n, txn->inc_index + 2);
3000         return false;
3001     }
3002
3003     /* We know that this is a JSON object because the loop in
3004      * ovsdb_idl_txn_process_reply() checked. */
3005     mutate = json_object(results->elems[txn->inc_index]);
3006     count = shash_find_data(mutate, "count");
3007     if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
3008         return false;
3009     }
3010     if (count->u.integer != 1) {
3011         VLOG_WARN_RL(&syntax_rl,
3012                      "\"mutate\" reply \"count\" is %lld instead of 1",
3013                      count->u.integer);
3014         return false;
3015     }
3016
3017     select = json_object(results->elems[txn->inc_index + 1]);
3018     rows = shash_find_data(select, "rows");
3019     if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
3020         return false;
3021     }
3022     if (rows->u.array.n != 1) {
3023         VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %"PRIuSIZE" elements "
3024                      "instead of 1",
3025                      rows->u.array.n);
3026         return false;
3027     }
3028     row = rows->u.array.elems[0];
3029     if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
3030         return false;
3031     }
3032     column = shash_find_data(json_object(row), txn->inc_column);
3033     if (!check_json_type(column, JSON_INTEGER,
3034                          "\"select\" reply inc column")) {
3035         return false;
3036     }
3037     txn->inc_new_value = column->u.integer;
3038     return true;
3039 }
3040
3041 static bool
3042 ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
3043                                    const struct json_array *results)
3044 {
3045     static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
3046     struct ovsdb_error *error;
3047     struct json *json_uuid;
3048     union ovsdb_atom uuid;
3049     struct shash *reply;
3050
3051     if (insert->op_index >= results->n) {
3052         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
3053                      "for insert (has %"PRIuSIZE", needs %u)",
3054                      results->n, insert->op_index);
3055         return false;
3056     }
3057
3058     /* We know that this is a JSON object because the loop in
3059      * ovsdb_idl_txn_process_reply() checked. */
3060     reply = json_object(results->elems[insert->op_index]);
3061     json_uuid = shash_find_data(reply, "uuid");
3062     if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
3063         return false;
3064     }
3065
3066     error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
3067     if (error) {
3068         char *s = ovsdb_error_to_string(error);
3069         VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
3070                      "UUID: %s", s);
3071         free(s);
3072         ovsdb_error_destroy(error);
3073         return false;
3074     }
3075
3076     insert->real = uuid.uuid;
3077
3078     return true;
3079 }
3080
3081 static bool
3082 ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
3083                             const struct jsonrpc_msg *msg)
3084 {
3085     struct ovsdb_idl_txn *txn;
3086     enum ovsdb_idl_txn_status status;
3087
3088     txn = ovsdb_idl_txn_find(idl, msg->id);
3089     if (!txn) {
3090         return false;
3091     }
3092
3093     if (msg->type == JSONRPC_ERROR) {
3094         status = TXN_ERROR;
3095     } else if (msg->result->type != JSON_ARRAY) {
3096         VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
3097         status = TXN_ERROR;
3098     } else {
3099         struct json_array *ops = &msg->result->u.array;
3100         int hard_errors = 0;
3101         int soft_errors = 0;
3102         int lock_errors = 0;
3103         size_t i;
3104
3105         for (i = 0; i < ops->n; i++) {
3106             struct json *op = ops->elems[i];
3107
3108             if (op->type == JSON_NULL) {
3109                 /* This isn't an error in itself but indicates that some prior
3110                  * operation failed, so make sure that we know about it. */
3111                 soft_errors++;
3112             } else if (op->type == JSON_OBJECT) {
3113                 struct json *error;
3114
3115                 error = shash_find_data(json_object(op), "error");
3116                 if (error) {
3117                     if (error->type == JSON_STRING) {
3118                         if (!strcmp(error->u.string, "timed out")) {
3119                             soft_errors++;
3120                         } else if (!strcmp(error->u.string, "not owner")) {
3121                             lock_errors++;
3122                         } else if (strcmp(error->u.string, "aborted")) {
3123                             hard_errors++;
3124                             ovsdb_idl_txn_set_error_json(txn, op);
3125                         }
3126                     } else {
3127                         hard_errors++;
3128                         ovsdb_idl_txn_set_error_json(txn, op);
3129                         VLOG_WARN_RL(&syntax_rl,
3130                                      "\"error\" in reply is not JSON string");
3131                     }
3132                 }
3133             } else {
3134                 hard_errors++;
3135                 ovsdb_idl_txn_set_error_json(txn, op);
3136                 VLOG_WARN_RL(&syntax_rl,
3137                              "operation reply is not JSON null or object");
3138             }
3139         }
3140
3141         if (!soft_errors && !hard_errors && !lock_errors) {
3142             struct ovsdb_idl_txn_insert *insert;
3143
3144             if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
3145                 hard_errors++;
3146             }
3147
3148             HMAP_FOR_EACH (insert, hmap_node, &txn->inserted_rows) {
3149                 if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
3150                     hard_errors++;
3151                 }
3152             }
3153         }
3154
3155         status = (hard_errors ? TXN_ERROR
3156                   : lock_errors ? TXN_NOT_LOCKED
3157                   : soft_errors ? TXN_TRY_AGAIN
3158                   : TXN_SUCCESS);
3159     }
3160
3161     ovsdb_idl_txn_complete(txn, status);
3162     return true;
3163 }
3164
3165 /* Returns the transaction currently active for 'row''s IDL.  A transaction
3166  * must currently be active. */
3167 struct ovsdb_idl_txn *
3168 ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
3169 {
3170     struct ovsdb_idl_txn *txn = row->table->idl->txn;
3171     ovs_assert(txn != NULL);
3172     return txn;
3173 }
3174
3175 /* Returns the IDL on which 'txn' acts. */
3176 struct ovsdb_idl *
3177 ovsdb_idl_txn_get_idl (struct ovsdb_idl_txn *txn)
3178 {
3179     return txn->idl;
3180 }
3181
3182 /* Blocks until 'idl' successfully connects to the remote database and
3183  * retrieves its contents. */
3184 void
3185 ovsdb_idl_get_initial_snapshot(struct ovsdb_idl *idl)
3186 {
3187     while (1) {
3188         ovsdb_idl_run(idl);
3189         if (ovsdb_idl_has_ever_connected(idl)) {
3190             return;
3191         }
3192         ovsdb_idl_wait(idl);
3193         poll_block();
3194     }
3195 }
3196 \f
3197 /* If 'lock_name' is nonnull, configures 'idl' to obtain the named lock from
3198  * the database server and to avoid modifying the database when the lock cannot
3199  * be acquired (that is, when another client has the same lock).
3200  *
3201  * If 'lock_name' is NULL, drops the locking requirement and releases the
3202  * lock. */
3203 void
3204 ovsdb_idl_set_lock(struct ovsdb_idl *idl, const char *lock_name)
3205 {
3206     ovs_assert(!idl->txn);
3207     ovs_assert(hmap_is_empty(&idl->outstanding_txns));
3208
3209     if (idl->lock_name && (!lock_name || strcmp(lock_name, idl->lock_name))) {
3210         /* Release previous lock. */
3211         ovsdb_idl_send_unlock_request(idl);
3212         free(idl->lock_name);
3213         idl->lock_name = NULL;
3214         idl->is_lock_contended = false;
3215     }
3216
3217     if (lock_name && !idl->lock_name) {
3218         /* Acquire new lock. */
3219         idl->lock_name = xstrdup(lock_name);
3220         ovsdb_idl_send_lock_request(idl);
3221     }
3222 }
3223
3224 /* Returns true if 'idl' is configured to obtain a lock and owns that lock.
3225  *
3226  * Locking and unlocking happens asynchronously from the database client's
3227  * point of view, so the information is only useful for optimization (e.g. if
3228  * the client doesn't have the lock then there's no point in trying to write to
3229  * the database). */
3230 bool
3231 ovsdb_idl_has_lock(const struct ovsdb_idl *idl)
3232 {
3233     return idl->has_lock;
3234 }
3235
3236 /* Returns true if 'idl' is configured to obtain a lock but the database server
3237  * has indicated that some other client already owns the requested lock. */
3238 bool
3239 ovsdb_idl_is_lock_contended(const struct ovsdb_idl *idl)
3240 {
3241     return idl->is_lock_contended;
3242 }
3243
3244 static void
3245 ovsdb_idl_update_has_lock(struct ovsdb_idl *idl, bool new_has_lock)
3246 {
3247     if (new_has_lock && !idl->has_lock) {
3248         if (idl->state == IDL_S_MONITORING ||
3249             idl->state == IDL_S_MONITORING2) {
3250             idl->change_seqno++;
3251         } else {
3252             /* We're setting up a session, so don't signal that the database
3253              * changed.  Finalizing the session will increment change_seqno
3254              * anyhow. */
3255         }
3256         idl->is_lock_contended = false;
3257     }
3258     idl->has_lock = new_has_lock;
3259 }
3260
3261 static void
3262 ovsdb_idl_send_lock_request__(struct ovsdb_idl *idl, const char *method,
3263                               struct json **idp)
3264 {
3265     ovsdb_idl_update_has_lock(idl, false);
3266
3267     json_destroy(idl->lock_request_id);
3268     idl->lock_request_id = NULL;
3269
3270     if (jsonrpc_session_is_connected(idl->session)) {
3271         struct json *params;
3272
3273         params = json_array_create_1(json_string_create(idl->lock_name));
3274         jsonrpc_session_send(idl->session,
3275                              jsonrpc_create_request(method, params, idp));
3276     }
3277 }
3278
3279 static void
3280 ovsdb_idl_send_lock_request(struct ovsdb_idl *idl)
3281 {
3282     ovsdb_idl_send_lock_request__(idl, "lock", &idl->lock_request_id);
3283 }
3284
3285 static void
3286 ovsdb_idl_send_unlock_request(struct ovsdb_idl *idl)
3287 {
3288     ovsdb_idl_send_lock_request__(idl, "unlock", NULL);
3289 }
3290
3291 static void
3292 ovsdb_idl_parse_lock_reply(struct ovsdb_idl *idl, const struct json *result)
3293 {
3294     bool got_lock;
3295
3296     json_destroy(idl->lock_request_id);
3297     idl->lock_request_id = NULL;
3298
3299     if (result->type == JSON_OBJECT) {
3300         const struct json *locked;
3301
3302         locked = shash_find_data(json_object(result), "locked");
3303         got_lock = locked && locked->type == JSON_TRUE;
3304     } else {
3305         got_lock = false;
3306     }
3307
3308     ovsdb_idl_update_has_lock(idl, got_lock);
3309     if (!got_lock) {
3310         idl->is_lock_contended = true;
3311     }
3312 }
3313
3314 static void
3315 ovsdb_idl_parse_lock_notify(struct ovsdb_idl *idl,
3316                             const struct json *params,
3317                             bool new_has_lock)
3318 {
3319     if (idl->lock_name
3320         && params->type == JSON_ARRAY
3321         && json_array(params)->n > 0
3322         && json_array(params)->elems[0]->type == JSON_STRING) {
3323         const char *lock_name = json_string(json_array(params)->elems[0]);
3324
3325         if (!strcmp(idl->lock_name, lock_name)) {
3326             ovsdb_idl_update_has_lock(idl, new_has_lock);
3327             if (!new_has_lock) {
3328                 idl->is_lock_contended = true;
3329             }
3330         }
3331     }
3332 }
3333
3334 /* Inserts a new Map Operation into current transaction. */
3335 static void
3336 ovsdb_idl_txn_add_map_op(struct ovsdb_idl_row *row,
3337                          const struct ovsdb_idl_column *column,
3338                          struct ovsdb_datum *datum,
3339                          enum map_op_type op_type)
3340 {
3341     const struct ovsdb_idl_table_class *class;
3342     size_t column_idx;
3343     struct map_op *map_op;
3344
3345     class = row->table->class;
3346     column_idx = column - class->columns;
3347
3348     /* Check if a map operation list exists for this column. */
3349     if (!row->map_op_written) {
3350         row->map_op_written = bitmap_allocate(class->n_columns);
3351         row->map_op_lists = xzalloc(class->n_columns *
3352                                     sizeof *row->map_op_lists);
3353     }
3354     if (!row->map_op_lists[column_idx]) {
3355         row->map_op_lists[column_idx] = map_op_list_create();
3356     }
3357
3358     /* Add a map operation to the corresponding list. */
3359     map_op = map_op_create(datum, op_type);
3360     bitmap_set1(row->map_op_written, column_idx);
3361     map_op_list_add(row->map_op_lists[column_idx], map_op, &column->type);
3362
3363     /* Add this row to transaction's list of rows. */
3364     if (hmap_node_is_null(&row->txn_node)) {
3365         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
3366                     uuid_hash(&row->uuid));
3367     }
3368 }
3369
3370 static bool
3371 is_valid_partial_update(const struct ovsdb_idl_row *row,
3372                         const struct ovsdb_idl_column *column,
3373                         struct ovsdb_datum *datum)
3374 {
3375     /* Verify that this column is being monitored. */
3376     unsigned int column_idx = column - row->table->class->columns;
3377     if (!(row->table->modes[column_idx] & OVSDB_IDL_MONITOR)) {
3378         VLOG_WARN("cannot partially update non-monitored column");
3379         return false;
3380     }
3381
3382     /* Verify that the update affects a single element. */
3383     if (datum->n != 1) {
3384         VLOG_WARN("invalid datum for partial update");
3385         return false;
3386     }
3387
3388     return true;
3389 }
3390
3391 /* Inserts the key-value specified in 'datum' into the map in 'column' in
3392  * 'row_'. If the key already exist in 'column', then it's value is updated
3393  * with the value in 'datum'. The key-value in 'datum' must be of the same type
3394  * as the keys-values in 'column'. This function takes ownership of 'datum'.
3395  *
3396  * Usually this function is used indirectly through one of the "update"
3397  * functions generated by vswitch-idl. */
3398 void
3399 ovsdb_idl_txn_write_partial_map(const struct ovsdb_idl_row *row_,
3400                                 const struct ovsdb_idl_column *column,
3401                                 struct ovsdb_datum *datum)
3402 {
3403     struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
3404     enum ovsdb_atomic_type key_type;
3405     enum map_op_type op_type;
3406     unsigned int pos;
3407     const struct ovsdb_datum *old_datum;
3408
3409     if (!is_valid_partial_update(row, column, datum)) {
3410         ovsdb_datum_destroy(datum, &column->type);
3411         return;
3412     }
3413
3414     /* Find out if this is an insert or an update. */
3415     key_type = column->type.key.type;
3416     old_datum = ovsdb_idl_read(row, column);
3417     pos = ovsdb_datum_find_key(old_datum, &datum->keys[0], key_type);
3418     op_type = pos == UINT_MAX ? MAP_OP_INSERT : MAP_OP_UPDATE;
3419
3420     ovsdb_idl_txn_add_map_op(row, column, datum, op_type);
3421 }
3422
3423 /* Deletes the key specified in 'datum' from the map in 'column' in 'row_'.
3424  * The key in 'datum' must be of the same type as the keys in 'column'.
3425  * The value in 'datum' must be NULL. This function takes ownership of
3426  * 'datum'.
3427  *
3428  * Usually this function is used indirectly through one of the "update"
3429  * functions generated by vswitch-idl. */
3430 void
3431 ovsdb_idl_txn_delete_partial_map(const struct ovsdb_idl_row *row_,
3432                                  const struct ovsdb_idl_column *column,
3433                                  struct ovsdb_datum *datum)
3434 {
3435     struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
3436
3437     if (!is_valid_partial_update(row, column, datum)) {
3438         struct ovsdb_type type_ = column->type;
3439         type_.value.type = OVSDB_TYPE_VOID;
3440         ovsdb_datum_destroy(datum, &type_);
3441         return;
3442     }
3443     ovsdb_idl_txn_add_map_op(row, column, datum, MAP_OP_DELETE);
3444 }
3445
3446 void
3447 ovsdb_idl_loop_destroy(struct ovsdb_idl_loop *loop)
3448 {
3449     if (loop) {
3450         ovsdb_idl_destroy(loop->idl);
3451     }
3452 }
3453
3454 struct ovsdb_idl_txn *
3455 ovsdb_idl_loop_run(struct ovsdb_idl_loop *loop)
3456 {
3457     ovsdb_idl_run(loop->idl);
3458     loop->open_txn = (loop->committing_txn
3459                       || ovsdb_idl_get_seqno(loop->idl) == loop->skip_seqno
3460                       ? NULL
3461                       : ovsdb_idl_txn_create(loop->idl));
3462     return loop->open_txn;
3463 }
3464
3465 void
3466 ovsdb_idl_loop_commit_and_wait(struct ovsdb_idl_loop *loop)
3467 {
3468     if (loop->open_txn) {
3469         loop->committing_txn = loop->open_txn;
3470         loop->open_txn = NULL;
3471
3472         loop->precommit_seqno = ovsdb_idl_get_seqno(loop->idl);
3473     }
3474
3475     struct ovsdb_idl_txn *txn = loop->committing_txn;
3476     if (txn) {
3477         enum ovsdb_idl_txn_status status = ovsdb_idl_txn_commit(txn);
3478         if (status != TXN_INCOMPLETE) {
3479             switch (status) {
3480             case TXN_TRY_AGAIN:
3481                 /* We want to re-evaluate the database when it's changed from
3482                  * the contents that it had when we started the commit.  (That
3483                  * might have already happened.) */
3484                 loop->skip_seqno = loop->precommit_seqno;
3485                 if (ovsdb_idl_get_seqno(loop->idl) != loop->skip_seqno) {
3486                     poll_immediate_wake();
3487                 }
3488                 break;
3489
3490             case TXN_SUCCESS:
3491                 /* If the database has already changed since we started the
3492                  * commit, re-evaluate it immediately to avoid missing a change
3493                  * for a while. */
3494                 if (ovsdb_idl_get_seqno(loop->idl) != loop->precommit_seqno) {
3495                     poll_immediate_wake();
3496                 }
3497                 break;
3498
3499             case TXN_UNCHANGED:
3500             case TXN_ABORTED:
3501             case TXN_NOT_LOCKED:
3502             case TXN_ERROR:
3503                 break;
3504
3505             case TXN_UNCOMMITTED:
3506             case TXN_INCOMPLETE:
3507                 OVS_NOT_REACHED();
3508
3509             }
3510             ovsdb_idl_txn_destroy(txn);
3511             loop->committing_txn = NULL;
3512         }
3513     }
3514
3515     ovsdb_idl_wait(loop->idl);
3516 }