ovsdb-idl: Transition to better interfaces for reading table columns.
[cascardo/ovs.git] / lib / ovsdb-idl.c
1 /* Copyright (c) 2009, 2010 Nicira Networks.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "ovsdb-idl.h"
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <stdlib.h>
25
26 #include "bitmap.h"
27 #include "dynamic-string.h"
28 #include "fatal-signal.h"
29 #include "json.h"
30 #include "jsonrpc.h"
31 #include "ovsdb-data.h"
32 #include "ovsdb-error.h"
33 #include "ovsdb-idl-provider.h"
34 #include "poll-loop.h"
35 #include "shash.h"
36 #include "util.h"
37
38 #define THIS_MODULE VLM_ovsdb_idl
39 #include "vlog.h"
40
41 /* An arc from one idl_row to another.  When row A contains a UUID that
42  * references row B, this is represented by an arc from A (the source) to B
43  * (the destination).
44  *
45  * Arcs from a row to itself are omitted, that is, src and dst are always
46  * different.
47  *
48  * Arcs are never duplicated, that is, even if there are multiple references
49  * from A to B, there is only a single arc from A to B.
50  *
51  * Arcs are directed: an arc from A to B is the converse of an an arc from B to
52  * A.  Both an arc and its converse may both be present, if each row refers
53  * to the other circularly.
54  *
55  * The source and destination row may be in the same table or in different
56  * tables.
57  */
58 struct ovsdb_idl_arc {
59     struct list src_node;       /* In src->src_arcs list. */
60     struct list dst_node;       /* In dst->dst_arcs list. */
61     struct ovsdb_idl_row *src;  /* Source row. */
62     struct ovsdb_idl_row *dst;  /* Destination row. */
63 };
64
65 struct ovsdb_idl {
66     const struct ovsdb_idl_class *class;
67     struct jsonrpc_session *session;
68     struct shash table_by_name;
69     struct ovsdb_idl_table *tables;
70     struct json *monitor_request_id;
71     unsigned int last_monitor_request_seqno;
72     unsigned int change_seqno;
73
74     /* Transaction support. */
75     struct ovsdb_idl_txn *txn;
76     struct hmap outstanding_txns;
77 };
78
79 struct ovsdb_idl_txn {
80     struct hmap_node hmap_node;
81     struct json *request_id;
82     struct ovsdb_idl *idl;
83     struct hmap txn_rows;
84     enum ovsdb_idl_txn_status status;
85     char *error;
86     bool dry_run;
87     struct ds comment;
88
89     /* Increments. */
90     char *inc_table;
91     char *inc_column;
92     struct json *inc_where;
93     unsigned int inc_index;
94     int64_t inc_new_value;
95
96     /* Inserted rows. */
97     struct hmap inserted_rows;
98 };
99
100 struct ovsdb_idl_txn_insert {
101     struct hmap_node hmap_node; /* In struct ovsdb_idl_txn's inserted_rows. */
102     struct uuid dummy;          /* Dummy UUID used locally. */
103     int op_index;               /* Index into transaction's operation array. */
104     struct uuid real;           /* Real UUID used by database server. */
105 };
106
107 static struct vlog_rate_limit syntax_rl = VLOG_RATE_LIMIT_INIT(1, 5);
108 static struct vlog_rate_limit semantic_rl = VLOG_RATE_LIMIT_INIT(1, 5);
109
110 static void ovsdb_idl_clear(struct ovsdb_idl *);
111 static void ovsdb_idl_send_monitor_request(struct ovsdb_idl *);
112 static void ovsdb_idl_parse_update(struct ovsdb_idl *, const struct json *);
113 static struct ovsdb_error *ovsdb_idl_parse_update__(struct ovsdb_idl *,
114                                                     const struct json *);
115 static void ovsdb_idl_process_update(struct ovsdb_idl_table *,
116                                      const struct uuid *,
117                                      const struct json *old,
118                                      const struct json *new);
119 static void ovsdb_idl_insert_row(struct ovsdb_idl_row *, const struct json *);
120 static void ovsdb_idl_delete_row(struct ovsdb_idl_row *);
121 static void ovsdb_idl_modify_row(struct ovsdb_idl_row *, const struct json *);
122
123 static bool ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *);
124 static struct ovsdb_idl_row *ovsdb_idl_row_create__(
125     const struct ovsdb_idl_table_class *);
126 static struct ovsdb_idl_row *ovsdb_idl_row_create(struct ovsdb_idl_table *,
127                                                   const struct uuid *);
128 static void ovsdb_idl_row_destroy(struct ovsdb_idl_row *);
129
130 static void ovsdb_idl_row_parse(struct ovsdb_idl_row *);
131 static void ovsdb_idl_row_unparse(struct ovsdb_idl_row *);
132 static void ovsdb_idl_row_clear_old(struct ovsdb_idl_row *);
133 static void ovsdb_idl_row_clear_new(struct ovsdb_idl_row *);
134
135 static void ovsdb_idl_txn_abort_all(struct ovsdb_idl *);
136 static bool ovsdb_idl_txn_process_reply(struct ovsdb_idl *,
137                                         const struct jsonrpc_msg *msg);
138
139 /* Creates and returns a connection to database 'remote', which should be in a
140  * form acceptable to jsonrpc_session_open().  The connection will maintain an
141  * in-memory replica of the remote database whose schema is described by
142  * 'class'.  (Ordinarily 'class' is compiled from an OVSDB schema automatically
143  * by ovsdb-idlc.) */
144 struct ovsdb_idl *
145 ovsdb_idl_create(const char *remote, const struct ovsdb_idl_class *class)
146 {
147     struct ovsdb_idl *idl;
148     size_t i;
149
150     idl = xzalloc(sizeof *idl);
151     idl->class = class;
152     idl->session = jsonrpc_session_open(remote);
153     shash_init(&idl->table_by_name);
154     idl->tables = xmalloc(class->n_tables * sizeof *idl->tables);
155     for (i = 0; i < class->n_tables; i++) {
156         const struct ovsdb_idl_table_class *tc = &class->tables[i];
157         struct ovsdb_idl_table *table = &idl->tables[i];
158         size_t j;
159
160         shash_add_assert(&idl->table_by_name, tc->name, table);
161         table->class = tc;
162         shash_init(&table->columns);
163         for (j = 0; j < tc->n_columns; j++) {
164             const struct ovsdb_idl_column *column = &tc->columns[j];
165
166             shash_add_assert(&table->columns, column->name, column);
167         }
168         hmap_init(&table->rows);
169         table->idl = idl;
170     }
171     idl->last_monitor_request_seqno = UINT_MAX;
172     hmap_init(&idl->outstanding_txns);
173
174     return idl;
175 }
176
177 /* Destroys 'idl' and all of the data structures that it manages. */
178 void
179 ovsdb_idl_destroy(struct ovsdb_idl *idl)
180 {
181     if (idl) {
182         size_t i;
183
184         assert(!idl->txn);
185         ovsdb_idl_clear(idl);
186         jsonrpc_session_close(idl->session);
187
188         for (i = 0; i < idl->class->n_tables; i++) {
189             struct ovsdb_idl_table *table = &idl->tables[i];
190             shash_destroy(&table->columns);
191             hmap_destroy(&table->rows);
192         }
193         shash_destroy(&idl->table_by_name);
194         free(idl->tables);
195         json_destroy(idl->monitor_request_id);
196         free(idl);
197     }
198 }
199
200 static void
201 ovsdb_idl_clear(struct ovsdb_idl *idl)
202 {
203     bool changed = false;
204     size_t i;
205
206     for (i = 0; i < idl->class->n_tables; i++) {
207         struct ovsdb_idl_table *table = &idl->tables[i];
208         struct ovsdb_idl_row *row, *next_row;
209
210         if (hmap_is_empty(&table->rows)) {
211             continue;
212         }
213
214         changed = true;
215         HMAP_FOR_EACH_SAFE (row, next_row, struct ovsdb_idl_row, hmap_node,
216                             &table->rows) {
217             struct ovsdb_idl_arc *arc, *next_arc;
218
219             if (!ovsdb_idl_row_is_orphan(row)) {
220                 ovsdb_idl_row_unparse(row);
221             }
222             LIST_FOR_EACH_SAFE (arc, next_arc, struct ovsdb_idl_arc, src_node,
223                                 &row->src_arcs) {
224                 free(arc);
225             }
226             /* No need to do anything with dst_arcs: some node has those arcs
227              * as forward arcs and will destroy them itself. */
228
229             ovsdb_idl_row_destroy(row);
230         }
231     }
232
233     if (changed) {
234         idl->change_seqno++;
235     }
236 }
237
238 /* Processes a batch of messages from the database server on 'idl'.  Returns
239  * true if the database as seen through 'idl' changed, false if it did not
240  * change.  The initial fetch of the entire contents of the remote database is
241  * considered to be one kind of change.
242  *
243  * When this function returns false, the client may continue to use any data
244  * structures it obtained from 'idl' in the past.  But when it returns true,
245  * the client must not access any of these data structures again, because they
246  * could have freed or reused for other purposes.
247  *
248  * This function can return occasional false positives, that is, report that
249  * the database changed even though it didn't.  This happens if the connection
250  * to the database drops and reconnects, which causes the database contents to
251  * be reloaded even if they didn't change.  (It could also happen if the
252  * database server sends out a "change" that reflects what we already thought
253  * was in the database, but the database server is not supposed to do that.)
254  *
255  * As an alternative to checking the return value, the client may check for
256  * changes in the value returned by ovsdb_idl_get_seqno().
257  */
258 bool
259 ovsdb_idl_run(struct ovsdb_idl *idl)
260 {
261     unsigned int initial_change_seqno = idl->change_seqno;
262     int i;
263
264     assert(!idl->txn);
265     jsonrpc_session_run(idl->session);
266     for (i = 0; jsonrpc_session_is_connected(idl->session) && i < 50; i++) {
267         struct jsonrpc_msg *msg, *reply;
268         unsigned int seqno;
269
270         seqno = jsonrpc_session_get_seqno(idl->session);
271         if (idl->last_monitor_request_seqno != seqno) {
272             idl->last_monitor_request_seqno = seqno;
273             ovsdb_idl_txn_abort_all(idl);
274             ovsdb_idl_send_monitor_request(idl);
275             break;
276         }
277
278         msg = jsonrpc_session_recv(idl->session);
279         if (!msg) {
280             break;
281         }
282
283         reply = NULL;
284         if (msg->type == JSONRPC_NOTIFY
285                    && !strcmp(msg->method, "update")
286                    && msg->params->type == JSON_ARRAY
287                    && msg->params->u.array.n == 2
288                    && msg->params->u.array.elems[0]->type == JSON_NULL) {
289             ovsdb_idl_parse_update(idl, msg->params->u.array.elems[1]);
290         } else if (msg->type == JSONRPC_REPLY
291                    && idl->monitor_request_id
292                    && json_equal(idl->monitor_request_id, msg->id)) {
293             json_destroy(idl->monitor_request_id);
294             idl->monitor_request_id = NULL;
295             ovsdb_idl_clear(idl);
296             ovsdb_idl_parse_update(idl, msg->result);
297         } else if (msg->type == JSONRPC_REPLY
298                    && msg->id && msg->id->type == JSON_STRING
299                    && !strcmp(msg->id->u.string, "echo")) {
300             /* It's a reply to our echo request.  Ignore it. */
301         } else if ((msg->type == JSONRPC_ERROR
302                     || msg->type == JSONRPC_REPLY)
303                    && ovsdb_idl_txn_process_reply(idl, msg)) {
304             /* ovsdb_idl_txn_process_reply() did everything needful. */
305         } else {
306             /* This can happen if ovsdb_idl_txn_destroy() is called to destroy
307              * a transaction before we receive the reply, so keep the log level
308              * low. */
309             VLOG_DBG("%s: received unexpected %s message",
310                      jsonrpc_session_get_name(idl->session),
311                      jsonrpc_msg_type_to_string(msg->type));
312         }
313         if (reply) {
314             jsonrpc_session_send(idl->session, reply);
315         }
316         jsonrpc_msg_destroy(msg);
317     }
318
319     return initial_change_seqno != idl->change_seqno;
320 }
321
322 /* Arranges for poll_block() to wake up when ovsdb_idl_run() has something to
323  * do or when activity occurs on a transaction on 'idl'. */
324 void
325 ovsdb_idl_wait(struct ovsdb_idl *idl)
326 {
327     jsonrpc_session_wait(idl->session);
328     jsonrpc_session_recv_wait(idl->session);
329 }
330
331 /* Returns a number that represents the state of 'idl'.  When 'idl' is updated
332  * (by ovsdb_idl_run()), the return value changes. */
333 unsigned int
334 ovsdb_idl_get_seqno(const struct ovsdb_idl *idl)
335 {
336     return idl->change_seqno;
337 }
338
339 /* Returns true if 'idl' successfully connected to the remote database and
340  * retrieved its contents (even if the connection subsequently dropped and is
341  * in the process of reconnecting).  If so, then 'idl' contains an atomic
342  * snapshot of the database's contents (but it might be arbitrarily old if the
343  * connection dropped).
344  *
345  * Returns false if 'idl' has never connected or retrieved the database's
346  * contents.  If so, 'idl' is empty. */
347 bool
348 ovsdb_idl_has_ever_connected(const struct ovsdb_idl *idl)
349 {
350     return ovsdb_idl_get_seqno(idl) != 0;
351 }
352
353 /* Forces 'idl' to drop its connection to the database and reconnect.  In the
354  * meantime, the contents of 'idl' will not change. */
355 void
356 ovsdb_idl_force_reconnect(struct ovsdb_idl *idl)
357 {
358     jsonrpc_session_force_reconnect(idl->session);
359 }
360 \f
361 static void
362 ovsdb_idl_send_monitor_request(struct ovsdb_idl *idl)
363 {
364     struct json *monitor_requests;
365     struct jsonrpc_msg *msg;
366     size_t i;
367
368     monitor_requests = json_object_create();
369     for (i = 0; i < idl->class->n_tables; i++) {
370         const struct ovsdb_idl_table *table = &idl->tables[i];
371         const struct ovsdb_idl_table_class *tc = table->class;
372         struct json *monitor_request, *columns;
373         size_t i;
374
375         monitor_request = json_object_create();
376         columns = json_array_create_empty();
377         for (i = 0; i < tc->n_columns; i++) {
378             const struct ovsdb_idl_column *column = &tc->columns[i];
379             json_array_add(columns, json_string_create(column->name));
380         }
381         json_object_put(monitor_request, "columns", columns);
382         json_object_put(monitor_requests, tc->name, monitor_request);
383     }
384
385     json_destroy(idl->monitor_request_id);
386     msg = jsonrpc_create_request(
387         "monitor",
388         json_array_create_3(json_string_create(idl->class->database),
389                             json_null_create(), monitor_requests),
390         &idl->monitor_request_id);
391     jsonrpc_session_send(idl->session, msg);
392 }
393
394 static void
395 ovsdb_idl_parse_update(struct ovsdb_idl *idl, const struct json *table_updates)
396 {
397     struct ovsdb_error *error;
398
399     idl->change_seqno++;
400
401     error = ovsdb_idl_parse_update__(idl, table_updates);
402     if (error) {
403         if (!VLOG_DROP_WARN(&syntax_rl)) {
404             char *s = ovsdb_error_to_string(error);
405             VLOG_WARN_RL(&syntax_rl, "%s", s);
406             free(s);
407         }
408         ovsdb_error_destroy(error);
409     }
410 }
411
412 static struct ovsdb_error *
413 ovsdb_idl_parse_update__(struct ovsdb_idl *idl,
414                          const struct json *table_updates)
415 {
416     const struct shash_node *tables_node;
417
418     if (table_updates->type != JSON_OBJECT) {
419         return ovsdb_syntax_error(table_updates, NULL,
420                                   "<table-updates> is not an object");
421     }
422     SHASH_FOR_EACH (tables_node, json_object(table_updates)) {
423         const struct json *table_update = tables_node->data;
424         const struct shash_node *table_node;
425         struct ovsdb_idl_table *table;
426
427         table = shash_find_data(&idl->table_by_name, tables_node->name);
428         if (!table) {
429             return ovsdb_syntax_error(
430                 table_updates, NULL,
431                 "<table-updates> includes unknown table \"%s\"",
432                 tables_node->name);
433         }
434
435         if (table_update->type != JSON_OBJECT) {
436             return ovsdb_syntax_error(table_update, NULL,
437                                       "<table-update> for table \"%s\" is "
438                                       "not an object", table->class->name);
439         }
440         SHASH_FOR_EACH (table_node, json_object(table_update)) {
441             const struct json *row_update = table_node->data;
442             const struct json *old_json, *new_json;
443             struct uuid uuid;
444
445             if (!uuid_from_string(&uuid, table_node->name)) {
446                 return ovsdb_syntax_error(table_update, NULL,
447                                           "<table-update> for table \"%s\" "
448                                           "contains bad UUID "
449                                           "\"%s\" as member name",
450                                           table->class->name,
451                                           table_node->name);
452             }
453             if (row_update->type != JSON_OBJECT) {
454                 return ovsdb_syntax_error(row_update, NULL,
455                                           "<table-update> for table \"%s\" "
456                                           "contains <row-update> for %s that "
457                                           "is not an object",
458                                           table->class->name,
459                                           table_node->name);
460             }
461
462             old_json = shash_find_data(json_object(row_update), "old");
463             new_json = shash_find_data(json_object(row_update), "new");
464             if (old_json && old_json->type != JSON_OBJECT) {
465                 return ovsdb_syntax_error(old_json, NULL,
466                                           "\"old\" <row> is not object");
467             } else if (new_json && new_json->type != JSON_OBJECT) {
468                 return ovsdb_syntax_error(new_json, NULL,
469                                           "\"new\" <row> is not object");
470             } else if ((old_json != NULL) + (new_json != NULL)
471                        != shash_count(json_object(row_update))) {
472                 return ovsdb_syntax_error(row_update, NULL,
473                                           "<row-update> contains unexpected "
474                                           "member");
475             } else if (!old_json && !new_json) {
476                 return ovsdb_syntax_error(row_update, NULL,
477                                           "<row-update> missing \"old\" "
478                                           "and \"new\" members");
479             }
480
481             ovsdb_idl_process_update(table, &uuid, old_json, new_json);
482         }
483     }
484
485     return NULL;
486 }
487
488 static struct ovsdb_idl_row *
489 ovsdb_idl_get_row(struct ovsdb_idl_table *table, const struct uuid *uuid)
490 {
491     struct ovsdb_idl_row *row;
492
493     HMAP_FOR_EACH_WITH_HASH (row, struct ovsdb_idl_row, hmap_node,
494                              uuid_hash(uuid), &table->rows) {
495         if (uuid_equals(&row->uuid, uuid)) {
496             return row;
497         }
498     }
499     return NULL;
500 }
501
502 static void
503 ovsdb_idl_process_update(struct ovsdb_idl_table *table,
504                          const struct uuid *uuid, const struct json *old,
505                          const struct json *new)
506 {
507     struct ovsdb_idl_row *row;
508
509     row = ovsdb_idl_get_row(table, uuid);
510     if (!new) {
511         /* Delete row. */
512         if (row && !ovsdb_idl_row_is_orphan(row)) {
513             /* XXX perhaps we should check the 'old' values? */
514             ovsdb_idl_delete_row(row);
515         } else {
516             VLOG_WARN_RL(&semantic_rl, "cannot delete missing row "UUID_FMT" "
517                          "from table %s",
518                          UUID_ARGS(uuid), table->class->name);
519         }
520     } else if (!old) {
521         /* Insert row. */
522         if (!row) {
523             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
524         } else if (ovsdb_idl_row_is_orphan(row)) {
525             ovsdb_idl_insert_row(row, new);
526         } else {
527             VLOG_WARN_RL(&semantic_rl, "cannot add existing row "UUID_FMT" to "
528                          "table %s", UUID_ARGS(uuid), table->class->name);
529             ovsdb_idl_modify_row(row, new);
530         }
531     } else {
532         /* Modify row. */
533         if (row) {
534             /* XXX perhaps we should check the 'old' values? */
535             if (!ovsdb_idl_row_is_orphan(row)) {
536                 ovsdb_idl_modify_row(row, new);
537             } else {
538                 VLOG_WARN_RL(&semantic_rl, "cannot modify missing but "
539                              "referenced row "UUID_FMT" in table %s",
540                              UUID_ARGS(uuid), table->class->name);
541                 ovsdb_idl_insert_row(row, new);
542             }
543         } else {
544             VLOG_WARN_RL(&semantic_rl, "cannot modify missing row "UUID_FMT" "
545                          "in table %s", UUID_ARGS(uuid), table->class->name);
546             ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid), new);
547         }
548     }
549 }
550
551 static void
552 ovsdb_idl_row_update(struct ovsdb_idl_row *row, const struct json *row_json)
553 {
554     struct ovsdb_idl_table *table = row->table;
555     struct shash_node *node;
556
557     SHASH_FOR_EACH (node, json_object(row_json)) {
558         const char *column_name = node->name;
559         const struct ovsdb_idl_column *column;
560         struct ovsdb_datum datum;
561         struct ovsdb_error *error;
562
563         column = shash_find_data(&table->columns, column_name);
564         if (!column) {
565             VLOG_WARN_RL(&syntax_rl, "unknown column %s updating row "UUID_FMT,
566                          column_name, UUID_ARGS(&row->uuid));
567             continue;
568         }
569
570         error = ovsdb_datum_from_json(&datum, &column->type, node->data, NULL);
571         if (!error) {
572             ovsdb_datum_swap(&row->old[column - table->class->columns],
573                              &datum);
574             ovsdb_datum_destroy(&datum, &column->type);
575         } else {
576             char *s = ovsdb_error_to_string(error);
577             VLOG_WARN_RL(&syntax_rl, "error parsing column %s in row "UUID_FMT
578                          " in table %s: %s", column_name,
579                          UUID_ARGS(&row->uuid), table->class->name, s);
580             free(s);
581             ovsdb_error_destroy(error);
582         }
583     }
584 }
585
586 /* When a row A refers to row B through a column with a "refTable" constraint,
587  * but row B does not exist, row B is called an "orphan row".  Orphan rows
588  * should not persist, because the database enforces referential integrity, but
589  * they can appear transiently as changes from the database are received (the
590  * database doesn't try to topologically sort them and circular references mean
591  * it isn't always possible anyhow).
592  *
593  * This function returns true if 'row' is an orphan row, otherwise false.
594  */
595 static bool
596 ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *row)
597 {
598     return !row->old && !row->new;
599 }
600
601 /* Returns true if 'row' is conceptually part of the database as modified by
602  * the current transaction (if any), false otherwise.
603  *
604  * This function will return true if 'row' is not an orphan (see the comment on
605  * ovsdb_idl_row_is_orphan()) and:
606  *
607  *   - 'row' exists in the database and has not been deleted within the
608  *     current transaction (if any).
609  *
610  *   - 'row' was inserted within the current transaction and has not been
611  *     deleted.  (In the latter case you should not have passed 'row' in at
612  *     all, because ovsdb_idl_txn_delete() freed it.)
613  *
614  * This function will return false if 'row' is an orphan or if 'row' was
615  * deleted within the current transaction.
616  */
617 static bool
618 ovsdb_idl_row_exists(const struct ovsdb_idl_row *row)
619 {
620     return row->new != NULL;
621 }
622
623 static void
624 ovsdb_idl_row_parse(struct ovsdb_idl_row *row)
625 {
626     const struct ovsdb_idl_table_class *class = row->table->class;
627     size_t i;
628
629     for (i = 0; i < class->n_columns; i++) {
630         const struct ovsdb_idl_column *c = &class->columns[i];
631         (c->parse)(row, &row->old[i]);
632     }
633 }
634
635 static void
636 ovsdb_idl_row_unparse(struct ovsdb_idl_row *row)
637 {
638     const struct ovsdb_idl_table_class *class = row->table->class;
639     size_t i;
640
641     for (i = 0; i < class->n_columns; i++) {
642         const struct ovsdb_idl_column *c = &class->columns[i];
643         (c->unparse)(row);
644     }
645 }
646
647 static void
648 ovsdb_idl_row_clear_old(struct ovsdb_idl_row *row)
649 {
650     assert(row->old == row->new);
651     if (!ovsdb_idl_row_is_orphan(row)) {
652         const struct ovsdb_idl_table_class *class = row->table->class;
653         size_t i;
654
655         for (i = 0; i < class->n_columns; i++) {
656             ovsdb_datum_destroy(&row->old[i], &class->columns[i].type);
657         }
658         free(row->old);
659         row->old = row->new = NULL;
660     }
661 }
662
663 static void
664 ovsdb_idl_row_clear_new(struct ovsdb_idl_row *row)
665 {
666     if (row->old != row->new) {
667         if (row->new) {
668             const struct ovsdb_idl_table_class *class = row->table->class;
669             size_t i;
670
671             if (row->written) {
672                 BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
673                     ovsdb_datum_destroy(&row->new[i], &class->columns[i].type);
674                 }
675             }
676             free(row->new);
677             free(row->written);
678             row->written = NULL;
679         }
680         row->new = row->old;
681     }
682 }
683
684 static void
685 ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
686 {
687     struct ovsdb_idl_arc *arc, *next;
688
689     /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
690      * that this causes to be unreferenced. */
691     LIST_FOR_EACH_SAFE (arc, next, struct ovsdb_idl_arc, src_node,
692                         &row->src_arcs) {
693         list_remove(&arc->dst_node);
694         if (destroy_dsts
695             && ovsdb_idl_row_is_orphan(arc->dst)
696             && list_is_empty(&arc->dst->dst_arcs)) {
697             ovsdb_idl_row_destroy(arc->dst);
698         }
699         free(arc);
700     }
701     list_init(&row->src_arcs);
702 }
703
704 /* Force nodes that reference 'row' to reparse. */
705 static void
706 ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
707 {
708     struct ovsdb_idl_arc *arc, *next;
709
710     /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
711      * 'arc', so we need to use the "safe" variant of list traversal.  However,
712      * calling an ovsdb_idl_column's 'parse' function will add an arc
713      * equivalent to 'arc' to row->arcs.  That could be a problem for
714      * traversal, but it adds it at the beginning of the list to prevent us
715      * from stumbling upon it again.
716      *
717      * (If duplicate arcs were possible then we would need to make sure that
718      * 'next' didn't also point into 'arc''s destination, but we forbid
719      * duplicate arcs.) */
720     LIST_FOR_EACH_SAFE (arc, next, struct ovsdb_idl_arc, dst_node,
721                         &row->dst_arcs) {
722         struct ovsdb_idl_row *ref = arc->src;
723
724         ovsdb_idl_row_unparse(ref);
725         ovsdb_idl_row_clear_arcs(ref, false);
726         ovsdb_idl_row_parse(ref);
727     }
728 }
729
730 static struct ovsdb_idl_row *
731 ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
732 {
733     struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
734     list_init(&row->src_arcs);
735     list_init(&row->dst_arcs);
736     hmap_node_nullify(&row->txn_node);
737     return row;
738 }
739
740 static struct ovsdb_idl_row *
741 ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
742 {
743     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class);
744     hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
745     row->uuid = *uuid;
746     row->table = table;
747     return row;
748 }
749
750 static void
751 ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
752 {
753     if (row) {
754         ovsdb_idl_row_clear_old(row);
755         hmap_remove(&row->table->rows, &row->hmap_node);
756         free(row);
757     }
758 }
759
760 static void
761 ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct json *row_json)
762 {
763     const struct ovsdb_idl_table_class *class = row->table->class;
764     size_t i;
765
766     assert(!row->old && !row->new);
767     row->old = row->new = xmalloc(class->n_columns * sizeof *row->old);
768     for (i = 0; i < class->n_columns; i++) {
769         ovsdb_datum_init_default(&row->old[i], &class->columns[i].type);
770     }
771     ovsdb_idl_row_update(row, row_json);
772     ovsdb_idl_row_parse(row);
773
774     ovsdb_idl_row_reparse_backrefs(row);
775 }
776
777 static void
778 ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
779 {
780     ovsdb_idl_row_unparse(row);
781     ovsdb_idl_row_clear_arcs(row, true);
782     ovsdb_idl_row_clear_old(row);
783     if (list_is_empty(&row->dst_arcs)) {
784         ovsdb_idl_row_destroy(row);
785     } else {
786         ovsdb_idl_row_reparse_backrefs(row);
787     }
788 }
789
790 static void
791 ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct json *row_json)
792 {
793     ovsdb_idl_row_unparse(row);
794     ovsdb_idl_row_clear_arcs(row, true);
795     ovsdb_idl_row_update(row, row_json);
796     ovsdb_idl_row_parse(row);
797 }
798
799 static bool
800 may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
801 {
802     const struct ovsdb_idl_arc *arc;
803
804     /* No self-arcs. */
805     if (src == dst) {
806         return false;
807     }
808
809     /* No duplicate arcs.
810      *
811      * We only need to test whether the first arc in dst->dst_arcs originates
812      * at 'src', since we add all of the arcs from a given source in a clump
813      * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
814      * added at the front of the dst_arcs list. */
815     if (list_is_empty(&dst->dst_arcs)) {
816         return true;
817     }
818     arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
819     return arc->src != src;
820 }
821
822 static struct ovsdb_idl_table *
823 ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
824                            const struct ovsdb_idl_table_class *table_class)
825 {
826     return &idl->tables[table_class - idl->class->tables];
827 }
828
829 struct ovsdb_idl_row *
830 ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
831                       struct ovsdb_idl_table_class *dst_table_class,
832                       const struct uuid *dst_uuid)
833 {
834     struct ovsdb_idl *idl = src->table->idl;
835     struct ovsdb_idl_table *dst_table;
836     struct ovsdb_idl_arc *arc;
837     struct ovsdb_idl_row *dst;
838
839     dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
840     dst = ovsdb_idl_get_row(dst_table, dst_uuid);
841     if (idl->txn) {
842         /* We're being called from ovsdb_idl_txn_write().  We must not update
843          * any arcs, because the transaction will be backed out at commit or
844          * abort time and we don't want our graph screwed up.
845          *
846          * Just return the destination row, if there is one and it has not been
847          * deleted. */
848         if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new)) {
849             return dst;
850         }
851         return NULL;
852     } else {
853         /* We're being called from some other context.  Update the graph. */
854         if (!dst) {
855             dst = ovsdb_idl_row_create(dst_table, dst_uuid);
856         }
857
858         /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
859         if (may_add_arc(src, dst)) {
860             /* The arc *must* be added at the front of the dst_arcs list.  See
861              * ovsdb_idl_row_reparse_backrefs() for details. */
862             arc = xmalloc(sizeof *arc);
863             list_push_front(&src->src_arcs, &arc->src_node);
864             list_push_front(&dst->dst_arcs, &arc->dst_node);
865             arc->src = src;
866             arc->dst = dst;
867         }
868
869         return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
870     }
871 }
872
873 const struct ovsdb_idl_row *
874 ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
875                            const struct ovsdb_idl_table_class *tc,
876                            const struct uuid *uuid)
877 {
878     return ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
879 }
880
881 static struct ovsdb_idl_row *
882 next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
883 {
884     for (; node; node = hmap_next(&table->rows, node)) {
885         struct ovsdb_idl_row *row;
886
887         row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
888         if (ovsdb_idl_row_exists(row)) {
889             return row;
890         }
891     }
892     return NULL;
893 }
894
895 const struct ovsdb_idl_row *
896 ovsdb_idl_first_row(const struct ovsdb_idl *idl,
897                     const struct ovsdb_idl_table_class *table_class)
898 {
899     struct ovsdb_idl_table *table
900         = ovsdb_idl_table_from_class(idl, table_class);
901     return next_real_row(table, hmap_first(&table->rows));
902 }
903
904 const struct ovsdb_idl_row *
905 ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
906 {
907     struct ovsdb_idl_table *table = row->table;
908
909     return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
910 }
911
912 /* Reads and returns the value of 'column' within 'row'.  If an ongoing
913  * transaction has changed 'column''s value, the modified value is returned.
914  *
915  * The caller must not modify or free the returned value.
916  *
917  * Various kinds of changes can invalidate the returned value: writing to the
918  * same 'column' in 'row' (e.g. with ovsdb_idl_txn_write()), deleting 'row'
919  * (e.g. with ovsdb_idl_txn_delete()), or completing an ongoing transaction
920  * (e.g. with ovsdb_idl_txn_commit() or ovsdb_idl_txn_abort()).  If the
921  * returned value is needed for a long time, it is best to make a copy of it
922  * with ovsdb_datum_clone(). */
923 const struct ovsdb_datum *
924 ovsdb_idl_read(const struct ovsdb_idl_row *row,
925                const struct ovsdb_idl_column *column)
926 {
927     const struct ovsdb_idl_table_class *class = row->table->class;
928     size_t column_idx = column - class->columns;
929
930     assert(row->new != NULL);
931     assert(column_idx < class->n_columns);
932
933     if (row->written && bitmap_is_set(row->written, column_idx)) {
934         return &row->new[column_idx];
935     } else if (row->old) {
936         return &row->old[column_idx];
937     } else {
938         return ovsdb_datum_default(&column->type);
939     }
940 }
941
942 /* Same as ovsdb_idl_read(), except that it also asserts that 'column' has key
943  * type 'key_type' and value type 'value_type'.  (Scalar and set types will
944  * have a value type of OVSDB_TYPE_VOID.)
945  *
946  * This is useful in code that "knows" that a particular column has a given
947  * type, so that it will abort if someone changes the column's type without
948  * updating the code that uses it. */
949 const struct ovsdb_datum *
950 ovsdb_idl_get(const struct ovsdb_idl_row *row,
951               const struct ovsdb_idl_column *column,
952               enum ovsdb_atomic_type key_type OVS_UNUSED,
953               enum ovsdb_atomic_type value_type OVS_UNUSED)
954 {
955     assert(column->type.key.type == key_type);
956     assert(column->type.value.type == value_type);
957
958     return ovsdb_idl_read(row, column);
959 }
960 \f
961 /* Transactions. */
962
963 static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
964                                    enum ovsdb_idl_txn_status);
965
966 const char *
967 ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
968 {
969     switch (status) {
970     case TXN_UNCHANGED:
971         return "unchanged";
972     case TXN_INCOMPLETE:
973         return "incomplete";
974     case TXN_ABORTED:
975         return "aborted";
976     case TXN_SUCCESS:
977         return "success";
978     case TXN_TRY_AGAIN:
979         return "try again";
980     case TXN_ERROR:
981         return "error";
982     }
983     return "<unknown>";
984 }
985
986 struct ovsdb_idl_txn *
987 ovsdb_idl_txn_create(struct ovsdb_idl *idl)
988 {
989     struct ovsdb_idl_txn *txn;
990
991     assert(!idl->txn);
992     idl->txn = txn = xmalloc(sizeof *txn);
993     txn->request_id = NULL;
994     txn->idl = idl;
995     hmap_init(&txn->txn_rows);
996     txn->status = TXN_INCOMPLETE;
997     txn->error = NULL;
998     txn->dry_run = false;
999     ds_init(&txn->comment);
1000
1001     txn->inc_table = NULL;
1002     txn->inc_column = NULL;
1003     txn->inc_where = NULL;
1004
1005     hmap_init(&txn->inserted_rows);
1006
1007     return txn;
1008 }
1009
1010 /* Appends 's', which is treated as a printf()-type format string, to the
1011  * comments that will be passed to the OVSDB server when 'txn' is committed.
1012  * (The comment will be committed to the OVSDB log, which "ovsdb-tool
1013  * show-log" can print in a relatively human-readable form.) */
1014 void
1015 ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s, ...)
1016 {
1017     va_list args;
1018
1019     if (txn->comment.length) {
1020         ds_put_char(&txn->comment, '\n');
1021     }
1022
1023     va_start(args, s);
1024     ds_put_format_valist(&txn->comment, s, args);
1025     va_end(args);
1026 }
1027
1028 void
1029 ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
1030 {
1031     txn->dry_run = true;
1032 }
1033
1034 void
1035 ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn, const char *table,
1036                         const char *column, const struct json *where)
1037 {
1038     assert(!txn->inc_table);
1039     txn->inc_table = xstrdup(table);
1040     txn->inc_column = xstrdup(column);
1041     txn->inc_where = where ? json_clone(where) : json_array_create_empty();
1042 }
1043
1044 void
1045 ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
1046 {
1047     struct ovsdb_idl_txn_insert *insert, *next;
1048
1049     json_destroy(txn->request_id);
1050     if (txn->status == TXN_INCOMPLETE) {
1051         hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1052     }
1053     ovsdb_idl_txn_abort(txn);
1054     ds_destroy(&txn->comment);
1055     free(txn->error);
1056     free(txn->inc_table);
1057     free(txn->inc_column);
1058     json_destroy(txn->inc_where);
1059     HMAP_FOR_EACH_SAFE (insert, next, struct ovsdb_idl_txn_insert, hmap_node,
1060                         &txn->inserted_rows) {
1061         free(insert);
1062     }
1063     hmap_destroy(&txn->inserted_rows);
1064     free(txn);
1065 }
1066
1067 void
1068 ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
1069 {
1070     if (txn->status != TXN_INCOMPLETE) {
1071         poll_immediate_wake();
1072     }
1073 }
1074
1075 static struct json *
1076 where_uuid_equals(const struct uuid *uuid)
1077 {
1078     return
1079         json_array_create_1(
1080             json_array_create_3(
1081                 json_string_create("_uuid"),
1082                 json_string_create("=="),
1083                 json_array_create_2(
1084                     json_string_create("uuid"),
1085                     json_string_create_nocopy(
1086                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
1087 }
1088
1089 static char *
1090 uuid_name_from_uuid(const struct uuid *uuid)
1091 {
1092     char *name;
1093     char *p;
1094
1095     name = xasprintf("row"UUID_FMT, UUID_ARGS(uuid));
1096     for (p = name; *p != '\0'; p++) {
1097         if (*p == '-') {
1098             *p = '_';
1099         }
1100     }
1101
1102     return name;
1103 }
1104
1105 static const struct ovsdb_idl_row *
1106 ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
1107 {
1108     const struct ovsdb_idl_row *row;
1109
1110     HMAP_FOR_EACH_WITH_HASH (row, struct ovsdb_idl_row, txn_node,
1111                              uuid_hash(uuid), &txn->txn_rows) {
1112         if (uuid_equals(&row->uuid, uuid)) {
1113             return row;
1114         }
1115     }
1116     return NULL;
1117 }
1118
1119 /* XXX there must be a cleaner way to do this */
1120 static struct json *
1121 substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
1122 {
1123     if (json->type == JSON_ARRAY) {
1124         struct uuid uuid;
1125         size_t i;
1126
1127         if (json->u.array.n == 2
1128             && json->u.array.elems[0]->type == JSON_STRING
1129             && json->u.array.elems[1]->type == JSON_STRING
1130             && !strcmp(json->u.array.elems[0]->u.string, "uuid")
1131             && uuid_from_string(&uuid, json->u.array.elems[1]->u.string)) {
1132             const struct ovsdb_idl_row *row;
1133
1134             row = ovsdb_idl_txn_get_row(txn, &uuid);
1135             if (row && !row->old && row->new) {
1136                 json_destroy(json);
1137
1138                 return json_array_create_2(
1139                     json_string_create("named-uuid"),
1140                     json_string_create_nocopy(uuid_name_from_uuid(&uuid)));
1141             }
1142         }
1143
1144         for (i = 0; i < json->u.array.n; i++) {
1145             json->u.array.elems[i] = substitute_uuids(json->u.array.elems[i],
1146                                                       txn);
1147         }
1148     } else if (json->type == JSON_OBJECT) {
1149         struct shash_node *node;
1150
1151         SHASH_FOR_EACH (node, json_object(json)) {
1152             node->data = substitute_uuids(node->data, txn);
1153         }
1154     }
1155     return json;
1156 }
1157
1158 static void
1159 ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
1160 {
1161     struct ovsdb_idl_row *row, *next;
1162
1163     /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
1164      * ovsdb_idl_column's 'parse' function, which will call
1165      * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
1166      * transaction and fail to update the graph.  */
1167     txn->idl->txn = NULL;
1168
1169     HMAP_FOR_EACH_SAFE (row, next, struct ovsdb_idl_row, txn_node,
1170                         &txn->txn_rows) {
1171         if (row->old) {
1172             if (row->written) {
1173                 ovsdb_idl_row_unparse(row);
1174                 ovsdb_idl_row_clear_arcs(row, false);
1175                 ovsdb_idl_row_parse(row);
1176             }
1177         } else {
1178             ovsdb_idl_row_unparse(row);
1179         }
1180         ovsdb_idl_row_clear_new(row);
1181
1182         free(row->prereqs);
1183         row->prereqs = NULL;
1184
1185         free(row->written);
1186         row->written = NULL;
1187
1188         hmap_remove(&txn->txn_rows, &row->txn_node);
1189         hmap_node_nullify(&row->txn_node);
1190         if (!row->old) {
1191             hmap_remove(&row->table->rows, &row->hmap_node);
1192             free(row);
1193         }
1194     }
1195     hmap_destroy(&txn->txn_rows);
1196     hmap_init(&txn->txn_rows);
1197 }
1198
1199 enum ovsdb_idl_txn_status
1200 ovsdb_idl_txn_commit(struct ovsdb_idl_txn *txn)
1201 {
1202     struct ovsdb_idl_row *row;
1203     struct json *operations;
1204     bool any_updates;
1205
1206     if (txn != txn->idl->txn) {
1207         return txn->status;
1208     }
1209
1210     operations = json_array_create_1(
1211         json_string_create(txn->idl->class->database));
1212
1213     /* Add prerequisites and declarations of new rows. */
1214     HMAP_FOR_EACH (row, struct ovsdb_idl_row, txn_node, &txn->txn_rows) {
1215         /* XXX check that deleted rows exist even if no prereqs? */
1216         if (row->prereqs) {
1217             const struct ovsdb_idl_table_class *class = row->table->class;
1218             size_t n_columns = class->n_columns;
1219             struct json *op, *columns, *row_json;
1220             size_t idx;
1221
1222             op = json_object_create();
1223             json_array_add(operations, op);
1224             json_object_put_string(op, "op", "wait");
1225             json_object_put_string(op, "table", class->name);
1226             json_object_put(op, "timeout", json_integer_create(0));
1227             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1228             json_object_put_string(op, "until", "==");
1229             columns = json_array_create_empty();
1230             json_object_put(op, "columns", columns);
1231             row_json = json_object_create();
1232             json_object_put(op, "rows", json_array_create_1(row_json));
1233
1234             BITMAP_FOR_EACH_1 (idx, n_columns, row->prereqs) {
1235                 const struct ovsdb_idl_column *column = &class->columns[idx];
1236                 json_array_add(columns, json_string_create(column->name));
1237                 json_object_put(row_json, column->name,
1238                                 ovsdb_datum_to_json(&row->old[idx],
1239                                                     &column->type));
1240             }
1241         }
1242     }
1243
1244     /* Add updates. */
1245     any_updates = false;
1246     HMAP_FOR_EACH (row, struct ovsdb_idl_row, txn_node, &txn->txn_rows) {
1247         const struct ovsdb_idl_table_class *class = row->table->class;
1248
1249         if (row->old == row->new) {
1250             continue;
1251         } else if (!row->new) {
1252             struct json *op = json_object_create();
1253             json_object_put_string(op, "op", "delete");
1254             json_object_put_string(op, "table", class->name);
1255             json_object_put(op, "where", where_uuid_equals(&row->uuid));
1256             json_array_add(operations, op);
1257             any_updates = true;
1258         } else {
1259             struct json *row_json;
1260             struct json *op;
1261             size_t idx;
1262
1263             op = json_object_create();
1264             json_object_put_string(op, "op", row->old ? "update" : "insert");
1265             json_object_put_string(op, "table", class->name);
1266             if (row->old) {
1267                 json_object_put(op, "where", where_uuid_equals(&row->uuid));
1268             } else {
1269                 struct ovsdb_idl_txn_insert *insert;
1270
1271                 json_object_put(op, "uuid-name",
1272                                 json_string_create_nocopy(
1273                                     uuid_name_from_uuid(&row->uuid)));
1274
1275                 insert = xmalloc(sizeof *insert);
1276                 insert->dummy = row->uuid;
1277                 insert->op_index = operations->u.array.n - 1;
1278                 uuid_zero(&insert->real);
1279                 hmap_insert(&txn->inserted_rows, &insert->hmap_node,
1280                             uuid_hash(&insert->dummy));
1281             }
1282             row_json = json_object_create();
1283             json_object_put(op, "row", row_json);
1284
1285             if (row->written) {
1286                 BITMAP_FOR_EACH_1 (idx, class->n_columns, row->written) {
1287                     const struct ovsdb_idl_column *column =
1288                                                         &class->columns[idx];
1289
1290                     if (row->old
1291                         ? !ovsdb_datum_equals(&row->old[idx], &row->new[idx],
1292                                               &column->type)
1293                         : !ovsdb_datum_is_default(&row->new[idx],
1294                                                   &column->type)) {
1295                         json_object_put(row_json, column->name,
1296                                         substitute_uuids(
1297                                             ovsdb_datum_to_json(&row->new[idx],
1298                                                                 &column->type),
1299                                             txn));
1300                     }
1301                 }
1302             }
1303
1304             if (!row->old || !shash_is_empty(json_object(row_json))) {
1305                 json_array_add(operations, op);
1306                 any_updates = true;
1307             } else {
1308                 json_destroy(op);
1309             }
1310         }
1311     }
1312
1313     /* Add increment. */
1314     if (txn->inc_table && any_updates) {
1315         struct json *op;
1316
1317         txn->inc_index = operations->u.array.n - 1;
1318
1319         op = json_object_create();
1320         json_object_put_string(op, "op", "mutate");
1321         json_object_put_string(op, "table", txn->inc_table);
1322         json_object_put(op, "where",
1323                         substitute_uuids(json_clone(txn->inc_where), txn));
1324         json_object_put(op, "mutations",
1325                         json_array_create_1(
1326                             json_array_create_3(
1327                                 json_string_create(txn->inc_column),
1328                                 json_string_create("+="),
1329                                 json_integer_create(1))));
1330         json_array_add(operations, op);
1331
1332         op = json_object_create();
1333         json_object_put_string(op, "op", "select");
1334         json_object_put_string(op, "table", txn->inc_table);
1335         json_object_put(op, "where",
1336                         substitute_uuids(json_clone(txn->inc_where), txn));
1337         json_object_put(op, "columns",
1338                         json_array_create_1(json_string_create(
1339                                                 txn->inc_column)));
1340         json_array_add(operations, op);
1341     }
1342
1343     if (txn->comment.length) {
1344         struct json *op = json_object_create();
1345         json_object_put_string(op, "op", "comment");
1346         json_object_put_string(op, "comment", ds_cstr(&txn->comment));
1347         json_array_add(operations, op);
1348     }
1349
1350     if (txn->dry_run) {
1351         struct json *op = json_object_create();
1352         json_object_put_string(op, "op", "abort");
1353         json_array_add(operations, op);
1354     }
1355
1356     if (!any_updates) {
1357         txn->status = TXN_UNCHANGED;
1358         json_destroy(operations);
1359     } else if (!jsonrpc_session_send(
1360                    txn->idl->session,
1361                    jsonrpc_create_request(
1362                        "transact", operations, &txn->request_id))) {
1363         hmap_insert(&txn->idl->outstanding_txns, &txn->hmap_node,
1364                     json_hash(txn->request_id, 0));
1365     } else {
1366         txn->status = TXN_TRY_AGAIN;
1367     }
1368
1369     ovsdb_idl_txn_disassemble(txn);
1370     return txn->status;
1371 }
1372
1373 /* Attempts to commit 'txn', blocking until the commit either succeeds or
1374  * fails.  Returns the final commit status, which may be any TXN_* value other
1375  * than TXN_INCOMPLETE. */
1376 enum ovsdb_idl_txn_status
1377 ovsdb_idl_txn_commit_block(struct ovsdb_idl_txn *txn)
1378 {
1379     enum ovsdb_idl_txn_status status;
1380
1381     fatal_signal_run();
1382     while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
1383         ovsdb_idl_run(txn->idl);
1384         ovsdb_idl_wait(txn->idl);
1385         ovsdb_idl_txn_wait(txn);
1386         poll_block();
1387     }
1388     return status;
1389 }
1390
1391 int64_t
1392 ovsdb_idl_txn_get_increment_new_value(const struct ovsdb_idl_txn *txn)
1393 {
1394     assert(txn->status == TXN_SUCCESS);
1395     return txn->inc_new_value;
1396 }
1397
1398 void
1399 ovsdb_idl_txn_abort(struct ovsdb_idl_txn *txn)
1400 {
1401     ovsdb_idl_txn_disassemble(txn);
1402     if (txn->status == TXN_INCOMPLETE) {
1403         txn->status = TXN_ABORTED;
1404     }
1405 }
1406
1407 const char *
1408 ovsdb_idl_txn_get_error(const struct ovsdb_idl_txn *txn)
1409 {
1410     if (txn->status != TXN_ERROR) {
1411         return ovsdb_idl_txn_status_to_string(txn->status);
1412     } else if (txn->error) {
1413         return txn->error;
1414     } else {
1415         return "no error details available";
1416     }
1417 }
1418
1419 static void
1420 ovsdb_idl_txn_set_error_json(struct ovsdb_idl_txn *txn,
1421                              const struct json *json)
1422 {
1423     if (txn->error == NULL) {
1424         txn->error = json_to_string(json, JSSF_SORT);
1425     }
1426 }
1427
1428 /* For transaction 'txn' that completed successfully, finds and returns the
1429  * permanent UUID that the database assigned to a newly inserted row, given the
1430  * 'uuid' that ovsdb_idl_txn_insert() assigned locally to that row.
1431  *
1432  * Returns NULL if 'uuid' is not a UUID assigned by ovsdb_idl_txn_insert() or
1433  * if it was assigned by that function and then deleted by
1434  * ovsdb_idl_txn_delete() within the same transaction.  (Rows that are inserted
1435  * and then deleted within a single transaction are never sent to the database
1436  * server, so it never assigns them a permanent UUID.) */
1437 const struct uuid *
1438 ovsdb_idl_txn_get_insert_uuid(const struct ovsdb_idl_txn *txn,
1439                               const struct uuid *uuid)
1440 {
1441     const struct ovsdb_idl_txn_insert *insert;
1442
1443     assert(txn->status == TXN_SUCCESS || txn->status == TXN_UNCHANGED);
1444     HMAP_FOR_EACH_IN_BUCKET (insert, struct ovsdb_idl_txn_insert, hmap_node,
1445                              uuid_hash(uuid), &txn->inserted_rows) {
1446         if (uuid_equals(uuid, &insert->dummy)) {
1447             return &insert->real;
1448         }
1449     }
1450     return NULL;
1451 }
1452
1453 static void
1454 ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
1455                        enum ovsdb_idl_txn_status status)
1456 {
1457     txn->status = status;
1458     hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
1459 }
1460
1461 void
1462 ovsdb_idl_txn_write(const struct ovsdb_idl_row *row_,
1463                     const struct ovsdb_idl_column *column,
1464                     struct ovsdb_datum *datum)
1465 {
1466     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1467     const struct ovsdb_idl_table_class *class = row->table->class;
1468     size_t column_idx = column - class->columns;
1469
1470     assert(row->new != NULL);
1471     assert(column_idx < class->n_columns);
1472     if (hmap_node_is_null(&row->txn_node)) {
1473         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1474                     uuid_hash(&row->uuid));
1475     }
1476     if (row->old == row->new) {
1477         row->new = xmalloc(class->n_columns * sizeof *row->new);
1478     }
1479     if (!row->written) {
1480         row->written = bitmap_allocate(class->n_columns);
1481     }
1482     if (bitmap_is_set(row->written, column_idx)) {
1483         ovsdb_datum_destroy(&row->new[column_idx], &column->type);
1484     } else {
1485         bitmap_set1(row->written, column_idx);
1486     }
1487     row->new[column_idx] = *datum;
1488     (column->unparse)(row);
1489     (column->parse)(row, &row->new[column_idx]);
1490 }
1491
1492 void
1493 ovsdb_idl_txn_verify(const struct ovsdb_idl_row *row_,
1494                      const struct ovsdb_idl_column *column)
1495 {
1496     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1497     const struct ovsdb_idl_table_class *class = row->table->class;
1498     size_t column_idx = column - class->columns;
1499
1500     assert(row->new != NULL);
1501     if (!row->old
1502         || (row->written && bitmap_is_set(row->written, column_idx))) {
1503         return;
1504     }
1505
1506     if (hmap_node_is_null(&row->txn_node)) {
1507         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1508                     uuid_hash(&row->uuid));
1509     }
1510     if (!row->prereqs) {
1511         row->prereqs = bitmap_allocate(class->n_columns);
1512     }
1513     bitmap_set1(row->prereqs, column_idx);
1514 }
1515
1516 void
1517 ovsdb_idl_txn_delete(const struct ovsdb_idl_row *row_)
1518 {
1519     struct ovsdb_idl_row *row = (struct ovsdb_idl_row *) row_;
1520
1521     assert(row->new != NULL);
1522     if (!row->old) {
1523         ovsdb_idl_row_unparse(row);
1524         ovsdb_idl_row_clear_new(row);
1525         assert(!row->prereqs);
1526         hmap_remove(&row->table->rows, &row->hmap_node);
1527         hmap_remove(&row->table->idl->txn->txn_rows, &row->txn_node);
1528         free(row);
1529         return;
1530     }
1531     if (hmap_node_is_null(&row->txn_node)) {
1532         hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
1533                     uuid_hash(&row->uuid));
1534     }
1535     ovsdb_idl_row_clear_new(row);
1536     row->new = NULL;
1537 }
1538
1539 const struct ovsdb_idl_row *
1540 ovsdb_idl_txn_insert(struct ovsdb_idl_txn *txn,
1541                      const struct ovsdb_idl_table_class *class,
1542                      const struct uuid *uuid)
1543 {
1544     struct ovsdb_idl_row *row = ovsdb_idl_row_create__(class);
1545
1546     if (uuid) {
1547         assert(!ovsdb_idl_txn_get_row(txn, uuid));
1548         row->uuid = *uuid;
1549     } else {
1550         uuid_generate(&row->uuid);
1551     }
1552
1553     row->table = ovsdb_idl_table_from_class(txn->idl, class);
1554     row->new = xmalloc(class->n_columns * sizeof *row->new);
1555     hmap_insert(&row->table->rows, &row->hmap_node, uuid_hash(&row->uuid));
1556     hmap_insert(&txn->txn_rows, &row->txn_node, uuid_hash(&row->uuid));
1557     return row;
1558 }
1559
1560 static void
1561 ovsdb_idl_txn_abort_all(struct ovsdb_idl *idl)
1562 {
1563     struct ovsdb_idl_txn *txn;
1564
1565     HMAP_FOR_EACH (txn, struct ovsdb_idl_txn, hmap_node,
1566                    &idl->outstanding_txns) {
1567         ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
1568     }
1569 }
1570
1571 static struct ovsdb_idl_txn *
1572 ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
1573 {
1574     struct ovsdb_idl_txn *txn;
1575
1576     HMAP_FOR_EACH_WITH_HASH (txn, struct ovsdb_idl_txn, hmap_node,
1577                              json_hash(id, 0), &idl->outstanding_txns) {
1578         if (json_equal(id, txn->request_id)) {
1579             return txn;
1580         }
1581     }
1582     return NULL;
1583 }
1584
1585 static bool
1586 check_json_type(const struct json *json, enum json_type type, const char *name)
1587 {
1588     if (!json) {
1589         VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
1590         return false;
1591     } else if (json->type != type) {
1592         VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
1593                      name, json_type_to_string(json->type),
1594                      json_type_to_string(type));
1595         return false;
1596     } else {
1597         return true;
1598     }
1599 }
1600
1601 static bool
1602 ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
1603                                 const struct json_array *results)
1604 {
1605     struct json *count, *rows, *row, *column;
1606     struct shash *mutate, *select;
1607
1608     if (txn->inc_index + 2 > results->n) {
1609         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1610                      "for increment (has %zu, needs %u)",
1611                      results->n, txn->inc_index + 2);
1612         return false;
1613     }
1614
1615     /* We know that this is a JSON object because the loop in
1616      * ovsdb_idl_txn_process_reply() checked. */
1617     mutate = json_object(results->elems[txn->inc_index]);
1618     count = shash_find_data(mutate, "count");
1619     if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
1620         return false;
1621     }
1622     if (count->u.integer != 1) {
1623         VLOG_WARN_RL(&syntax_rl,
1624                      "\"mutate\" reply \"count\" is %lld instead of 1",
1625                      count->u.integer);
1626         return false;
1627     }
1628
1629     select = json_object(results->elems[txn->inc_index + 1]);
1630     rows = shash_find_data(select, "rows");
1631     if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
1632         return false;
1633     }
1634     if (rows->u.array.n != 1) {
1635         VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %zu elements "
1636                      "instead of 1",
1637                      rows->u.array.n);
1638         return false;
1639     }
1640     row = rows->u.array.elems[0];
1641     if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
1642         return false;
1643     }
1644     column = shash_find_data(json_object(row), txn->inc_column);
1645     if (!check_json_type(column, JSON_INTEGER,
1646                          "\"select\" reply inc column")) {
1647         return false;
1648     }
1649     txn->inc_new_value = column->u.integer;
1650     return true;
1651 }
1652
1653 static bool
1654 ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
1655                                    const struct json_array *results)
1656 {
1657     static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
1658     struct ovsdb_error *error;
1659     struct json *json_uuid;
1660     union ovsdb_atom uuid;
1661     struct shash *reply;
1662
1663     if (insert->op_index >= results->n) {
1664         VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
1665                      "for insert (has %zu, needs %u)",
1666                      results->n, insert->op_index);
1667         return false;
1668     }
1669
1670     /* We know that this is a JSON object because the loop in
1671      * ovsdb_idl_txn_process_reply() checked. */
1672     reply = json_object(results->elems[insert->op_index]);
1673     json_uuid = shash_find_data(reply, "uuid");
1674     if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
1675         return false;
1676     }
1677
1678     error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
1679     if (error) {
1680         char *s = ovsdb_error_to_string(error);
1681         VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
1682                      "UUID: %s", s);
1683         free(s);
1684         return false;
1685     }
1686
1687     insert->real = uuid.uuid;
1688
1689     return true;
1690 }
1691
1692 static bool
1693 ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
1694                             const struct jsonrpc_msg *msg)
1695 {
1696     struct ovsdb_idl_txn *txn;
1697     enum ovsdb_idl_txn_status status;
1698
1699     txn = ovsdb_idl_txn_find(idl, msg->id);
1700     if (!txn) {
1701         return false;
1702     }
1703
1704     if (msg->type == JSONRPC_ERROR) {
1705         status = TXN_ERROR;
1706     } else if (msg->result->type != JSON_ARRAY) {
1707         VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
1708         status = TXN_ERROR;
1709     } else {
1710         struct json_array *ops = &msg->result->u.array;
1711         int hard_errors = 0;
1712         int soft_errors = 0;
1713         size_t i;
1714
1715         for (i = 0; i < ops->n; i++) {
1716             struct json *op = ops->elems[i];
1717
1718             if (op->type == JSON_NULL) {
1719                 /* This isn't an error in itself but indicates that some prior
1720                  * operation failed, so make sure that we know about it. */
1721                 soft_errors++;
1722             } else if (op->type == JSON_OBJECT) {
1723                 struct json *error;
1724
1725                 error = shash_find_data(json_object(op), "error");
1726                 if (error) {
1727                     if (error->type == JSON_STRING) {
1728                         if (!strcmp(error->u.string, "timed out")) {
1729                             soft_errors++;
1730                         } else if (strcmp(error->u.string, "aborted")) {
1731                             hard_errors++;
1732                             ovsdb_idl_txn_set_error_json(txn, op);
1733                         }
1734                     } else {
1735                         hard_errors++;
1736                         ovsdb_idl_txn_set_error_json(txn, op);
1737                         VLOG_WARN_RL(&syntax_rl,
1738                                      "\"error\" in reply is not JSON string");
1739                     }
1740                 }
1741             } else {
1742                 hard_errors++;
1743                 ovsdb_idl_txn_set_error_json(txn, op);
1744                 VLOG_WARN_RL(&syntax_rl,
1745                              "operation reply is not JSON null or object");
1746             }
1747         }
1748
1749         if (!soft_errors && !hard_errors) {
1750             struct ovsdb_idl_txn_insert *insert;
1751
1752             if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
1753                 hard_errors++;
1754             }
1755
1756             HMAP_FOR_EACH (insert, struct ovsdb_idl_txn_insert, hmap_node,
1757                            &txn->inserted_rows) {
1758                 if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
1759                     hard_errors++;
1760                 }
1761             }
1762         }
1763
1764         status = (hard_errors ? TXN_ERROR
1765                   : soft_errors ? TXN_TRY_AGAIN
1766                   : TXN_SUCCESS);
1767     }
1768
1769     ovsdb_idl_txn_complete(txn, status);
1770     return true;
1771 }
1772
1773 struct ovsdb_idl_txn *
1774 ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
1775 {
1776     struct ovsdb_idl_txn *txn = row->table->idl->txn;
1777     assert(txn != NULL);
1778     return txn;
1779 }
1780
1781 struct ovsdb_idl *
1782 ovsdb_idl_txn_get_idl (struct ovsdb_idl_txn *txn)
1783 {
1784     return txn->idl;
1785 }
1786