ovsdb-server: Refactor parsing of remote names to avoid ovs_fatal().
[cascardo/ovs.git] / ovsdb / ovsdb-server.c
1 /* Copyright (c) 2009, 2010, 2011, 2012 Nicira, Inc.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include <errno.h>
19 #include <getopt.h>
20 #include <signal.h>
21 #include <unistd.h>
22
23 #include "column.h"
24 #include "command-line.h"
25 #include "daemon.h"
26 #include "dirs.h"
27 #include "dummy.h"
28 #include "dynamic-string.h"
29 #include "file.h"
30 #include "hash.h"
31 #include "json.h"
32 #include "jsonrpc.h"
33 #include "jsonrpc-server.h"
34 #include "leak-checker.h"
35 #include "list.h"
36 #include "memory.h"
37 #include "ovsdb.h"
38 #include "ovsdb-data.h"
39 #include "ovsdb-types.h"
40 #include "ovsdb-error.h"
41 #include "poll-loop.h"
42 #include "process.h"
43 #include "row.h"
44 #include "simap.h"
45 #include "stream-ssl.h"
46 #include "stream.h"
47 #include "stress.h"
48 #include "sset.h"
49 #include "table.h"
50 #include "timeval.h"
51 #include "transaction.h"
52 #include "trigger.h"
53 #include "util.h"
54 #include "unixctl.h"
55 #include "vlog.h"
56
57 VLOG_DEFINE_THIS_MODULE(ovsdb_server);
58
59 struct db {
60     /* Initialized in main(). */
61     char *filename;
62     struct ovsdb_file *file;
63     struct ovsdb *db;
64
65     /* Only used by update_remote_status(). */
66     struct ovsdb_txn *txn;
67 };
68
69 /* SSL configuration. */
70 static char *private_key_file;
71 static char *certificate_file;
72 static char *ca_cert_file;
73 static bool bootstrap_ca_cert;
74
75 static unixctl_cb_func ovsdb_server_exit;
76 static unixctl_cb_func ovsdb_server_compact;
77 static unixctl_cb_func ovsdb_server_reconnect;
78
79 static void parse_options(int *argc, char **argvp[],
80                           struct sset *remotes, char **unixctl_pathp,
81                           char **run_command);
82 static void usage(void) NO_RETURN;
83
84 static void reconfigure_from_db(struct ovsdb_jsonrpc_server *jsonrpc,
85                                 const struct db dbs[], size_t n_dbs,
86                                 struct sset *remotes);
87
88 static void update_remote_status(const struct ovsdb_jsonrpc_server *jsonrpc,
89                                  const struct sset *remotes,
90                                  struct db dbs[], size_t n_dbs);
91
92 int
93 main(int argc, char *argv[])
94 {
95     char *unixctl_path = NULL;
96     char *run_command = NULL;
97     struct unixctl_server *unixctl;
98     struct ovsdb_jsonrpc_server *jsonrpc;
99     struct sset remotes;
100     struct process *run_process;
101     bool exiting;
102     int retval;
103     long long int status_timer = LLONG_MIN;
104
105     struct db *dbs;
106     int n_dbs;
107     int i;
108
109     proctitle_init(argc, argv);
110     set_program_name(argv[0]);
111     stress_init_command();
112     signal(SIGPIPE, SIG_IGN);
113     process_init();
114
115     parse_options(&argc, &argv, &remotes, &unixctl_path, &run_command);
116
117     daemonize_start();
118
119     n_dbs = MAX(1, argc);
120     dbs = xcalloc(n_dbs + 1, sizeof *dbs);
121     if (argc > 0) {
122         for (i = 0; i < argc; i++) {
123             dbs[i].filename = argv[i];
124         }
125     } else {
126         dbs[0].filename = xasprintf("%s/conf.db", ovs_dbdir());
127     }
128
129     for (i = 0; i < n_dbs; i++) {
130         struct ovsdb_error *error;
131
132         error = ovsdb_file_open(dbs[i].filename, false,
133                                 &dbs[i].db, &dbs[i].file);
134         if (error) {
135             ovs_fatal(0, "%s", ovsdb_error_to_string(error));
136         }
137     }
138
139     jsonrpc = ovsdb_jsonrpc_server_create();
140     for (i = 0; i < n_dbs; i++) {
141         if (!ovsdb_jsonrpc_server_add_db(jsonrpc, dbs[i].db)) {
142             ovs_fatal(0, "%s: duplicate database name",
143                       dbs[i].db->schema->name);
144         }
145     }
146     reconfigure_from_db(jsonrpc, dbs, n_dbs, &remotes);
147
148     retval = unixctl_server_create(unixctl_path, &unixctl);
149     if (retval) {
150         exit(EXIT_FAILURE);
151     }
152
153     if (run_command) {
154         char *run_argv[4];
155
156         run_argv[0] = "/bin/sh";
157         run_argv[1] = "-c";
158         run_argv[2] = run_command;
159         run_argv[3] = NULL;
160
161         retval = process_start(run_argv, NULL, 0, NULL, 0, &run_process);
162         if (retval) {
163             ovs_fatal(retval, "%s: process failed to start", run_command);
164         }
165     } else {
166         run_process = NULL;
167     }
168
169     daemonize_complete();
170
171     if (!run_command) {
172         /* ovsdb-server is usually a long-running process, in which case it
173          * makes plenty of sense to log the version, but --run makes
174          * ovsdb-server more like a command-line tool, so skip it.  */
175         VLOG_INFO("%s (Open vSwitch) %s", program_name, VERSION);
176     }
177
178     unixctl_command_register("exit", "", 0, 0, ovsdb_server_exit, &exiting);
179     unixctl_command_register("ovsdb-server/compact", "", 0, 1,
180                              ovsdb_server_compact, dbs);
181     unixctl_command_register("ovsdb-server/reconnect", "", 0, 0,
182                              ovsdb_server_reconnect, jsonrpc);
183
184     exiting = false;
185     while (!exiting) {
186         int i;
187
188         memory_run();
189         if (memory_should_report()) {
190             struct simap usage;
191
192             simap_init(&usage);
193             ovsdb_jsonrpc_server_get_memory_usage(jsonrpc, &usage);
194             for (i = 0; i < n_dbs; i++) {
195                 ovsdb_get_memory_usage(dbs[i].db, &usage);
196             }
197             memory_report(&usage);
198             simap_destroy(&usage);
199         }
200
201         reconfigure_from_db(jsonrpc, dbs, n_dbs, &remotes);
202         ovsdb_jsonrpc_server_run(jsonrpc);
203         unixctl_server_run(unixctl);
204
205         for (i = 0; i < n_dbs; i++) {
206             ovsdb_trigger_run(dbs[i].db, time_msec());
207         }
208         if (run_process && process_exited(run_process)) {
209             exiting = true;
210         }
211
212         /* update Manager status(es) every 5 seconds */
213         if (time_msec() >= status_timer) {
214             status_timer = time_msec() + 5000;
215             update_remote_status(jsonrpc, &remotes, dbs, n_dbs);
216         }
217
218         memory_wait();
219         ovsdb_jsonrpc_server_wait(jsonrpc);
220         unixctl_server_wait(unixctl);
221         for (i = 0; i < n_dbs; i++) {
222             ovsdb_trigger_wait(dbs[i].db, time_msec());
223         }
224         if (run_process) {
225             process_wait(run_process);
226         }
227         if (exiting) {
228             poll_immediate_wake();
229         }
230         poll_timer_wait_until(status_timer);
231         poll_block();
232     }
233     ovsdb_jsonrpc_server_destroy(jsonrpc);
234     for (i = 0; i < n_dbs; i++) {
235         ovsdb_destroy(dbs[i].db);
236     }
237     sset_destroy(&remotes);
238     unixctl_server_destroy(unixctl);
239
240     if (run_process && process_exited(run_process)) {
241         int status = process_status(run_process);
242         if (status) {
243             ovs_fatal(0, "%s: child exited, %s",
244                       run_command, process_status_msg(status));
245         }
246     }
247
248     return 0;
249 }
250
251 static const struct db *
252 find_db(const struct db dbs[], size_t n_dbs, const char *db_name)
253 {
254     size_t i;
255
256     for (i = 0; i < n_dbs; i++) {
257         if (!strcmp(dbs[i].db->schema->name, db_name)) {
258             return &dbs[i];
259         }
260     }
261
262     return NULL;
263 }
264
265 static char * WARN_UNUSED_RESULT
266 parse_db_column__(const struct db dbs[], size_t n_dbs,
267                   const char *name_, char *name,
268                   const struct db **dbp,
269                   const struct ovsdb_table **tablep,
270                   const struct ovsdb_column **columnp)
271 {
272     const char *table_name, *column_name;
273     const struct ovsdb_column *column;
274     const struct ovsdb_table *table;
275     const char *tokens[3];
276     char *save_ptr = NULL;
277     const struct db *db;
278
279     *dbp = NULL;
280     *tablep = NULL;
281     *columnp = NULL;
282
283     strtok_r(name, ":", &save_ptr); /* "db:" */
284     tokens[0] = strtok_r(NULL, ",", &save_ptr);
285     tokens[1] = strtok_r(NULL, ",", &save_ptr);
286     tokens[2] = strtok_r(NULL, ",", &save_ptr);
287     if (!tokens[0] || !tokens[1]) {
288         return xasprintf("\"%s\": invalid syntax", name_);
289     }
290     if (tokens[2]) {
291         const char *db_name = tokens[0];
292         table_name = tokens[1];
293         column_name = tokens[2];
294
295         db = find_db(dbs, n_dbs, tokens[0]);
296         if (!db) {
297             return xasprintf("\"%s\": no database named %s", name_, db_name);
298         }
299     } else {
300         if (n_dbs > 1) {
301             return xasprintf("\"%s\": database name must be specified "
302                              "(because multiple databases are configured)",
303                              name_);
304         }
305
306         table_name = tokens[0];
307         column_name = tokens[1];
308         db = &dbs[0];
309     }
310
311     table = ovsdb_get_table(db->db, table_name);
312     if (!table) {
313         return xasprintf("\"%s\": no table named %s", name_, table_name);
314     }
315
316     column = ovsdb_table_schema_get_column(table->schema, column_name);
317     if (!column) {
318         return xasprintf("\"%s\": table \"%s\" has no column \"%s\"",
319                          name_, table_name, column_name);
320     }
321
322     *dbp = db;
323     *columnp = column;
324     *tablep = table;
325     return NULL;
326 }
327
328 /* Returns NULL if successful, otherwise a malloc()'d string describing the
329  * error. */
330 static char * WARN_UNUSED_RESULT
331 parse_db_column(const struct db dbs[], size_t n_dbs,
332                 const char *name_,
333                 const struct db **dbp,
334                 const struct ovsdb_table **tablep,
335                 const struct ovsdb_column **columnp)
336 {
337     char *name = xstrdup(name_);
338     char *retval = parse_db_column__(dbs, n_dbs, name_, name,
339                                      dbp, tablep, columnp);
340     free(name);
341     return retval;
342 }
343
344 /* Returns NULL if successful, otherwise a malloc()'d string describing the
345  * error. */
346 static char * WARN_UNUSED_RESULT
347 parse_db_string_column(const struct db dbs[], size_t n_dbs,
348                        const char *name,
349                        const struct db **dbp,
350                        const struct ovsdb_table **tablep,
351                        const struct ovsdb_column **columnp)
352 {
353     char *retval;
354
355     retval = parse_db_column(dbs, n_dbs, name, dbp, tablep, columnp);
356     if (retval) {
357         return retval;
358     }
359
360     if ((*columnp)->type.key.type != OVSDB_TYPE_STRING
361         || (*columnp)->type.value.type != OVSDB_TYPE_VOID) {
362         return xasprintf("\"%s\": table \"%s\" column \"%s\" is "
363                          "not string or set of strings",
364                          name, (*tablep)->schema->name, (*columnp)->name);
365     }
366
367     return NULL;
368 }
369
370 static OVS_UNUSED const char *
371 query_db_string(const struct db dbs[], size_t n_dbs, const char *name)
372 {
373     if (!name || strncmp(name, "db:", 3)) {
374         return name;
375     } else {
376         const struct ovsdb_column *column;
377         const struct ovsdb_table *table;
378         const struct ovsdb_row *row;
379         const struct db *db;
380         char *retval;
381
382         retval = parse_db_string_column(dbs, n_dbs, name,
383                                         &db, &table, &column);
384         if (retval) {
385             ovs_fatal(0, "%s", retval);
386         }
387
388         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
389             const struct ovsdb_datum *datum;
390             size_t i;
391
392             datum = &row->fields[column->index];
393             for (i = 0; i < datum->n; i++) {
394                 if (datum->keys[i].string[0]) {
395                     return datum->keys[i].string;
396                 }
397             }
398         }
399         return NULL;
400     }
401 }
402
403 static struct ovsdb_jsonrpc_options *
404 add_remote(struct shash *remotes, const char *target)
405 {
406     struct ovsdb_jsonrpc_options *options;
407
408     options = shash_find_data(remotes, target);
409     if (!options) {
410         options = ovsdb_jsonrpc_default_options(target);
411         shash_add(remotes, target, options);
412     }
413
414     return options;
415 }
416
417 static struct ovsdb_datum *
418 get_datum(struct ovsdb_row *row, const char *column_name,
419           const enum ovsdb_atomic_type key_type,
420           const enum ovsdb_atomic_type value_type,
421           const size_t n_max)
422 {
423     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
424     const struct ovsdb_table_schema *schema = row->table->schema;
425     const struct ovsdb_column *column;
426
427     column = ovsdb_table_schema_get_column(schema, column_name);
428     if (!column) {
429         VLOG_DBG_RL(&rl, "Table `%s' has no `%s' column",
430                     schema->name, column_name);
431         return NULL;
432     }
433
434     if (column->type.key.type != key_type
435         || column->type.value.type != value_type
436         || column->type.n_max != n_max) {
437         if (!VLOG_DROP_DBG(&rl)) {
438             char *type_name = ovsdb_type_to_english(&column->type);
439             VLOG_DBG("Table `%s' column `%s' has type %s, not expected "
440                      "key type %s, value type %s, max elements %zd.",
441                      schema->name, column_name, type_name,
442                      ovsdb_atomic_type_to_string(key_type),
443                      ovsdb_atomic_type_to_string(value_type),
444                      n_max);
445             free(type_name);
446         }
447         return NULL;
448     }
449
450     return &row->fields[column->index];
451 }
452
453 /* Read string-string key-values from a map.  Returns the value associated with
454  * 'key', if found, or NULL */
455 static const char *
456 read_map_string_column(const struct ovsdb_row *row, const char *column_name,
457                        const char *key)
458 {
459     const struct ovsdb_datum *datum;
460     union ovsdb_atom *atom_key = NULL, *atom_value = NULL;
461     size_t i;
462
463     datum = get_datum(CONST_CAST(struct ovsdb_row *, row), column_name,
464                       OVSDB_TYPE_STRING, OVSDB_TYPE_STRING, UINT_MAX);
465
466     if (!datum) {
467         return NULL;
468     }
469
470     for (i = 0; i < datum->n; i++) {
471         atom_key = &datum->keys[i];
472         if (!strcmp(atom_key->string, key)){
473             atom_value = &datum->values[i];
474             break;
475         }
476     }
477
478     return atom_value ? atom_value->string : NULL;
479 }
480
481 static const union ovsdb_atom *
482 read_column(const struct ovsdb_row *row, const char *column_name,
483             enum ovsdb_atomic_type type)
484 {
485     const struct ovsdb_datum *datum;
486
487     datum = get_datum(CONST_CAST(struct ovsdb_row *, row), column_name, type,
488                       OVSDB_TYPE_VOID, 1);
489     return datum && datum->n ? datum->keys : NULL;
490 }
491
492 static bool
493 read_integer_column(const struct ovsdb_row *row, const char *column_name,
494                     long long int *integerp)
495 {
496     const union ovsdb_atom *atom;
497
498     atom = read_column(row, column_name, OVSDB_TYPE_INTEGER);
499     *integerp = atom ? atom->integer : 0;
500     return atom != NULL;
501 }
502
503 static bool
504 read_string_column(const struct ovsdb_row *row, const char *column_name,
505                    const char **stringp)
506 {
507     const union ovsdb_atom *atom;
508
509     atom = read_column(row, column_name, OVSDB_TYPE_STRING);
510     *stringp = atom ? atom->string : NULL;
511     return atom != NULL;
512 }
513
514 static void
515 write_bool_column(struct ovsdb_row *row, const char *column_name, bool value)
516 {
517     const struct ovsdb_column *column;
518     struct ovsdb_datum *datum;
519
520     column = ovsdb_table_schema_get_column(row->table->schema, column_name);
521     datum = get_datum(row, column_name, OVSDB_TYPE_BOOLEAN,
522                       OVSDB_TYPE_VOID, 1);
523     if (!datum) {
524         return;
525     }
526
527     if (datum->n != 1) {
528         ovsdb_datum_destroy(datum, &column->type);
529
530         datum->n = 1;
531         datum->keys = xmalloc(sizeof *datum->keys);
532         datum->values = NULL;
533     }
534
535     datum->keys[0].boolean = value;
536 }
537
538 static void
539 write_string_string_column(struct ovsdb_row *row, const char *column_name,
540                            char **keys, char **values, size_t n)
541 {
542     const struct ovsdb_column *column;
543     struct ovsdb_datum *datum;
544     size_t i;
545
546     column = ovsdb_table_schema_get_column(row->table->schema, column_name);
547     datum = get_datum(row, column_name, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING,
548                       UINT_MAX);
549     if (!datum) {
550         for (i = 0; i < n; i++) {
551             free(keys[i]);
552             free(values[i]);
553         }
554         return;
555     }
556
557     /* Free existing data. */
558     ovsdb_datum_destroy(datum, &column->type);
559
560     /* Allocate space for new values. */
561     datum->n = n;
562     datum->keys = xmalloc(n * sizeof *datum->keys);
563     datum->values = xmalloc(n * sizeof *datum->values);
564
565     for (i = 0; i < n; ++i) {
566         datum->keys[i].string = keys[i];
567         datum->values[i].string = values[i];
568     }
569
570     /* Sort and check constraints. */
571     ovsdb_datum_sort_assert(datum, column->type.key.type);
572 }
573
574 /* Adds a remote and options to 'remotes', based on the Manager table row in
575  * 'row'. */
576 static void
577 add_manager_options(struct shash *remotes, const struct ovsdb_row *row)
578 {
579     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
580     struct ovsdb_jsonrpc_options *options;
581     long long int max_backoff, probe_interval;
582     const char *target, *dscp_string;
583
584     if (!read_string_column(row, "target", &target) || !target) {
585         VLOG_INFO_RL(&rl, "Table `%s' has missing or invalid `target' column",
586                      row->table->schema->name);
587         return;
588     }
589
590     options = add_remote(remotes, target);
591     if (read_integer_column(row, "max_backoff", &max_backoff)) {
592         options->max_backoff = max_backoff;
593     }
594     if (read_integer_column(row, "inactivity_probe", &probe_interval)) {
595         options->probe_interval = probe_interval;
596     }
597
598     options->dscp = DSCP_DEFAULT;
599     dscp_string = read_map_string_column(row, "other_config", "dscp");
600     if (dscp_string) {
601         int dscp = atoi(dscp_string);
602         if (dscp >= 0 && dscp <= 63) {
603             options->dscp = dscp;
604         }
605     }
606 }
607
608 static void
609 query_db_remotes(const char *name, const struct db dbs[], size_t n_dbs,
610                  struct shash *remotes)
611 {
612     const struct ovsdb_column *column;
613     const struct ovsdb_table *table;
614     const struct ovsdb_row *row;
615     const struct db *db;
616     char *retval;
617
618     retval = parse_db_column(dbs, n_dbs, name, &db, &table, &column);
619     if (retval) {
620         ovs_fatal(0, "%s", retval);
621     }
622
623     if (column->type.key.type == OVSDB_TYPE_STRING
624         && column->type.value.type == OVSDB_TYPE_VOID) {
625         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
626             const struct ovsdb_datum *datum;
627             size_t i;
628
629             datum = &row->fields[column->index];
630             for (i = 0; i < datum->n; i++) {
631                 add_remote(remotes, datum->keys[i].string);
632             }
633         }
634     } else if (column->type.key.type == OVSDB_TYPE_UUID
635                && column->type.key.u.uuid.refTable
636                && column->type.value.type == OVSDB_TYPE_VOID) {
637         const struct ovsdb_table *ref_table = column->type.key.u.uuid.refTable;
638         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
639             const struct ovsdb_datum *datum;
640             size_t i;
641
642             datum = &row->fields[column->index];
643             for (i = 0; i < datum->n; i++) {
644                 const struct ovsdb_row *ref_row;
645
646                 ref_row = ovsdb_table_get_row(ref_table, &datum->keys[i].uuid);
647                 if (ref_row) {
648                     add_manager_options(remotes, ref_row);
649                 }
650             }
651         }
652     }
653 }
654
655 static void
656 update_remote_row(const struct ovsdb_row *row, struct ovsdb_txn *txn,
657                   const struct ovsdb_jsonrpc_server *jsonrpc)
658 {
659     struct ovsdb_jsonrpc_remote_status status;
660     struct ovsdb_row *rw_row;
661     const char *target;
662     char *keys[8], *values[8];
663     size_t n = 0;
664
665     /* Get the "target" (protocol/host/port) spec. */
666     if (!read_string_column(row, "target", &target)) {
667         /* Bad remote spec or incorrect schema. */
668         return;
669     }
670     rw_row = ovsdb_txn_row_modify(txn, row);
671     ovsdb_jsonrpc_server_get_remote_status(jsonrpc, target, &status);
672
673     /* Update status information columns. */
674     write_bool_column(rw_row, "is_connected", status.is_connected);
675
676     if (status.state) {
677         keys[n] = xstrdup("state");
678         values[n++] = xstrdup(status.state);
679     }
680     if (status.sec_since_connect != UINT_MAX) {
681         keys[n] = xstrdup("sec_since_connect");
682         values[n++] = xasprintf("%u", status.sec_since_connect);
683     }
684     if (status.sec_since_disconnect != UINT_MAX) {
685         keys[n] = xstrdup("sec_since_disconnect");
686         values[n++] = xasprintf("%u", status.sec_since_disconnect);
687     }
688     if (status.last_error) {
689         keys[n] = xstrdup("last_error");
690         values[n++] =
691             xstrdup(ovs_retval_to_string(status.last_error));
692     }
693     if (status.locks_held && status.locks_held[0]) {
694         keys[n] = xstrdup("locks_held");
695         values[n++] = xstrdup(status.locks_held);
696     }
697     if (status.locks_waiting && status.locks_waiting[0]) {
698         keys[n] = xstrdup("locks_waiting");
699         values[n++] = xstrdup(status.locks_waiting);
700     }
701     if (status.locks_lost && status.locks_lost[0]) {
702         keys[n] = xstrdup("locks_lost");
703         values[n++] = xstrdup(status.locks_lost);
704     }
705     if (status.n_connections > 1) {
706         keys[n] = xstrdup("n_connections");
707         values[n++] = xasprintf("%d", status.n_connections);
708     }
709     write_string_string_column(rw_row, "status", keys, values, n);
710
711     ovsdb_jsonrpc_server_free_remote_status(&status);
712 }
713
714 static void
715 update_remote_rows(const struct db dbs[], size_t n_dbs,
716                    const char *remote_name,
717                    const struct ovsdb_jsonrpc_server *jsonrpc)
718 {
719     const struct ovsdb_table *table, *ref_table;
720     const struct ovsdb_column *column;
721     const struct ovsdb_row *row;
722     const struct db *db;
723     char *retval;
724
725     if (strncmp("db:", remote_name, 3)) {
726         return;
727     }
728
729     retval = parse_db_column(dbs, n_dbs, remote_name, &db, &table, &column);
730     if (retval) {
731         ovs_fatal(0, "%s", retval);
732     }
733
734     if (column->type.key.type != OVSDB_TYPE_UUID
735         || !column->type.key.u.uuid.refTable
736         || column->type.value.type != OVSDB_TYPE_VOID) {
737         return;
738     }
739
740     ref_table = column->type.key.u.uuid.refTable;
741
742     HMAP_FOR_EACH (row, hmap_node, &table->rows) {
743         const struct ovsdb_datum *datum;
744         size_t i;
745
746         datum = &row->fields[column->index];
747         for (i = 0; i < datum->n; i++) {
748             const struct ovsdb_row *ref_row;
749
750             ref_row = ovsdb_table_get_row(ref_table, &datum->keys[i].uuid);
751             if (ref_row) {
752                 update_remote_row(ref_row, db->txn, jsonrpc);
753             }
754         }
755     }
756 }
757
758 static void
759 update_remote_status(const struct ovsdb_jsonrpc_server *jsonrpc,
760                      const struct sset *remotes,
761                      struct db dbs[], size_t n_dbs)
762 {
763     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
764     const char *remote;
765     size_t i;
766
767     for (i = 0; i < n_dbs; i++) {
768         dbs[i].txn = ovsdb_txn_create(dbs[i].db);
769     }
770
771     /* Iterate over --remote arguments given on command line. */
772     SSET_FOR_EACH (remote, remotes) {
773         update_remote_rows(dbs, n_dbs, remote, jsonrpc);
774     }
775
776     for (i = 0; i < n_dbs; i++) {
777         struct ovsdb_error *error = ovsdb_txn_commit(dbs[i].txn, false);
778         if (error) {
779             VLOG_ERR_RL(&rl, "Failed to update remote status: %s",
780                         ovsdb_error_to_string(error));
781             ovsdb_error_destroy(error);
782         }
783     }
784 }
785
786 /* Reconfigures ovsdb-server based on information in the database. */
787 static void
788 reconfigure_from_db(struct ovsdb_jsonrpc_server *jsonrpc,
789                     const struct db dbs[], size_t n_dbs, struct sset *remotes)
790 {
791     struct shash resolved_remotes;
792     const char *name;
793
794     /* Configure remotes. */
795     shash_init(&resolved_remotes);
796     SSET_FOR_EACH (name, remotes) {
797         if (!strncmp(name, "db:", 3)) {
798             query_db_remotes(name, dbs, n_dbs, &resolved_remotes);
799         } else {
800             add_remote(&resolved_remotes, name);
801         }
802     }
803     ovsdb_jsonrpc_server_set_remotes(jsonrpc, &resolved_remotes);
804     shash_destroy_free_data(&resolved_remotes);
805
806     /* Configure SSL. */
807     stream_ssl_set_key_and_cert(query_db_string(dbs, n_dbs, private_key_file),
808                                 query_db_string(dbs, n_dbs, certificate_file));
809     stream_ssl_set_ca_cert_file(query_db_string(dbs, n_dbs, ca_cert_file),
810                                 bootstrap_ca_cert);
811 }
812
813 static void
814 ovsdb_server_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
815                   const char *argv[] OVS_UNUSED,
816                   void *exiting_)
817 {
818     bool *exiting = exiting_;
819     *exiting = true;
820     unixctl_command_reply(conn, NULL);
821 }
822
823 static void
824 ovsdb_server_compact(struct unixctl_conn *conn, int argc,
825                      const char *argv[], void *dbs_)
826 {
827     struct db *dbs = dbs_;
828     struct ds reply;
829     struct db *db;
830     int n = 0;
831
832     ds_init(&reply);
833     for (db = dbs; db->filename != NULL; db++) {
834         const char *name = db->db->schema->name;
835
836         if (argc < 2 || !strcmp(argv[1], name)) {
837             struct ovsdb_error *error;
838
839             VLOG_INFO("compacting %s database by user request", name);
840
841             error = ovsdb_file_compact(db->file);
842             if (error) {
843                 char *s = ovsdb_error_to_string(error);
844                 ds_put_format(&reply, "%s\n", s);
845                 free(s);
846             }
847
848             n++;
849         }
850     }
851
852     if (!n) {
853         unixctl_command_reply_error(conn, "no database by that name");
854     } else if (reply.length) {
855         unixctl_command_reply_error(conn, ds_cstr(&reply));
856     } else {
857         unixctl_command_reply(conn, NULL);
858     }
859     ds_destroy(&reply);
860 }
861
862 /* "ovsdb-server/reconnect": makes ovsdb-server drop all of its JSON-RPC
863  * connections and reconnect. */
864 static void
865 ovsdb_server_reconnect(struct unixctl_conn *conn, int argc OVS_UNUSED,
866                        const char *argv[] OVS_UNUSED, void *jsonrpc_)
867 {
868     struct ovsdb_jsonrpc_server *jsonrpc = jsonrpc_;
869
870     ovsdb_jsonrpc_server_reconnect(jsonrpc);
871     unixctl_command_reply(conn, NULL);
872 }
873
874 static void
875 parse_options(int *argcp, char **argvp[],
876               struct sset *remotes, char **unixctl_pathp, char **run_command)
877 {
878     enum {
879         OPT_REMOTE = UCHAR_MAX + 1,
880         OPT_UNIXCTL,
881         OPT_RUN,
882         OPT_BOOTSTRAP_CA_CERT,
883         OPT_ENABLE_DUMMY,
884         VLOG_OPTION_ENUMS,
885         LEAK_CHECKER_OPTION_ENUMS,
886         DAEMON_OPTION_ENUMS
887     };
888     static struct option long_options[] = {
889         {"remote",      required_argument, NULL, OPT_REMOTE},
890         {"unixctl",     required_argument, NULL, OPT_UNIXCTL},
891         {"run",         required_argument, NULL, OPT_RUN},
892         {"help",        no_argument, NULL, 'h'},
893         {"version",     no_argument, NULL, 'V'},
894         DAEMON_LONG_OPTIONS,
895         VLOG_LONG_OPTIONS,
896         LEAK_CHECKER_LONG_OPTIONS,
897         {"bootstrap-ca-cert", required_argument, NULL, OPT_BOOTSTRAP_CA_CERT},
898         {"private-key", required_argument, NULL, 'p'},
899         {"certificate", required_argument, NULL, 'c'},
900         {"ca-cert",     required_argument, NULL, 'C'},
901         {"enable-dummy", optional_argument, NULL, OPT_ENABLE_DUMMY},
902         {NULL, 0, NULL, 0},
903     };
904     char *short_options = long_options_to_short_options(long_options);
905     int argc = *argcp;
906     char **argv = *argvp;
907
908     sset_init(remotes);
909     for (;;) {
910         int c;
911
912         c = getopt_long(argc, argv, short_options, long_options, NULL);
913         if (c == -1) {
914             break;
915         }
916
917         switch (c) {
918         case OPT_REMOTE:
919             sset_add(remotes, optarg);
920             break;
921
922         case OPT_UNIXCTL:
923             *unixctl_pathp = optarg;
924             break;
925
926         case OPT_RUN:
927             *run_command = optarg;
928             break;
929
930         case 'h':
931             usage();
932
933         case 'V':
934             ovs_print_version(0, 0);
935             exit(EXIT_SUCCESS);
936
937         VLOG_OPTION_HANDLERS
938         DAEMON_OPTION_HANDLERS
939         LEAK_CHECKER_OPTION_HANDLERS
940
941         case 'p':
942             private_key_file = optarg;
943             break;
944
945         case 'c':
946             certificate_file = optarg;
947             break;
948
949         case 'C':
950             ca_cert_file = optarg;
951             bootstrap_ca_cert = false;
952             break;
953
954         case OPT_BOOTSTRAP_CA_CERT:
955             ca_cert_file = optarg;
956             bootstrap_ca_cert = true;
957             break;
958
959         case OPT_ENABLE_DUMMY:
960             dummy_enable(optarg && !strcmp(optarg, "override"));
961             break;
962
963         case '?':
964             exit(EXIT_FAILURE);
965
966         default:
967             abort();
968         }
969     }
970     free(short_options);
971
972     *argcp -= optind;
973     *argvp += optind;
974 }
975
976 static void
977 usage(void)
978 {
979     printf("%s: Open vSwitch database server\n"
980            "usage: %s [OPTIONS] [DATABASE...]\n"
981            "where each DATABASE is a database file in ovsdb format.\n"
982            "The default DATABASE, if none is given, is\n%s/conf.db.\n",
983            program_name, program_name, ovs_dbdir());
984     printf("\nJSON-RPC options (may be specified any number of times):\n"
985            "  --remote=REMOTE         connect or listen to REMOTE\n");
986     stream_usage("JSON-RPC", true, true, true);
987     daemon_usage();
988     vlog_usage();
989     printf("\nOther options:\n"
990            "  --run COMMAND           run COMMAND as subprocess then exit\n"
991            "  --unixctl=SOCKET        override default control socket name\n"
992            "  -h, --help              display this help message\n"
993            "  -V, --version           display version information\n");
994     leak_checker_usage();
995     exit(EXIT_SUCCESS);
996 }