Coverage Report

Created: 2026-09-02 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openvswitch/lib/ovsdb-idl.c
Line
Count
Source
1
/* Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Nicira, Inc.
2
 * Copyright (C) 2016 Hewlett Packard Enterprise Development LP
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at:
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
17
#include <config.h>
18
19
#include "ovsdb-idl.h"
20
21
#include <errno.h>
22
#include <inttypes.h>
23
#include <limits.h>
24
#include <stdlib.h>
25
26
#include "bitmap.h"
27
#include "coverage.h"
28
#include "hash.h"
29
#include "openvswitch/dynamic-string.h"
30
#include "fatal-signal.h"
31
#include "openvswitch/json.h"
32
#include "jsonrpc.h"
33
#include "ovsdb/ovsdb.h"
34
#include "ovsdb/table.h"
35
#include "ovsdb-cs.h"
36
#include "ovsdb-data.h"
37
#include "ovsdb-error.h"
38
#include "ovsdb-idl-provider.h"
39
#include "ovsdb-parser.h"
40
#include "ovsdb-server-idl.h"
41
#include "ovsdb-session.h"
42
#include "openvswitch/poll-loop.h"
43
#include "openvswitch/shash.h"
44
#include "skiplist.h"
45
#include "simap.h"
46
#include "sset.h"
47
#include "svec.h"
48
#include "util.h"
49
#include "uuid.h"
50
#include "openvswitch/vlog.h"
51
52
VLOG_DEFINE_THIS_MODULE(ovsdb_idl);
53
54
COVERAGE_DEFINE(txn_uncommitted);
55
COVERAGE_DEFINE(txn_unchanged);
56
COVERAGE_DEFINE(txn_incomplete);
57
COVERAGE_DEFINE(txn_aborted);
58
COVERAGE_DEFINE(txn_success);
59
COVERAGE_DEFINE(txn_try_again);
60
COVERAGE_DEFINE(txn_not_locked);
61
COVERAGE_DEFINE(txn_error);
62
63
/* An arc from one idl_row to another.  When row A contains a UUID that
64
 * references row B, this is represented by an arc from A (the source) to B
65
 * (the destination).
66
 *
67
 * Arcs from a row to itself are omitted, that is, src and dst are always
68
 * different.
69
 *
70
 * Arcs are never duplicated, that is, even if there are multiple references
71
 * from A to B, there is only a single arc from A to B.
72
 *
73
 * Arcs are directed: an arc from A to B is the converse of an an arc from B to
74
 * A.  Both an arc and its converse may both be present, if each row refers
75
 * to the other circularly.
76
 *
77
 * The source and destination row may be in the same table or in different
78
 * tables.
79
 */
80
struct ovsdb_idl_arc {
81
    struct ovs_list src_node;   /* In src->src_arcs list. */
82
    struct ovs_list dst_node;   /* In dst->dst_arcs list. */
83
    struct ovsdb_idl_row *src;  /* Source row. */
84
    struct ovsdb_idl_row *dst;  /* Destination row. */
85
};
86
87
struct ovsdb_idl {
88
    struct ovsdb_cs *cs;
89
    const struct ovsdb_idl_class *class_;
90
    struct shash table_by_name; /* Contains "struct ovsdb_idl_table *"s.*/
91
    struct ovsdb_idl_table *tables; /* Array of ->class_->n_tables elements. */
92
    unsigned int change_seqno;
93
    struct ovsdb_idl_txn *txn;
94
    struct hmap outstanding_txns;
95
    bool verify_write_only;
96
    struct ovs_list deleted_untracked_rows; /* Stores rows deleted in the
97
                                             * current run, that are not yet
98
                                             * added to the track_list. */
99
    struct ovs_list rows_to_reparse; /* Stores rows that might need to be
100
                                      * re-parsed due to insertion of a
101
                                      * referenced row. */
102
    bool server_schema_received; /* Set to true when the IDL has received
103
                                  * the DB schema from the server. */
104
};
105
106
static struct ovsdb_cs_ops ovsdb_idl_cs_ops;
107
108
struct ovsdb_idl_txn {
109
    struct hmap_node hmap_node;
110
    struct json *request_id;
111
    struct ovsdb_idl *idl;
112
    struct hmap txn_rows;
113
    enum ovsdb_idl_txn_status status;
114
    char *error;
115
    bool dry_run;
116
    bool assert_read_only;
117
    struct ds comment;
118
119
    /* Increments. */
120
    const char *inc_table;
121
    const char *inc_column;
122
    struct uuid inc_row;
123
    bool inc_force;
124
    unsigned int inc_index;
125
    int64_t inc_new_value;
126
127
    /* Inserted rows. */
128
    struct hmap inserted_rows;  /* Contains "struct ovsdb_idl_txn_insert"s. */
129
};
130
131
struct ovsdb_idl_txn_insert {
132
    struct hmap_node hmap_node; /* In struct ovsdb_idl_txn's inserted_rows. */
133
    struct uuid dummy;          /* Dummy UUID used locally. */
134
    int op_index;               /* Index into transaction's operation array. */
135
    struct uuid real;           /* Real UUID used by database server. */
136
};
137
138
static struct vlog_rate_limit syntax_rl = VLOG_RATE_LIMIT_INIT(1, 5);
139
static struct vlog_rate_limit semantic_rl = VLOG_RATE_LIMIT_INIT(1, 5);
140
static struct vlog_rate_limit other_rl = VLOG_RATE_LIMIT_INIT(1, 5);
141
142
enum update_result {
143
    OVSDB_IDL_UPDATE_DB_CHANGED,
144
    OVSDB_IDL_UPDATE_NO_CHANGES,
145
    OVSDB_IDL_UPDATE_INCONSISTENT,
146
};
147
static void ovsdb_idl_clear(struct ovsdb_idl *);
148
static enum update_result ovsdb_idl_process_update(
149
    struct ovsdb_idl_table *, const struct ovsdb_cs_row_update *);
150
static void ovsdb_idl_insert_row(struct ovsdb_idl_row *,
151
                                 const struct shash *values);
152
static void ovsdb_idl_delete_row(struct ovsdb_idl_row *);
153
static bool ovsdb_idl_modify_row(struct ovsdb_idl_row *,
154
                                 const struct shash *values, bool xor);
155
static void ovsdb_idl_parse_update(struct ovsdb_idl *,
156
                                   const struct ovsdb_cs_update_event *);
157
static void ovsdb_idl_reparse_deleted(struct ovsdb_idl *);
158
static void ovsdb_idl_reparse_refs_to_inserted(struct ovsdb_idl *);
159
160
static void ovsdb_idl_txn_process_reply(struct ovsdb_idl *,
161
                                        const struct jsonrpc_msg *);
162
163
static bool ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *);
164
static struct ovsdb_idl_row *ovsdb_idl_row_create__(
165
    const struct ovsdb_idl_table_class *);
166
static struct ovsdb_idl_row *ovsdb_idl_row_create(struct ovsdb_idl_table *,
167
                                                  const struct uuid *);
168
static void ovsdb_idl_row_destroy(struct ovsdb_idl_row *);
169
static void ovsdb_idl_row_destroy_postprocess(struct ovsdb_idl *);
170
static void ovsdb_idl_destroy_all_map_op_lists(struct ovsdb_idl_row *);
171
static void ovsdb_idl_destroy_all_set_op_lists(struct ovsdb_idl_row *);
172
173
static void ovsdb_idl_row_parse(struct ovsdb_idl_row *);
174
static void ovsdb_idl_row_unparse(struct ovsdb_idl_row *);
175
static void ovsdb_idl_row_clear_old(struct ovsdb_idl_row *);
176
static void ovsdb_idl_row_clear_new(struct ovsdb_idl_row *);
177
static void ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *, bool destroy_dsts);
178
static void ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *);
179
static void ovsdb_idl_row_mark_backrefs_for_reparsing(struct ovsdb_idl_row *);
180
static void ovsdb_idl_row_track_change(struct ovsdb_idl_row *,
181
                                       enum ovsdb_idl_change);
182
static void ovsdb_idl_row_untrack_change(struct ovsdb_idl_row *);
183
static void ovsdb_idl_row_clear_changeseqno(struct ovsdb_idl_row *);
184
185
static void ovsdb_idl_txn_abort_all(struct ovsdb_idl *);
186
static bool ovsdb_idl_txn_extract_mutations(struct ovsdb_idl_row *,
187
                                            struct json *);
188
static void ovsdb_idl_txn_add_map_op(struct ovsdb_idl_row *,
189
                                     const struct ovsdb_idl_column *,
190
                                     struct ovsdb_datum *,
191
                                     enum map_op_type);
192
static void ovsdb_idl_txn_add_set_op(struct ovsdb_idl_row *,
193
                                     const struct ovsdb_idl_column *,
194
                                     struct ovsdb_datum *,
195
                                     enum set_op_type);
196
197
static struct ovsdb_idl_table *
198
ovsdb_idl_table_from_class(const struct ovsdb_idl *,
199
                              const struct ovsdb_idl_table_class *);
200
static struct ovsdb_idl_table *
201
ovsdb_idl_table_from_class(const struct ovsdb_idl *,
202
                           const struct ovsdb_idl_table_class *);
203
static void ovsdb_idl_track_clear__(struct ovsdb_idl *, bool flush_all);
204
205
static void ovsdb_idl_destroy_indexes(struct ovsdb_idl_table *);
206
static void ovsdb_idl_add_to_indexes(const struct ovsdb_idl_row *);
207
static void ovsdb_idl_remove_from_indexes(const struct ovsdb_idl_row *);
208
static int ovsdb_idl_try_commit_loop_txn(struct ovsdb_idl_loop *loop,
209
                                         bool *may_need_wakeup);
210
static void ovsdb_idl_condition_clone(struct ovsdb_idl_condition *dest,
211
                                      const struct ovsdb_idl_condition *);
212
static void ovsdb_idl_create_req_condition(
213
        struct ovsdb_idl *,
214
        const struct ovsdb_idl_table_class *,
215
        const struct ovsdb_idl_condition *);
216
static void ovsdb_idl_destroy_req_condition(struct ovsdb_idl_table *);
217
static unsigned int ovsdb_idl_set_condition__(
218
        struct ovsdb_idl *,
219
        const struct ovsdb_idl_table_class *,
220
        const struct ovsdb_idl_condition *);
221
222
static void add_tracked_change_for_references(struct ovsdb_idl_row *);
223
224
/* Creates and returns a connection to database 'remote', which should be in a
225
 * form acceptable to jsonrpc_session_open().  The connection will maintain an
226
 * in-memory replica of the remote database whose schema is described by
227
 * 'class'.  (Ordinarily 'class' is compiled from an OVSDB schema automatically
228
 * by ovsdb-idlc.)
229
 *
230
 * Passes 'retry' to jsonrpc_session_open().  See that function for
231
 * documentation.
232
 *
233
 * If 'monitor_everything_by_default' is true, then everything in the remote
234
 * database will be replicated by default.  ovsdb_idl_omit() and
235
 * ovsdb_idl_omit_alert() may be used to selectively drop some columns from
236
 * monitoring.
237
 *
238
 * If 'monitor_everything_by_default' is false, then no columns or tables will
239
 * be replicated by default.  ovsdb_idl_add_column() and ovsdb_idl_add_table()
240
 * must be used to choose some columns or tables to replicate.
241
 */
242
struct ovsdb_idl *
243
ovsdb_idl_create(const char *remote, const struct ovsdb_idl_class *class,
244
                 bool monitor_everything_by_default, bool retry)
245
0
{
246
0
    struct ovsdb_idl *idl = ovsdb_idl_create_unconnected(
247
0
        class, monitor_everything_by_default);
248
0
    ovsdb_idl_set_remote(idl, remote, retry);
249
0
    return idl;
250
0
}
251
252
/* Creates and returns a connection to an in-memory replica of the remote
253
 * database whose schema is described by 'class'.  (Ordinarily 'class' is
254
 * compiled from an OVSDB schema automatically by ovsdb-idlc.)
255
 *
256
 * Use ovsdb_idl_set_remote() to configure the database to which to connect.
257
 * Until a remote is configured, no data can be retrieved.
258
 *
259
 * If 'monitor_everything_by_default' is true, then everything in the remote
260
 * database will be replicated by default.  ovsdb_idl_omit() and
261
 * ovsdb_idl_omit_alert() may be used to selectively drop some columns from
262
 * monitoring.
263
 *
264
 * If 'monitor_everything_by_default' is false, then no columns or tables will
265
 * be replicated by default.  ovsdb_idl_add_column() and ovsdb_idl_add_table()
266
 * must be used to choose some columns or tables to replicate.
267
 */
268
struct ovsdb_idl *
269
ovsdb_idl_create_unconnected(const struct ovsdb_idl_class *class,
270
                             bool monitor_everything_by_default)
271
0
{
272
0
    struct ovsdb_idl *idl = xmalloc(sizeof *idl);
273
0
    *idl = (struct ovsdb_idl) {
274
0
        .cs = ovsdb_cs_create(class->database, 3, &ovsdb_idl_cs_ops, idl),
275
0
        .class_ = class,
276
0
        .table_by_name = SHASH_INITIALIZER(&idl->table_by_name),
277
0
        .tables = xmalloc(class->n_tables * sizeof *idl->tables),
278
0
        .change_seqno = 0,
279
0
        .txn = NULL,
280
0
        .outstanding_txns = HMAP_INITIALIZER(&idl->outstanding_txns),
281
0
        .verify_write_only = false,
282
0
        .server_schema_received = false,
283
0
        .deleted_untracked_rows
284
0
            = OVS_LIST_INITIALIZER(&idl->deleted_untracked_rows),
285
0
        .rows_to_reparse
286
0
            = OVS_LIST_INITIALIZER(&idl->rows_to_reparse),
287
0
    };
288
289
0
    uint8_t default_mode = (monitor_everything_by_default
290
0
                            ? OVSDB_IDL_MONITOR | OVSDB_IDL_ALERT
291
0
                            : 0);
292
0
    for (size_t i = 0; i < class->n_tables; i++) {
293
0
        const struct ovsdb_idl_table_class *tc = &class->tables[i];
294
0
        struct ovsdb_idl_table *table = &idl->tables[i];
295
296
0
        shash_add_assert(&idl->table_by_name, tc->name, table);
297
0
        table->class_ = tc;
298
0
        table->modes = xmalloc(tc->n_columns);
299
0
        memset(table->modes, default_mode, tc->n_columns);
300
0
        table->need_table = false;
301
0
        shash_init(&table->columns);
302
0
        ovs_list_init(&table->indexes);
303
0
        for (size_t j = 0; j < tc->n_columns; j++) {
304
0
            const struct ovsdb_idl_column *column = &tc->columns[j];
305
306
0
            shash_add_assert(&table->columns, column->name, column);
307
0
        }
308
0
        hmap_init(&table->rows);
309
0
        ovs_list_init(&table->track_list);
310
0
        table->change_seqno[OVSDB_IDL_CHANGE_INSERT]
311
0
            = table->change_seqno[OVSDB_IDL_CHANGE_MODIFY]
312
0
            = table->change_seqno[OVSDB_IDL_CHANGE_DELETE] = 0;
313
0
        table->idl = idl;
314
0
        table->in_server_schema = false;
315
0
        table->req_cond = NULL;
316
0
        shash_init(&table->schema_columns);
317
0
    }
318
319
0
    return idl;
320
0
}
321
322
/* Changes the remote and creates a new session.
323
 *
324
 * If 'retry' is true, the connection to the remote will automatically retry
325
 * when it fails.  If 'retry' is false, the connection is one-time. */
326
void
327
ovsdb_idl_set_remote(struct ovsdb_idl *idl, const char *remote, bool retry)
328
0
{
329
0
    ovsdb_cs_set_remote(idl->cs, remote, retry);
330
0
}
331
332
/* Set whether the order of remotes should be shuffled, when there
333
 * are more than one remotes.  The setting doesn't take effect
334
 * until the next time when ovsdb_idl_set_remote() is called. */
335
void
336
ovsdb_idl_set_shuffle_remotes(struct ovsdb_idl *idl, bool shuffle)
337
0
{
338
0
    ovsdb_cs_set_shuffle_remotes(idl->cs, shuffle);
339
0
}
340
341
/* Passes 'set_db_change_aware' to ovsdb_cs_set_db_change_aware().  See that
342
 * function for documentation. */
343
void
344
ovsdb_idl_set_db_change_aware(struct ovsdb_idl *idl, bool set_db_change_aware)
345
0
{
346
0
    ovsdb_cs_set_db_change_aware(idl->cs, set_db_change_aware);
347
0
}
348
349
/* Reset min_index to 0. This prevents a situation where the client
350
 * thinks all databases have stale data, when they actually have all
351
 * been destroyed and rebuilt from scratch.
352
 */
353
void
354
ovsdb_idl_reset_min_index(struct ovsdb_idl *idl)
355
0
{
356
0
    ovsdb_cs_reset_min_index(idl->cs);
357
0
}
358
359
static void
360
ovsdb_idl_schema_columns_clear(struct shash *schema_columns)
361
0
{
362
0
    struct shash_node *node;
363
364
0
    SHASH_FOR_EACH (node, schema_columns) {
365
0
        ovsdb_type_destroy(node->data);
366
0
    }
367
0
    shash_clear_free_data(schema_columns);
368
0
}
369
370
/* Destroys 'idl' and all of the data structures that it manages. */
371
void
372
ovsdb_idl_destroy(struct ovsdb_idl *idl)
373
0
{
374
0
    if (idl) {
375
0
        ovs_assert(!idl->txn);
376
377
0
        ovsdb_idl_txn_abort_all(idl);
378
0
        hmap_destroy(&idl->outstanding_txns);
379
380
0
        ovsdb_idl_clear(idl);
381
0
        ovsdb_cs_destroy(idl->cs);
382
0
        for (size_t i = 0; i < idl->class_->n_tables; i++) {
383
0
            struct ovsdb_idl_table *table = &idl->tables[i];
384
385
0
            ovsdb_idl_destroy_indexes(table);
386
0
            shash_destroy(&table->columns);
387
388
0
            ovsdb_idl_schema_columns_clear(&table->schema_columns);
389
0
            shash_destroy(&table->schema_columns);
390
0
            ovsdb_idl_destroy_req_condition(table);
391
392
0
            hmap_destroy(&table->rows);
393
0
            free(table->modes);
394
0
        }
395
0
        shash_destroy(&idl->table_by_name);
396
0
        free(idl->tables);
397
0
        free(idl);
398
0
    }
399
0
}
400
401
/* By default, or if 'leader_only' is true, when 'idl' connects to a clustered
402
 * database, the IDL will avoid servers other than the cluster leader. This
403
 * ensures that any data that it reads and reports is up-to-date.  If
404
 * 'leader_only' is false, the IDL will accept any server in the cluster, which
405
 * means that for read-only transactions it can report and act on stale data
406
 * (transactions that modify the database are always serialized even with false
407
 * 'leader_only').  Refer to Understanding Cluster Consistency in ovsdb(7) for
408
 * more information. */
409
void
410
ovsdb_idl_set_leader_only(struct ovsdb_idl *idl, bool leader_only)
411
0
{
412
0
    ovsdb_cs_set_leader_only(idl->cs, leader_only);
413
0
}
414
415
static void
416
ovsdb_idl_clear(struct ovsdb_idl *db)
417
0
{
418
    /* Process deleted rows, removing them from the 'deleted_untracked_rows'
419
     * list and reparsing their backrefs.
420
     */
421
0
    ovsdb_idl_reparse_deleted(db);
422
423
    /* Process backrefs of inserted rows, removing them from the
424
     * 'rows_to_reparse' list.
425
     */
426
0
    ovsdb_idl_reparse_refs_to_inserted(db);
427
428
    /* Cleanup all rows; each row gets added to its own table's
429
     * 'track_list'.
430
     */
431
0
    for (size_t i = 0; i < db->class_->n_tables; i++) {
432
0
        struct ovsdb_idl_table *table = &db->tables[i];
433
0
        struct ovsdb_idl_row *row;
434
435
0
        if (hmap_is_empty(&table->rows)) {
436
0
            continue;
437
0
        }
438
439
0
        HMAP_FOR_EACH_SAFE (row, hmap_node, &table->rows) {
440
0
            struct ovsdb_idl_arc *arc;
441
442
0
            if (!ovsdb_idl_row_is_orphan(row)) {
443
0
                ovsdb_idl_remove_from_indexes(row);
444
0
                ovsdb_idl_row_unparse(row);
445
0
            }
446
0
            LIST_FOR_EACH_SAFE (arc, src_node, &row->src_arcs) {
447
0
                ovs_list_remove(&arc->src_node);
448
0
                ovs_list_remove(&arc->dst_node);
449
0
                free(arc);
450
0
            }
451
0
            LIST_FOR_EACH_SAFE (arc, dst_node, &row->dst_arcs) {
452
0
                ovs_list_remove(&arc->src_node);
453
0
                ovs_list_remove(&arc->dst_node);
454
0
                free(arc);
455
0
            }
456
457
0
            ovsdb_idl_row_destroy(row);
458
0
        }
459
0
    }
460
461
    /* Free rows deleted from tables with change tracking disabled. */
462
0
    ovsdb_idl_row_destroy_postprocess(db);
463
464
    /* Free rows deleted from tables with change tracking enabled. */
465
0
    ovsdb_idl_track_clear__(db, true);
466
0
    ovs_assert(ovs_list_is_empty(&db->deleted_untracked_rows));
467
0
    ovs_assert(ovs_list_is_empty(&db->rows_to_reparse));
468
0
    db->change_seqno++;
469
0
}
470
471
/* Processes a batch of messages from the database server on 'idl'.  This may
472
 * cause the IDL's contents to change.  The client may check for that with
473
 * ovsdb_idl_get_seqno(). */
474
void
475
ovsdb_idl_run(struct ovsdb_idl *idl)
476
0
{
477
0
    ovs_assert(!idl->txn);
478
479
0
    struct ovs_list events;
480
0
    ovsdb_cs_run(idl->cs, &events);
481
482
0
    struct ovsdb_cs_event *event;
483
0
    LIST_FOR_EACH_POP (event, list_node, &events) {
484
0
        switch (event->type) {
485
0
        case OVSDB_CS_EVENT_TYPE_RECONNECT:
486
0
            ovsdb_idl_txn_abort_all(idl);
487
0
            break;
488
489
0
        case OVSDB_CS_EVENT_TYPE_LOCKED:
490
0
            if (ovsdb_cs_may_send_transaction(idl->cs)) {
491
                /* If the client couldn't run a transaction because it didn't
492
                 * have the lock, this will encourage it to try again. */
493
0
                idl->change_seqno++;
494
0
            } else {
495
                /* We're setting up a session, so don't signal that the
496
                 * database changed.  Finalizing the session will increment
497
                 * change_seqno anyhow. */
498
0
            }
499
0
            break;
500
501
0
        case OVSDB_CS_EVENT_TYPE_UPDATE:
502
0
            ovsdb_idl_parse_update(idl, &event->update);
503
0
            break;
504
505
0
        case OVSDB_CS_EVENT_TYPE_TXN_REPLY:
506
0
            ovsdb_idl_txn_process_reply(idl, event->txn_reply);
507
0
            break;
508
0
        }
509
0
        ovsdb_cs_event_destroy(event);
510
0
    }
511
0
    ovsdb_idl_reparse_refs_to_inserted(idl);
512
0
    ovsdb_idl_reparse_deleted(idl);
513
0
    ovsdb_idl_row_destroy_postprocess(idl);
514
0
}
515
516
/* Arranges for poll_block() to wake up when ovsdb_idl_run() has something to
517
 * do or when activity occurs on a transaction on 'idl'. */
518
void
519
ovsdb_idl_wait(struct ovsdb_idl *idl)
520
0
{
521
0
    ovsdb_cs_wait(idl->cs);
522
0
}
523
524
/* Returns memory usage statistics. */
525
void
526
ovsdb_idl_get_memory_usage(struct ovsdb_idl *idl, struct simap *usage)
527
0
{
528
0
    unsigned int cells = 0;
529
530
0
    if (!idl) {
531
0
        return;
532
0
    }
533
534
0
    for (size_t i = 0; i < idl->class_->n_tables; i++) {
535
0
        struct ovsdb_idl_table *table = &idl->tables[i];
536
0
        unsigned int n_columns = table->class_->n_columns;
537
0
        unsigned int n_rows = hmap_count(&table->rows);
538
539
0
        cells += n_rows * n_columns;
540
0
    }
541
542
0
    struct {
543
0
        const char *name;
544
0
        unsigned int val;
545
0
    } idl_mem_stats[] = {
546
0
        {"idl-outstanding-txns", hmap_count(&idl->outstanding_txns)},
547
0
        {"idl-cells", cells},
548
0
    };
549
550
0
    for (size_t i = 0; i < ARRAY_SIZE(idl_mem_stats); i++) {
551
0
        char *stat_name = xasprintf("%s-%s", idl_mem_stats[i].name,
552
0
                                             idl->class_->database);
553
0
        simap_increase(usage, stat_name, idl_mem_stats[i].val);
554
0
        free(stat_name);
555
0
    }
556
0
}
557
558
/* Returns a "sequence number" that represents the state of 'idl'.  When
559
 * ovsdb_idl_run() changes the database, the sequence number changes.  The
560
 * initial fetch of the entire contents of the remote database is considered to
561
 * be one kind of change.  Successfully acquiring a lock, if one has been
562
 * configured with ovsdb_idl_set_lock(), is also considered to be a change.
563
 *
564
 * As long as the sequence number does not change, the client may continue to
565
 * use any data structures it obtains from 'idl'.  But when it changes, the
566
 * client must not access any of these data structures again, because they
567
 * could have freed or reused for other purposes.
568
 *
569
 * The sequence number can occasionally change even if the database does not.
570
 * This happens if the connection to the database drops and reconnects, which
571
 * causes the database contents to be reloaded even if they didn't change.  (It
572
 * could also happen if the database server sends out a "change" that reflects
573
 * what the IDL already thought was in the database.  The database server is
574
 * not supposed to do that, but bugs could in theory cause it to do so.) */
575
unsigned int
576
ovsdb_idl_get_seqno(const struct ovsdb_idl *idl)
577
0
{
578
0
    return idl->change_seqno;
579
0
}
580
581
/* Returns a "sequence number" that represents the number of conditional
582
 * monitoring updates successfully received by the OVSDB server of an IDL
583
 * connection.
584
 *
585
 * ovsdb_idl_set_condition() sets a new condition that is different from
586
 * the current condtion, the next expected "sequence number" is returned.
587
 *
588
 * Whenever ovsdb_idl_get_cond_seqno() returns a value that matches
589
 * the return value of ovsdb_idl_set_condition(),  The client is
590
 * assured that:
591
 *   -  The ovsdb_idl_set_condition() changes has been acknowledged by
592
 *      the OVSDB sever.
593
 *
594
 *   -  'idl' now contains the content matches the new conditions.   */
595
unsigned int
596
ovsdb_idl_get_condition_seqno(const struct ovsdb_idl *idl)
597
0
{
598
0
    return ovsdb_cs_get_condition_seqno(idl->cs);
599
0
}
600
601
/* Returns true if 'idl' successfully connected to the remote database and
602
 * retrieved its contents (even if the connection subsequently dropped and is
603
 * in the process of reconnecting).  If so, then 'idl' contains an atomic
604
 * snapshot of the database's contents (but it might be arbitrarily old if the
605
 * connection dropped).
606
 *
607
 * Returns false if 'idl' has never connected or retrieved the database's
608
 * contents.  If so, 'idl' is empty. */
609
bool
610
ovsdb_idl_has_ever_connected(const struct ovsdb_idl *idl)
611
0
{
612
0
    return ovsdb_idl_get_seqno(idl) != 0;
613
0
}
614
615
/* Reconfigures 'idl' so that it would reconnect to the database, if
616
 * connection was dropped. */
617
void
618
ovsdb_idl_enable_reconnect(struct ovsdb_idl *idl)
619
0
{
620
0
    ovsdb_cs_enable_reconnect(idl->cs);
621
0
}
622
623
/* Forces 'idl' to drop its connection to the database and reconnect.  In the
624
 * meantime, the contents of 'idl' will not change. */
625
void
626
ovsdb_idl_force_reconnect(struct ovsdb_idl *idl)
627
0
{
628
0
    ovsdb_cs_force_reconnect(idl->cs);
629
0
}
630
631
/* Some IDL users should only write to write-only columns.  Furthermore,
632
 * writing to a column which is not write-only can cause serious performance
633
 * degradations for these users.  This function causes 'idl' to reject writes
634
 * to columns which are not marked write only using ovsdb_idl_omit_alert(). */
635
void
636
ovsdb_idl_verify_write_only(struct ovsdb_idl *idl)
637
0
{
638
0
    idl->verify_write_only = true;
639
0
}
640
641
/* Returns true if 'idl' is currently connected or trying to connect
642
 * and a negative response to a schema request has not been received */
643
bool
644
ovsdb_idl_is_alive(const struct ovsdb_idl *idl)
645
0
{
646
0
    return ovsdb_cs_is_alive(idl->cs);
647
0
}
648
649
bool
650
ovsdb_idl_is_connected(const struct ovsdb_idl *idl)
651
0
{
652
0
    return ovsdb_cs_is_connected(idl->cs);
653
0
}
654
655
/* Returns the last error reported on a connection by 'idl'.  The return value
656
 * is 0 only if no connection made by 'idl' has ever encountered an error and
657
 * a negative response to a schema request has never been received. See
658
 * jsonrpc_get_status() for jsonrpc_session_get_last_error() return value
659
 * interpretation. */
660
int
661
ovsdb_idl_get_last_error(const struct ovsdb_idl *idl)
662
0
{
663
0
    return ovsdb_cs_get_last_error(idl->cs);
664
0
}
665
666
/* Sets the "probe interval" for 'idl->session' to 'probe_interval', in
667
 * milliseconds.
668
 */
669
void
670
ovsdb_idl_set_probe_interval(const struct ovsdb_idl *idl, int probe_interval)
671
0
{
672
0
    ovsdb_cs_set_probe_interval(idl->cs, probe_interval);
673
0
}
674
675
static size_t
676
find_uuid_in_array(const struct uuid *target,
677
                   const struct uuid *array, size_t n)
678
0
{
679
0
    for (size_t i = 0; i < n; i++) {
680
0
        if (uuid_equals(&array[i], target)) {
681
0
            return i;
682
0
        }
683
0
    }
684
0
    return SIZE_MAX;
685
0
}
686
687
static size_t
688
array_contains_uuid(const struct uuid *target,
689
                    const struct uuid *array, size_t n)
690
0
{
691
0
    return find_uuid_in_array(target, array, n) != SIZE_MAX;
692
0
}
693
694
static bool
695
remove_uuid_from_array(const struct uuid *target,
696
                       struct uuid *array, size_t *n)
697
0
{
698
0
    size_t i = find_uuid_in_array(target, array, *n);
699
0
    if (i != SIZE_MAX) {
700
0
        array[i] = array[--*n];
701
0
        return true;
702
0
    } else {
703
0
        return false;
704
0
    }
705
0
}
706
707
static void
708
add_row_references(const struct ovsdb_base_type *type,
709
                   const union ovsdb_atom *atoms, size_t n_atoms,
710
                   const struct uuid *exclude_uuid,
711
                   struct uuid **dstsp, size_t *n_dstsp,
712
                   size_t *allocated_dstsp)
713
0
{
714
0
    if (type->type != OVSDB_TYPE_UUID || !type->uuid.refTableName) {
715
0
        return;
716
0
    }
717
718
0
    for (size_t i = 0; i < n_atoms; i++) {
719
0
        const struct uuid *uuid = &atoms[i].uuid;
720
0
        if (!uuid_equals(uuid, exclude_uuid)
721
0
            && !array_contains_uuid(uuid, *dstsp, *n_dstsp)) {
722
0
            if (*n_dstsp >= *allocated_dstsp) {
723
0
                *dstsp = x2nrealloc(*dstsp, allocated_dstsp,
724
0
                                    sizeof **dstsp);
725
726
0
            }
727
0
            (*dstsp)[*n_dstsp] = *uuid;
728
0
            ++*n_dstsp;
729
0
        }
730
0
    }
731
0
}
732
733
/* Checks for consistency in 'idl''s graph of arcs between database rows.  Each
734
 * reference from one row to a different row should be reflected as a "struct
735
 * ovsdb_idl_arc" between those rows.
736
 *
737
 * This function is slow, big-O wise, and aborts if it finds an inconsistency,
738
 * thus it is only for use in test programs. */
739
void
740
ovsdb_idl_check_consistency(const struct ovsdb_idl *idl)
741
0
{
742
    /* Consistency is broken while a transaction is in progress. */
743
0
    if (!idl->txn) {
744
0
        return;
745
0
    }
746
747
0
    bool ok = true;
748
749
0
    struct uuid *dsts = NULL;
750
0
    size_t allocated_dsts = 0;
751
752
0
    for (size_t i = 0; i < idl->class_->n_tables; i++) {
753
0
        const struct ovsdb_idl_table *table = &idl->tables[i];
754
0
        const struct ovsdb_idl_table_class *class = table->class_;
755
756
0
        const struct ovsdb_idl_row *row;
757
0
        HMAP_FOR_EACH (row, hmap_node, &table->rows) {
758
0
            size_t n_dsts = 0;
759
0
            if (row->new_datum) {
760
0
                size_t n_columns = shash_count(&row->table->columns);
761
0
                for (size_t j = 0; j < n_columns; j++) {
762
0
                    const struct ovsdb_type *type = &class->columns[j].type;
763
0
                    const struct ovsdb_datum *datum;
764
765
0
                    datum = ovsdb_idl_read(row, &class->columns[j]);
766
0
                    add_row_references(&type->key,
767
0
                                       datum->keys, datum->n, &row->uuid,
768
0
                                       &dsts, &n_dsts, &allocated_dsts);
769
0
                    add_row_references(&type->value,
770
0
                                       datum->values, datum->n, &row->uuid,
771
0
                                       &dsts, &n_dsts, &allocated_dsts);
772
0
                }
773
0
            }
774
0
            const struct ovsdb_idl_arc *arc;
775
0
            LIST_FOR_EACH (arc, src_node, &row->src_arcs) {
776
0
                if (!remove_uuid_from_array(&arc->dst->uuid,
777
0
                                            dsts, &n_dsts)) {
778
0
                    VLOG_ERR("unexpected arc from %s row "UUID_FMT" to %s "
779
0
                             "row "UUID_FMT,
780
0
                             table->class_->name,
781
0
                             UUID_ARGS(&row->uuid),
782
0
                             arc->dst->table->class_->name,
783
0
                             UUID_ARGS(&arc->dst->uuid));
784
0
                    ok = false;
785
0
                }
786
0
            }
787
0
            for (size_t j = 0; j < n_dsts; j++) {
788
0
                VLOG_ERR("%s row "UUID_FMT" missing arc to row "UUID_FMT,
789
0
                         table->class_->name, UUID_ARGS(&row->uuid),
790
0
                         UUID_ARGS(&dsts[j]));
791
0
                ok = false;
792
0
            }
793
0
        }
794
0
    }
795
0
    free(dsts);
796
0
    ovs_assert(ok);
797
0
}
798
799
static struct json *
800
ovsdb_idl_compose_monitor_request(const struct json *schema_json, void *idl_)
801
0
{
802
0
    struct ovsdb_idl *idl = idl_;
803
804
0
    struct shash *schema = ovsdb_cs_parse_schema(schema_json);
805
0
    struct json *monitor_requests = json_object_create();
806
807
0
    idl->server_schema_received = true;
808
0
    for (size_t i = 0; i < idl->class_->n_tables; i++) {
809
0
        struct ovsdb_idl_table *table = &idl->tables[i];
810
0
        const struct ovsdb_idl_table_class *tc = table->class_;
811
0
        struct json *monitor_request;
812
0
        struct shash *table_schema
813
0
            = schema ? shash_find_data(schema, table->class_->name) : NULL;
814
815
0
        struct json *columns
816
0
            = table->need_table ? json_array_create_empty() : NULL;
817
818
0
        ovsdb_idl_schema_columns_clear(&table->schema_columns);
819
0
        for (size_t j = 0; j < tc->n_columns; j++) {
820
0
            const struct ovsdb_idl_column *column = &tc->columns[j];
821
0
            bool idl_has_column = false;
822
0
            struct shash_node *node;
823
824
0
            if (table_schema) {
825
0
                node = shash_find(table_schema, column->name);
826
0
                if (node) {
827
0
                    idl_has_column = true;
828
0
                    shash_add(&table->schema_columns,
829
0
                              column->name, node->data);
830
0
                    shash_delete(table_schema, node);
831
0
                }
832
0
            }
833
834
0
            if (column->is_synthetic) {
835
0
                if (idl_has_column) {
836
0
                    VLOG_WARN("%s table in %s database has synthetic "
837
0
                              "column %s", table->class_->name,
838
0
                              idl->class_->database, column->name);
839
0
                }
840
0
            } else if (table->modes[j] & OVSDB_IDL_MONITOR) {
841
0
                if (table_schema && !idl_has_column) {
842
0
                    VLOG_WARN("%s table in %s database lacks %s column "
843
0
                              "(database needs upgrade?)",
844
0
                              table->class_->name, idl->class_->database,
845
0
                              column->name);
846
0
                    continue;
847
0
                }
848
0
                if (!columns) {
849
0
                    columns = json_array_create_empty();
850
0
                }
851
0
                json_array_add(columns, json_string_create(column->name));
852
0
            }
853
0
        }
854
855
0
        if (columns) {
856
0
            if (schema && !table_schema) {
857
0
                VLOG_WARN("%s database lacks %s table "
858
0
                          "(database needs upgrade?)",
859
0
                          idl->class_->database, table->class_->name);
860
0
                json_destroy(columns);
861
0
                table->in_server_schema = false;
862
0
                ovsdb_cs_clear_condition(idl->cs, table->class_->name);
863
0
                continue;
864
0
            } else if (schema && table_schema) {
865
0
                if (!table->in_server_schema) {
866
                    /* The server didn't have this table before and now it
867
                     * does.  It should've dropped the transaction history,
868
                     * but it's better if we do not ask for it in the first
869
                     * place, as our conditions could be out of sync. */
870
0
                    ovsdb_cs_reset_last_id(idl->cs);
871
0
                }
872
0
                table->in_server_schema = true;
873
0
            }
874
875
0
            monitor_request = json_object_create();
876
0
            json_object_put(monitor_request, "columns", columns);
877
0
            json_object_put(monitor_requests, tc->name,
878
0
                            json_array_create_1(monitor_request));
879
0
        }
880
881
0
        if (!table->in_server_schema) {
882
0
            ovsdb_cs_clear_condition(idl->cs, table->class_->name);
883
0
        } else if (table->req_cond) {
884
            /* Update the monitor condition request according to the
885
             * db schema. */
886
0
            ovsdb_idl_set_condition__(idl, tc, table->req_cond);
887
0
        }
888
0
    }
889
0
    ovsdb_cs_free_schema(schema);
890
891
0
    return monitor_requests;
892
0
}
893
894
static struct ovsdb_cs_ops ovsdb_idl_cs_ops = {
895
    ovsdb_idl_compose_monitor_request,
896
};
897

898
const struct ovsdb_idl_class *
899
ovsdb_idl_get_class(const struct ovsdb_idl *idl)
900
0
{
901
0
    return idl->class_;
902
0
}
903
904
/* Given 'column' in some table in 'class', returns the table's class. */
905
const struct ovsdb_idl_table_class *
906
ovsdb_idl_table_class_from_column(const struct ovsdb_idl_class *class,
907
                                  const struct ovsdb_idl_column *column)
908
0
{
909
0
    for (size_t i = 0; i < class->n_tables; i++) {
910
0
        const struct ovsdb_idl_table_class *tc = &class->tables[i];
911
0
        if (column >= tc->columns && column < &tc->columns[tc->n_columns]) {
912
0
            return tc;
913
0
        }
914
0
    }
915
916
0
    OVS_NOT_REACHED();
917
0
}
918
919
/* Given 'column' in some table in 'idl', returns the table. */
920
static struct ovsdb_idl_table *
921
ovsdb_idl_table_from_column(const struct ovsdb_idl *idl,
922
                            const struct ovsdb_idl_column *column)
923
0
{
924
0
    const struct ovsdb_idl_table_class *tc =
925
0
        ovsdb_idl_table_class_from_column(idl->class_, column);
926
0
    return &idl->tables[tc - idl->class_->tables];
927
0
}
928
929
static unsigned char *
930
ovsdb_idl_get_mode(struct ovsdb_idl *idl,
931
                   const struct ovsdb_idl_column *column)
932
0
{
933
0
    ovs_assert(!idl->change_seqno);
934
935
0
    const struct ovsdb_idl_table *table = ovsdb_idl_table_from_column(idl,
936
0
                                                                      column);
937
0
    return &table->modes[column - table->class_->columns];
938
0
}
939
940
static void
941
ovsdb_idl_set_mode(struct ovsdb_idl *idl,
942
                   const struct ovsdb_idl_column *column,
943
                   unsigned char mode)
944
0
{
945
0
    const struct ovsdb_idl_table *table = ovsdb_idl_table_from_column(idl,
946
0
                                                                      column);
947
0
    size_t column_idx = column - table->class_->columns;
948
949
0
    if (table->modes[column_idx] != mode) {
950
0
        *ovsdb_idl_get_mode(idl, column) = mode;
951
0
    }
952
0
}
953
954
static void
955
add_ref_table(struct ovsdb_idl *idl, const struct ovsdb_base_type *base)
956
0
{
957
0
    if (base->type == OVSDB_TYPE_UUID && base->uuid.refTableName) {
958
0
        struct ovsdb_idl_table *table;
959
960
0
        table = shash_find_data(&idl->table_by_name, base->uuid.refTableName);
961
0
        if (table) {
962
0
            table->need_table = true;
963
0
        } else {
964
0
            VLOG_WARN("%s IDL class missing referenced table %s",
965
0
                      idl->class_->database, base->uuid.refTableName);
966
0
        }
967
0
    }
968
0
}
969
970
/* Turns on OVSDB_IDL_MONITOR and OVSDB_IDL_ALERT for 'column' in 'idl'.  Also
971
 * ensures that any tables referenced by 'column' will be replicated, even if
972
 * no columns in that table are selected for replication (see
973
 * ovsdb_idl_add_table() for more information).
974
 *
975
 * This function is only useful if 'monitor_everything_by_default' was false in
976
 * the call to ovsdb_idl_create().  This function should be called between
977
 * ovsdb_idl_create() and the first call to ovsdb_idl_run().
978
 */
979
void
980
ovsdb_idl_add_column(struct ovsdb_idl *idl,
981
                     const struct ovsdb_idl_column *column)
982
0
{
983
0
    ovsdb_idl_set_mode(idl, column, OVSDB_IDL_MONITOR | OVSDB_IDL_ALERT);
984
0
    add_ref_table(idl, &column->type.key);
985
0
    add_ref_table(idl, &column->type.value);
986
0
}
987
988
/* Ensures that the table with class 'tc' will be replicated on 'idl' even if
989
 * no columns are selected for replication. Just the necessary data for table
990
 * references will be replicated (the UUID of the rows, for instance), any
991
 * columns not selected for replication will remain unreplicated.
992
 * This can be useful because it allows 'idl' to keep track of what rows in the
993
 * table actually exist, which in turn allows columns that reference the table
994
 * to have accurate contents. (The IDL presents the database with references to
995
 * rows that do not exist removed.)
996
 *
997
 * This function is only useful if 'monitor_everything_by_default' was false in
998
 * the call to ovsdb_idl_create().  This function should be called between
999
 * ovsdb_idl_create() and the first call to ovsdb_idl_run().
1000
 */
1001
void
1002
ovsdb_idl_add_table(struct ovsdb_idl *idl,
1003
                    const struct ovsdb_idl_table_class *tc)
1004
0
{
1005
0
    for (size_t i = 0; i < idl->class_->n_tables; i++) {
1006
0
        struct ovsdb_idl_table *table = &idl->tables[i];
1007
1008
0
        if (table->class_ == tc) {
1009
0
            table->need_table = true;
1010
0
            return;
1011
0
        }
1012
0
    }
1013
1014
0
    OVS_NOT_REACHED();
1015
0
}
1016
1017
/* Returns 'true' if the 'idl' has seen the table for the 'table_class'
1018
 * in the schema reported by the server.  Returns 'false' otherwise.
1019
 *
1020
 * Always returns 'false' if idl has never been connected.
1021
 *
1022
 * Please see ovsdb_idl_compose_monitor_request() which sets
1023
 * 'struct ovsdb_idl_table *'->in_server_schema accordingly.
1024
 *
1025
 * Usually this function is used indirectly through one of the
1026
 * "server_has_table" functions generated by ovsdb-idlc. */
1027
bool
1028
ovsdb_idl_server_has_table(const struct ovsdb_idl *idl,
1029
                           const struct ovsdb_idl_table_class *table_class)
1030
0
{
1031
0
    const struct ovsdb_idl_table *table =
1032
0
        ovsdb_idl_table_from_class(idl, table_class);
1033
1034
0
    return (table && table->in_server_schema);
1035
0
}
1036
1037
/* Returns 'true' if the 'idl' has seen the 'column' in the schema
1038
 * reported by the server.  Returns 'false' otherwise.
1039
 *
1040
 * Always returns 'false' if idl has never been connected.
1041
 *
1042
 * Please see ovsdb_idl_compose_monitor_request() which sets
1043
 * 'struct ovsdb_idl_table *'->schema_columns accordingly.
1044
 *
1045
 * Usually this function is used indirectly through one of the
1046
 * "server_has_column" functions generated by ovsdb-idlc. */
1047
bool
1048
ovsdb_idl_server_has_column(const struct ovsdb_idl *idl,
1049
                            const struct ovsdb_idl_column *column)
1050
0
{
1051
0
    const struct ovsdb_idl_table *table =
1052
0
        ovsdb_idl_table_from_column(idl, column);
1053
1054
0
    return (table->in_server_schema && shash_find(&table->schema_columns,
1055
0
                                                  column->name));
1056
0
}
1057
1058
/* Returns the type of a 'column' as defined in the schema reported
1059
 * by the server if the 'idl' has seen the 'column' in that schema.
1060
 * Returns NULL otherwise.
1061
 *
1062
 * Always returns NULL if idl has never been connected.
1063
 *
1064
 * Please see ovsdb_idl_compose_monitor_request() which sets
1065
 * 'struct ovsdb_idl_table *'->schema_columns accordingly.
1066
 *
1067
 * Usually this function is used indirectly through one of the
1068
 * "server_column_type" functions generated by ovsdb-idlc.
1069
 *
1070
 * Having different types between the server and the client in many
1071
 * cases will result in complete communication breakdown, so this
1072
 * function is mostly useful for checking for type constraints (enum,
1073
 * n_max) in case the server's schema is older or newer. */
1074
const struct ovsdb_type *
1075
ovsdb_idl_server_column_type(const struct ovsdb_idl *idl,
1076
                             const struct ovsdb_idl_column *column)
1077
0
{
1078
0
    const struct ovsdb_idl_table *table =
1079
0
        ovsdb_idl_table_from_column(idl, column);
1080
1081
0
    if (!table->in_server_schema) {
1082
0
        return NULL;
1083
0
    }
1084
1085
0
    return shash_find_data(&table->schema_columns, column->name);
1086
0
}
1087

1088
/* A single clause within an ovsdb_idl_condition. */
1089
struct ovsdb_idl_clause {
1090
    struct hmap_node hmap_node;   /* In struct ovsdb_idl_condition. */
1091
    enum ovsdb_function function; /* Never OVSDB_F_TRUE or OVSDB_F_FALSE. */
1092
    const struct ovsdb_idl_column *column; /* Must be nonnull. */
1093
    struct ovsdb_datum arg;       /* Has ovsdb_type ->column->type. */
1094
};
1095
1096
static uint32_t
1097
ovsdb_idl_clause_hash(const struct ovsdb_idl_clause *clause)
1098
0
{
1099
0
    uint32_t hash = hash_pointer(clause->column, clause->function);
1100
0
    return ovsdb_datum_hash(&clause->arg, &clause->column->type, hash);
1101
0
}
1102
1103
static int
1104
ovsdb_idl_clause_equals(const struct ovsdb_idl_clause *a,
1105
                        const struct ovsdb_idl_clause *b)
1106
0
{
1107
0
    return (a->function == b->function
1108
0
            && a->column == b->column
1109
0
            && ovsdb_datum_equals(&a->arg, &b->arg, &a->column->type));
1110
0
}
1111
1112
static struct json *
1113
ovsdb_idl_clause_to_json(const struct ovsdb_idl_clause *clause)
1114
0
{
1115
0
    const char *function = ovsdb_function_to_string(clause->function);
1116
0
    return json_array_create_3(json_string_create(clause->column->name),
1117
0
                               json_string_create(function),
1118
0
                               ovsdb_datum_to_json(&clause->arg,
1119
0
                                                   &clause->column->type));
1120
0
}
1121
1122
static void
1123
ovsdb_idl_clause_destroy(struct ovsdb_idl_clause *clause)
1124
0
{
1125
0
    if (clause) {
1126
0
        ovsdb_datum_destroy(&clause->arg, &clause->column->type);
1127
0
        free(clause);
1128
0
    }
1129
0
}
1130

1131
/* ovsdb_idl_condition. */
1132
1133
void
1134
ovsdb_idl_condition_init(struct ovsdb_idl_condition *cnd)
1135
0
{
1136
0
    hmap_init(&cnd->clauses);
1137
0
    cnd->is_true = false;
1138
0
}
1139
1140
void
1141
ovsdb_idl_condition_destroy(struct ovsdb_idl_condition *cond)
1142
0
{
1143
0
    if (cond) {
1144
0
        ovsdb_idl_condition_clear(cond);
1145
0
        hmap_destroy(&cond->clauses);
1146
0
    }
1147
0
}
1148
1149
void
1150
ovsdb_idl_condition_clear(struct ovsdb_idl_condition *cond)
1151
0
{
1152
0
    struct ovsdb_idl_clause *clause;
1153
0
    HMAP_FOR_EACH_SAFE (clause, hmap_node, &cond->clauses) {
1154
0
        hmap_remove(&cond->clauses, &clause->hmap_node);
1155
0
        ovsdb_idl_clause_destroy(clause);
1156
0
    }
1157
0
    cond->is_true = false;
1158
0
}
1159
1160
bool
1161
ovsdb_idl_condition_is_true(const struct ovsdb_idl_condition *condition)
1162
0
{
1163
0
    return condition->is_true;
1164
0
}
1165
1166
static struct ovsdb_idl_clause *
1167
ovsdb_idl_condition_find_clause(const struct ovsdb_idl_condition *condition,
1168
                                const struct ovsdb_idl_clause *target,
1169
                                uint32_t hash)
1170
0
{
1171
0
    struct ovsdb_idl_clause *clause;
1172
0
    HMAP_FOR_EACH_WITH_HASH (clause, hmap_node, hash, &condition->clauses) {
1173
0
        if (ovsdb_idl_clause_equals(clause, target)) {
1174
0
            return clause;
1175
0
        }
1176
0
    }
1177
0
    return NULL;
1178
0
}
1179
1180
static void
1181
ovsdb_idl_condition_add_clause__(struct ovsdb_idl_condition *condition,
1182
                                 const struct ovsdb_idl_clause *src,
1183
                                 uint32_t hash)
1184
0
{
1185
0
    struct ovsdb_idl_clause *clause = xmalloc(sizeof *clause);
1186
0
    clause->function = src->function;
1187
0
    clause->column = src->column;
1188
0
    ovsdb_datum_clone(&clause->arg, &src->arg);
1189
0
    hmap_insert(&condition->clauses, &clause->hmap_node, hash);
1190
0
}
1191
1192
static void
1193
ovsdb_idl_destroy_req_condition(struct ovsdb_idl_table *table)
1194
0
{
1195
0
    ovsdb_idl_condition_destroy(table->req_cond);
1196
0
    free(table->req_cond);
1197
0
    table->req_cond = NULL;
1198
0
}
1199
1200
static void
1201
ovsdb_idl_condition_clone(struct ovsdb_idl_condition *dest,
1202
                          const struct ovsdb_idl_condition *source)
1203
0
{
1204
0
    ovsdb_idl_condition_init(dest);
1205
1206
0
    struct ovsdb_idl_clause *clause;
1207
0
    HMAP_FOR_EACH (clause, hmap_node, &source->clauses) {
1208
0
        ovsdb_idl_condition_add_clause__(dest, clause, clause->hmap_node.hash);
1209
0
    }
1210
0
    dest->is_true = source->is_true;
1211
0
}
1212
1213
static void
1214
ovsdb_idl_create_req_condition(struct ovsdb_idl *idl,
1215
                               const struct ovsdb_idl_table_class *tc,
1216
                               const struct ovsdb_idl_condition *condition)
1217
0
{
1218
0
    struct ovsdb_idl_table *table = shash_find_data(&idl->table_by_name,
1219
0
                                                    tc->name);
1220
0
    if (table) {
1221
0
        ovsdb_idl_destroy_req_condition(table);
1222
0
        table->req_cond = xzalloc(sizeof *table->req_cond);
1223
0
        ovsdb_idl_condition_clone(table->req_cond, condition);
1224
0
    }
1225
0
}
1226
1227
/* Adds a clause to the condition for replicating the table with class 'tc' in
1228
 * 'idl'.
1229
 *
1230
 * The IDL replicates only rows in a table that satisfy at least one clause in
1231
 * the table's condition.  The default condition for a table has a single
1232
 * clause with function OVSDB_F_TRUE, so that the IDL replicates all rows in
1233
 * the table.  When the IDL client replaces the default condition by one of its
1234
 * own, the condition can have any number of clauses.  If it has no conditions,
1235
 * then no rows are replicated.
1236
 *
1237
 * Two distinct of clauses can usefully be added:
1238
 *
1239
 *    - A 'function' of OVSDB_F_TRUE.  A "true" clause causes every row to be
1240
 *      replicated, regardless of whether other clauses exist.  'column' and
1241
 *      'arg' are ignored.
1242
 *
1243
 *    - Binary 'functions' add a clause of the form "<column> <function>
1244
 *      <arg>", e.g. "column == 5" or "column <= 10".  In this case, 'arg' must
1245
 *      have a type that is compatible with 'column'.
1246
 */
1247
void
1248
ovsdb_idl_condition_add_clause(struct ovsdb_idl_condition *condition,
1249
                               enum ovsdb_function function,
1250
                               const struct ovsdb_idl_column *column,
1251
                               const struct ovsdb_datum *arg)
1252
0
{
1253
0
    if (condition->is_true) {
1254
        /* Adding a clause to an always-true condition has no effect.  */
1255
0
    } else if (function == OVSDB_F_TRUE) {
1256
0
        ovsdb_idl_condition_add_clause_true(condition);
1257
0
    } else if (function == OVSDB_F_FALSE) {
1258
        /* Adding a "false" clause never has any effect. */
1259
0
    } else {
1260
0
        struct ovsdb_idl_clause clause = {
1261
0
            .function = function,
1262
0
            .column = column,
1263
0
        };
1264
0
        ovsdb_datum_clone(&clause.arg, arg);
1265
1266
0
        uint32_t hash = ovsdb_idl_clause_hash(&clause);
1267
0
        if (!ovsdb_idl_condition_find_clause(condition, &clause, hash)) {
1268
0
            ovsdb_idl_condition_add_clause__(condition, &clause, hash);
1269
0
        }
1270
0
        ovsdb_datum_destroy(&clause.arg, &column->type);
1271
0
    }
1272
0
}
1273
1274
void
1275
ovsdb_idl_condition_add_clause_true(struct ovsdb_idl_condition *condition)
1276
0
{
1277
0
    if (!condition->is_true) {
1278
0
        ovsdb_idl_condition_clear(condition);
1279
0
        condition->is_true = true;
1280
0
    }
1281
0
}
1282
1283
static struct json *
1284
ovsdb_idl_condition_to_json(const struct ovsdb_idl_condition *cnd)
1285
0
{
1286
0
    if (cnd->is_true) {
1287
0
        return NULL;
1288
0
    }
1289
1290
0
    size_t n = hmap_count(&cnd->clauses);
1291
0
    if (!n) {
1292
0
        return json_array_create_1(json_boolean_create(false));
1293
0
    }
1294
1295
0
    struct json **clauses = xmalloc(n * sizeof *clauses);
1296
0
    const struct ovsdb_idl_clause *clause;
1297
0
    size_t i = 0;
1298
0
    HMAP_FOR_EACH (clause, hmap_node, &cnd->clauses) {
1299
0
        clauses[i++] = ovsdb_idl_clause_to_json(clause);
1300
0
    }
1301
0
    ovs_assert(i == n);
1302
0
    return json_array_create(clauses, n);
1303
0
}
1304
1305
static unsigned int
1306
ovsdb_idl_set_condition__(struct ovsdb_idl *idl,
1307
                          const struct ovsdb_idl_table_class *tc,
1308
                          const struct ovsdb_idl_condition *condition)
1309
0
{
1310
0
    struct ovsdb_idl_condition filter_cond =
1311
0
        OVSDB_IDL_CONDITION_INIT(&filter_cond);
1312
0
    struct json *cond_json;
1313
0
    unsigned int seqno;
1314
1315
0
    if (!idl->server_schema_received) {
1316
        /* Can't filter yet - pass through.  Will be filtered once we know
1317
         * the server schema. */
1318
0
        goto set_condition;
1319
0
    }
1320
1321
0
    struct ovsdb_idl_table *t = ovsdb_idl_table_from_class(idl, tc);
1322
0
    if (!t || !t->in_server_schema) {
1323
        /* Not on the server, should not set. */
1324
0
        seqno = ovsdb_idl_get_condition_seqno(idl);
1325
0
        goto exit;
1326
0
    }
1327
1328
0
    if (hmap_is_empty(&condition->clauses)) {
1329
        /* Trivial condition and the table is present on the server. */
1330
0
        goto set_condition;
1331
0
    }
1332
1333
    /* Non-trivial condition for a table that is in the server schema.
1334
     * Filter out columns that are not. */
1335
0
    struct ovsdb_idl_clause *clause;
1336
0
    HMAP_FOR_EACH (clause, hmap_node, &condition->clauses) {
1337
0
        if (ovsdb_idl_server_has_column(idl, clause->column)) {
1338
0
            ovsdb_idl_condition_add_clause__(&filter_cond, clause,
1339
0
                                             clause->hmap_node.hash);
1340
0
        }
1341
0
    }
1342
0
    condition = &filter_cond;
1343
1344
0
set_condition:
1345
0
    cond_json = ovsdb_idl_condition_to_json(condition);
1346
0
    seqno = ovsdb_cs_set_condition(idl->cs, tc->name, cond_json);
1347
0
    json_destroy(cond_json);
1348
1349
0
exit:
1350
0
    ovsdb_idl_condition_destroy(&filter_cond);
1351
0
    return seqno;
1352
0
}
1353
1354
/* Sets the replication condition for 'tc' in 'idl' to 'condition' and
1355
 * arranges to send the new condition to the database server.
1356
 *
1357
 * Return the next conditional update sequence number.  When this
1358
 * value and ovsdb_idl_get_condition_seqno() matches, the 'idl'
1359
 * contains rows that match the 'condition'. */
1360
unsigned int
1361
ovsdb_idl_set_condition(struct ovsdb_idl *idl,
1362
                        const struct ovsdb_idl_table_class *tc,
1363
                        const struct ovsdb_idl_condition *condition)
1364
0
{
1365
0
    ovsdb_idl_create_req_condition(idl, tc, condition);
1366
0
    return ovsdb_idl_set_condition__(idl, tc, condition);
1367
0
}
1368
1369
/* Turns off OVSDB_IDL_ALERT and OVSDB_IDL_TRACK for 'column' in 'idl'.
1370
 *
1371
 * This function should be called between ovsdb_idl_create() and the first call
1372
 * to ovsdb_idl_run().
1373
 */
1374
void
1375
ovsdb_idl_omit_alert(struct ovsdb_idl *idl,
1376
                     const struct ovsdb_idl_column *column)
1377
0
{
1378
0
    *ovsdb_idl_get_mode(idl, column) &= ~(OVSDB_IDL_ALERT | OVSDB_IDL_TRACK);
1379
0
}
1380
1381
/* Sets the mode for 'column' in 'idl' to 0.  See the big comment above
1382
 * OVSDB_IDL_MONITOR for details.
1383
 *
1384
 * This function should be called between ovsdb_idl_create() and the first call
1385
 * to ovsdb_idl_run().
1386
 */
1387
void
1388
ovsdb_idl_omit(struct ovsdb_idl *idl, const struct ovsdb_idl_column *column)
1389
0
{
1390
0
    *ovsdb_idl_get_mode(idl, column) = 0;
1391
0
}
1392
1393
/* Returns the most recent IDL change sequence number that caused a
1394
 * insert, modify or delete update to the table with class 'table_class'.
1395
 */
1396
unsigned int
1397
ovsdb_idl_table_get_seqno(const struct ovsdb_idl *idl,
1398
                          const struct ovsdb_idl_table_class *table_class)
1399
0
{
1400
0
    struct ovsdb_idl_table *table
1401
0
        = ovsdb_idl_table_from_class(idl, table_class);
1402
0
    unsigned int max_seqno = table->change_seqno[OVSDB_IDL_CHANGE_INSERT];
1403
1404
0
    if (max_seqno < table->change_seqno[OVSDB_IDL_CHANGE_MODIFY]) {
1405
0
        max_seqno = table->change_seqno[OVSDB_IDL_CHANGE_MODIFY];
1406
0
    }
1407
0
    if (max_seqno < table->change_seqno[OVSDB_IDL_CHANGE_DELETE]) {
1408
0
        max_seqno = table->change_seqno[OVSDB_IDL_CHANGE_DELETE];
1409
0
    }
1410
0
    return max_seqno;
1411
0
}
1412
1413
/* For each row that contains tracked columns, IDL stores the most
1414
 * recent IDL change sequence numbers associateed with insert, modify
1415
 * and delete updates to the table.
1416
 */
1417
unsigned int
1418
ovsdb_idl_row_get_seqno(const struct ovsdb_idl_row *row,
1419
                        enum ovsdb_idl_change change)
1420
0
{
1421
0
    return row->change_seqno[change];
1422
0
}
1423
1424
/* Turns on OVSDB_IDL_TRACK for 'column' in 'idl', ensuring that
1425
 * all rows whose 'column' is modified are traced. Similarly, insert
1426
 * or delete of rows having 'column' are tracked. Clients are able
1427
 * to retrieve the tracked rows with the ovsdb_idl_track_get_*()
1428
 * functions.
1429
 *
1430
 * This function should be called between ovsdb_idl_create() and
1431
 * the first call to ovsdb_idl_run(). The column to be tracked
1432
 * should have OVSDB_IDL_ALERT turned on.
1433
 */
1434
void
1435
ovsdb_idl_track_add_column(struct ovsdb_idl *idl,
1436
                           const struct ovsdb_idl_column *column)
1437
0
{
1438
0
    if (!(*ovsdb_idl_get_mode(idl, column) & OVSDB_IDL_ALERT)) {
1439
0
        ovsdb_idl_add_column(idl, column);
1440
0
    }
1441
0
    *ovsdb_idl_get_mode(idl, column) |= OVSDB_IDL_TRACK;
1442
0
}
1443
1444
void
1445
ovsdb_idl_track_add_all(struct ovsdb_idl *idl)
1446
0
{
1447
0
    size_t i, j;
1448
1449
0
    for (i = 0; i < idl->class_->n_tables; i++) {
1450
0
        const struct ovsdb_idl_table_class *tc = &idl->class_->tables[i];
1451
1452
0
        for (j = 0; j < tc->n_columns; j++) {
1453
0
            const struct ovsdb_idl_column *column = &tc->columns[j];
1454
0
            ovsdb_idl_track_add_column(idl, column);
1455
0
        }
1456
0
    }
1457
0
}
1458
1459
/* Returns true if 'table' has any tracked column. */
1460
bool
1461
ovsdb_idl_track_is_set(struct ovsdb_idl_table *table)
1462
0
{
1463
0
    size_t i;
1464
1465
0
    for (i = 0; i < table->class_->n_columns; i++) {
1466
0
        if (table->modes[i] & OVSDB_IDL_TRACK) {
1467
0
            return true;
1468
0
        }
1469
0
    }
1470
0
   return false;
1471
0
}
1472
1473
/* Returns the first tracked row in table with class 'table_class'
1474
 * for the specified 'idl'. Returns NULL if there are no tracked rows.
1475
 * Pure orphan rows, i.e. rows that never had any datum, are skipped. */
1476
const struct ovsdb_idl_row *
1477
ovsdb_idl_track_get_first(const struct ovsdb_idl *idl,
1478
                          const struct ovsdb_idl_table_class *table_class)
1479
0
{
1480
0
    struct ovsdb_idl_table *table
1481
0
        = ovsdb_idl_table_from_class(idl, table_class);
1482
0
    struct ovsdb_idl_row *row;
1483
1484
0
    LIST_FOR_EACH (row, track_node, &table->track_list) {
1485
0
        if (!ovsdb_idl_row_is_orphan(row) || row->tracked_old_datum) {
1486
0
            return row;
1487
0
        }
1488
0
    }
1489
0
    return NULL;
1490
0
}
1491
1492
/* Returns the next tracked row in table after the specified 'row'
1493
 * (in no particular order). Returns NULL if there are no tracked rows.
1494
 * Pure orphan rows, i.e. rows that never had any datum, are skipped. */
1495
const struct ovsdb_idl_row *
1496
ovsdb_idl_track_get_next(const struct ovsdb_idl_row *row)
1497
0
{
1498
0
    struct ovsdb_idl_table *table = row->table;
1499
1500
0
    LIST_FOR_EACH_CONTINUE (row, track_node, &table->track_list) {
1501
0
        if (!ovsdb_idl_row_is_orphan(row) || row->tracked_old_datum) {
1502
0
            return row;
1503
0
        }
1504
0
    }
1505
0
    return NULL;
1506
0
}
1507
1508
/* Returns true if a tracked 'column' in 'row' was updated by IDL, false
1509
 * otherwise. The tracking data is cleared by ovsdb_idl_track_clear()
1510
 *
1511
 * Function returns false if 'column' is not tracked (see
1512
 * ovsdb_idl_track_add_column()).
1513
 */
1514
bool
1515
ovsdb_idl_track_is_updated(const struct ovsdb_idl_row *row,
1516
                           const struct ovsdb_idl_column *column)
1517
0
{
1518
0
    const struct ovsdb_idl_table_class *class;
1519
0
    size_t column_idx;
1520
1521
0
    class = row->table->class_;
1522
0
    column_idx = column - class->columns;
1523
1524
0
    if (row->updated && bitmap_is_set(row->updated, column_idx)) {
1525
0
        return true;
1526
0
    } else {
1527
0
        return false;
1528
0
    }
1529
0
}
1530
1531
static void
1532
ovsdb_idl_track_clear__(struct ovsdb_idl *idl, bool flush_all)
1533
0
{
1534
0
    size_t i;
1535
1536
0
    for (i = 0; i < idl->class_->n_tables; i++) {
1537
0
        struct ovsdb_idl_table *table = &idl->tables[i];
1538
1539
0
        if (!ovs_list_is_empty(&table->track_list)) {
1540
0
            struct ovsdb_idl_row *row;
1541
1542
0
            LIST_FOR_EACH_SAFE (row, track_node, &table->track_list) {
1543
0
                if (row->updated) {
1544
0
                    free(row->updated);
1545
0
                    row->updated = NULL;
1546
0
                }
1547
0
                ovsdb_idl_row_untrack_change(row);
1548
0
                ovsdb_idl_row_clear_changeseqno(row);
1549
1550
0
                if (ovsdb_idl_row_is_orphan(row)) {
1551
0
                    ovsdb_idl_row_unparse(row);
1552
0
                    if (row->tracked_old_datum) {
1553
0
                        const struct ovsdb_idl_table_class *class =
1554
0
                            row->table->class_;
1555
0
                        for (size_t c = 0; c < class->n_columns; c++) {
1556
0
                            ovsdb_datum_destroy(&row->tracked_old_datum[c],
1557
0
                                                &class->columns[c].type);
1558
0
                        }
1559
0
                        free(row->tracked_old_datum);
1560
0
                        row->tracked_old_datum = NULL;
1561
0
                    }
1562
1563
                    /* Rows that were reused as orphan after being processed
1564
                     * for deletion are still in the table hmap and will be
1565
                     * cleaned up when their src arcs are removed.  These rows
1566
                     * will not be reported anymore as "deleted" to IDL
1567
                     * clients.
1568
                     *
1569
                     * The exception is when 'destroy' is explicitly set to
1570
                     * 'true' which usually happens when the complete IDL
1571
                     * contents are being flushed.
1572
                     */
1573
0
                    if (flush_all || ovs_list_is_empty(&row->dst_arcs)) {
1574
0
                        free(row);
1575
0
                    }
1576
0
                }
1577
0
            }
1578
0
        }
1579
0
    }
1580
0
}
1581
1582
/* Flushes the tracked rows. Client calls this function after calling
1583
 * ovsdb_idl_run() and read all tracked rows with the ovsdb_idl_track_get_*()
1584
 * functions. This is usually done at the end of the client's processing
1585
 * loop when it is ready to do ovsdb_idl_run() again.
1586
 */
1587
void
1588
ovsdb_idl_track_clear(struct ovsdb_idl *idl)
1589
0
{
1590
0
    ovsdb_idl_track_clear__(idl, false);
1591
0
}
1592
1593
/* Sets or clears (depending on 'enable') OVSDB_IDL_WRITE_CHANGED_ONLY
1594
 * for 'column' in 'idl', ensuring that the column will be included in a
1595
 * transaction only if its value has actually changed locally.  Normally
1596
 * read/write columns that are written to are always included in the
1597
 * transaction but, in specific cases, when the application doesn't
1598
 * require atomicity of writes across different columns, the ones that
1599
 * don't change value may be skipped.
1600
 *
1601
 * This function should be called between ovsdb_idl_create() and
1602
 * the first call to ovsdb_idl_run().
1603
 */
1604
void
1605
ovsdb_idl_set_write_changed_only(struct ovsdb_idl *idl,
1606
                                 const struct ovsdb_idl_column *column,
1607
                                 bool enable)
1608
0
{
1609
0
    if (enable) {
1610
0
        *ovsdb_idl_get_mode(idl, column) |= OVSDB_IDL_WRITE_CHANGED_ONLY;
1611
0
    } else {
1612
0
        *ovsdb_idl_get_mode(idl, column) &= ~OVSDB_IDL_WRITE_CHANGED_ONLY;
1613
0
    }
1614
0
}
1615
1616
/* Helper function to wrap calling ovsdb_idl_set_write_changed_only() for
1617
 * all columns that are part of 'idl'.
1618
 */
1619
void
1620
ovsdb_idl_set_write_changed_only_all(struct ovsdb_idl *idl, bool enable)
1621
0
{
1622
0
    for (size_t i = 0; i < idl->class_->n_tables; i++) {
1623
0
        const struct ovsdb_idl_table_class *tc = &idl->class_->tables[i];
1624
1625
0
        for (size_t j = 0; j < tc->n_columns; j++) {
1626
0
            const struct ovsdb_idl_column *column = &tc->columns[j];
1627
0
            ovsdb_idl_set_write_changed_only(idl, column, enable);
1628
0
        }
1629
0
    }
1630
0
}
1631

1632
static void
1633
log_parse_update_error(struct ovsdb_error *error)
1634
0
{
1635
0
    if (!VLOG_DROP_WARN(&syntax_rl)) {
1636
0
        char *s = ovsdb_error_to_string(error);
1637
0
        VLOG_WARN_RL(&syntax_rl, "%s", s);
1638
0
        free(s);
1639
0
    }
1640
0
    ovsdb_error_destroy(error);
1641
0
}
1642
1643
static struct ovsdb_error *
1644
ovsdb_idl_parse_update__(struct ovsdb_idl *idl,
1645
                         const struct ovsdb_cs_db_update *du)
1646
0
{
1647
0
    for (size_t i = 0; i < du->n; i++) {
1648
0
        const struct ovsdb_cs_table_update *tu = &du->table_updates[i];
1649
1650
0
        struct ovsdb_idl_table *table = shash_find_data(&idl->table_by_name,
1651
0
                                                        tu->table_name);
1652
0
        if (!table) {
1653
0
            return ovsdb_syntax_error(
1654
0
                NULL, NULL, "update to unknown table \"%s\"", tu->table_name);
1655
0
        }
1656
1657
0
        for (size_t j = 0; j < tu->n; j++) {
1658
0
            const struct ovsdb_cs_row_update *ru = &tu->row_updates[j];
1659
0
            switch (ovsdb_idl_process_update(table, ru)) {
1660
0
            case OVSDB_IDL_UPDATE_DB_CHANGED:
1661
0
                idl->change_seqno++;
1662
0
                break;
1663
0
            case OVSDB_IDL_UPDATE_NO_CHANGES:
1664
0
                break;
1665
0
            case OVSDB_IDL_UPDATE_INCONSISTENT:
1666
0
                ovsdb_cs_flag_inconsistency(idl->cs);
1667
0
                return ovsdb_error(NULL,
1668
0
                                   "row update received for inconsistent "
1669
0
                                   "IDL: reconnecting IDL and resync all "
1670
0
                                   "data");
1671
0
            }
1672
0
        }
1673
0
    }
1674
1675
0
    return NULL;
1676
0
}
1677
1678
static void
1679
ovsdb_idl_parse_update(struct ovsdb_idl *idl,
1680
                       const struct ovsdb_cs_update_event *update)
1681
0
{
1682
0
    if (update->monitor_reply) {
1683
        /* XXX This isn't semantically required, because we only need to
1684
         * increment change_seqno if there's a real change, which we'll do
1685
         * below, but older versions of the IDL always incremented change_seqno
1686
         * when a monitor reply was received and if we don't do it then tests
1687
         * will fail. */
1688
0
        idl->change_seqno++;
1689
0
    }
1690
1691
0
    struct ovsdb_cs_db_update *du;
1692
0
    struct ovsdb_error *error = ovsdb_cs_parse_db_update(
1693
0
        update->table_updates, update->version, &du);
1694
0
    if (!error) {
1695
0
        if (update->clear) {
1696
0
            ovsdb_idl_clear(idl);
1697
0
        }
1698
0
        error = ovsdb_idl_parse_update__(idl, du);
1699
0
    }
1700
0
    ovsdb_cs_db_update_destroy(du);
1701
0
    if (error) {
1702
0
        log_parse_update_error(error);
1703
0
    }
1704
0
}
1705
1706
/* Reparses references to rows that have been deleted in the current IDL run.
1707
 *
1708
 * To ensure that reference sources that are deleted are not reparsed,
1709
 * this function must be called after all updates have been processed in
1710
 * the current IDL run, i.e., after all calls to ovsdb_idl_parse_update().
1711
 */
1712
static void
1713
ovsdb_idl_reparse_deleted(struct ovsdb_idl *db)
1714
0
{
1715
0
    struct ovsdb_idl_row *row;
1716
1717
0
    LIST_FOR_EACH_SAFE (row, track_node, &db->deleted_untracked_rows) {
1718
0
        ovsdb_idl_row_untrack_change(row);
1719
0
        add_tracked_change_for_references(row);
1720
0
        ovsdb_idl_row_reparse_backrefs(row);
1721
1722
        /* Orphan rows that are still unreferenced or are part of tables that
1723
         * have change tracking enabled should be added to their table's
1724
         * 'track_list'.
1725
         */
1726
0
        if (ovs_list_is_empty(&row->dst_arcs)
1727
0
                || ovsdb_idl_track_is_set(row->table)) {
1728
0
            ovsdb_idl_row_track_change(row, OVSDB_IDL_CHANGE_DELETE);
1729
0
        }
1730
0
    }
1731
0
}
1732
1733
/* Reparses rows that refer to rows that were inserted in the
1734
 * current IDL run. */
1735
static void
1736
ovsdb_idl_reparse_refs_to_inserted(struct ovsdb_idl *db)
1737
0
{
1738
0
    struct ovsdb_idl_row *row;
1739
1740
0
    LIST_FOR_EACH_POP (row, reparse_node, &db->rows_to_reparse) {
1741
0
        ovs_list_init(&row->reparse_node);
1742
1743
        /* Skip rows that have been deleted in the meantime. */
1744
0
        if (ovsdb_idl_row_is_orphan(row)) {
1745
0
            continue;
1746
0
        }
1747
0
        ovsdb_idl_row_unparse(row);
1748
0
        ovsdb_idl_row_clear_arcs(row, false);
1749
0
        ovsdb_idl_row_parse(row);
1750
0
    }
1751
0
}
1752
1753
static struct ovsdb_idl_row *
1754
ovsdb_idl_get_row(struct ovsdb_idl_table *table, const struct uuid *uuid)
1755
0
{
1756
0
    struct ovsdb_idl_row *row;
1757
1758
0
    HMAP_FOR_EACH_WITH_HASH (row, hmap_node, uuid_hash(uuid), &table->rows) {
1759
0
        if (uuid_equals(&row->uuid, uuid)) {
1760
0
            return row;
1761
0
        }
1762
0
    }
1763
0
    return NULL;
1764
0
}
1765
1766
/* Returns OVSDB_IDL_UPDATE_DB_CHANGED if a column with mode
1767
 * OVSDB_IDL_MODE_RW changed.
1768
 *
1769
 * Some IDL inconsistencies can be detected when processing updates:
1770
 * - trying to insert an already existing row
1771
 * - trying to update a missing row
1772
 * - trying to delete a non existent row
1773
 *
1774
 * In such cases OVSDB_IDL_UPDATE_INCONSISTENT is returned.
1775
 * Even though the IDL client could recover, it's best to report the
1776
 * inconsistent state because the state the server is in is unknown so the
1777
 * safest thing to do is to retry (potentially connecting to a new server).
1778
 *
1779
 * Returns OVSDB_IDL_UPDATE_NO_CHANGES otherwise.
1780
 */
1781
static enum update_result
1782
ovsdb_idl_process_update(struct ovsdb_idl_table *table,
1783
                         const struct ovsdb_cs_row_update *ru)
1784
0
{
1785
0
    const struct uuid *uuid = &ru->row_uuid;
1786
0
    struct ovsdb_idl_row *row = ovsdb_idl_get_row(table, uuid);
1787
1788
0
    switch (ru->type) {
1789
0
    case OVSDB_CS_ROW_DELETE:
1790
0
        if (row && !ovsdb_idl_row_is_orphan(row)) {
1791
            /* XXX perhaps we should check the 'old' values? */
1792
0
            ovsdb_idl_delete_row(row);
1793
0
        } else {
1794
0
            VLOG_ERR_RL(&semantic_rl, "cannot delete missing row "UUID_FMT" "
1795
0
                        "from table %s",
1796
0
                        UUID_ARGS(uuid), table->class_->name);
1797
0
            return OVSDB_IDL_UPDATE_INCONSISTENT;
1798
0
        }
1799
0
        break;
1800
1801
0
    case OVSDB_CS_ROW_INSERT:
1802
0
        if (!row) {
1803
0
            ovsdb_idl_insert_row(ovsdb_idl_row_create(table, uuid),
1804
0
                                 ru->columns);
1805
0
        } else if (ovsdb_idl_row_is_orphan(row)) {
1806
0
            ovsdb_idl_row_untrack_change(row);
1807
0
            ovsdb_idl_row_clear_changeseqno(row);
1808
0
            ovsdb_idl_insert_row(row, ru->columns);
1809
0
        } else {
1810
0
            VLOG_ERR_RL(&semantic_rl, "cannot add existing row "UUID_FMT" to "
1811
0
                        "table %s", UUID_ARGS(uuid), table->class_->name);
1812
0
            return OVSDB_IDL_UPDATE_INCONSISTENT;
1813
0
        }
1814
0
        break;
1815
1816
0
    case OVSDB_CS_ROW_UPDATE:
1817
0
    case OVSDB_CS_ROW_XOR:
1818
0
        if (row) {
1819
0
            if (!ovsdb_idl_row_is_orphan(row)) {
1820
0
                return ovsdb_idl_modify_row(row, ru->columns,
1821
0
                                            ru->type == OVSDB_CS_ROW_XOR)
1822
0
                       ? OVSDB_IDL_UPDATE_DB_CHANGED
1823
0
                       : OVSDB_IDL_UPDATE_NO_CHANGES;
1824
0
            } else {
1825
0
                VLOG_ERR_RL(&semantic_rl, "cannot modify missing but "
1826
0
                            "referenced row "UUID_FMT" in table %s",
1827
0
                            UUID_ARGS(uuid), table->class_->name);
1828
0
                return OVSDB_IDL_UPDATE_INCONSISTENT;
1829
0
            }
1830
0
        } else {
1831
0
            VLOG_ERR_RL(&semantic_rl, "cannot modify missing row "UUID_FMT" "
1832
0
                        "in table %s", UUID_ARGS(uuid), table->class_->name);
1833
0
            return OVSDB_IDL_UPDATE_INCONSISTENT;
1834
0
        }
1835
0
        break;
1836
1837
0
    default:
1838
0
        OVS_NOT_REACHED();
1839
0
    }
1840
1841
0
    return OVSDB_IDL_UPDATE_DB_CHANGED;
1842
0
}
1843
1844
/* Recursively add rows to tracked change lists for all rows that reference
1845
   'row'. */
1846
static void
1847
add_tracked_change_for_references(struct ovsdb_idl_row *row)
1848
0
{
1849
0
    const struct ovsdb_idl_arc *arc;
1850
0
    LIST_FOR_EACH (arc, dst_node, &row->dst_arcs) {
1851
0
        struct ovsdb_idl_row *ref = arc->src;
1852
1853
0
        if (ovs_list_is_empty(&ref->track_node) &&
1854
0
            ovsdb_idl_track_is_set(ref->table)) {
1855
1856
0
            ovsdb_idl_row_track_change(ref, OVSDB_IDL_CHANGE_MODIFY);
1857
0
            add_tracked_change_for_references(ref);
1858
0
        }
1859
0
    }
1860
0
}
1861
1862
1863
/* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
1864
 * otherwise.
1865
 *
1866
 * Change 'row' either with the content of 'row_json' or by apply 'diff'.
1867
 * Caller needs to provide either valid 'row_json' or 'diff', but not
1868
 * both.  */
1869
static bool
1870
ovsdb_idl_row_change(struct ovsdb_idl_row *row, const struct shash *values,
1871
                     bool xor, enum ovsdb_idl_change change)
1872
0
{
1873
0
    struct ovsdb_idl_table *table = row->table;
1874
0
    const struct ovsdb_idl_table_class *class = table->class_;
1875
0
    struct shash_node *node;
1876
0
    bool changed = false;
1877
1878
0
    SHASH_FOR_EACH (node, values) {
1879
0
        const char *column_name = node->name;
1880
0
        const struct ovsdb_idl_column *column;
1881
0
        struct ovsdb_error *error;
1882
0
        unsigned int column_idx;
1883
0
        struct ovsdb_datum *old;
1884
0
        bool datum_changed = false;
1885
1886
0
        column = shash_find_data(&table->columns, column_name);
1887
0
        if (!column) {
1888
0
            VLOG_WARN_RL(&syntax_rl, "unknown column %s updating row "UUID_FMT,
1889
0
                         column_name, UUID_ARGS(&row->uuid));
1890
0
            continue;
1891
0
        }
1892
1893
0
        column_idx = column - table->class_->columns;
1894
0
        old = &row->old_datum[column_idx];
1895
1896
0
        if (xor) {
1897
0
            struct ovsdb_datum diff;
1898
1899
0
            error = ovsdb_transient_datum_from_json(&diff, &column->type,
1900
0
                                                    node->data);
1901
0
            if (!error) {
1902
0
                error = ovsdb_datum_apply_diff_in_place(old, &diff,
1903
0
                                                        &column->type);
1904
0
                ovsdb_datum_destroy(&diff, &column->type);
1905
0
                datum_changed = true;
1906
0
            }
1907
0
        } else {
1908
0
            struct ovsdb_datum datum;
1909
1910
0
            error = ovsdb_datum_from_json(&datum, &column->type, node->data,
1911
0
                                          NULL);
1912
0
            if (!error) {
1913
0
                if (!ovsdb_datum_equals(old, &datum, &column->type)) {
1914
0
                    ovsdb_datum_swap(old, &datum);
1915
0
                    datum_changed = true;
1916
0
                }
1917
0
                ovsdb_datum_destroy(&datum, &column->type);
1918
0
            }
1919
0
        }
1920
1921
0
        if (error) {
1922
0
            char *s = ovsdb_error_to_string_free(error);
1923
0
            VLOG_WARN_RL(&syntax_rl, "error parsing column %s in row "UUID_FMT
1924
0
                         " in table %s: %s", column_name,
1925
0
                         UUID_ARGS(&row->uuid), table->class_->name, s);
1926
0
            free(s);
1927
0
            continue;
1928
0
        }
1929
1930
0
        if (datum_changed && table->modes[column_idx] & OVSDB_IDL_ALERT) {
1931
0
            changed = true;
1932
0
            row->change_seqno[change]
1933
0
                = row->table->change_seqno[change]
1934
0
                = row->table->idl->change_seqno + 1;
1935
1936
0
            if (table->modes[column_idx] & OVSDB_IDL_TRACK) {
1937
0
                if (ovs_list_is_empty(&row->track_node) &&
1938
0
                    ovsdb_idl_track_is_set(row->table)) {
1939
0
                    ovs_list_push_back(&row->table->track_list,
1940
0
                                       &row->track_node);
1941
0
                }
1942
1943
0
                add_tracked_change_for_references(row);
1944
0
                if (!row->updated) {
1945
0
                    row->updated = bitmap_allocate(class->n_columns);
1946
0
                }
1947
0
                bitmap_set1(row->updated, column_idx);
1948
0
            }
1949
0
        }
1950
0
    }
1951
0
    return changed;
1952
0
}
1953
1954
/* When a row A refers to row B through a column with a "refTable" constraint,
1955
 * but row B does not exist, row B is called an "orphan row".  Orphan rows
1956
 * should not persist, because the database enforces referential integrity, but
1957
 * they can appear transiently as changes from the database are received (the
1958
 * database doesn't try to topologically sort them and circular references mean
1959
 * it isn't always possible anyhow).
1960
 *
1961
 * This function returns true if 'row' is an orphan row, otherwise false.
1962
 */
1963
static bool
1964
ovsdb_idl_row_is_orphan(const struct ovsdb_idl_row *row)
1965
0
{
1966
0
    return !row->old_datum && !row->new_datum;
1967
0
}
1968
1969
/* Returns true if 'row' is conceptually part of the database as modified by
1970
 * the current transaction (if any), false otherwise.
1971
 *
1972
 * This function will return true if 'row' is not an orphan (see the comment on
1973
 * ovsdb_idl_row_is_orphan()) and:
1974
 *
1975
 *   - 'row' exists in the database and has not been deleted within the
1976
 *     current transaction (if any).
1977
 *
1978
 *   - 'row' was inserted within the current transaction and has not been
1979
 *     deleted.  (In the latter case you should not have passed 'row' in at
1980
 *     all, because ovsdb_idl_txn_delete() freed it.)
1981
 *
1982
 * This function will return false if 'row' is an orphan or if 'row' was
1983
 * deleted within the current transaction.
1984
 */
1985
static bool
1986
ovsdb_idl_row_exists(const struct ovsdb_idl_row *row)
1987
0
{
1988
0
    return row->new_datum != NULL;
1989
0
}
1990
1991
static void
1992
ovsdb_idl_row_parse(struct ovsdb_idl_row *row)
1993
0
{
1994
0
    const struct ovsdb_idl_table_class *class = row->table->class_;
1995
0
    size_t i;
1996
1997
0
    if (row->parsed) {
1998
0
        ovsdb_idl_row_unparse(row);
1999
0
    }
2000
0
    for (i = 0; i < class->n_columns; i++) {
2001
0
        const struct ovsdb_idl_column *c = &class->columns[i];
2002
0
        (c->parse)(row, &row->old_datum[i]);
2003
0
    }
2004
0
    row->parsed = true;
2005
0
}
2006
2007
static void
2008
ovsdb_idl_row_unparse(struct ovsdb_idl_row *row)
2009
0
{
2010
0
    const struct ovsdb_idl_table_class *class = row->table->class_;
2011
0
    size_t i;
2012
2013
0
    if (!row->parsed) {
2014
0
        return;
2015
0
    }
2016
0
    for (i = 0; i < class->n_columns; i++) {
2017
0
        const struct ovsdb_idl_column *c = &class->columns[i];
2018
0
        (c->unparse)(row);
2019
0
    }
2020
0
    row->parsed = false;
2021
0
}
2022

2023
/* The OVSDB-IDL Compound Indexes feature allows for the creation of custom
2024
 * table indexes over one or more columns in the IDL. These indexes provide
2025
 * the ability to retrieve rows matching a particular search criteria and to
2026
 * iterate over a subset of rows in a defined order.
2027
 */
2028
2029
/* Generic comparator that can compare each index, using the custom
2030
 * configuration (an struct ovsdb_idl_index) passed to it.
2031
 * Not intended for direct usage.
2032
 */
2033
static int
2034
ovsdb_idl_index_generic_comparer(const void *a,
2035
                                 const void *b, const void *conf)
2036
0
{
2037
0
    const struct ovsdb_idl_column *column;
2038
0
    const struct ovsdb_idl_index *index;
2039
0
    size_t i;
2040
2041
0
    index = CONST_CAST(struct ovsdb_idl_index *, conf);
2042
2043
0
    if (a == b) {
2044
0
        return 0;
2045
0
    }
2046
2047
0
    for (i = 0; i < index->n_columns; i++) {
2048
0
        int val;
2049
0
        if (index->columns[i].comparer) {
2050
0
            val = index->columns[i].comparer(a, b);
2051
0
        } else {
2052
0
            column = index->columns[i].column;
2053
0
            const struct ovsdb_idl_row *row_a, *row_b;
2054
0
            row_a = CONST_CAST(struct ovsdb_idl_row *, a);
2055
0
            row_b = CONST_CAST(struct ovsdb_idl_row *, b);
2056
0
            const struct ovsdb_datum *datum_a, *datum_b;
2057
0
            datum_a = ovsdb_idl_read(row_a, column);
2058
0
            datum_b = ovsdb_idl_read(row_b, column);
2059
0
            val = ovsdb_datum_compare_3way(datum_a, datum_b, &column->type);
2060
0
        }
2061
2062
0
        if (val) {
2063
0
            return index->columns[i].order == OVSDB_INDEX_ASC ? val : -val;
2064
0
        }
2065
0
    }
2066
2067
    /* If ins_del is true then a row is being inserted into or deleted from
2068
     * the index list. In this case, we augment the search key with
2069
     * additional values (row UUID and memory address) to create a unique
2070
     * search key in order to locate the correct entry efficiently and to
2071
     * ensure that the correct entry is deleted in the case of a "delete"
2072
     * operation.
2073
     */
2074
0
    if (index->ins_del) {
2075
0
        const struct ovsdb_idl_row *row_a, *row_b;
2076
2077
0
        row_a = (const struct ovsdb_idl_row *) a;
2078
0
        row_b = (const struct ovsdb_idl_row *) b;
2079
0
        int value = uuid_compare_3way(&row_a->uuid, &row_b->uuid);
2080
2081
0
        return value ? value : (a < b) - (a > b);
2082
0
    } else {
2083
0
        return 0;
2084
0
    }
2085
0
}
2086
2087
/* Creates a new index for the given 'idl' and with the 'n' specified
2088
 * 'columns'.
2089
 *
2090
 * All indexes must be created before the first call to ovsdb_idl_run(). */
2091
struct ovsdb_idl_index *
2092
ovsdb_idl_index_create(struct ovsdb_idl *idl,
2093
                       const struct ovsdb_idl_index_column *columns,
2094
                       size_t n)
2095
0
{
2096
0
    ovs_assert(n > 0);
2097
2098
0
    struct ovsdb_idl_index *index = xzalloc(sizeof *index);
2099
2100
0
    index->table = ovsdb_idl_table_from_column(idl, columns[0].column);
2101
0
    for (size_t i = 0; i < n; i++) {
2102
0
        const struct ovsdb_idl_index_column *c = &columns[i];
2103
0
        ovs_assert(ovsdb_idl_table_from_column(idl,
2104
0
                                               c->column) == index->table);
2105
0
        ovs_assert(*ovsdb_idl_get_mode(idl, c->column) & OVSDB_IDL_MONITOR);
2106
0
    }
2107
2108
0
    index->columns = xmemdup(columns, n * sizeof *columns);
2109
0
    index->n_columns = n;
2110
0
    index->skiplist = skiplist_create(ovsdb_idl_index_generic_comparer, index);
2111
2112
0
    ovs_list_push_back(&index->table->indexes, &index->node);
2113
2114
0
    return index;
2115
0
}
2116
2117
struct ovsdb_idl_index *
2118
ovsdb_idl_index_create1(struct ovsdb_idl *idl,
2119
                        const struct ovsdb_idl_column *column1)
2120
0
{
2121
0
    const struct ovsdb_idl_index_column columns[] = {
2122
0
        { .column = column1 },
2123
0
    };
2124
0
    return ovsdb_idl_index_create(idl, columns, ARRAY_SIZE(columns));
2125
0
}
2126
2127
struct ovsdb_idl_index *
2128
ovsdb_idl_index_create2(struct ovsdb_idl *idl,
2129
                        const struct ovsdb_idl_column *column1,
2130
                        const struct ovsdb_idl_column *column2)
2131
0
{
2132
0
    const struct ovsdb_idl_index_column columns[] = {
2133
0
        { .column = column1 },
2134
0
        { .column = column2 },
2135
0
    };
2136
0
    return ovsdb_idl_index_create(idl, columns, ARRAY_SIZE(columns));
2137
0
}
2138
2139
static void
2140
ovsdb_idl_destroy_indexes(struct ovsdb_idl_table *table)
2141
0
{
2142
0
    struct ovsdb_idl_index *index;
2143
0
    LIST_FOR_EACH_SAFE (index, node, &table->indexes) {
2144
0
        skiplist_destroy(index->skiplist, NULL);
2145
0
        free(index->columns);
2146
0
        free(index);
2147
0
    }
2148
0
}
2149
2150
static void
2151
ovsdb_idl_add_to_indexes(const struct ovsdb_idl_row *row)
2152
0
{
2153
0
    struct ovsdb_idl_table *table = row->table;
2154
0
    struct ovsdb_idl_index *index;
2155
0
    LIST_FOR_EACH (index, node, &table->indexes) {
2156
0
        index->ins_del = true;
2157
0
        skiplist_insert(index->skiplist, row);
2158
0
        index->ins_del = false;
2159
0
    }
2160
0
}
2161
2162
static void
2163
ovsdb_idl_remove_from_indexes(const struct ovsdb_idl_row *row)
2164
0
{
2165
0
    struct ovsdb_idl_table *table = row->table;
2166
0
    struct ovsdb_idl_index *index;
2167
0
    LIST_FOR_EACH (index, node, &table->indexes) {
2168
0
        index->ins_del = true;
2169
0
        skiplist_delete(index->skiplist, row);
2170
0
        index->ins_del = false;
2171
0
    }
2172
0
}
2173
2174
/* Writes a datum in an ovsdb_idl_row, and updates the corresponding field in
2175
 * the table record.  Not intended for direct usage. */
2176
void
2177
ovsdb_idl_index_write(struct ovsdb_idl_row *const_row,
2178
                       const struct ovsdb_idl_column *column,
2179
                       struct ovsdb_datum *datum,
2180
                       const struct ovsdb_idl_table_class *class)
2181
0
{
2182
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, const_row);
2183
0
    size_t column_idx = column - class->columns;
2184
2185
0
    if (bitmap_is_set(row->written, column_idx)) {
2186
0
        free(row->new_datum[column_idx].values);
2187
0
        free(row->new_datum[column_idx].keys);
2188
0
    } else {
2189
0
        bitmap_set1(row->written, column_idx);
2190
0
     }
2191
0
    row->new_datum[column_idx] = *datum;
2192
0
    (column->unparse)(row);
2193
0
    (column->parse)(row, &row->new_datum[column_idx]);
2194
0
}
2195
2196
/* Magic UUID for index rows */
2197
static const struct uuid index_row_uuid = {
2198
        .parts = {0xdeadbeef,
2199
                  0xdeadbeef,
2200
                  0xdeadbeef,
2201
                  0xdeadbeef}};
2202
2203
/* Check if a row is an index row */
2204
static bool
2205
is_index_row(const struct ovsdb_idl_row *row)
2206
0
{
2207
0
    return uuid_equals(&row->uuid, &index_row_uuid);
2208
0
}
2209
2210
/* Initializes a row for use in an indexed query.
2211
 * Not intended for direct usage.
2212
 */
2213
struct ovsdb_idl_row *
2214
ovsdb_idl_index_init_row(struct ovsdb_idl_index *index)
2215
0
{
2216
0
    const struct ovsdb_idl_table_class *class = index->table->class_;
2217
0
    struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
2218
0
    class->row_init(row);
2219
0
    row->uuid = index_row_uuid;
2220
0
    row->new_datum = xmalloc(class->n_columns * sizeof *row->new_datum);
2221
0
    row->written = bitmap_allocate(class->n_columns);
2222
0
    row->table = index->table;
2223
    /* arcs are not used for index row, but it doesn't harm to initialize */
2224
0
    ovs_list_init(&row->src_arcs);
2225
0
    ovs_list_init(&row->dst_arcs);
2226
0
    return row;
2227
0
}
2228
2229
/* Destroys 'row_' and frees all associated memory. This function is intended
2230
 * to be used indirectly through one of the "index_destroy_row" functions
2231
 * generated by ovsdb-idlc.
2232
 */
2233
void
2234
ovsdb_idl_index_destroy_row(const struct ovsdb_idl_row *row_)
2235
0
{
2236
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
2237
0
    const struct ovsdb_idl_table_class *class = row->table->class_;
2238
0
    const struct ovsdb_idl_column *c;
2239
0
    size_t i;
2240
2241
0
    ovs_assert(is_index_row(row_));
2242
0
    ovs_assert(ovs_list_is_empty(&row_->src_arcs));
2243
0
    ovs_assert(ovs_list_is_empty(&row_->dst_arcs));
2244
0
    BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
2245
0
        c = &class->columns[i];
2246
0
        (c->unparse) (row);
2247
0
        ovsdb_datum_destroy(&row->new_datum[i], &c->type);
2248
0
    }
2249
0
    free(row->new_datum);
2250
0
    free(row->written);
2251
0
    free(row);
2252
0
}
2253
2254
struct ovsdb_idl_row *
2255
ovsdb_idl_index_find(struct ovsdb_idl_index *index,
2256
                     const struct ovsdb_idl_row *target)
2257
0
{
2258
0
    return skiplist_get_data(skiplist_find(index->skiplist, target));
2259
0
}
2260
2261
struct ovsdb_idl_cursor
2262
ovsdb_idl_cursor_first(struct ovsdb_idl_index *index)
2263
0
{
2264
0
    struct skiplist_node *node = skiplist_first(index->skiplist);
2265
0
    return (struct ovsdb_idl_cursor) { index, node };
2266
0
}
2267
2268
struct ovsdb_idl_cursor
2269
ovsdb_idl_cursor_first_eq(struct ovsdb_idl_index *index,
2270
                          const struct ovsdb_idl_row *target)
2271
0
{
2272
0
    struct skiplist_node *node = skiplist_find(index->skiplist, target);
2273
0
    return (struct ovsdb_idl_cursor) { index, node };
2274
0
}
2275
2276
struct ovsdb_idl_cursor
2277
ovsdb_idl_cursor_first_ge(struct ovsdb_idl_index *index,
2278
                          const struct ovsdb_idl_row *target)
2279
0
{
2280
0
    struct skiplist_node *node = (target
2281
0
                                  ? skiplist_forward_to(index->skiplist,
2282
0
                                                        target)
2283
0
                                  : skiplist_first(index->skiplist));
2284
0
    return (struct ovsdb_idl_cursor) { index, node };
2285
0
}
2286
2287
void
2288
ovsdb_idl_cursor_next(struct ovsdb_idl_cursor *cursor)
2289
0
{
2290
0
    cursor->position = skiplist_next(cursor->position);
2291
0
}
2292
2293
void
2294
ovsdb_idl_cursor_next_eq(struct ovsdb_idl_cursor *cursor)
2295
0
{
2296
0
    struct ovsdb_idl_row *data = skiplist_get_data(cursor->position);
2297
0
    struct skiplist_node *next_position = skiplist_next(cursor->position);
2298
0
    struct ovsdb_idl_row *next_data = skiplist_get_data(next_position);
2299
0
    cursor->position = (!ovsdb_idl_index_compare(cursor->index,
2300
0
                                                 data, next_data)
2301
0
                        ? next_position : NULL);
2302
0
}
2303
2304
struct ovsdb_idl_row *
2305
ovsdb_idl_cursor_data(struct ovsdb_idl_cursor *cursor)
2306
0
{
2307
0
    return skiplist_get_data(cursor->position);
2308
0
}
2309
2310
/* Returns the result of comparing two rows using the comparison function
2311
 * for this index.
2312
 * Returns:
2313
 * < 0 if a < b
2314
 * 0 if a == b
2315
 * > 0 if a > b
2316
 * When the pointer to either row is NULL, this function considers NULL to be
2317
 * greater than any other value, and NULL == NULL.
2318
 */
2319
int
2320
ovsdb_idl_index_compare(struct ovsdb_idl_index *index,
2321
                        const struct ovsdb_idl_row *a,
2322
                        const struct ovsdb_idl_row *b)
2323
0
{
2324
0
    if (a && b) {
2325
0
        return ovsdb_idl_index_generic_comparer(a, b, index);
2326
0
    } else if (!a && !b) {
2327
0
        return 0;
2328
0
    } else if (a) {
2329
0
        return -1;
2330
0
    } else {
2331
0
        return 1;
2332
0
    }
2333
0
}
2334
2335
static void
2336
ovsdb_idl_row_clear_old(struct ovsdb_idl_row *row)
2337
0
{
2338
0
    ovs_assert(row->old_datum == row->new_datum);
2339
0
    if (!ovsdb_idl_row_is_orphan(row)) {
2340
0
        if (ovsdb_idl_track_is_set(row->table) && !row->tracked_old_datum) {
2341
0
            row->tracked_old_datum = row->old_datum;
2342
0
        } else {
2343
0
            const struct ovsdb_idl_table_class *class = row->table->class_;
2344
0
            size_t i;
2345
2346
0
            for (i = 0; i < class->n_columns; i++) {
2347
0
                ovsdb_datum_destroy(&row->old_datum[i],
2348
0
                                    &class->columns[i].type);
2349
0
            }
2350
0
            free(row->old_datum);
2351
0
        }
2352
0
        row->old_datum = row->new_datum = NULL;
2353
0
    }
2354
0
}
2355
2356
static void
2357
ovsdb_idl_row_clear_new(struct ovsdb_idl_row *row)
2358
0
{
2359
0
    if (row->old_datum != row->new_datum) {
2360
0
        if (row->new_datum) {
2361
0
            const struct ovsdb_idl_table_class *class = row->table->class_;
2362
0
            size_t i;
2363
2364
0
            if (row->written) {
2365
0
                BITMAP_FOR_EACH_1 (i, class->n_columns, row->written) {
2366
0
                    ovsdb_datum_destroy(&row->new_datum[i],
2367
0
                                        &class->columns[i].type);
2368
0
                }
2369
0
            }
2370
0
            free(row->new_datum);
2371
0
            free(row->written);
2372
0
            row->written = NULL;
2373
0
        }
2374
0
        row->new_datum = row->old_datum;
2375
0
    }
2376
0
}
2377
2378
static void
2379
ovsdb_idl_row_clear_arcs(struct ovsdb_idl_row *row, bool destroy_dsts)
2380
0
{
2381
0
    struct ovsdb_idl_arc *arc;
2382
2383
    /* Delete all forward arcs.  If 'destroy_dsts', destroy any orphaned rows
2384
     * that this causes to be unreferenced.
2385
     */
2386
0
    LIST_FOR_EACH_SAFE (arc, src_node, &row->src_arcs) {
2387
0
        ovs_list_remove(&arc->dst_node);
2388
0
        if (destroy_dsts
2389
0
            && ovsdb_idl_row_is_orphan(arc->dst)
2390
0
            && ovs_list_is_empty(&arc->dst->dst_arcs)) {
2391
0
            ovsdb_idl_row_destroy(arc->dst);
2392
0
        }
2393
0
        free(arc);
2394
0
    }
2395
0
    ovs_list_init(&row->src_arcs);
2396
0
}
2397
2398
/* Force nodes that reference 'row' to reparse. */
2399
static void
2400
ovsdb_idl_row_reparse_backrefs(struct ovsdb_idl_row *row)
2401
0
{
2402
0
    struct ovsdb_idl_arc *arc;
2403
2404
    /* This is trickier than it looks.  ovsdb_idl_row_clear_arcs() will destroy
2405
     * 'arc', so we need to use the "safe" variant of list traversal.  However,
2406
     * calling an ovsdb_idl_column's 'parse' function will add an arc
2407
     * equivalent to 'arc' to row->arcs.  That could be a problem for
2408
     * traversal, but it adds it at the beginning of the list to prevent us
2409
     * from stumbling upon it again.
2410
     *
2411
     * (If duplicate arcs were possible then we would need to make sure that
2412
     * 'next' didn't also point into 'arc''s destination, but we forbid
2413
     * duplicate arcs.) */
2414
0
    LIST_FOR_EACH_SAFE (arc, dst_node, &row->dst_arcs) {
2415
0
        struct ovsdb_idl_row *ref = arc->src;
2416
2417
0
        ovsdb_idl_row_unparse(ref);
2418
0
        ovsdb_idl_row_clear_arcs(ref, false);
2419
0
        ovsdb_idl_row_parse(ref);
2420
0
    }
2421
0
}
2422
2423
/* Add all backrefs of a row to the 'rows_to_reparse' list, so they can be
2424
 * re-parsed later. */
2425
static void
2426
ovsdb_idl_row_mark_backrefs_for_reparsing(struct ovsdb_idl_row *row)
2427
0
{
2428
0
    struct ovsdb_idl_arc *arc;
2429
2430
0
    LIST_FOR_EACH (arc, dst_node, &row->dst_arcs) {
2431
0
        struct ovsdb_idl_row *ref = arc->src;
2432
2433
0
        if (ovs_list_is_empty(&ref->reparse_node)) {
2434
0
            ovs_list_push_back(&ref->table->idl->rows_to_reparse,
2435
0
                               &ref->reparse_node);
2436
0
        }
2437
0
    }
2438
0
}
2439
2440
static void
2441
ovsdb_idl_row_track_change(struct ovsdb_idl_row *row,
2442
                           enum ovsdb_idl_change change)
2443
0
{
2444
0
    row->change_seqno[change]
2445
0
        = row->table->change_seqno[change]
2446
0
        = row->table->idl->change_seqno + 1;
2447
0
    if (ovs_list_is_empty(&row->track_node)) {
2448
0
        ovs_list_push_back(&row->table->track_list, &row->track_node);
2449
0
    }
2450
0
}
2451
2452
static void
2453
ovsdb_idl_row_untrack_change(struct ovsdb_idl_row *row)
2454
0
{
2455
0
    if (ovs_list_is_empty(&row->track_node)) {
2456
0
        return;
2457
0
    }
2458
2459
0
    ovs_list_remove(&row->track_node);
2460
0
    ovs_list_init(&row->track_node);
2461
0
}
2462
2463
static void ovsdb_idl_row_clear_changeseqno(struct ovsdb_idl_row *row)
2464
0
{
2465
0
    row->change_seqno[OVSDB_IDL_CHANGE_INSERT] =
2466
0
        row->change_seqno[OVSDB_IDL_CHANGE_MODIFY] =
2467
0
        row->change_seqno[OVSDB_IDL_CHANGE_DELETE] = 0;
2468
0
}
2469
2470
static struct ovsdb_idl_row *
2471
ovsdb_idl_row_create__(const struct ovsdb_idl_table_class *class)
2472
0
{
2473
0
    struct ovsdb_idl_row *row = xzalloc(class->allocation_size);
2474
0
    class->row_init(row);
2475
0
    ovs_list_init(&row->src_arcs);
2476
0
    ovs_list_init(&row->dst_arcs);
2477
0
    ovs_list_init(&row->reparse_node);
2478
0
    hmap_node_nullify(&row->txn_node);
2479
0
    ovs_list_init(&row->track_node);
2480
0
    return row;
2481
0
}
2482
2483
static struct ovsdb_idl_row *
2484
ovsdb_idl_row_create(struct ovsdb_idl_table *table, const struct uuid *uuid)
2485
0
{
2486
0
    struct ovsdb_idl_row *row = ovsdb_idl_row_create__(table->class_);
2487
0
    hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
2488
0
    row->uuid = *uuid;
2489
0
    row->table = table;
2490
0
    row->map_op_written = NULL;
2491
0
    row->map_op_lists = NULL;
2492
0
    row->set_op_written = NULL;
2493
0
    row->set_op_lists = NULL;
2494
0
    return row;
2495
0
}
2496
2497
/* If 'row' is not referenced anymore, removes 'row' from the table hmap,
2498
 * clears the old datum and adds 'row' to the table's track_list.
2499
 *
2500
 * If 'row' is still referenced, i.e., became "orphan", queues 'row' for
2501
 * reparsing after all updates have been processed by adding it to the
2502
 * 'deleted_untracked_rows' list.
2503
 */
2504
static void
2505
ovsdb_idl_row_destroy(struct ovsdb_idl_row *row)
2506
0
{
2507
0
    ovsdb_idl_row_clear_old(row);
2508
0
    if (ovs_list_is_empty(&row->dst_arcs)) {
2509
0
        hmap_remove(&row->table->rows, &row->hmap_node);
2510
0
        ovsdb_idl_destroy_all_map_op_lists(row);
2511
0
        ovsdb_idl_destroy_all_set_op_lists(row);
2512
0
        ovsdb_idl_row_track_change(row, OVSDB_IDL_CHANGE_DELETE);
2513
0
    } else {
2514
0
        ovsdb_idl_row_untrack_change(row);
2515
0
        ovs_list_push_back(&row->table->idl->deleted_untracked_rows,
2516
0
                           &row->track_node);
2517
0
    }
2518
0
}
2519
2520
static void
2521
ovsdb_idl_destroy_all_map_op_lists(struct ovsdb_idl_row *row)
2522
0
{
2523
0
    if (row->map_op_written) {
2524
        /* Clear Map Operation Lists */
2525
0
        size_t idx, n_columns;
2526
0
        const struct ovsdb_idl_column *columns;
2527
0
        const struct ovsdb_type *type;
2528
0
        n_columns = row->table->class_->n_columns;
2529
0
        columns = row->table->class_->columns;
2530
0
        BITMAP_FOR_EACH_1 (idx, n_columns, row->map_op_written) {
2531
0
            type = &columns[idx].type;
2532
0
            map_op_list_destroy(row->map_op_lists[idx], type);
2533
0
        }
2534
0
        free(row->map_op_lists);
2535
0
        bitmap_free(row->map_op_written);
2536
0
        row->map_op_lists = NULL;
2537
0
        row->map_op_written = NULL;
2538
0
    }
2539
0
}
2540
2541
static void
2542
ovsdb_idl_destroy_all_set_op_lists(struct ovsdb_idl_row *row)
2543
0
{
2544
0
    if (row->set_op_written) {
2545
        /* Clear Set Operation Lists */
2546
0
        size_t idx, n_columns;
2547
0
        const struct ovsdb_idl_column *columns;
2548
0
        const struct ovsdb_type *type;
2549
0
        n_columns = row->table->class_->n_columns;
2550
0
        columns = row->table->class_->columns;
2551
0
        BITMAP_FOR_EACH_1 (idx, n_columns, row->set_op_written) {
2552
0
            type = &columns[idx].type;
2553
0
            set_op_list_destroy(row->set_op_lists[idx], type);
2554
0
        }
2555
0
        free(row->set_op_lists);
2556
0
        bitmap_free(row->set_op_written);
2557
0
        row->set_op_lists = NULL;
2558
0
        row->set_op_written = NULL;
2559
0
    }
2560
0
}
2561
2562
static void
2563
ovsdb_idl_row_destroy_postprocess(struct ovsdb_idl *idl)
2564
0
{
2565
0
    for (size_t i = 0; i < idl->class_->n_tables; i++) {
2566
0
        struct ovsdb_idl_table *table = &idl->tables[i];
2567
2568
0
        if (!ovs_list_is_empty(&table->track_list)) {
2569
0
            struct ovsdb_idl_row *row;
2570
2571
0
            LIST_FOR_EACH_SAFE (row, track_node, &table->track_list) {
2572
0
                if (!ovsdb_idl_track_is_set(row->table)) {
2573
0
                    ovs_list_remove(&row->track_node);
2574
0
                    ovsdb_idl_row_unparse(row);
2575
0
                    free(row);
2576
0
                }
2577
0
            }
2578
0
        }
2579
0
    }
2580
0
}
2581
2582
static void
2583
ovsdb_idl_insert_row(struct ovsdb_idl_row *row, const struct shash *data)
2584
0
{
2585
0
    const struct ovsdb_idl_table_class *class = row->table->class_;
2586
0
    size_t i, datum_size;
2587
2588
0
    ovs_assert(!row->old_datum && !row->new_datum);
2589
0
    datum_size = class->n_columns * sizeof *row->old_datum;
2590
0
    row->old_datum = row->new_datum = xmalloc(datum_size);
2591
0
    for (i = 0; i < class->n_columns; i++) {
2592
0
        ovsdb_datum_init_default(&row->old_datum[i], &class->columns[i].type);
2593
0
    }
2594
0
    ovsdb_idl_row_change(row, data, false, OVSDB_IDL_CHANGE_INSERT);
2595
0
    ovsdb_idl_row_parse(row);
2596
2597
    /* Backrefs will be re-parsed after all updates processed to avoid
2598
     * re-parsing same rows more than once if they are referencing more
2599
     * than one inserted row. */
2600
0
    ovsdb_idl_row_mark_backrefs_for_reparsing(row);
2601
0
    ovsdb_idl_add_to_indexes(row);
2602
0
}
2603
2604
static void
2605
ovsdb_idl_delete_row(struct ovsdb_idl_row *row)
2606
0
{
2607
    /* If row has to be reparsed, reparse it before it's deleted. */
2608
0
    if (!ovs_list_is_empty(&row->reparse_node)) {
2609
0
        ovsdb_idl_row_parse(row);
2610
0
    }
2611
0
    ovsdb_idl_remove_from_indexes(row);
2612
0
    ovsdb_idl_row_clear_arcs(row, true);
2613
0
    ovsdb_idl_row_destroy(row);
2614
0
}
2615
2616
/* Returns true if a column with mode OVSDB_IDL_MODE_RW changed, false
2617
 * otherwise. */
2618
static bool
2619
ovsdb_idl_modify_row(struct ovsdb_idl_row *row, const struct shash *values,
2620
                     bool xor)
2621
0
{
2622
0
    ovsdb_idl_remove_from_indexes(row);
2623
0
    ovsdb_idl_row_unparse(row);
2624
0
    ovsdb_idl_row_clear_arcs(row, true);
2625
0
    bool changed = ovsdb_idl_row_change(row, values, xor,
2626
0
                                        OVSDB_IDL_CHANGE_MODIFY);
2627
0
    ovsdb_idl_row_parse(row);
2628
0
    ovsdb_idl_add_to_indexes(row);
2629
2630
0
    return changed;
2631
0
}
2632
2633
static bool
2634
may_add_arc(const struct ovsdb_idl_row *src, const struct ovsdb_idl_row *dst)
2635
0
{
2636
0
    const struct ovsdb_idl_arc *arc;
2637
2638
    /* No self-arcs. */
2639
0
    if (src == dst) {
2640
0
        return false;
2641
0
    }
2642
2643
    /* No duplicate arcs.
2644
     *
2645
     * We only need to test whether the first arc in dst->dst_arcs originates
2646
     * at 'src', since we add all of the arcs from a given source in a clump
2647
     * (in a single call to ovsdb_idl_row_parse()) and new arcs are always
2648
     * added at the front of the dst_arcs list. */
2649
0
    if (ovs_list_is_empty(&dst->dst_arcs)) {
2650
0
        return true;
2651
0
    }
2652
0
    arc = CONTAINER_OF(dst->dst_arcs.next, struct ovsdb_idl_arc, dst_node);
2653
0
    return arc->src != src;
2654
0
}
2655
2656
static struct ovsdb_idl_table *
2657
ovsdb_idl_table_from_class(const struct ovsdb_idl *idl,
2658
                           const struct ovsdb_idl_table_class *table_class)
2659
0
{
2660
0
    ptrdiff_t idx = table_class - idl->class_->tables;
2661
0
    return idx >= 0 && idx < idl->class_->n_tables ? &idl->tables[idx] : NULL;
2662
0
}
2663
2664
/* Called by ovsdb-idlc generated code. */
2665
struct ovsdb_idl_row *
2666
ovsdb_idl_get_row_arc(struct ovsdb_idl_row *src,
2667
                      const struct ovsdb_idl_table_class *dst_table_class,
2668
                      const struct uuid *dst_uuid)
2669
0
{
2670
0
    struct ovsdb_idl *idl = src->table->idl;
2671
0
    struct ovsdb_idl_table *dst_table;
2672
0
    struct ovsdb_idl_arc *arc;
2673
0
    struct ovsdb_idl_row *dst;
2674
2675
0
    dst_table = ovsdb_idl_table_from_class(idl, dst_table_class);
2676
0
    dst = ovsdb_idl_get_row(dst_table, dst_uuid);
2677
0
    if (idl->txn || is_index_row(src)) {
2678
        /* There are two cases we should not update any arcs:
2679
         *
2680
         * 1. We're being called from ovsdb_idl_txn_write(). We must not update
2681
         * any arcs, because the transaction will be backed out at commit or
2682
         * abort time and we don't want our graph screwed up.
2683
         *
2684
         * 2. The row is used as an index for querying purpose only.
2685
         *
2686
         * In these cases, just return the destination row, if there is one and
2687
         * it has not been deleted. */
2688
0
        if (dst && (hmap_node_is_null(&dst->txn_node) || dst->new_datum)) {
2689
0
            return dst;
2690
0
        }
2691
0
        return NULL;
2692
0
    } else {
2693
        /* We're being called from some other context.  Update the graph. */
2694
0
        if (!dst) {
2695
0
            dst = ovsdb_idl_row_create(dst_table, dst_uuid);
2696
0
        }
2697
2698
        /* Add a new arc, if it wouldn't be a self-arc or a duplicate arc. */
2699
0
        if (may_add_arc(src, dst)) {
2700
            /* The arc *must* be added at the front of the dst_arcs list.  See
2701
             * ovsdb_idl_row_reparse_backrefs() for details. */
2702
0
            arc = xmalloc(sizeof *arc);
2703
0
            ovs_list_push_front(&src->src_arcs, &arc->src_node);
2704
0
            ovs_list_push_front(&dst->dst_arcs, &arc->dst_node);
2705
0
            arc->src = src;
2706
0
            arc->dst = dst;
2707
0
        }
2708
2709
0
        return !ovsdb_idl_row_is_orphan(dst) ? dst : NULL;
2710
0
    }
2711
0
}
2712
2713
/* Searches 'tc''s table in 'idl' for a row with UUID 'uuid'.  Returns a
2714
 * pointer to the row if there is one, otherwise a null pointer.  */
2715
const struct ovsdb_idl_row *
2716
ovsdb_idl_get_row_for_uuid(const struct ovsdb_idl *idl,
2717
                           const struct ovsdb_idl_table_class *tc,
2718
                           const struct uuid *uuid)
2719
0
{
2720
0
    const struct ovsdb_idl_row *row;
2721
2722
0
    row = ovsdb_idl_get_row(ovsdb_idl_table_from_class(idl, tc), uuid);
2723
0
    return (row && ovsdb_idl_row_exists(row)) ? row : NULL;
2724
0
}
2725
2726
static struct ovsdb_idl_row *
2727
next_real_row(struct ovsdb_idl_table *table, struct hmap_node *node)
2728
0
{
2729
0
    for (; node; node = hmap_next(&table->rows, node)) {
2730
0
        struct ovsdb_idl_row *row;
2731
2732
0
        row = CONTAINER_OF(node, struct ovsdb_idl_row, hmap_node);
2733
0
        if (ovsdb_idl_row_exists(row)) {
2734
0
            return row;
2735
0
        }
2736
0
    }
2737
0
    return NULL;
2738
0
}
2739
2740
/* Returns a row in 'table_class''s table in 'idl', or a null pointer if that
2741
 * table is empty.
2742
 *
2743
 * Database tables are internally maintained as hash tables, so adding or
2744
 * removing rows while traversing the same table can cause some rows to be
2745
 * visited twice or not at apply. */
2746
const struct ovsdb_idl_row *
2747
ovsdb_idl_first_row(const struct ovsdb_idl *idl,
2748
                    const struct ovsdb_idl_table_class *table_class)
2749
0
{
2750
0
    struct ovsdb_idl_table *table = ovsdb_idl_table_from_class(idl,
2751
0
                                                               table_class);
2752
0
    return next_real_row(table, hmap_first(&table->rows));
2753
0
}
2754
2755
/* Returns a row following 'row' within its table, or a null pointer if 'row'
2756
 * is the last row in its table. */
2757
const struct ovsdb_idl_row *
2758
ovsdb_idl_next_row(const struct ovsdb_idl_row *row)
2759
0
{
2760
0
    struct ovsdb_idl_table *table = row->table;
2761
2762
0
    return next_real_row(table, hmap_next(&table->rows, &row->hmap_node));
2763
0
}
2764
2765
/* Reads and returns the value of 'column' within 'row'.  If an ongoing
2766
 * transaction has changed 'column''s value, the modified value is returned.
2767
 *
2768
 * The caller must not modify or free the returned value.
2769
 *
2770
 * Various kinds of changes can invalidate the returned value: writing to the
2771
 * same 'column' in 'row' (e.g. with ovsdb_idl_txn_write()), deleting 'row'
2772
 * (e.g. with ovsdb_idl_txn_delete()), or completing an ongoing transaction
2773
 * (e.g. with ovsdb_idl_txn_commit() or ovsdb_idl_txn_abort()).  If the
2774
 * returned value is needed for a long time, it is best to make a copy of it
2775
 * with ovsdb_datum_clone(). */
2776
const struct ovsdb_datum *
2777
ovsdb_idl_read(const struct ovsdb_idl_row *row,
2778
               const struct ovsdb_idl_column *column)
2779
0
{
2780
0
    const struct ovsdb_idl_table_class *class;
2781
0
    size_t column_idx;
2782
2783
0
    ovs_assert(!ovsdb_idl_row_is_synthetic(row));
2784
2785
0
    class = row->table->class_;
2786
0
    column_idx = column - class->columns;
2787
2788
0
    ovs_assert(row->new_datum != NULL);
2789
0
    ovs_assert(column_idx < class->n_columns);
2790
2791
0
    if (row->written && bitmap_is_set(row->written, column_idx)) {
2792
0
        return &row->new_datum[column_idx];
2793
0
    } else if (row->old_datum) {
2794
0
        return &row->old_datum[column_idx];
2795
0
    } else {
2796
0
        return ovsdb_datum_default(&column->type);
2797
0
    }
2798
0
}
2799
2800
/* Same as ovsdb_idl_read(), except that it also asserts that 'column' has key
2801
 * type 'key_type' and value type 'value_type'.  (Scalar and set types will
2802
 * have a value type of OVSDB_TYPE_VOID.)
2803
 *
2804
 * This is useful in code that "knows" that a particular column has a given
2805
 * type, so that it will abort if someone changes the column's type without
2806
 * updating the code that uses it. */
2807
const struct ovsdb_datum *
2808
ovsdb_idl_get(const struct ovsdb_idl_row *row,
2809
              const struct ovsdb_idl_column *column,
2810
              enum ovsdb_atomic_type key_type OVS_UNUSED,
2811
              enum ovsdb_atomic_type value_type OVS_UNUSED)
2812
0
{
2813
0
    ovs_assert(column->type.key.type == key_type);
2814
0
    ovs_assert(column->type.value.type == value_type);
2815
2816
0
    return ovsdb_idl_read(row, column);
2817
0
}
2818
2819
/* Returns true if the field represented by 'column' in 'row' may be modified,
2820
 * false if it is immutable.
2821
 *
2822
 * Normally, whether a field is mutable is controlled by its column's schema.
2823
 * However, an immutable column can be set to any initial value at the time of
2824
 * insertion, so if 'row' is a new row (one that is being added as part of the
2825
 * current transaction, supposing that a transaction is in progress) then even
2826
 * its "immutable" fields are actually mutable. */
2827
bool
2828
ovsdb_idl_is_mutable(const struct ovsdb_idl_row *row,
2829
                     const struct ovsdb_idl_column *column)
2830
0
{
2831
0
    return column->is_mutable || (row->new_datum && !row->old_datum);
2832
0
}
2833
2834
/* Returns false if 'row' was obtained from the IDL, true if it was initialized
2835
 * to all-zero-bits by some other entity.  If 'row' was set up some other way
2836
 * then the return value is indeterminate. */
2837
bool
2838
ovsdb_idl_row_is_synthetic(const struct ovsdb_idl_row *row)
2839
0
{
2840
0
    return row->table == NULL;
2841
0
}
2842

2843
/* Transactions. */
2844
2845
static void ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
2846
                                   enum ovsdb_idl_txn_status);
2847
2848
/* Returns a string representation of 'status'.  The caller must not modify or
2849
 * free the returned string.
2850
 *
2851
 * The return value is probably useful only for debug log messages and unit
2852
 * tests. */
2853
const char *
2854
ovsdb_idl_txn_status_to_string(enum ovsdb_idl_txn_status status)
2855
0
{
2856
0
    switch (status) {
2857
0
    case TXN_UNCOMMITTED:
2858
0
        return "uncommitted";
2859
0
    case TXN_UNCHANGED:
2860
0
        return "unchanged";
2861
0
    case TXN_INCOMPLETE:
2862
0
        return "incomplete";
2863
0
    case TXN_ABORTED:
2864
0
        return "aborted";
2865
0
    case TXN_SUCCESS:
2866
0
        return "success";
2867
0
    case TXN_TRY_AGAIN:
2868
0
        return "try again";
2869
0
    case TXN_NOT_LOCKED:
2870
0
        return "not locked";
2871
0
    case TXN_ERROR:
2872
0
        return "error";
2873
0
    }
2874
0
    return "<unknown>";
2875
0
}
2876
2877
/* Starts a new transaction on 'idl'.  A given ovsdb_idl may only have a single
2878
 * active transaction at a time.  See the large comment in ovsdb-idl.h for
2879
 * general information on transactions. */
2880
struct ovsdb_idl_txn *
2881
ovsdb_idl_txn_create(struct ovsdb_idl *idl)
2882
0
{
2883
0
    struct ovsdb_idl_txn *txn;
2884
2885
0
    ovs_assert(!idl->txn);
2886
0
    idl->txn = txn = xmalloc(sizeof *txn);
2887
0
    txn->request_id = NULL;
2888
0
    txn->idl = idl;
2889
0
    hmap_init(&txn->txn_rows);
2890
0
    txn->status = TXN_UNCOMMITTED;
2891
0
    txn->error = NULL;
2892
0
    txn->dry_run = false;
2893
0
    txn->assert_read_only = false;
2894
0
    ds_init(&txn->comment);
2895
2896
0
    txn->inc_table = NULL;
2897
0
    txn->inc_column = NULL;
2898
2899
0
    hmap_init(&txn->inserted_rows);
2900
2901
0
    return txn;
2902
0
}
2903
2904
/* Appends 's', which is treated as a printf()-type format string, to the
2905
 * comments that will be passed to the OVSDB server when 'txn' is committed.
2906
 * (The comment will be committed to the OVSDB log, which "ovsdb-tool
2907
 * show-log" can print in a relatively human-readable form.) */
2908
void
2909
ovsdb_idl_txn_add_comment(struct ovsdb_idl_txn *txn, const char *s, ...)
2910
0
{
2911
0
    va_list args;
2912
2913
0
    if (txn->comment.length) {
2914
0
        ds_put_char(&txn->comment, '\n');
2915
0
    }
2916
2917
0
    va_start(args, s);
2918
0
    ds_put_format_valist(&txn->comment, s, args);
2919
0
    va_end(args);
2920
0
}
2921
2922
/* Marks 'txn' as a transaction that will not actually modify the database.  In
2923
 * almost every way, the transaction is treated like other transactions.  It
2924
 * must be committed or aborted like other transactions, it will be sent to the
2925
 * database server like other transactions, and so on.  The only difference is
2926
 * that the operations sent to the database server will include, as the last
2927
 * step, an "abort" operation, so that any changes made by the transaction will
2928
 * not actually take effect. */
2929
void
2930
ovsdb_idl_txn_set_dry_run(struct ovsdb_idl_txn *txn)
2931
0
{
2932
0
    txn->dry_run = true;
2933
0
}
2934
2935
/* Causes 'txn', when committed, to increment the value of 'column' within
2936
 * 'row' by 1.  'column' must have an integer type.  After 'txn' commits
2937
 * successfully, the client may retrieve the final (incremented) value of
2938
 * 'column' with ovsdb_idl_txn_get_increment_new_value().
2939
 *
2940
 * If at time of commit the transaction is otherwise empty, that is, it doesn't
2941
 * change the database, then 'force' is important.  If 'force' is false in this
2942
 * case, the IDL suppresses the increment and skips a round trip to the
2943
 * database server.  If 'force' is true, the IDL will still increment the
2944
 * column.
2945
 *
2946
 * The client could accomplish something similar with ovsdb_idl_read(),
2947
 * ovsdb_idl_txn_verify() and ovsdb_idl_txn_write(), or with ovsdb-idlc
2948
 * generated wrappers for these functions.  However, ovsdb_idl_txn_increment()
2949
 * will never (by itself) fail because of a verify error.
2950
 *
2951
 * The intended use is for incrementing the "next_cfg" column in the
2952
 * Open_vSwitch table. */
2953
void
2954
ovsdb_idl_txn_increment(struct ovsdb_idl_txn *txn,
2955
                        const struct ovsdb_idl_row *row,
2956
                        const struct ovsdb_idl_column *column,
2957
                        bool force)
2958
0
{
2959
0
    ovs_assert(!txn->inc_table);
2960
0
    ovs_assert(column->type.key.type == OVSDB_TYPE_INTEGER);
2961
0
    ovs_assert(column->type.value.type == OVSDB_TYPE_VOID);
2962
0
    ovs_assert(!txn->assert_read_only);
2963
2964
0
    txn->inc_table = row->table->class_->name;
2965
0
    txn->inc_column = column->name;
2966
0
    txn->inc_row = row->uuid;
2967
0
    txn->inc_force = force;
2968
0
}
2969
2970
/* Destroys 'txn' and frees all associated memory.  If ovsdb_idl_txn_commit()
2971
 * has been called for 'txn' but the commit is still incomplete (that is, the
2972
 * last call returned TXN_INCOMPLETE) then the transaction may or may not still
2973
 * end up committing at the database server, but the client will not be able to
2974
 * get any further status information back. */
2975
void
2976
ovsdb_idl_txn_destroy(struct ovsdb_idl_txn *txn)
2977
0
{
2978
0
    struct ovsdb_idl_txn_insert *insert;
2979
2980
0
    if (txn->status == TXN_INCOMPLETE) {
2981
0
        ovsdb_cs_forget_transaction(txn->idl->cs, txn->request_id);
2982
0
        hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
2983
0
    }
2984
0
    json_destroy(txn->request_id);
2985
0
    ovsdb_idl_txn_abort(txn);
2986
0
    ds_destroy(&txn->comment);
2987
0
    free(txn->error);
2988
0
    HMAP_FOR_EACH_SAFE (insert, hmap_node, &txn->inserted_rows) {
2989
0
        free(insert);
2990
0
    }
2991
0
    hmap_destroy(&txn->inserted_rows);
2992
0
    free(txn);
2993
0
}
2994
2995
/* Causes poll_block() to wake up if 'txn' has completed committing. */
2996
void
2997
ovsdb_idl_txn_wait(const struct ovsdb_idl_txn *txn)
2998
0
{
2999
0
    if (txn->status != TXN_UNCOMMITTED && txn->status != TXN_INCOMPLETE) {
3000
0
        poll_immediate_wake();
3001
0
    }
3002
0
}
3003
3004
static struct json *
3005
where_uuid_equals(const struct uuid *uuid)
3006
0
{
3007
0
    return
3008
0
        json_array_create_1(
3009
0
            json_array_create_3(
3010
0
                json_string_create("_uuid"),
3011
0
                json_string_create("=="),
3012
0
                json_array_create_2(
3013
0
                    json_string_create("uuid"),
3014
0
                    json_string_create_uuid(uuid))));
3015
0
}
3016
3017
static const struct ovsdb_idl_row *
3018
ovsdb_idl_txn_get_row(const struct ovsdb_idl_txn *txn, const struct uuid *uuid)
3019
0
{
3020
0
    const struct ovsdb_idl_row *row;
3021
3022
0
    HMAP_FOR_EACH_WITH_HASH (row, txn_node, uuid_hash(uuid), &txn->txn_rows) {
3023
0
        if (uuid_equals(&row->uuid, uuid)) {
3024
0
            return row;
3025
0
        }
3026
0
    }
3027
0
    return NULL;
3028
0
}
3029
3030
/* XXX there must be a cleaner way to do this */
3031
static struct json *
3032
substitute_uuids(struct json *json, const struct ovsdb_idl_txn *txn)
3033
0
{
3034
0
    if (json->type == JSON_ARRAY) {
3035
0
        struct uuid uuid;
3036
0
        size_t i;
3037
3038
0
        if (json_array_size(json) == 2
3039
0
            && json_array_at(json, 0)->type == JSON_STRING
3040
0
            && json_array_at(json, 1)->type == JSON_STRING
3041
0
            && !strcmp(json_string(json_array_at(json, 0)), "uuid")
3042
0
            && uuid_from_string(&uuid, json_string(json_array_at(json, 1)))) {
3043
0
            const struct ovsdb_idl_row *row;
3044
3045
0
            row = ovsdb_idl_txn_get_row(txn, &uuid);
3046
0
            if (row && !row->old_datum && row->new_datum) {
3047
0
                if (row->persist_uuid) {
3048
0
                    return json;
3049
0
                } else {
3050
0
                    json_destroy(json);
3051
0
                    return json_array_create_2(
3052
0
                        json_string_create("named-uuid"),
3053
0
                        json_string_create_nocopy(ovsdb_data_row_name(&uuid)));
3054
0
                }
3055
0
            }
3056
0
        }
3057
3058
0
        for (i = 0; i < json_array_size(json); i++) {
3059
0
            json_array_set(
3060
0
                json, i,
3061
0
                substitute_uuids(
3062
0
                    CONST_CAST(struct json *, json_array_at(json, i)), txn));
3063
0
        }
3064
0
    } else if (json->type == JSON_OBJECT) {
3065
0
        struct shash_node *node;
3066
3067
0
        SHASH_FOR_EACH (node, json_object(json)) {
3068
0
            node->data = substitute_uuids(node->data, txn);
3069
0
        }
3070
0
    }
3071
0
    return json;
3072
0
}
3073
3074
static void
3075
ovsdb_idl_txn_disassemble(struct ovsdb_idl_txn *txn)
3076
0
{
3077
0
    struct ovsdb_idl_row *row;
3078
3079
    /* This must happen early.  Otherwise, ovsdb_idl_row_parse() will call an
3080
     * ovsdb_idl_column's 'parse' function, which will call
3081
     * ovsdb_idl_get_row_arc(), which will seen that the IDL is in a
3082
     * transaction and fail to update the graph.  */
3083
0
    txn->idl->txn = NULL;
3084
3085
0
    HMAP_FOR_EACH_SAFE (row, txn_node, &txn->txn_rows) {
3086
0
        enum { INSERTED, MODIFIED, DELETED } op
3087
0
            = (!row->new_datum ? DELETED
3088
0
               : !row->old_datum ? INSERTED
3089
0
               : MODIFIED);
3090
3091
0
        if (op != DELETED) {
3092
0
            ovsdb_idl_remove_from_indexes(row);
3093
0
        }
3094
3095
0
        ovsdb_idl_destroy_all_map_op_lists(row);
3096
0
        ovsdb_idl_destroy_all_set_op_lists(row);
3097
0
        if (op != INSERTED) {
3098
0
            if (row->written) {
3099
0
                ovsdb_idl_row_unparse(row);
3100
0
                ovsdb_idl_row_clear_arcs(row, false);
3101
0
                ovsdb_idl_row_parse(row);
3102
0
            }
3103
0
        } else {
3104
0
            ovsdb_idl_row_unparse(row);
3105
0
        }
3106
0
        ovsdb_idl_row_clear_new(row);
3107
3108
0
        free(row->prereqs);
3109
0
        row->prereqs = NULL;
3110
3111
0
        free(row->written);
3112
0
        row->written = NULL;
3113
3114
0
        hmap_remove(&txn->txn_rows, &row->txn_node);
3115
0
        hmap_node_nullify(&row->txn_node);
3116
0
        if (op != INSERTED) {
3117
0
            ovsdb_idl_add_to_indexes(row);
3118
0
        } else {
3119
0
            hmap_remove(&row->table->rows, &row->hmap_node);
3120
0
            free(row);
3121
0
        }
3122
0
    }
3123
0
    hmap_destroy(&txn->txn_rows);
3124
0
    hmap_init(&txn->txn_rows);
3125
0
}
3126
3127
static bool
3128
ovsdb_idl_txn_extract_mutations(struct ovsdb_idl_row *row,
3129
                                struct json *mutations)
3130
0
{
3131
0
    const struct ovsdb_idl_table_class *class = row->table->class_;
3132
0
    size_t idx;
3133
0
    bool any_mutations = false;
3134
3135
0
    if (row->map_op_written) {
3136
0
        BITMAP_FOR_EACH_1(idx, class->n_columns, row->map_op_written) {
3137
0
            struct map_op_list *map_op_list;
3138
0
            const struct ovsdb_idl_column *column;
3139
0
            const struct ovsdb_datum *old_datum;
3140
0
            enum ovsdb_atomic_type key_type, value_type;
3141
0
            struct json *mutation, *map, *col_name, *mutator;
3142
0
            struct json *del_set, *ins_map;
3143
0
            bool any_del, any_ins;
3144
3145
0
            map_op_list = row->map_op_lists[idx];
3146
0
            column = &class->columns[idx];
3147
0
            key_type = column->type.key.type;
3148
0
            value_type = column->type.value.type;
3149
3150
            /* Get the value to be changed */
3151
0
            if (row->new_datum && row->written
3152
0
                && bitmap_is_set(row->written,idx)) {
3153
0
                old_datum = &row->new_datum[idx];
3154
0
            } else if (row->old_datum != NULL) {
3155
0
                old_datum = &row->old_datum[idx];
3156
0
            } else {
3157
0
                old_datum = ovsdb_datum_default(&column->type);
3158
0
            }
3159
3160
0
            del_set = json_array_create_empty();
3161
0
            ins_map = json_array_create_empty();
3162
0
            any_del = false;
3163
0
            any_ins = false;
3164
3165
0
            for (struct map_op *map_op = map_op_list_first(map_op_list); map_op;
3166
0
                 map_op = map_op_list_next(map_op_list, map_op)) {
3167
3168
0
                if (map_op_type(map_op) == MAP_OP_UPDATE) {
3169
                    /* Find out if value really changed. */
3170
0
                    struct ovsdb_datum *new_datum;
3171
0
                    unsigned int pos;
3172
3173
0
                    new_datum = map_op_datum(map_op);
3174
0
                    if (!ovsdb_datum_find_key(old_datum, &new_datum->keys[0],
3175
0
                                              key_type, &pos)) {
3176
0
                        VLOG_WARN("Trying to update a value for a key that no "
3177
0
                                  "longer exists in the map.");
3178
0
                        continue;
3179
0
                    }
3180
0
                    if (ovsdb_atom_equals(&new_datum->values[0],
3181
0
                                          &old_datum->values[pos],
3182
0
                                          value_type)) {
3183
                        /* No change in value. Move on to next update. */
3184
0
                        continue;
3185
0
                    }
3186
0
                } else if (map_op_type(map_op) == MAP_OP_DELETE){
3187
                    /* Verify that there is a key to delete. */
3188
0
                    if (!ovsdb_datum_find_key(old_datum,
3189
0
                                              &map_op_datum(map_op)->keys[0],
3190
0
                                              key_type, NULL)) {
3191
                        /* No key to delete.  Move on to next update. */
3192
0
                        VLOG_WARN("Trying to delete a key that doesn't "
3193
0
                                  "exist in the map.");
3194
0
                        continue;
3195
0
                    }
3196
0
                }
3197
3198
0
                if (map_op_type(map_op) == MAP_OP_INSERT) {
3199
0
                    map = json_array_create_2(
3200
0
                        ovsdb_atom_to_json(&map_op_datum(map_op)->keys[0],
3201
0
                                           key_type),
3202
0
                        ovsdb_atom_to_json(&map_op_datum(map_op)->values[0],
3203
0
                                           value_type));
3204
0
                    json_array_add(ins_map, map);
3205
0
                    any_ins = true;
3206
0
                } else { /* MAP_OP_UPDATE or MAP_OP_DELETE */
3207
0
                    map = ovsdb_atom_to_json(&map_op_datum(map_op)->keys[0],
3208
0
                                             key_type);
3209
0
                    json_array_add(del_set, map);
3210
0
                    any_del = true;
3211
0
                }
3212
3213
                /* Generate an additional insert mutate for updates. */
3214
0
                if (map_op_type(map_op) == MAP_OP_UPDATE) {
3215
0
                    map = json_array_create_2(
3216
0
                        ovsdb_atom_to_json(&map_op_datum(map_op)->keys[0],
3217
0
                                           key_type),
3218
0
                        ovsdb_atom_to_json(&map_op_datum(map_op)->values[0],
3219
0
                                           value_type));
3220
0
                    json_array_add(ins_map, map);
3221
0
                    any_ins = true;
3222
0
                }
3223
0
            }
3224
3225
0
            if (any_del) {
3226
0
                col_name = json_string_create(column->name);
3227
0
                mutator = json_string_create("delete");
3228
0
                map = json_array_create_2(json_string_create("set"), del_set);
3229
0
                mutation = json_array_create_3(col_name, mutator, map);
3230
0
                json_array_add(mutations, mutation);
3231
0
                any_mutations = true;
3232
0
            } else {
3233
0
                json_destroy(del_set);
3234
0
            }
3235
0
            if (any_ins) {
3236
0
                col_name = json_string_create(column->name);
3237
0
                mutator = json_string_create("insert");
3238
0
                map = json_array_create_2(json_string_create("map"), ins_map);
3239
0
                mutation = json_array_create_3(col_name, mutator, map);
3240
0
                json_array_add(mutations, mutation);
3241
0
                any_mutations = true;
3242
0
            } else {
3243
0
                json_destroy(ins_map);
3244
0
            }
3245
0
        }
3246
0
    }
3247
0
    if (row->set_op_written) {
3248
0
        BITMAP_FOR_EACH_1(idx, class->n_columns, row->set_op_written) {
3249
0
            struct set_op_list *set_op_list;
3250
0
            const struct ovsdb_idl_column *column;
3251
0
            const struct ovsdb_datum *old_datum;
3252
0
            enum ovsdb_atomic_type key_type;
3253
0
            struct json *mutation, *set, *col_name, *mutator;
3254
0
            struct json *del_set, *ins_set;
3255
0
            bool any_del, any_ins;
3256
3257
0
            set_op_list = row->set_op_lists[idx];
3258
0
            column = &class->columns[idx];
3259
0
            key_type = column->type.key.type;
3260
3261
            /* Get the value to be changed */
3262
0
            if (row->new_datum && row->written
3263
0
                && bitmap_is_set(row->written,idx)) {
3264
0
                old_datum = &row->new_datum[idx];
3265
0
            } else if (row->old_datum != NULL) {
3266
0
                old_datum = &row->old_datum[idx];
3267
0
            } else {
3268
0
                old_datum = ovsdb_datum_default(&column->type);
3269
0
            }
3270
3271
0
            del_set = json_array_create_empty();
3272
0
            ins_set = json_array_create_empty();
3273
0
            any_del = false;
3274
0
            any_ins = false;
3275
3276
0
            for (struct set_op *set_op = set_op_list_first(set_op_list); set_op;
3277
0
                 set_op = set_op_list_next(set_op_list, set_op)) {
3278
0
                if (set_op_type(set_op) == SET_OP_INSERT) {
3279
0
                    set = ovsdb_atom_to_json(&set_op_datum(set_op)->keys[0],
3280
0
                                             key_type);
3281
0
                    json_array_add(ins_set, set);
3282
0
                    any_ins = true;
3283
0
                } else { /* SETP_OP_DELETE */
3284
                    /* Verify that there is a key to delete. */
3285
0
                    if (!ovsdb_datum_find_key(old_datum,
3286
0
                                              &set_op_datum(set_op)->keys[0],
3287
0
                                              key_type, NULL)) {
3288
                        /* No key to delete.  Move on to next update. */
3289
0
                        VLOG_WARN("Trying to delete a key that doesn't "
3290
0
                                  "exist in the set.");
3291
0
                        continue;
3292
0
                    }
3293
0
                    set = ovsdb_atom_to_json(&set_op_datum(set_op)->keys[0],
3294
0
                                             key_type);
3295
0
                    json_array_add(del_set, set);
3296
0
                    any_del = true;
3297
0
                }
3298
0
            }
3299
0
            if (any_del) {
3300
0
                col_name = json_string_create(column->name);
3301
0
                mutator = json_string_create("delete");
3302
0
                set = json_array_create_2(json_string_create("set"), del_set);
3303
0
                mutation = json_array_create_3(col_name, mutator, set);
3304
0
                json_array_add(mutations, mutation);
3305
0
                any_mutations = true;
3306
0
            } else {
3307
0
                json_destroy(del_set);
3308
0
            }
3309
0
            if (any_ins) {
3310
0
                col_name = json_string_create(column->name);
3311
0
                mutator = json_string_create("insert");
3312
0
                set = json_array_create_2(json_string_create("set"), ins_set);
3313
0
                mutation = json_array_create_3(col_name, mutator, set);
3314
0
                json_array_add(mutations, mutation);
3315
0
                any_mutations = true;
3316
0
            } else {
3317
0
                json_destroy(ins_set);
3318
0
            }
3319
0
        }
3320
0
    }
3321
0
    return any_mutations;
3322
0
}
3323
3324
/* Attempts to commit 'txn'.  Returns the status of the commit operation, one
3325
 * of the following TXN_* constants:
3326
 *
3327
 *   TXN_INCOMPLETE:
3328
 *
3329
 *       The transaction is in progress, but not yet complete.  The caller
3330
 *       should call again later, after calling ovsdb_idl_run() to let the IDL
3331
 *       do OVSDB protocol processing.
3332
 *
3333
 *   TXN_UNCHANGED:
3334
 *
3335
 *       The transaction is complete.  (It didn't actually change the database,
3336
 *       so the IDL didn't send any request to the database server.)
3337
 *
3338
 *   TXN_ABORTED:
3339
 *
3340
 *       The caller previously called ovsdb_idl_txn_abort().
3341
 *
3342
 *   TXN_SUCCESS:
3343
 *
3344
 *       The transaction was successful.  The update made by the transaction
3345
 *       (and possibly other changes made by other database clients) should
3346
 *       already be visible in the IDL.
3347
 *
3348
 *   TXN_TRY_AGAIN:
3349
 *
3350
 *       The transaction failed for some transient reason, e.g. because a
3351
 *       "verify" operation reported an inconsistency or due to a network
3352
 *       problem.  The caller should wait for a change to the database, then
3353
 *       compose a new transaction, and commit the new transaction.
3354
 *
3355
 *       Use the return value of ovsdb_idl_get_seqno() to wait for a change in
3356
 *       the database.  It is important to use its return value *before* the
3357
 *       initial call to ovsdb_idl_txn_commit() as the baseline for this
3358
 *       purpose, because the change that one should wait for can happen after
3359
 *       the initial call but before the call that returns TXN_TRY_AGAIN, and
3360
 *       using some other baseline value in that situation could cause an
3361
 *       indefinite wait if the database rarely changes.
3362
 *
3363
 *   TXN_NOT_LOCKED:
3364
 *
3365
 *       The transaction failed because the IDL has been configured to require
3366
 *       a database lock (with ovsdb_idl_set_lock()) but didn't get it yet or
3367
 *       has already lost it.
3368
 *
3369
 * Committing a transaction rolls back all of the changes that it made to the
3370
 * IDL's copy of the database.  If the transaction commits successfully, then
3371
 * the database server will send an update and, thus, the IDL will be updated
3372
 * with the committed changes. */
3373
enum ovsdb_idl_txn_status
3374
ovsdb_idl_txn_commit(struct ovsdb_idl_txn *txn)
3375
0
{
3376
0
    struct ovsdb_idl *idl = txn->idl;
3377
0
    if (txn != idl->txn) {
3378
0
        goto coverage_out;
3379
0
    } else if (!ovsdb_cs_may_send_transaction(idl->cs)) {
3380
0
        txn->status = TXN_TRY_AGAIN;
3381
0
        goto disassemble_out;
3382
0
    } else if (ovsdb_cs_get_lock(idl->cs) && !ovsdb_cs_has_lock(idl->cs)) {
3383
0
        txn->status = TXN_NOT_LOCKED;
3384
0
        goto disassemble_out;
3385
0
    }
3386
3387
0
    struct json *operations = json_array_create_1(
3388
0
        json_string_create(idl->class_->database));
3389
3390
    /* Add prerequisites and declarations of new rows. */
3391
0
    struct ovsdb_idl_row *row;
3392
0
    HMAP_FOR_EACH (row, txn_node, &txn->txn_rows) {
3393
        /* XXX check that deleted rows exist even if no prereqs? */
3394
0
        if (row->prereqs) {
3395
0
            const struct ovsdb_idl_table_class *class = row->table->class_;
3396
0
            size_t n_columns = class->n_columns;
3397
0
            struct json *op, *columns, *row_json;
3398
0
            size_t idx;
3399
3400
0
            op = json_object_create();
3401
0
            json_array_add(operations, op);
3402
0
            json_object_put_string(op, "op", "wait");
3403
0
            json_object_put_string(op, "table", class->name);
3404
0
            json_object_put(op, "timeout", json_integer_create(0));
3405
0
            json_object_put(op, "where", where_uuid_equals(&row->uuid));
3406
0
            json_object_put_string(op, "until", "==");
3407
0
            columns = json_array_create_empty();
3408
0
            json_object_put(op, "columns", columns);
3409
0
            row_json = json_object_create();
3410
0
            json_object_put(op, "rows", json_array_create_1(row_json));
3411
3412
0
            BITMAP_FOR_EACH_1 (idx, n_columns, row->prereqs) {
3413
0
                const struct ovsdb_idl_column *column = &class->columns[idx];
3414
0
                json_array_add(columns, json_string_create(column->name));
3415
0
                json_object_put(row_json, column->name,
3416
0
                                ovsdb_datum_to_json(&row->old_datum[idx],
3417
0
                                                    &column->type));
3418
0
            }
3419
0
        }
3420
0
    }
3421
3422
    /* Add updates. */
3423
0
    bool any_updates = false;
3424
3425
    /* For tables constrained to have only a single row (a fairly common OVSDB
3426
     * pattern for storing global data), identify whether we're inserting a
3427
     * row.  If so, then verify that the table is empty before inserting the
3428
     * row.  This gives us a clear verification-related failure if there was an
3429
     * insertion race with another client. */
3430
0
    for (size_t i = 0; i < idl->class_->n_tables; i++) {
3431
0
        struct ovsdb_idl_table *table = &idl->tables[i];
3432
0
        if (table->class_->is_singleton) {
3433
            /* Count the number of rows in the table before and after our
3434
             * transaction commits.  This is O(n) in the number of rows in the
3435
             * table, but that's OK since we know that the table should only
3436
             * have one row. */
3437
0
            size_t initial_rows = 0;
3438
0
            size_t final_rows = 0;
3439
0
            HMAP_FOR_EACH (row, hmap_node, &table->rows) {
3440
0
                initial_rows += row->old_datum != NULL;
3441
0
                final_rows += row->new_datum != NULL;
3442
0
            }
3443
3444
0
            if (initial_rows == 0 && final_rows == 1) {
3445
0
                struct json *op = json_object_create();
3446
0
                json_array_add(operations, op);
3447
0
                json_object_put_string(op, "op", "wait");
3448
0
                json_object_put_string(op, "table", table->class_->name);
3449
0
                json_object_put(op, "where", json_array_create_empty());
3450
0
                json_object_put(op, "timeout", json_integer_create(0));
3451
0
                json_object_put_string(op, "until", "==");
3452
0
                json_object_put(op, "rows", json_array_create_empty());
3453
0
            }
3454
0
        }
3455
0
    }
3456
3457
0
    HMAP_FOR_EACH (row, txn_node, &txn->txn_rows) {
3458
0
        const struct ovsdb_idl_table_class *class = row->table->class_;
3459
3460
0
        if (!row->new_datum) {
3461
0
            if (class->is_root) {
3462
0
                struct json *op = json_object_create();
3463
0
                json_object_put_string(op, "op", "delete");
3464
0
                json_object_put_string(op, "table", class->name);
3465
0
                json_object_put(op, "where", where_uuid_equals(&row->uuid));
3466
0
                json_array_add(operations, op);
3467
0
                any_updates = true;
3468
0
            } else {
3469
                /* Let ovsdb-server decide whether to really delete it. */
3470
0
            }
3471
0
        } else if (row->old_datum != row->new_datum) {
3472
0
            struct json *row_json;
3473
0
            size_t idx;
3474
3475
0
            struct json *op = json_object_create();
3476
0
            json_object_put_string(op, "op",
3477
0
                                   row->old_datum ? "update" : "insert");
3478
0
            json_object_put_string(op, "table", class->name);
3479
0
            if (row->old_datum) {
3480
0
                json_object_put(op, "where", where_uuid_equals(&row->uuid));
3481
0
            } else {
3482
0
                struct ovsdb_idl_txn_insert *insert;
3483
3484
0
                any_updates = true;
3485
3486
0
                char *uuid_json;
3487
0
                struct json *value;
3488
0
                if (row->persist_uuid) {
3489
0
                    uuid_json = "uuid";
3490
0
                    value = json_string_create_uuid(&row->uuid);
3491
0
                } else {
3492
0
                    uuid_json = "uuid-name";
3493
0
                    value = json_string_create_nocopy(
3494
0
                                ovsdb_data_row_name(&row->uuid));
3495
0
                }
3496
3497
0
                json_object_put(op, uuid_json, value);
3498
3499
0
                insert = xmalloc(sizeof *insert);
3500
0
                insert->dummy = row->uuid;
3501
0
                insert->op_index = json_array_size(operations) - 1;
3502
0
                uuid_zero(&insert->real);
3503
0
                hmap_insert(&txn->inserted_rows, &insert->hmap_node,
3504
0
                            uuid_hash(&insert->dummy));
3505
0
            }
3506
0
            row_json = json_object_create();
3507
0
            json_object_put(op, "row", row_json);
3508
3509
0
            if (row->written) {
3510
0
                BITMAP_FOR_EACH_1 (idx, class->n_columns, row->written) {
3511
0
                    const struct ovsdb_idl_column *column =
3512
0
                                                        &class->columns[idx];
3513
3514
0
                    if (row->old_datum
3515
0
                        || !ovsdb_datum_is_default(&row->new_datum[idx],
3516
0
                                                  &column->type)) {
3517
0
                        struct json *value;
3518
3519
0
                        value = ovsdb_datum_to_json(&row->new_datum[idx],
3520
0
                                                    &column->type);
3521
0
                        json_object_put(row_json, column->name,
3522
0
                                        substitute_uuids(value, txn));
3523
3524
                        /* If anything really changed, consider it an update.
3525
                         * We can't suppress not-really-changed values earlier
3526
                         * or transactions would become nonatomic (see the big
3527
                         * comment inside ovsdb_idl_txn_write()). */
3528
0
                        if (!any_updates && row->old_datum &&
3529
0
                            !ovsdb_datum_equals(&row->old_datum[idx],
3530
0
                                                &row->new_datum[idx],
3531
0
                                                &column->type)) {
3532
0
                            any_updates = true;
3533
0
                        }
3534
0
                    }
3535
0
                }
3536
0
            }
3537
3538
0
            if (!row->old_datum || !shash_is_empty(json_object(row_json))) {
3539
0
                json_array_add(operations, op);
3540
0
            } else {
3541
0
                json_destroy(op);
3542
0
            }
3543
0
        }
3544
3545
        /* Add mutate operation, for partial map or partial set updates. */
3546
0
        if (row->map_op_written || row->set_op_written) {
3547
0
            struct json *op, *mutations;
3548
0
            bool any_mutations;
3549
3550
0
            op = json_object_create();
3551
0
            json_object_put_string(op, "op", "mutate");
3552
0
            json_object_put_string(op, "table", class->name);
3553
0
            json_object_put(op, "where", where_uuid_equals(&row->uuid));
3554
0
            mutations = json_array_create_empty();
3555
0
            any_mutations = ovsdb_idl_txn_extract_mutations(row, mutations);
3556
0
            json_object_put(op, "mutations", mutations);
3557
3558
0
            if (any_mutations) {
3559
0
                op = substitute_uuids(op, txn);
3560
0
                json_array_add(operations, op);
3561
0
                any_updates = true;
3562
0
            } else {
3563
0
                json_destroy(op);
3564
0
            }
3565
0
        }
3566
0
    }
3567
3568
    /* Add increment. */
3569
0
    if (txn->inc_table && (any_updates || txn->inc_force)) {
3570
0
        any_updates = true;
3571
0
        txn->inc_index = json_array_size(operations) - 1;
3572
3573
0
        struct json *op = json_object_create();
3574
0
        json_object_put_string(op, "op", "mutate");
3575
0
        json_object_put_string(op, "table", txn->inc_table);
3576
0
        json_object_put(op, "where",
3577
0
                        substitute_uuids(where_uuid_equals(&txn->inc_row),
3578
0
                                         txn));
3579
0
        json_object_put(op, "mutations",
3580
0
                        json_array_create_1(
3581
0
                            json_array_create_3(
3582
0
                                json_string_create(txn->inc_column),
3583
0
                                json_string_create("+="),
3584
0
                                json_integer_create(1))));
3585
0
        json_array_add(operations, op);
3586
3587
0
        op = json_object_create();
3588
0
        json_object_put_string(op, "op", "select");
3589
0
        json_object_put_string(op, "table", txn->inc_table);
3590
0
        json_object_put(op, "where",
3591
0
                        substitute_uuids(where_uuid_equals(&txn->inc_row),
3592
0
                                         txn));
3593
0
        json_object_put(op, "columns",
3594
0
                        json_array_create_1(json_string_create(
3595
0
                                                txn->inc_column)));
3596
0
        json_array_add(operations, op);
3597
0
    }
3598
3599
0
    if (txn->comment.length) {
3600
0
        struct json *op = json_object_create();
3601
0
        json_object_put_string(op, "op", "comment");
3602
0
        json_object_put_string(op, "comment", ds_cstr(&txn->comment));
3603
0
        json_array_add(operations, op);
3604
0
    }
3605
3606
0
    if (txn->dry_run) {
3607
0
        struct json *op = json_object_create();
3608
0
        json_object_put_string(op, "op", "abort");
3609
0
        json_array_add(operations, op);
3610
0
    }
3611
3612
0
    if (!any_updates) {
3613
0
        txn->status = TXN_UNCHANGED;
3614
0
        json_destroy(operations);
3615
0
    } else {
3616
0
        txn->request_id = ovsdb_cs_send_transaction(idl->cs, operations);
3617
0
        if (txn->request_id) {
3618
0
            hmap_insert(&idl->outstanding_txns, &txn->hmap_node,
3619
0
                        json_hash(txn->request_id, 0));
3620
0
            txn->status = TXN_INCOMPLETE;
3621
0
        } else {
3622
0
            txn->status = TXN_TRY_AGAIN;
3623
0
        }
3624
0
    }
3625
3626
0
disassemble_out:
3627
0
    ovsdb_idl_txn_disassemble(txn);
3628
0
coverage_out:
3629
0
    switch (txn->status) {
3630
0
    case TXN_UNCOMMITTED:   COVERAGE_INC(txn_uncommitted);    break;
3631
0
    case TXN_UNCHANGED:     COVERAGE_INC(txn_unchanged);      break;
3632
0
    case TXN_INCOMPLETE:    COVERAGE_INC(txn_incomplete);     break;
3633
0
    case TXN_ABORTED:       COVERAGE_INC(txn_aborted);        break;
3634
0
    case TXN_SUCCESS:       COVERAGE_INC(txn_success);        break;
3635
0
    case TXN_TRY_AGAIN:     COVERAGE_INC(txn_try_again);      break;
3636
0
    case TXN_NOT_LOCKED:    COVERAGE_INC(txn_not_locked);     break;
3637
0
    case TXN_ERROR:         COVERAGE_INC(txn_error);          break;
3638
0
    }
3639
3640
0
    return txn->status;
3641
0
}
3642
3643
/* Attempts to commit 'txn', blocking until the commit either succeeds or
3644
 * fails.  Returns the final commit status, which may be any TXN_* value other
3645
 * than TXN_INCOMPLETE.
3646
 *
3647
 * This function calls ovsdb_idl_run() on 'txn''s IDL, so it may cause the
3648
 * return value of ovsdb_idl_get_seqno() to change. */
3649
enum ovsdb_idl_txn_status
3650
ovsdb_idl_txn_commit_block(struct ovsdb_idl_txn *txn)
3651
0
{
3652
0
    enum ovsdb_idl_txn_status status;
3653
3654
0
    fatal_signal_run();
3655
0
    while ((status = ovsdb_idl_txn_commit(txn)) == TXN_INCOMPLETE) {
3656
0
        ovsdb_idl_run(txn->idl);
3657
0
        ovsdb_idl_wait(txn->idl);
3658
0
        ovsdb_idl_txn_wait(txn);
3659
0
        poll_block();
3660
0
    }
3661
0
    return status;
3662
0
}
3663
3664
/* Returns the final (incremented) value of the column in 'txn' that was set to
3665
 * be incremented by ovsdb_idl_txn_increment().  'txn' must have committed
3666
 * successfully. */
3667
int64_t
3668
ovsdb_idl_txn_get_increment_new_value(const struct ovsdb_idl_txn *txn)
3669
0
{
3670
0
    ovs_assert(txn->status == TXN_SUCCESS);
3671
0
    return txn->inc_new_value;
3672
0
}
3673
3674
/* Aborts 'txn' without sending it to the database server.  This is effective
3675
 * only if ovsdb_idl_txn_commit() has not yet been called for 'txn'.
3676
 * Otherwise, it has no effect.
3677
 *
3678
 * Aborting a transaction doesn't free its memory.  Use
3679
 * ovsdb_idl_txn_destroy() to do that. */
3680
void
3681
ovsdb_idl_txn_abort(struct ovsdb_idl_txn *txn)
3682
0
{
3683
0
    ovsdb_idl_txn_disassemble(txn);
3684
0
    if (txn->status == TXN_UNCOMMITTED || txn->status == TXN_INCOMPLETE) {
3685
0
        txn->status = TXN_ABORTED;
3686
0
    }
3687
0
}
3688
3689
/* If 'assert' is true, configures the IDL to generate an assertion
3690
 * failure when a write operation is attempted on the transaction.
3691
 * Otherwise, write operations are allowed on the transaction.
3692
 * The check will turn into no-op when building with NDEBUG. */
3693
void
3694
ovsdb_idl_txn_assert_read_only(struct ovsdb_idl_txn *txn, bool assert)
3695
0
{
3696
0
    if (txn) {
3697
0
        txn->assert_read_only = assert;
3698
0
    }
3699
0
}
3700
3701
/* Returns a string that reports the error status for 'txn'.  The caller must
3702
 * not modify or free the returned string.  A call to ovsdb_idl_txn_destroy()
3703
 * for 'txn' may free the returned string.
3704
 *
3705
 * The return value is ordinarily one of the strings that
3706
 * ovsdb_idl_txn_status_to_string() would return, but if the transaction failed
3707
 * due to an error reported by the database server, the return value is that
3708
 * error. */
3709
const char *
3710
ovsdb_idl_txn_get_error(const struct ovsdb_idl_txn *txn)
3711
0
{
3712
0
    if (txn->status != TXN_ERROR) {
3713
0
        return ovsdb_idl_txn_status_to_string(txn->status);
3714
0
    } else if (txn->error) {
3715
0
        return txn->error;
3716
0
    } else {
3717
0
        return "no error details available";
3718
0
    }
3719
0
}
3720
3721
static void
3722
ovsdb_idl_txn_set_error_json(struct ovsdb_idl_txn *txn,
3723
                             const struct json *json)
3724
0
{
3725
0
    if (json && txn->error == NULL) {
3726
0
        txn->error = json_to_string(json, JSSF_SORT);
3727
0
    }
3728
0
}
3729
3730
/* For transaction 'txn' that completed successfully, finds and returns the
3731
 * permanent UUID that the database assigned to a newly inserted row, given the
3732
 * 'uuid' that ovsdb_idl_txn_insert() assigned locally to that row.
3733
 *
3734
 * Returns NULL if 'uuid' is not a UUID assigned by ovsdb_idl_txn_insert() or
3735
 * if it was assigned by that function and then deleted by
3736
 * ovsdb_idl_txn_delete() within the same transaction.  (Rows that are inserted
3737
 * and then deleted within a single transaction are never sent to the database
3738
 * server, so it never assigns them a permanent UUID.) */
3739
const struct uuid *
3740
ovsdb_idl_txn_get_insert_uuid(const struct ovsdb_idl_txn *txn,
3741
                              const struct uuid *uuid)
3742
0
{
3743
0
    const struct ovsdb_idl_txn_insert *insert;
3744
3745
0
    ovs_assert(txn->status == TXN_SUCCESS || txn->status == TXN_UNCHANGED);
3746
0
    HMAP_FOR_EACH_IN_BUCKET (insert, hmap_node,
3747
0
                             uuid_hash(uuid), &txn->inserted_rows) {
3748
0
        if (uuid_equals(uuid, &insert->dummy)) {
3749
0
            return &insert->real;
3750
0
        }
3751
0
    }
3752
0
    return NULL;
3753
0
}
3754
3755
static void
3756
ovsdb_idl_txn_complete(struct ovsdb_idl_txn *txn,
3757
                       enum ovsdb_idl_txn_status status)
3758
0
{
3759
0
    txn->status = status;
3760
0
    hmap_remove(&txn->idl->outstanding_txns, &txn->hmap_node);
3761
0
}
3762
3763
static void
3764
ovsdb_idl_txn_write__(const struct ovsdb_idl_row *row_,
3765
                      const struct ovsdb_idl_column *column,
3766
                      struct ovsdb_datum *datum, bool owns_datum)
3767
0
{
3768
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
3769
0
    const struct ovsdb_idl_table_class *class;
3770
0
    unsigned char column_mode;
3771
0
    bool optimize_rewritten;
3772
0
    size_t column_idx;
3773
0
    bool write_only;
3774
3775
0
    ovs_assert(!column->is_synthetic);
3776
0
    if (ovsdb_idl_row_is_synthetic(row)) {
3777
0
        goto discard_datum;
3778
0
    }
3779
3780
0
    class = row->table->class_;
3781
0
    column_idx = column - class->columns;
3782
0
    column_mode = row->table->modes[column_idx];
3783
0
    write_only = column_mode == OVSDB_IDL_MONITOR;
3784
0
    optimize_rewritten =
3785
0
        write_only || (column_mode & OVSDB_IDL_WRITE_CHANGED_ONLY);
3786
3787
3788
0
    ovs_assert(row->new_datum != NULL);
3789
0
    ovs_assert(column_idx < class->n_columns);
3790
0
    ovs_assert(row->old_datum == NULL || column_mode & OVSDB_IDL_MONITOR);
3791
0
    ovs_assert(!row->table->idl->txn->assert_read_only);
3792
3793
0
    if (row->table->idl->verify_write_only && !write_only) {
3794
0
        VLOG_ERR("Bug: Attempt to write to a read/write column (%s:%s) when"
3795
0
                 " explicitly configured not to.", class->name, column->name);
3796
0
        goto discard_datum;
3797
0
    }
3798
3799
    /* If this is a write-only column and the datum being written is the same
3800
     * as the one already there, just skip the update entirely.  This is worth
3801
     * optimizing because we have a lot of columns that get periodically
3802
     * refreshed into the database but don't actually change that often.
3803
     *
3804
     * We don't do this for read/write columns because that would break
3805
     * atomicity of transactions--some other client might have written a
3806
     * different value in that column since we read it.  (But if a whole
3807
     * transaction only does writes of existing values, without making any real
3808
     * changes, we will drop the whole transaction later in
3809
     * ovsdb_idl_txn_commit().)
3810
     *
3811
     * The application may choose to bypass this restriction and always
3812
     * optimize by setting OVSDB_IDL_WRITE_CHANGED_ONLY.
3813
     */
3814
0
    if (optimize_rewritten && ovsdb_datum_equals(ovsdb_idl_read(row, column),
3815
0
                                                 datum, &column->type)) {
3816
0
        goto discard_datum;
3817
0
    }
3818
3819
0
    bool index_row = is_index_row(row);
3820
0
    if (!index_row) {
3821
0
        ovsdb_idl_remove_from_indexes(row);
3822
0
    }
3823
0
    if (hmap_node_is_null(&row->txn_node)) {
3824
0
        hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
3825
0
                    uuid_hash(&row->uuid));
3826
0
    }
3827
0
    if (row->old_datum == row->new_datum) {
3828
0
        row->new_datum = xmalloc(class->n_columns * sizeof *row->new_datum);
3829
0
    }
3830
0
    if (!row->written) {
3831
0
        row->written = bitmap_allocate(class->n_columns);
3832
0
    }
3833
0
    if (bitmap_is_set(row->written, column_idx)) {
3834
0
        ovsdb_datum_destroy(&row->new_datum[column_idx], &column->type);
3835
0
    } else {
3836
0
        bitmap_set1(row->written, column_idx);
3837
0
    }
3838
0
    if (owns_datum) {
3839
0
        row->new_datum[column_idx] = *datum;
3840
0
    } else {
3841
0
        ovsdb_datum_clone(&row->new_datum[column_idx], datum);
3842
0
    }
3843
0
    (column->unparse)(row);
3844
0
    (column->parse)(row, &row->new_datum[column_idx]);
3845
0
    row->parsed = true;
3846
0
    if (!index_row) {
3847
0
        ovsdb_idl_add_to_indexes(row);
3848
0
    }
3849
0
    return;
3850
3851
0
discard_datum:
3852
0
    if (owns_datum) {
3853
0
        ovsdb_datum_destroy(datum, &column->type);
3854
0
    }
3855
0
}
3856
3857
/* Writes 'datum' to the specified 'column' in 'row_'.  Updates both 'row_'
3858
 * itself and the structs derived from it (e.g. the "struct ovsrec_*", for
3859
 * ovs-vswitchd).
3860
 *
3861
 * 'datum' must have the correct type for its column, but it needs not be
3862
 * sorted or unique because this function will take care of that.  The IDL does
3863
 * not check that it meets schema constraints, but ovsdb-server will do so at
3864
 * commit time so it had better be correct.
3865
 *
3866
 * A transaction must be in progress.  Replication of 'column' must not have
3867
 * been disabled (by calling ovsdb_idl_omit()).
3868
 *
3869
 * Usually this function is used indirectly through one of the "set" functions
3870
 * generated by ovsdb-idlc.
3871
 *
3872
 * Takes ownership of what 'datum' points to (and in some cases destroys that
3873
 * data before returning) but makes a copy of 'datum' itself.  (Commonly
3874
 * 'datum' is on the caller's stack.) */
3875
void
3876
ovsdb_idl_txn_write(const struct ovsdb_idl_row *row,
3877
                    const struct ovsdb_idl_column *column,
3878
                    struct ovsdb_datum *datum)
3879
0
{
3880
0
    ovsdb_datum_sort_unique(datum, &column->type);
3881
0
    ovsdb_idl_txn_write__(row, column, datum, true);
3882
0
}
3883
3884
/* Similar to ovsdb_idl_txn_write(), except:
3885
 *
3886
 *     - The caller retains ownership of 'datum' and what it points to.
3887
 *
3888
 *     - The caller must ensure that 'datum' is sorted and unique (e.g. via
3889
 *       ovsdb_datum_sort_unique().) */
3890
void
3891
ovsdb_idl_txn_write_clone(const struct ovsdb_idl_row *row,
3892
                          const struct ovsdb_idl_column *column,
3893
                          const struct ovsdb_datum *datum)
3894
0
{
3895
0
    ovsdb_idl_txn_write__(row, column,
3896
0
                          CONST_CAST(struct ovsdb_datum *, datum), false);
3897
0
}
3898
3899
/* Causes the original contents of 'column' in 'row_' to be verified as a
3900
 * prerequisite to completing the transaction.  That is, if 'column' in 'row_'
3901
 * changed (or if 'row_' was deleted) between the time that the IDL originally
3902
 * read its contents and the time that the transaction commits, then the
3903
 * transaction aborts and ovsdb_idl_txn_commit() returns TXN_TRY_AGAIN.
3904
 *
3905
 * The intention is that, to ensure that no transaction commits based on dirty
3906
 * reads, an application should call ovsdb_idl_txn_verify() on each data item
3907
 * read as part of a read-modify-write operation.
3908
 *
3909
 * In some cases ovsdb_idl_txn_verify() reduces to a no-op, because the current
3910
 * value of 'column' is already known:
3911
 *
3912
 *   - If 'row_' is a row created by the current transaction (returned by
3913
 *     ovsdb_idl_txn_insert()).
3914
 *
3915
 *   - If 'column' has already been modified (with ovsdb_idl_txn_write())
3916
 *     within the current transaction.
3917
 *
3918
 * Because of the latter property, always call ovsdb_idl_txn_verify() *before*
3919
 * ovsdb_idl_txn_write() for a given read-modify-write.
3920
 *
3921
 * A transaction must be in progress.
3922
 *
3923
 * Usually this function is used indirectly through one of the "verify"
3924
 * functions generated by ovsdb-idlc. */
3925
void
3926
ovsdb_idl_txn_verify(const struct ovsdb_idl_row *row_,
3927
                     const struct ovsdb_idl_column *column)
3928
0
{
3929
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
3930
0
    const struct ovsdb_idl_table_class *class;
3931
0
    size_t column_idx;
3932
3933
0
    if (ovsdb_idl_row_is_synthetic(row)) {
3934
0
        return;
3935
0
    }
3936
3937
0
    class = row->table->class_;
3938
0
    column_idx = column - class->columns;
3939
3940
0
    ovs_assert(row->new_datum != NULL);
3941
0
    ovs_assert(row->old_datum == NULL ||
3942
0
               row->table->modes[column_idx] & OVSDB_IDL_MONITOR);
3943
0
    if (!row->old_datum
3944
0
        || (row->written && bitmap_is_set(row->written, column_idx))) {
3945
0
        return;
3946
0
    }
3947
3948
0
    if (hmap_node_is_null(&row->txn_node)) {
3949
0
        hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
3950
0
                    uuid_hash(&row->uuid));
3951
0
    }
3952
0
    if (!row->prereqs) {
3953
0
        row->prereqs = bitmap_allocate(class->n_columns);
3954
0
    }
3955
0
    bitmap_set1(row->prereqs, column_idx);
3956
0
}
3957
3958
/* Deletes 'row_' from its table.  May free 'row_', so it must not be
3959
 * accessed afterward.
3960
 *
3961
 * A transaction must be in progress.
3962
 *
3963
 * Usually this function is used indirectly through one of the "delete"
3964
 * functions generated by ovsdb-idlc. */
3965
void
3966
ovsdb_idl_txn_delete(const struct ovsdb_idl_row *row_)
3967
0
{
3968
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
3969
3970
0
    if (ovsdb_idl_row_is_synthetic(row)) {
3971
0
        return;
3972
0
    }
3973
3974
0
    ovs_assert(row->new_datum != NULL);
3975
0
    ovs_assert(!is_index_row(row_));
3976
0
    ovs_assert(!row->table->idl->txn->assert_read_only);
3977
0
    ovsdb_idl_remove_from_indexes(row_);
3978
0
    if (!row->old_datum) {
3979
0
        ovsdb_idl_row_unparse(row);
3980
0
        ovsdb_idl_destroy_all_map_op_lists(row);
3981
0
        ovsdb_idl_destroy_all_set_op_lists(row);
3982
0
        ovsdb_idl_row_clear_new(row);
3983
0
        ovs_assert(!row->prereqs);
3984
0
        hmap_remove(&row->table->rows, &row->hmap_node);
3985
0
        hmap_remove(&row->table->idl->txn->txn_rows, &row->txn_node);
3986
0
        free(row);
3987
0
        return;
3988
0
    }
3989
0
    if (hmap_node_is_null(&row->txn_node)) {
3990
0
        hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
3991
0
                    uuid_hash(&row->uuid));
3992
0
    }
3993
0
    ovsdb_idl_row_clear_new(row);
3994
0
    row->new_datum = NULL;
3995
0
}
3996
3997
static const struct ovsdb_idl_row *
3998
ovsdb_idl_txn_insert__(struct ovsdb_idl_txn *txn,
3999
                       const struct ovsdb_idl_table_class *class,
4000
                       const struct uuid *uuid,
4001
                       bool persist_uuid)
4002
0
{
4003
0
    struct ovsdb_idl_row *row = ovsdb_idl_row_create__(class);
4004
4005
0
    ovs_assert(uuid || !persist_uuid);
4006
0
    ovs_assert(!txn->assert_read_only);
4007
0
    if (uuid) {
4008
0
        ovs_assert(!ovsdb_idl_txn_get_row(txn, uuid));
4009
0
        row->uuid = *uuid;
4010
0
    } else {
4011
0
        uuid_generate(&row->uuid);
4012
0
    }
4013
0
    row->persist_uuid = persist_uuid;
4014
0
    row->table = ovsdb_idl_table_from_class(txn->idl, class);
4015
0
    row->new_datum = xmalloc(class->n_columns * sizeof *row->new_datum);
4016
0
    hmap_insert(&row->table->rows, &row->hmap_node, uuid_hash(&row->uuid));
4017
0
    hmap_insert(&txn->txn_rows, &row->txn_node, uuid_hash(&row->uuid));
4018
0
    ovsdb_idl_add_to_indexes(row);
4019
4020
0
    return row;
4021
0
}
4022
4023
/* Inserts and returns a new row in the table with the specified 'class' in the
4024
 * database with open transaction 'txn'.
4025
 *
4026
 * The new row is assigned a provisional UUID.  If 'uuid' is null then one is
4027
 * randomly generated; otherwise 'uuid' should specify a randomly generated
4028
 * UUID not otherwise in use.  ovsdb-server will assign a different UUID when
4029
 * 'txn' is committed, but the IDL will replace any uses of the provisional
4030
 * UUID in the data to be to be committed by the UUID assigned by
4031
 * ovsdb-server.
4032
 *
4033
 * Usually this function is used indirectly through one of the "insert"
4034
 * functions generated by ovsdb-idlc. */
4035
const struct ovsdb_idl_row *
4036
ovsdb_idl_txn_insert(struct ovsdb_idl_txn *txn,
4037
                     const struct ovsdb_idl_table_class *class,
4038
                     const struct uuid *uuid)
4039
0
{
4040
0
    return ovsdb_idl_txn_insert__(txn, class, uuid, false);
4041
0
}
4042
4043
/* Inserts and returns a new row in the table with the specified 'class' in the
4044
 * database with open transaction 'txn'.
4045
 *
4046
 * The new row is assigned the specified UUID (which cannot be null).
4047
 *
4048
 * Usually this function is used indirectly through one of the
4049
 * "insert_persist_uuid" functions generated by ovsdb-idlc. */
4050
const struct ovsdb_idl_row *
4051
ovsdb_idl_txn_insert_persist_uuid(struct ovsdb_idl_txn *txn,
4052
                                  const struct ovsdb_idl_table_class *class,
4053
                                  const struct uuid *uuid)
4054
0
{
4055
0
    ovs_assert(uuid);
4056
0
    return ovsdb_idl_txn_insert__(txn, class, uuid, true);
4057
0
}
4058
4059
static void
4060
ovsdb_idl_txn_abort_all(struct ovsdb_idl *idl)
4061
0
{
4062
0
    struct ovsdb_idl_txn *txn;
4063
4064
0
    HMAP_FOR_EACH (txn, hmap_node, &idl->outstanding_txns) {
4065
0
        ovsdb_idl_txn_complete(txn, TXN_TRY_AGAIN);
4066
0
    }
4067
0
}
4068
4069
static struct ovsdb_idl_txn *
4070
ovsdb_idl_txn_find(struct ovsdb_idl *idl, const struct json *id)
4071
0
{
4072
0
    struct ovsdb_idl_txn *txn;
4073
4074
0
    HMAP_FOR_EACH_WITH_HASH (txn, hmap_node,
4075
0
                             json_hash(id, 0), &idl->outstanding_txns) {
4076
0
        if (json_equal(id, txn->request_id)) {
4077
0
            return txn;
4078
0
        }
4079
0
    }
4080
0
    return NULL;
4081
0
}
4082
4083
static bool
4084
check_json_type(const struct json *json, enum json_type type, const char *name)
4085
0
{
4086
0
    if (!json) {
4087
0
        VLOG_WARN_RL(&syntax_rl, "%s is missing", name);
4088
0
        return false;
4089
0
    } else if (json->type != type) {
4090
0
        VLOG_WARN_RL(&syntax_rl, "%s is %s instead of %s",
4091
0
                     name, json_type_to_string(json->type),
4092
0
                     json_type_to_string(type));
4093
0
        return false;
4094
0
    } else {
4095
0
        return true;
4096
0
    }
4097
0
}
4098
4099
static bool
4100
ovsdb_idl_txn_process_inc_reply(struct ovsdb_idl_txn *txn,
4101
                                const struct json *results)
4102
0
{
4103
0
    const struct json *count, *rows, *row, *column;
4104
0
    struct shash *mutate, *select;
4105
4106
0
    if (txn->inc_index + 2 > json_array_size(results)) {
4107
0
        VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
4108
0
                     "for increment (has %"PRIuSIZE", needs %u)",
4109
0
                     json_array_size(results), txn->inc_index + 2);
4110
0
        return false;
4111
0
    }
4112
4113
    /* We know that this is a JSON object because the loop in
4114
     * ovsdb_idl_txn_process_reply() checked. */
4115
0
    mutate = json_object(json_array_at(results, txn->inc_index));
4116
0
    count = shash_find_data(mutate, "count");
4117
0
    if (!check_json_type(count, JSON_INTEGER, "\"mutate\" reply \"count\"")) {
4118
0
        return false;
4119
0
    }
4120
0
    if (count->integer != 1) {
4121
0
        VLOG_WARN_RL(&syntax_rl,
4122
0
                     "\"mutate\" reply \"count\" is %lld instead of 1",
4123
0
                     count->integer);
4124
0
        return false;
4125
0
    }
4126
4127
0
    select = json_object(json_array_at(results, txn->inc_index + 1));
4128
0
    rows = shash_find_data(select, "rows");
4129
0
    if (!check_json_type(rows, JSON_ARRAY, "\"select\" reply \"rows\"")) {
4130
0
        return false;
4131
0
    }
4132
0
    if (json_array_size(rows) != 1) {
4133
0
        VLOG_WARN_RL(&syntax_rl, "\"select\" reply \"rows\" has %"PRIuSIZE" elements "
4134
0
                     "instead of 1",
4135
0
                     json_array_size(rows));
4136
0
        return false;
4137
0
    }
4138
0
    row = json_array_at(rows, 0);
4139
0
    if (!check_json_type(row, JSON_OBJECT, "\"select\" reply row")) {
4140
0
        return false;
4141
0
    }
4142
0
    column = shash_find_data(json_object(row), txn->inc_column);
4143
0
    if (!check_json_type(column, JSON_INTEGER,
4144
0
                         "\"select\" reply inc column")) {
4145
0
        return false;
4146
0
    }
4147
0
    txn->inc_new_value = column->integer;
4148
0
    return true;
4149
0
}
4150
4151
static bool
4152
ovsdb_idl_txn_process_insert_reply(struct ovsdb_idl_txn_insert *insert,
4153
                                   const struct json *results)
4154
0
{
4155
0
    static const struct ovsdb_base_type uuid_type = OVSDB_BASE_UUID_INIT;
4156
0
    struct ovsdb_error *error;
4157
0
    struct json *json_uuid;
4158
0
    union ovsdb_atom uuid;
4159
0
    struct shash *reply;
4160
4161
0
    if (insert->op_index >= json_array_size(results)) {
4162
0
        VLOG_WARN_RL(&syntax_rl, "reply does not contain enough operations "
4163
0
                     "for insert (has %"PRIuSIZE", needs %u)",
4164
0
                     json_array_size(results), insert->op_index);
4165
0
        return false;
4166
0
    }
4167
4168
    /* We know that this is a JSON object because the loop in
4169
     * ovsdb_idl_txn_process_reply() checked. */
4170
0
    reply = json_object(json_array_at(results, insert->op_index));
4171
0
    json_uuid = shash_find_data(reply, "uuid");
4172
0
    if (!check_json_type(json_uuid, JSON_ARRAY, "\"insert\" reply \"uuid\"")) {
4173
0
        return false;
4174
0
    }
4175
4176
0
    error = ovsdb_atom_from_json(&uuid, &uuid_type, json_uuid, NULL);
4177
0
    if (error) {
4178
0
        char *s = ovsdb_error_to_string_free(error);
4179
0
        VLOG_WARN_RL(&syntax_rl, "\"insert\" reply \"uuid\" is not a JSON "
4180
0
                     "UUID: %s", s);
4181
0
        free(s);
4182
0
        return false;
4183
0
    }
4184
4185
0
    insert->real = uuid.uuid;
4186
4187
0
    return true;
4188
0
}
4189
4190
static void
4191
ovsdb_idl_txn_process_reply(struct ovsdb_idl *idl,
4192
                            const struct jsonrpc_msg *msg)
4193
0
{
4194
0
    struct ovsdb_idl_txn *txn = ovsdb_idl_txn_find(idl, msg->id);
4195
0
    if (!txn) {
4196
0
        return;
4197
0
    }
4198
4199
0
    enum ovsdb_idl_txn_status status;
4200
0
    if (msg->type == JSONRPC_ERROR) {
4201
0
        if (msg->error
4202
0
            && msg->error->type == JSON_STRING
4203
0
            && !strcmp(json_string(msg->error), "canceled")) {
4204
            /* ovsdb-server uses this error message to indicate that the
4205
            * transaction was canceled because the database in question was
4206
            * removed, converted, etc. */
4207
0
            status = TXN_TRY_AGAIN;
4208
0
        } else {
4209
0
            status = TXN_ERROR;
4210
0
            ovsdb_idl_txn_set_error_json(txn, msg->error);
4211
0
        }
4212
0
    } else if (msg->result->type != JSON_ARRAY) {
4213
0
        VLOG_WARN_RL(&syntax_rl, "reply to \"transact\" is not JSON array");
4214
0
        status = TXN_ERROR;
4215
0
        ovsdb_idl_txn_set_error_json(txn, msg->result);
4216
0
    } else {
4217
0
        const struct json *ops = msg->result;
4218
0
        int hard_errors = 0;
4219
0
        int soft_errors = 0;
4220
0
        int lock_errors = 0;
4221
0
        size_t i, n;
4222
4223
0
        n = json_array_size(ops);
4224
0
        for (i = 0; i < n; i++) {
4225
0
            const struct json *op = json_array_at(ops, i);
4226
4227
0
            if (op->type == JSON_NULL) {
4228
                /* This isn't an error in itself but indicates that some prior
4229
                 * operation failed, so make sure that we know about it. */
4230
0
                soft_errors++;
4231
0
            } else if (op->type == JSON_OBJECT) {
4232
0
                struct json *error;
4233
4234
0
                error = shash_find_data(json_object(op), "error");
4235
0
                if (error) {
4236
0
                    if (error->type == JSON_STRING) {
4237
0
                        const char *error_string = json_string(error);
4238
4239
0
                        if (!strcmp(error_string, "timed out")) {
4240
0
                            soft_errors++;
4241
0
                        } else if (!strcmp(error_string,
4242
0
                                           "unknown database")) {
4243
0
                            ovsdb_cs_flag_inconsistency(idl->cs);
4244
0
                            soft_errors++;
4245
0
                        } else if (!strcmp(error_string, "not owner")) {
4246
0
                            lock_errors++;
4247
0
                        } else if (!strcmp(error_string, "not allowed")) {
4248
0
                            hard_errors++;
4249
0
                            ovsdb_idl_txn_set_error_json(txn, op);
4250
0
                        } else if (strcmp(error_string, "aborted")) {
4251
0
                            hard_errors++;
4252
0
                            ovsdb_idl_txn_set_error_json(txn, op);
4253
0
                            VLOG_WARN_RL(&other_rl,
4254
0
                                         "transaction error: %s", txn->error);
4255
0
                        }
4256
0
                    } else {
4257
0
                        hard_errors++;
4258
0
                        ovsdb_idl_txn_set_error_json(txn, op);
4259
0
                        VLOG_WARN_RL(&syntax_rl,
4260
0
                                     "\"error\" in reply is not JSON string");
4261
0
                    }
4262
0
                }
4263
0
            } else {
4264
0
                hard_errors++;
4265
0
                ovsdb_idl_txn_set_error_json(txn, op);
4266
0
                VLOG_WARN_RL(&syntax_rl,
4267
0
                             "operation reply is not JSON null or object");
4268
0
            }
4269
0
        }
4270
4271
0
        if (!soft_errors && !hard_errors && !lock_errors) {
4272
0
            struct ovsdb_idl_txn_insert *insert;
4273
4274
0
            if (txn->inc_table && !ovsdb_idl_txn_process_inc_reply(txn, ops)) {
4275
0
                hard_errors++;
4276
0
            }
4277
4278
0
            HMAP_FOR_EACH (insert, hmap_node, &txn->inserted_rows) {
4279
0
                if (!ovsdb_idl_txn_process_insert_reply(insert, ops)) {
4280
0
                    hard_errors++;
4281
0
                }
4282
0
            }
4283
0
        }
4284
4285
0
        status = (hard_errors ? TXN_ERROR
4286
0
                  : lock_errors ? TXN_NOT_LOCKED
4287
0
                  : soft_errors ? TXN_TRY_AGAIN
4288
0
                  : TXN_SUCCESS);
4289
0
    }
4290
4291
0
    ovsdb_idl_txn_complete(txn, status);
4292
0
}
4293
4294
/* Returns the transaction currently active for 'row''s IDL.  A transaction
4295
 * must currently be active. */
4296
struct ovsdb_idl_txn *
4297
ovsdb_idl_txn_get(const struct ovsdb_idl_row *row)
4298
0
{
4299
0
    struct ovsdb_idl_txn *txn = row->table->idl->txn;
4300
0
    ovs_assert(txn != NULL);
4301
0
    return txn;
4302
0
}
4303
4304
/* Returns the IDL on which 'txn' acts. */
4305
struct ovsdb_idl *
4306
ovsdb_idl_txn_get_idl (struct ovsdb_idl_txn *txn)
4307
0
{
4308
0
    return txn->idl;
4309
0
}
4310
4311
/* Blocks until 'idl' successfully connects to the remote database and
4312
 * retrieves its contents. */
4313
void
4314
ovsdb_idl_get_initial_snapshot(struct ovsdb_idl *idl)
4315
0
{
4316
0
    while (1) {
4317
0
        ovsdb_idl_run(idl);
4318
0
        if (ovsdb_idl_has_ever_connected(idl)) {
4319
0
            return;
4320
0
        }
4321
0
        ovsdb_idl_wait(idl);
4322
0
        poll_block();
4323
0
    }
4324
0
}
4325

4326
/* If 'lock_name' is nonnull, configures 'idl' to obtain the named lock from
4327
 * the database server and to avoid modifying the database when the lock cannot
4328
 * be acquired (that is, when another client has the same lock).
4329
 *
4330
 * If 'lock_name' is NULL, drops the locking requirement and releases the
4331
 * lock. */
4332
void
4333
ovsdb_idl_set_lock(struct ovsdb_idl *idl, const char *lock_name)
4334
0
{
4335
0
    ovsdb_cs_set_lock(idl->cs, lock_name);
4336
0
}
4337
4338
/* Returns true if 'idl' is configured to obtain a lock and owns that lock.
4339
 *
4340
 * Locking and unlocking happens asynchronously from the database client's
4341
 * point of view, so the information is only useful for optimization (e.g. if
4342
 * the client doesn't have the lock then there's no point in trying to write to
4343
 * the database). */
4344
bool
4345
ovsdb_idl_has_lock(const struct ovsdb_idl *idl)
4346
0
{
4347
0
    return ovsdb_cs_has_lock(idl->cs);
4348
0
}
4349
4350
/* Returns true if 'idl' is configured to obtain a lock but the database server
4351
 * has indicated that some other client already owns the requested lock. */
4352
bool
4353
ovsdb_idl_is_lock_contended(const struct ovsdb_idl *idl)
4354
0
{
4355
0
    return ovsdb_cs_is_lock_contended(idl->cs);
4356
0
}
4357
4358
/* Inserts a new Map Operation into current transaction. */
4359
static void
4360
ovsdb_idl_txn_add_map_op(struct ovsdb_idl_row *row,
4361
                         const struct ovsdb_idl_column *column,
4362
                         struct ovsdb_datum *datum,
4363
                         enum map_op_type op_type)
4364
0
{
4365
0
    ovs_assert(!row->table->idl->txn->assert_read_only);
4366
4367
0
    const struct ovsdb_idl_table_class *class;
4368
0
    size_t column_idx;
4369
0
    struct map_op *map_op;
4370
4371
0
    class = row->table->class_;
4372
0
    column_idx = column - class->columns;
4373
4374
    /* Check if a map operation list exists for this column. */
4375
0
    if (!row->map_op_written) {
4376
0
        row->map_op_written = bitmap_allocate(class->n_columns);
4377
0
        row->map_op_lists = xzalloc(class->n_columns *
4378
0
                                    sizeof *row->map_op_lists);
4379
0
    }
4380
0
    if (!row->map_op_lists[column_idx]) {
4381
0
        row->map_op_lists[column_idx] = map_op_list_create();
4382
0
    }
4383
4384
    /* Add a map operation to the corresponding list. */
4385
0
    map_op = map_op_create(datum, op_type);
4386
0
    bitmap_set1(row->map_op_written, column_idx);
4387
0
    map_op_list_add(row->map_op_lists[column_idx], map_op, &column->type);
4388
4389
    /* Add this row to transaction's list of rows. */
4390
0
    if (hmap_node_is_null(&row->txn_node)) {
4391
0
        hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
4392
0
                    uuid_hash(&row->uuid));
4393
0
    }
4394
0
}
4395
4396
/* Inserts a new Set Operation into current transaction. */
4397
static void
4398
ovsdb_idl_txn_add_set_op(struct ovsdb_idl_row *row,
4399
                         const struct ovsdb_idl_column *column,
4400
                         struct ovsdb_datum *datum,
4401
                         enum set_op_type op_type)
4402
0
{
4403
0
    ovs_assert(!row->table->idl->txn->assert_read_only);
4404
4405
0
    const struct ovsdb_idl_table_class *class;
4406
0
    size_t column_idx;
4407
0
    struct set_op *set_op;
4408
4409
0
    class = row->table->class_;
4410
0
    column_idx = column - class->columns;
4411
4412
    /* Check if a set operation list exists for this column. */
4413
0
    if (!row->set_op_written) {
4414
0
        row->set_op_written = bitmap_allocate(class->n_columns);
4415
0
        row->set_op_lists = xzalloc(class->n_columns *
4416
0
                                    sizeof *row->set_op_lists);
4417
0
    }
4418
0
    if (!row->set_op_lists[column_idx]) {
4419
0
        row->set_op_lists[column_idx] = set_op_list_create();
4420
0
    }
4421
4422
    /* Add a set operation to the corresponding list. */
4423
0
    set_op = set_op_create(datum, op_type);
4424
0
    bitmap_set1(row->set_op_written, column_idx);
4425
0
    set_op_list_add(row->set_op_lists[column_idx], set_op, &column->type);
4426
4427
    /* Add this row to the transactions's list of rows. */
4428
0
    if (hmap_node_is_null(&row->txn_node)) {
4429
0
        hmap_insert(&row->table->idl->txn->txn_rows, &row->txn_node,
4430
0
                    uuid_hash(&row->uuid));
4431
0
    }
4432
0
}
4433
4434
static bool
4435
is_valid_partial_update(const struct ovsdb_idl_row *row,
4436
                        const struct ovsdb_idl_column *column,
4437
                        struct ovsdb_datum *datum)
4438
0
{
4439
    /* Verify that this column is being monitored. */
4440
0
    unsigned int column_idx = column - row->table->class_->columns;
4441
0
    if (!(row->table->modes[column_idx] & OVSDB_IDL_MONITOR)) {
4442
0
        VLOG_WARN("cannot partially update non-monitored column");
4443
0
        return false;
4444
0
    }
4445
4446
    /* Verify that the update affects a single element. */
4447
0
    if (datum->n != 1) {
4448
0
        VLOG_WARN("invalid datum for partial update");
4449
0
        return false;
4450
0
    }
4451
4452
0
    return true;
4453
0
}
4454
4455
/* Inserts the value described in 'datum' into the map in 'column' in
4456
 * 'row_'. If the value doesn't already exist in 'column' then it's value
4457
 * is added.  The value in 'datum' must be of the same type as the values
4458
 * in 'column'.  This function takes ownership of 'datum'.
4459
 *
4460
 * Usually this function is used indirectly through one of the "update"
4461
 * functions generated by vswitch-idl. */
4462
void
4463
ovsdb_idl_txn_write_partial_set(const struct ovsdb_idl_row *row_,
4464
                                const struct ovsdb_idl_column *column,
4465
                                struct ovsdb_datum *datum)
4466
0
{
4467
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
4468
0
    enum set_op_type op_type;
4469
4470
0
    if (!is_valid_partial_update(row, column, datum)) {
4471
0
        ovsdb_datum_destroy(datum, &column->type);
4472
0
        free(datum);
4473
0
        return;
4474
0
    }
4475
4476
0
    op_type = SET_OP_INSERT;
4477
4478
0
    ovsdb_idl_txn_add_set_op(row, column, datum, op_type);
4479
0
}
4480
4481
/* Deletes the value specified in 'datum' from the set in 'column' in 'row_'.
4482
 * The value in 'datum' must be of the same type as the keys in 'column'.
4483
 * This function takes ownership of 'datum'.
4484
 *
4485
 * Usually this function is used indirectly through one of the "update"
4486
 * functions generated by vswitch-idl. */
4487
void
4488
ovsdb_idl_txn_delete_partial_set(const struct ovsdb_idl_row *row_,
4489
                                 const struct ovsdb_idl_column *column,
4490
                                 struct ovsdb_datum *datum)
4491
0
{
4492
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
4493
4494
0
    if (!is_valid_partial_update(row, column, datum)) {
4495
0
        struct ovsdb_type type_ = column->type;
4496
0
        type_.value.type = OVSDB_TYPE_VOID;
4497
0
        ovsdb_datum_destroy(datum, &type_);
4498
0
        free(datum);
4499
0
        return;
4500
0
    }
4501
0
    ovsdb_idl_txn_add_set_op(row, column, datum, SET_OP_DELETE);
4502
0
}
4503
4504
/* Inserts the key-value specified in 'datum' into the map in 'column' in
4505
 * 'row_'. If the key already exist in 'column', then it's value is updated
4506
 * with the value in 'datum'. The key-value in 'datum' must be of the same type
4507
 * as the keys-values in 'column'. This function takes ownership of 'datum'.
4508
 *
4509
 * Usually this function is used indirectly through one of the "update"
4510
 * functions generated by vswitch-idl. */
4511
void
4512
ovsdb_idl_txn_write_partial_map(const struct ovsdb_idl_row *row_,
4513
                                const struct ovsdb_idl_column *column,
4514
                                struct ovsdb_datum *datum)
4515
0
{
4516
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
4517
0
    enum ovsdb_atomic_type key_type;
4518
0
    enum map_op_type op_type;
4519
0
    const struct ovsdb_datum *old_datum;
4520
4521
0
    if (!is_valid_partial_update(row, column, datum)) {
4522
0
        ovsdb_datum_destroy(datum, &column->type);
4523
0
        free(datum);
4524
0
        return;
4525
0
    }
4526
4527
    /* Find out if this is an insert or an update. */
4528
0
    key_type = column->type.key.type;
4529
0
    old_datum = ovsdb_idl_read(row, column);
4530
0
    if (ovsdb_datum_find_key(old_datum, &datum->keys[0], key_type, NULL)) {
4531
0
        op_type = MAP_OP_UPDATE;
4532
0
    } else {
4533
0
        op_type = MAP_OP_INSERT;
4534
0
    }
4535
4536
0
    ovsdb_idl_txn_add_map_op(row, column, datum, op_type);
4537
0
}
4538
4539
/* Deletes the key specified in 'datum' from the map in 'column' in 'row_'.
4540
 * The key in 'datum' must be of the same type as the keys in 'column'.
4541
 * The value in 'datum' must be NULL. This function takes ownership of
4542
 * 'datum'.
4543
 *
4544
 * Usually this function is used indirectly through one of the "update"
4545
 * functions generated by vswitch-idl. */
4546
void
4547
ovsdb_idl_txn_delete_partial_map(const struct ovsdb_idl_row *row_,
4548
                                 const struct ovsdb_idl_column *column,
4549
                                 struct ovsdb_datum *datum)
4550
0
{
4551
0
    struct ovsdb_idl_row *row = CONST_CAST(struct ovsdb_idl_row *, row_);
4552
4553
0
    if (!is_valid_partial_update(row, column, datum)) {
4554
0
        struct ovsdb_type type_ = column->type;
4555
0
        type_.value.type = OVSDB_TYPE_VOID;
4556
0
        ovsdb_datum_destroy(datum, &type_);
4557
0
        free(datum);
4558
0
        return;
4559
0
    }
4560
0
    ovsdb_idl_txn_add_map_op(row, column, datum, MAP_OP_DELETE);
4561
0
}
4562
4563
void
4564
ovsdb_idl_loop_destroy(struct ovsdb_idl_loop *loop)
4565
0
{
4566
0
    if (loop) {
4567
0
        if (loop->committing_txn) {
4568
0
            ovsdb_idl_txn_destroy(loop->committing_txn);
4569
0
        }
4570
0
        ovsdb_idl_destroy(loop->idl);
4571
0
    }
4572
0
}
4573
4574
struct ovsdb_idl_txn *
4575
ovsdb_idl_loop_run(struct ovsdb_idl_loop *loop)
4576
0
{
4577
0
    ovsdb_idl_run(loop->idl);
4578
4579
    /* See if the 'committing_txn' succeeded in the meantime. */
4580
0
    if (loop->committing_txn && loop->committing_txn->status == TXN_SUCCESS) {
4581
0
        ovsdb_idl_try_commit_loop_txn(loop, NULL);
4582
0
    }
4583
4584
0
    loop->open_txn = (loop->committing_txn
4585
0
                      || ovsdb_idl_get_seqno(loop->idl) == loop->skip_seqno
4586
0
                      ? NULL
4587
0
                      : ovsdb_idl_txn_create(loop->idl));
4588
0
    if (loop->open_txn) {
4589
0
        ovsdb_idl_txn_add_comment(loop->open_txn, "%s", program_name);
4590
0
    }
4591
0
    return loop->open_txn;
4592
0
}
4593
4594
/* Attempts to commit the current transaction, if one is open.
4595
 *
4596
 * If a transaction was open, in this or a previous iteration of the main loop,
4597
 * and had not before finished committing (successfully or unsuccessfully), the
4598
 * return value is one of:
4599
 *
4600
 *  1: The transaction committed successfully (or it did not change anything in
4601
 *     the database).
4602
 *  0: The transaction failed.
4603
 * -1: The commit is still in progress.
4604
 *
4605
 * Thus, the return value is -1 if the transaction is in progress and otherwise
4606
 * true for success, false for failure.
4607
 *
4608
 * (In the corner case where the IDL sends a transaction to the database and
4609
 * the database commits it, and the connection between the IDL and the database
4610
 * drops before the IDL receives the message confirming the commit, this
4611
 * function can return 0 even though the transaction succeeded.)
4612
 */
4613
static int
4614
ovsdb_idl_try_commit_loop_txn(struct ovsdb_idl_loop *loop,
4615
                              bool *may_need_wakeup)
4616
0
{
4617
0
    if (!loop->committing_txn) {
4618
        /* Not a meaningful return value: no transaction was in progress. */
4619
0
        return 1;
4620
0
    }
4621
4622
0
    int retval;
4623
0
    struct ovsdb_idl_txn *txn = loop->committing_txn;
4624
4625
0
    enum ovsdb_idl_txn_status status = ovsdb_idl_txn_commit(txn);
4626
0
    if (status != TXN_INCOMPLETE) {
4627
0
        switch (status) {
4628
0
        case TXN_TRY_AGAIN:
4629
            /* We want to re-evaluate the database when it's changed from
4630
             * the contents that it had when we started the commit.  (That
4631
             * might have already happened.) */
4632
0
            loop->skip_seqno = loop->precommit_seqno;
4633
0
            if (ovsdb_idl_get_seqno(loop->idl) != loop->skip_seqno
4634
0
                && may_need_wakeup) {
4635
0
                *may_need_wakeup = true;
4636
0
            }
4637
0
            retval = 0;
4638
0
            break;
4639
4640
0
        case TXN_SUCCESS:
4641
            /* Possibly some work on the database was deferred because no
4642
             * further transaction could proceed.  Wake up again. */
4643
0
            retval = 1;
4644
0
            loop->cur_cfg = loop->next_cfg;
4645
0
            if (may_need_wakeup) {
4646
0
                *may_need_wakeup =  true;
4647
0
            }
4648
0
            break;
4649
4650
0
        case TXN_UNCHANGED:
4651
0
            retval = 1;
4652
0
            loop->cur_cfg = loop->next_cfg;
4653
0
            break;
4654
4655
0
        case TXN_ABORTED:
4656
0
        case TXN_NOT_LOCKED:
4657
0
        case TXN_ERROR:
4658
0
            retval = 0;
4659
0
            break;
4660
4661
0
        case TXN_UNCOMMITTED:
4662
0
        case TXN_INCOMPLETE:
4663
0
        default:
4664
0
            OVS_NOT_REACHED();
4665
0
        }
4666
0
        ovsdb_idl_txn_destroy(txn);
4667
0
        loop->committing_txn = NULL;
4668
0
    } else {
4669
0
        retval = -1;
4670
0
    }
4671
4672
0
    return retval;
4673
0
}
4674
4675
/* Attempts to commit the current transaction, if one is open, and sets up the
4676
 * poll loop to wake up when some more work might be needed.
4677
 *
4678
 * If a transaction was open, in this or a previous iteration of the main loop,
4679
 * and had not before finished committing (successfully or unsuccessfully), the
4680
 * return value is one of:
4681
 *
4682
 *  1: The transaction committed successfully (or it did not change anything in
4683
 *     the database).
4684
 *  0: The transaction failed.
4685
 * -1: The commit is still in progress.
4686
 *
4687
 * Thus, the return value is -1 if the transaction is in progress and otherwise
4688
 * true for success, false for failure.
4689
 *
4690
 * (In the corner case where the IDL sends a transaction to the database and
4691
 * the database commits it, and the connection between the IDL and the database
4692
 * drops before the IDL receives the message confirming the commit, this
4693
 * function can return 0 even though the transaction succeeded.)
4694
 */
4695
int
4696
ovsdb_idl_loop_commit_and_wait(struct ovsdb_idl_loop *loop)
4697
0
{
4698
0
    if (loop->open_txn) {
4699
0
        loop->committing_txn = loop->open_txn;
4700
0
        loop->open_txn = NULL;
4701
4702
0
        loop->precommit_seqno = ovsdb_idl_get_seqno(loop->idl);
4703
0
    }
4704
4705
0
    bool may_need_wakeup = false;
4706
0
    int retval = ovsdb_idl_try_commit_loop_txn(loop, &may_need_wakeup);
4707
0
    if (may_need_wakeup) {
4708
0
        poll_immediate_wake();
4709
0
    }
4710
0
    ovsdb_idl_wait(loop->idl);
4711
4712
0
    return retval;
4713
0
}