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