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